/// <summary> /// 构建数节点 /// </summary> /// <param name="htmlHelper">被扩展的htmlhelper实例</param> /// <param name="name"> 树选择器的名称</param> /// <param name="treeOptions">树的设置</param> /// <param name="treeNodes">树节点集合如果不填则通过ViewData传值</param> /// <exception cref="ArgumentNullException">ViewData为空时</exception> /// <returns></returns> public static MvcHtmlString Tree(this HtmlHelper htmlHelper, string name, TreeOptions treeOptions, IEnumerable<TreeNode> treeNodes = null) { if (treeNodes == null) if (htmlHelper.ViewData[name] != null) treeNodes = htmlHelper.ViewData[name] as IEnumerable<TreeNode>; if (treeNodes == null) throw new ExceptionFacade("ViewData没有对name赋值"); //定义属性字典 Dictionary<string, object> result = new Dictionary<string, object>(); //data属性字典 Dictionary<string, object> data = new Dictionary<string, object>(); //添加树节点数据 data.TryAdd("TreeNodes", treeNodes.Select(n => n.ToUnobtrusiveHtmlAttributes())); //添加树属性数据 data.TryAdd("Settings", treeOptions.ToUnobtrusiveHtmlAttributes()); //将数据添加到集合中 //建立标签元素 TagBuilder builder = new TagBuilder("ul"); //添加初始化数据树 //添加用于脚本操作的标识 result["plugin"] = "Tree"; result.Add("data", Json.Encode(data)); builder.MergeAttributes(result); builder.MergeAttribute("id", name); //样式 builder.MergeAttribute("class", "ztree"); htmlHelper.Script("~/Scripts/tunynet/zTree.js"); return MvcHtmlString.Create(builder.ToString().Replace(""|", "").Replace("|"", "")); }
public void TryAdd() { var dictionary = new Dictionary<int, string>(); dictionary.TryAdd(0, "zero").ShouldBe(true); dictionary[0].ShouldBe("zero"); dictionary.TryAdd(0, "0").ShouldBe(false); dictionary[0].ShouldBe("zero"); }
public static IDictionary<string, TestDefinition> GetTestDefinitions( this IEnumerable<Type> monitoringTests) { var definitions = monitoringTests .SelectMany( t => t .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(m => m.GetParameters().All(p => p.HasDefaultValue)) .Where(m => !m.IsSpecialName) .Select(TestDefinition.Create)); var dictionary = new Dictionary<string, TestDefinition>(); var collisionCount = 0; foreach (var testDefinition in definitions) { if (!dictionary.TryAdd(testDefinition.TestName, testDefinition)) { var name = "TEST_NAME_COLLISION_" + ++collisionCount; var definition = testDefinition; dictionary.Add(name, new AnonymousTestDefinition(name, _ => { throw new InvalidOperationException("Test could not be routed:\n" + definition.ToLogString()); })); } } return dictionary; }
static void Main(string[] args) { //string a = "admin"; //Console.WriteLine(a.To16bitMD5()); //Console.WriteLine(a.To32bitMD5()); //Console.WriteLine(a.ToSHA1()); //Example1(); //Example2(); var a2 = "2010-12-12".To<DateTime>(DateTime.Now); Dictionary<string, string> dict = new Dictionary<string, string>(); Dictionary<string, string> dict2 = new Dictionary<string, string>(); dict2.Add("22222222", ""); dict.TryAdd("12", "").TryAdd("34", "").AddOrReplace("34", "").AddRange(dict2, false); var asdf = "123".CompareTo("1"); List<string> lst = new List<string>() { "wer", "dsfdsf", "sad" }; lst.ForEach((item) => { Console.WriteLine(item); }); List<User> lstUser = new List<User> { new User{Id=1, Name="柳永法",Age=28,IsMan=true}, new User{Id=2, Name="柳永法1",Age=28,IsMan=true}, new User{Id=3, Name="柳永法",Age=29,IsMan=true}, new User{Id=4, Name="柳永法1",Age=29,IsMan=true}, }; var result1 = lstUser.Distinct(p => p.Age); var result2 = lstUser.Distinct((x, y) => x.Age == y.Age && x.IsMan == y.IsMan); }
public void op_TryAdd_IDictionaryOfT_TKey_TValue_whenFalse() { var list = new Dictionary<string, int> { { "example", 123 } }; Assert.False(list.TryAdd("example", 456)); }
public void op_TryAdd_IDictionaryOfT_KeyValuePair_whenFalse() { var list = new Dictionary<string, int> { { "example", 123 } }; Assert.False(list.TryAdd(new KeyValuePair<string, int>("example", 456))); }
static void Main(string[] args) { if (args.Length < 2) { throw new ArgumentException("Not enough arguments! Required: file, outdir, (build in x.x.x format)"); } if (!File.Exists(args[0])) { throw new FileNotFoundException("File not found!"); } var file = MemoryMappedFile.CreateFromFile(args[0], FileMode.Open); var maps = EXEParsing.GenerateMap(file.CreateViewAccessor()); ulong translate(ulong search) => maps.Select(map => map.translateMemoryToFile(search)).FirstOrDefault(r => r != 0x0); using (var bin = new BinaryReader(file.CreateViewStream())) { var chunkSize = 1024; // Find version var buildPattern = new byte?[] { 0x42, 0x75, 0x69, 0x6C, 0x64, 0x20, null, null, null, null, null, 0x20, 0x28, null, null, null, null, null, 0x29, 0x20, 0x28 }; var buildPatternLength = buildPattern.Length; var build = ""; if (args.Length == 3) { build = args[2]; } while (true) { if ((bin.BaseStream.Length - bin.BaseStream.Position) < chunkSize) { break; } var posInStack = Search(bin.ReadBytes(chunkSize), buildPattern); if (posInStack != chunkSize) { var matchPos = bin.BaseStream.Position - chunkSize + posInStack; bin.BaseStream.Position = matchPos; bin.ReadBytes(6); var buildNumber = new string(bin.ReadChars(5)); bin.ReadBytes(2); var patch = new string(bin.ReadChars(5)); build = patch + "." + buildNumber; } else { bin.BaseStream.Position = bin.BaseStream.Position - buildPatternLength; } } if (build == "") { // Retry with backup pattern (crash log output) bin.BaseStream.Position = 0; buildPattern = new byte?[] { 0x00, 0x3C, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x3E, 0x20 }; // <Version> buildPatternLength = buildPattern.Length; while (true) { if ((bin.BaseStream.Length - bin.BaseStream.Position) < chunkSize) { break; } var posInStack = Search(bin.ReadBytes(chunkSize), buildPattern); if (posInStack != chunkSize) { var matchPos = bin.BaseStream.Position - chunkSize + posInStack; bin.BaseStream.Position = matchPos; bin.ReadBytes(11); build = new string(bin.ReadChars(11)); } else { bin.BaseStream.Position = bin.BaseStream.Position - buildPatternLength; } } } if (build == "") { // Retry with RenderService pattern.. bin.BaseStream.Position = 0; buildPattern = new byte?[] { 0x52, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, null, null, null, null, null, 0x00 }; // <Version> buildPatternLength = buildPattern.Length; while (true) { if ((bin.BaseStream.Length - bin.BaseStream.Position) < chunkSize) { break; } var posInStack = Search(bin.ReadBytes(chunkSize), buildPattern); if (posInStack != chunkSize) { var matchPos = bin.BaseStream.Position - chunkSize + posInStack; bin.BaseStream.Position = matchPos; bin.ReadBytes(14); build = new string(bin.ReadChars(5)); if (args.Length == 3) { build = args[2]; } else { Console.WriteLine("Expansion, major and minor version not found in binary. Please enter it in this format X.X.X: "); build = Console.ReadLine() + "." + build; } } else { bin.BaseStream.Position = bin.BaseStream.Position - buildPatternLength; } } } if (build == "") { Console.WriteLine("Build was not found! Please enter a build in this format: X.X.X.XXXXX"); build = Console.ReadLine(); } // Reset position for DBMeta reading bin.BaseStream.Position = 0; // Extract DBMeta var metas = new Dictionary <string, DBMeta>(); var patternBuilder = new PatternBuilder(); foreach (var pattern in patternBuilder.patterns) { // Skip versions of the pattern that aren't for this expansion if (build.StartsWith("1")) { if (!pattern.compatiblePatches.Contains(build.Substring(0, 6))) { Console.WriteLine("Skipping " + pattern.name + " as it does not list " + build + " as compatible!"); continue; } if (!pattern.compatiblePatches.Contains(build.Substring(0, 6))) { Console.WriteLine("Skipping " + pattern.name + " as it does not list " + build + " as compatible!"); continue; } if (pattern.minBuild != 0 && pattern.minBuild > int.Parse(build.Substring(7))) { Console.WriteLine("Skipping " + pattern.name + " as minimum build " + pattern.minBuild + " exceeds build of " + build.Substring(6)); continue; } if (pattern.maxBuild != 0 && int.Parse(build.Substring(7)) > pattern.maxBuild) { Console.WriteLine("Skipping " + pattern.name + " as maximum build " + pattern.maxBuild + " exceeds build of " + build.Substring(6)); continue; } } else { if (!pattern.compatiblePatches.Contains(build.Substring(0, 5))) { Console.WriteLine("Skipping " + pattern.name + " as it does not list " + build + " as compatible!"); continue; } if (!pattern.compatiblePatches.Contains(build.Substring(0, 5))) { Console.WriteLine("Skipping " + pattern.name + " as it does not list " + build + " as compatible!"); continue; } if (pattern.minBuild != 0 && pattern.minBuild > int.Parse(build.Substring(6))) { Console.WriteLine("Skipping " + pattern.name + " as minimum build " + pattern.minBuild + " exceeds build of " + build.Substring(6)); continue; } if (pattern.maxBuild != 0 && int.Parse(build.Substring(6)) > pattern.maxBuild) { Console.WriteLine("Skipping " + pattern.name + " as maximum build " + pattern.maxBuild + " exceeds build of " + build.Substring(6)); continue; } } var patternBytes = ParsePattern(pattern.cur_pattern).ToArray(); var patternLength = patternBytes.Length; while (true) { if ((bin.BaseStream.Length - bin.BaseStream.Position) < chunkSize) { break; } var posInStack = Search(bin.ReadBytes(chunkSize), patternBytes); if (posInStack != chunkSize) { var matchPos = bin.BaseStream.Position - chunkSize + posInStack; Console.WriteLine("Pattern " + pattern.name + " matched at " + matchPos); if (pattern.offsets.ContainsKey(Name.FDID)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.FDID]; var fdid = bin.ReadUInt32(); if (fdid < 53183) { Console.WriteLine("Invalid filedataid " + fdid + ", skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.RECORD_SIZE)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.RECORD_SIZE]; if (bin.ReadUInt32() == 0) { Console.WriteLine("Record size is 0, skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.DB_NAME)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_NAME]; if (bin.ReadUInt32() < 10) { Console.WriteLine("Name offset is invalid, skipping match.."); continue; } bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_NAME]; var targetOffset = (long)translate(bin.ReadUInt64()); if (targetOffset > bin.BaseStream.Length) { Console.WriteLine("Name offset is out of range of file, skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.DB_FILENAME)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_FILENAME]; if (bin.ReadUInt32() < 10) { Console.WriteLine("Name offset is invalid, skipping match.."); continue; } bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_FILENAME]; var targetOffset = (long)translate(bin.ReadUInt64()); if (targetOffset > bin.BaseStream.Length) { Console.WriteLine("Name offset is out of range of file, skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.NUM_FIELD_IN_FILE)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.NUM_FIELD_IN_FILE]; if (bin.ReadUInt32() > 5000) { Console.WriteLine("Num fields in file is over 5000, skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.FIELD_TYPES_IN_FILE) && pattern.offsets.ContainsKey(Name.FIELD_SIZES_IN_FILE)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.FIELD_TYPES_IN_FILE]; var fieldTypesInFile = bin.ReadInt64(); bin.BaseStream.Position = matchPos + pattern.offsets[Name.FIELD_SIZES_IN_FILE]; var fieldSizesInFileOffs = bin.ReadInt64(); if (fieldTypesInFile == fieldSizesInFileOffs) { Console.WriteLine("Field types in file offset == field sizes in file offset, skipping match.."); continue; } } if (pattern.offsets.ContainsKey(Name.DB_CACHE_FILENAME)) { bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_CACHE_FILENAME]; bin.BaseStream.Position = (long)translate((ulong)bin.ReadInt64()); var adbname = bin.ReadCString(); bin.BaseStream.Position = matchPos + pattern.offsets[Name.DB_CACHE_FILENAME]; if (!adbname.EndsWith("adb")) { Console.WriteLine("ADB filename does not end in adb, skipping match.."); continue; } } bin.BaseStream.Position = matchPos; var meta = ReadMeta(bin, pattern); if (pattern.offsets.ContainsKey(Name.DB_NAME)) { bin.BaseStream.Position = (long)translate((ulong)meta.nameOffset); var filename = bin.ReadCString(); if (filename.Contains("DBFilesClient")) { filename = filename.Substring(filename.IndexOf("\\") + 1); } metas.TryAdd(Path.GetFileNameWithoutExtension(filename), meta); } else if (pattern.offsets.ContainsKey(Name.DB_FILENAME)) { bin.BaseStream.Position = (long)translate((ulong)meta.dbFilenameOffs); var name = bin.ReadCString(); metas.TryAdd(Path.GetFileNameWithoutExtension(name), meta); } bin.BaseStream.Position = matchPos + patternLength; } else { bin.BaseStream.Position = bin.BaseStream.Position - patternLength; } } bin.BaseStream.Position = 0; } var outputDirectory = Path.Combine(args[1], build); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } // Process DBMetas foreach (var meta in metas) { if ((long)translate((ulong)meta.Value.field_offsets_offs) > bin.BaseStream.Length) { Console.WriteLine("Skipping reading of " + meta.Key + " because first offset is way out of range!"); continue; } var writer = new StreamWriter(Path.Combine(outputDirectory, meta.Key + ".dbd")); writer.WriteLine("COLUMNS"); Console.Write("Writing " + meta.Key + ".dbd.."); var fieldCount = 0; if (meta.Value.num_fields == 0 && meta.Value.num_fields_in_file != 0) { fieldCount = meta.Value.num_fields_in_file; } else { fieldCount = meta.Value.num_fields; } var field_offsets = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_offsets_offs)); var field_sizes = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_sizes_offs)); var field_types = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_types_offs)); var field_flags = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_flags_offs)); var field_sizes_in_file = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_sizes_in_file_offs)); var field_types_in_file = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_types_in_file_offs)); var field_flags_in_file = ReadFieldArray(bin, fieldCount, (long)translate((ulong)meta.Value.field_flags_in_file_offs)); var field_names_in_file = ReadFieldOffsetArray(bin, fieldCount, (long)translate((ulong)meta.Value.namesInFileOffs)); if (meta.Value.id_column == -1) { writer.WriteLine("int ID"); } var columnNames = new List <string>(); var columnTypeFlags = new List <Tuple <int, int> >(); for (var i = 0; i < meta.Value.num_fields_in_file; i++) { if (field_flags_in_file.Count == 0) { columnTypeFlags.Add(new Tuple <int, int>(field_types_in_file[i], 0)); } else { columnTypeFlags.Add(new Tuple <int, int>(field_types_in_file[i], field_flags_in_file[i])); } } if (meta.Value.num_fields != 0 && (meta.Value.num_fields_in_file != meta.Value.num_fields)) { columnTypeFlags.Add(new Tuple <int, int>(field_types[meta.Value.num_fields_in_file], field_flags[meta.Value.num_fields_in_file])); } for (var i = 0; i < columnTypeFlags.Count; i++) { if (field_names_in_file.Count > 0) { bin.BaseStream.Position = (long)translate(field_names_in_file[i]); columnNames.Add(CleanRealName(bin.ReadCString())); } else { columnNames.Add(GenerateName(i, build)); } var t = TypeToT(columnTypeFlags[i].Item1, (FieldFlags)columnTypeFlags[i].Item2); if (t.Item1 == "locstring") { writer.WriteLine(t.Item1 + " " + columnNames[i] + "_lang"); } else { if (t.Item1 == "uint") { writer.WriteLine("int " + columnNames[i]); } else { writer.WriteLine(t.Item1 + " " + columnNames[i]); } } } writer.WriteLine(); if (meta.Value.layout_hash != 0) { writer.WriteLine("LAYOUT " + meta.Value.layout_hash.ToString("X8").ToUpper()); } writer.WriteLine("BUILD " + build); if (meta.Value.sparseTable == 1) { writer.WriteLine("COMMENT table is sparse"); } if (meta.Value.id_column == -1) { writer.WriteLine("$noninline,id$ID<32>"); } for (var i = 0; i < meta.Value.num_fields_in_file; i++) { var typeFlags = ("int", 32); if (field_flags_in_file.Count == 0) { typeFlags = TypeToT(field_types_in_file[i], 0); } else { typeFlags = TypeToT(field_types_in_file[i], (FieldFlags)field_flags_in_file[i]); } if (meta.Value.id_column == i) { writer.Write("$id$"); } if (build.StartsWith("7.3.5") || build.StartsWith("8")) { if (meta.Value.column_8C == i) { writer.Write("$relation$"); if (meta.Value.column_90 != i) { throw new Exception("No column_90 but there is column_8C send help!"); } } } writer.Write(columnNames[i]); if (typeFlags.Item1 == "locstring") { writer.Write("_lang"); } if (typeFlags.Item2 > 0) { if (typeFlags.Item1 == "uint") { writer.Write("<u" + typeFlags.Item2 + ">"); } else { writer.Write("<" + typeFlags.Item2 + ">"); } } if (field_sizes_in_file[i] != 1) { // 6.0.1 has sizes in bytes if (build.StartsWith("6.0.1")) { var supposedSize = 0; if ((typeFlags.Item1 == "uint" || typeFlags.Item1 == "int") && typeFlags.Item2 != 32) { supposedSize = typeFlags.Item2 / 8; } else { supposedSize = 4; } var fixedSize = field_sizes_in_file[i] / supposedSize; if (fixedSize > 1) { writer.Write("[" + fixedSize + "]"); } } else { writer.Write("[" + field_sizes_in_file[i] + "]"); } } writer.WriteLine(); } if (meta.Value.num_fields != 0 && (meta.Value.num_fields_in_file != meta.Value.num_fields)) { var i = meta.Value.num_fields_in_file; var typeFlags = TypeToT(field_types[i], (FieldFlags)field_flags[i]); writer.Write("$noninline,relation$" + columnNames[i]); if (typeFlags.Item1 == "locstring") { writer.Write("_lang"); } if (typeFlags.Item2 > 0) { if (typeFlags.Item1 == "uint") { writer.Write("<u" + typeFlags.Item2 + ">"); } else if (typeFlags.Item1 == "int") { writer.Write("<" + typeFlags.Item2 + ">"); } } if (field_sizes[i] != 1) { writer.Write("[" + field_sizes[i] + "]"); } } writer.Flush(); writer.Close(); Console.Write("..done!\n"); } } Environment.Exit(0); }
public async Task PermCheckGuild(Context ctx) { Guild guild; GuildMemberPartial senderGuildUser = null; if (ctx.Guild != null && !ctx.HasNext()) { guild = ctx.Guild; senderGuildUser = ctx.Member; } else { var guildIdStr = ctx.RemainderOrNull() ?? throw new PKSyntaxError("You must pass a server ID or run this command in a server."); if (!ulong.TryParse(guildIdStr, out var guildId)) { throw new PKSyntaxError($"Could not parse {guildIdStr.AsCode()} as an ID."); } try { guild = await _rest.GetGuild(guildId); } catch (ForbiddenException) { throw Errors.GuildNotFound(guildId); } if (guild != null) { senderGuildUser = await _rest.GetGuildMember(guildId, ctx.Author.Id); } if (guild == null || senderGuildUser == null) { throw Errors.GuildNotFound(guildId); } } var guildMember = await _rest.GetGuildMember(guild.Id, await _cache.GetOwnUser()); // Loop through every channel and group them by sets of permissions missing var permissionsMissing = new Dictionary <ulong, List <Channel> >(); var hiddenChannels = false; var missingEmojiPermissions = false; foreach (var channel in await _rest.GetGuildChannels(guild.Id)) { var botPermissions = PermissionExtensions.PermissionsFor(guild, channel, await _cache.GetOwnUser(), guildMember); var webhookPermissions = PermissionExtensions.EveryonePermissions(guild, channel); var userPermissions = PermissionExtensions.PermissionsFor(guild, channel, ctx.Author.Id, senderGuildUser); if ((userPermissions & PermissionSet.ViewChannel) == 0) { // If the user can't see this channel, don't calculate permissions for it // (to prevent info-leaking, mostly) // Instead, show the user that some channels got ignored (so they don't get confused) hiddenChannels = true; continue; } // We use a bitfield so we can set individual permission bits in the loop // TODO: Rewrite with proper bitfield math ulong missingPermissionField = 0; foreach (var requiredPermission in requiredPermissions) { if ((botPermissions & requiredPermission) == 0) { missingPermissionField |= (ulong)requiredPermission; } } if ((webhookPermissions & PermissionSet.UseExternalEmojis) == 0) { missingPermissionField |= (ulong)PermissionSet.UseExternalEmojis; missingEmojiPermissions = true; } // If we're not missing any permissions, don't bother adding it to the dict // This means we can check if the dict is empty to see if all channels are proxyable if (missingPermissionField != 0) { permissionsMissing.TryAdd(missingPermissionField, new List <Channel>()); permissionsMissing[missingPermissionField].Add(channel); } } // Generate the output embed var eb = new EmbedBuilder() .Title($"Permission check for **{guild.Name}**"); if (permissionsMissing.Count == 0) { eb.Description("No errors found, all channels proxyable :)").Color(DiscordUtils.Green); } else { foreach (var(missingPermissionField, channels) in permissionsMissing) { // Each missing permission field can have multiple missing channels // so we extract them all and generate a comma-separated list var missingPermissionNames = ((PermissionSet)missingPermissionField).ToPermissionString(); var channelsList = string.Join("\n", channels .OrderBy(c => c.Position) .Select(c => $"#{c.Name}")); eb.Field(new Embed.Field($"Missing *{missingPermissionNames}*", channelsList.Truncate(1000))); eb.Color(DiscordUtils.Red); } } var footer = ""; if (hiddenChannels) { footer += "Some channels were ignored as you do not have view access to them."; } if (missingEmojiPermissions) { if (hiddenChannels) { footer += " | "; } footer += "Use External Emojis permissions must be granted to the @everyone role / Default Permissions."; } if (footer.Length > 0) { eb.Footer(new Embed.EmbedFooter(footer)); } // Send! :) await ctx.Reply(embed : eb.Build()); }
/// <summary> /// Adds a list of content security to which the provided directive is applied. /// </summary> /// <param name="directive">Directive to apply.</param> /// <param name="fetchDirective">Content security fetch directive.</param> /// <param name="hostSources">List of uri if the directive requires one.</param> /// <param name="schemeSources">List of scheme source authorized.</param> /// <param name="reportOnly">Indicates whether the rules are only there to generate a report.</param> /// <returns></returns> public SecurityHeadersBuilder AddContentSecurityPolicy(CommonPolicyDirective.Directive directive, ContentSecurityPolicyConstants.FetchDirectives fetchDirective, CommonPolicySchemeSource.SchemeSources schemeSources, IList <Uri> hostSources = null, bool reportOnly = true) { if (reportOnly && _reportUri == null) { throw new ReportUriMissingException(); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ChildSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ChildSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ConnectSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ConnectSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.DefaultSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.DefaultSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.FontSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.FontSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.FrameSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.FrameSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ImgSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ImgSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ManifestSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ManifestSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.MediaSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.MediaSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ObjectSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ObjectSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.PrefetchSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.PrefetchSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrc, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrcAttr)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrcAttr, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrcElem)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.ScriptSrcElem, directive); } if (fetchDirective.HasFlag(ContentSecurityPolicyConstants.FetchDirectives.WorkerSrc)) { _directives.TryAdd(ContentSecurityPolicyConstants.FetchDirectives.WorkerSrc, directive); } string header = ContentSecurityToString(hostSources); header += SchemeSourceToString(schemeSources); if (_reportUri != null) { header += "; " + CommonPolicyDirective.ReportUri + " " + _reportUri.AbsoluteUri; } if (reportOnly) { _policy.SetHeaders[ContentSecurityPolicyConstants.HeaderReportOnly] = header; } else { _policy.SetHeaders[ContentSecurityPolicyConstants.Header] = header; } return(this); }
private void ProcessElasticSection(IConfiguration conf, int cle, string nomApplication) { string destinationElastic = conf.GetSection(string.Format("Serilog:WriteTo:{0}:Args:nodeUris", cle)).Value; if (!string.IsNullOrEmpty(destinationElastic)) { StringBuilder sb = new StringBuilder(); sb.Append(nomApplication.Length > 8 ? nomApplication.Substring(0, 8) : nomApplication); sb.Append("-{0:yyyy.MM.dd}"); ElasticsearchSinkOptions elasticOption = new ElasticsearchSinkOptions(new Uri(destinationElastic)) { AutoRegisterTemplate = true, CustomFormatter = new ExceptionAsObjectJsonFormatter(renderMessage: true), AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, IndexFormat = sb.ToString(), }; ILogger elasticLogger = new LoggerConfiguration().WriteTo.Elasticsearch(elasticOption).Enrich.FromLogContext().CreateLogger(); if (!monDico.TryAdd(new Tuple <string, string>("Elastic", "Perf"), elasticLogger)) { Debug.Assert(false, "Section Elastic en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Elastic", "Diag"), elasticLogger)) { Debug.Assert(false, "Section Elastic en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Elastic", "Error"), elasticLogger)) { Debug.Assert(false, "Section Elastic en double!!!!"); } if (!monDico.TryAdd(new Tuple <string, string>("Elastic", "Usage"), elasticLogger)) { Debug.Assert(false, "Section Elastic en double!!!!"); } } }
public bool TryFilterSerializableProps( JsonSourceGenerationOptionsAttribute options, [NotNullWhen(true)] out Dictionary <string, PropertyGenerationSpec>?serializableProperties, out bool castingRequiredForProps) { serializableProperties = new Dictionary <string, PropertyGenerationSpec>(); Dictionary <string, PropertyGenerationSpec>?ignoredMembers = null; for (int i = 0; i < PropertyGenSpecList.Count; i++) { PropertyGenerationSpec propGenSpec = PropertyGenSpecList[i]; JsonIgnoreCondition? ignoreCondition = propGenSpec.DefaultIgnoreCondition; if (ignoreCondition == JsonIgnoreCondition.WhenWritingNull && !propGenSpec.TypeGenerationSpec.CanBeNull) { goto ReturnFalse; } // In case of JsonInclude fail if either: // 1. the getter is not accessible by the source generator or // 2. neither getter or setter methods are public. if (propGenSpec.HasJsonInclude && (!propGenSpec.CanUseGetter || !propGenSpec.IsPublic)) { goto ReturnFalse; } // Discard any getters not accessible by the source generator. if (!propGenSpec.CanUseGetter) { continue; } if (!propGenSpec.IsProperty && !propGenSpec.HasJsonInclude && !options.IncludeFields) { continue; } string memberName = propGenSpec.ClrName !; // The JsonPropertyNameAttribute or naming policy resulted in a collision. if (!serializableProperties.TryAdd(propGenSpec.RuntimePropertyName, propGenSpec)) { PropertyGenerationSpec other = serializableProperties[propGenSpec.RuntimePropertyName] !; if (other.DefaultIgnoreCondition == JsonIgnoreCondition.Always) { // Overwrite previously cached property since it has [JsonIgnore]. serializableProperties[propGenSpec.RuntimePropertyName] = propGenSpec; } else if ( // Does the current property have `JsonIgnoreAttribute`? propGenSpec.DefaultIgnoreCondition != JsonIgnoreCondition.Always && // Is the current property hidden by the previously cached property // (with `new` keyword, or by overriding)? other.ClrName != memberName && // Was a property with the same CLR name was ignored? That property hid the current property, // thus, if it was ignored, the current property should be ignored too. ignoredMembers?.ContainsKey(memberName) != true) { // We throw if we have two public properties that have the same JSON property name, and neither have been ignored. serializableProperties = null; castingRequiredForProps = false; return(false); } // Ignore the current property. } if (propGenSpec.DefaultIgnoreCondition == JsonIgnoreCondition.Always) { (ignoredMembers ??= new Dictionary <string, PropertyGenerationSpec>()).Add(memberName, propGenSpec); } } Debug.Assert(PropertyGenSpecList.Count >= serializableProperties.Count); castingRequiredForProps = PropertyGenSpecList.Count > serializableProperties.Count; return(true); ReturnFalse: serializableProperties = null; castingRequiredForProps = false; return(false); }
static ReadOnlySpan <byte> IndexKeyword => new byte[] { 0x69, 0x6E, 0x64, 0x65, 0x78 }; // = index /// <summary> /// Parses FFprobe JSON output and returns a new <see cref="MediaInfo"/> /// </summary> /// <param name="data">JSON output</param> /// <param name="file">The file the JSON output format is about</param> /// <returns><see cref="MediaInfo"/> containing information from FFprobe output</returns> public static MediaInfo Read(ReadOnlySpan <byte> data, string file) { var json = new Utf8JsonReader(data, isFinalBlock: false, state: default); var streams = new List <Dictionary <string, object> >(); var format = new Dictionary <string, object>(); var currentStream = -1; var currentObject = JsonObjects.None; string?lastKey = null; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan <byte> valueSpan = json.ValueSpan; switch (tokenType) { case JsonTokenType.StartObject: case JsonTokenType.EndObject: case JsonTokenType.Null: case JsonTokenType.StartArray: case JsonTokenType.EndArray: break; case JsonTokenType.PropertyName: if (valueSpan.SequenceEqual(StreamsKeyword)) { currentObject = JsonObjects.Streams; break; } if (valueSpan.SequenceEqual(FormatKeyword)) { currentObject = JsonObjects.Format; break; } if (valueSpan.SequenceEqual(IndexKeyword)) { streams.Add(new Dictionary <string, object>()); currentStream++; } if (currentObject == JsonObjects.Streams) { lastKey = json.GetString(); streams[currentStream].TryAdd(lastKey, new object()); } else if (currentObject == JsonObjects.Format) { lastKey = json.GetString(); format.TryAdd(lastKey, new object()); } break; case JsonTokenType.String: if (currentObject == JsonObjects.Streams && lastKey != null) { streams[currentStream][lastKey] = json.GetString(); } else if (currentObject == JsonObjects.Format && lastKey != null) { format[lastKey] = json.GetString(); } break; case JsonTokenType.Number: if (!json.TryGetInt32(out int valueInteger)) { #if DEBUG System.Diagnostics.Trace.TraceWarning($"JSON number parse error: \"{lastKey}\" = {System.Text.Encoding.UTF8.GetString(valueSpan.ToArray())}, file = {file}"); #endif break; } if (currentObject == JsonObjects.Streams && lastKey != null) { streams[currentStream][lastKey] = valueInteger; } else if (currentObject == JsonObjects.Format && lastKey != null) { format[lastKey] = valueInteger; } break; case JsonTokenType.True: case JsonTokenType.False: bool valueBool = json.GetBoolean(); if (currentObject == JsonObjects.Streams && lastKey != null) { streams[currentStream][lastKey] = valueBool; } else if (currentObject == JsonObjects.Format && lastKey != null) { format[lastKey] = valueBool; } break; default: throw new ArgumentException(); } } var info = new MediaInfo { Streams = new MediaInfo.StreamInfo[streams.Count] }; if (format.ContainsKey("duration") && TimeSpan.TryParse((string)format["duration"], out var duration)) { /* * Trim miliseconds here as we would have done it later anyway. * Reasons are: * - More user friendly * - Allows an improved check against equality * Cons are: * - Not 100% accurate if you consider a difference of e.g. 2 miliseconds makes a duplicate no longer a duplicate * - Breaking change at the moment of implementation as it doesn't apply to already scanned files */ info.Duration = duration.TrimMiliseconds(); } var foundBitRate = false; for (int i = 0; i < streams.Count; i++) { info.Streams[i] = new MediaInfo.StreamInfo(); if (streams[i].ContainsKey("bit_rate") && long.TryParse((string)streams[i]["bit_rate"], out var bitrate)) { foundBitRate = true; info.Streams[i].BitRate = bitrate; } if (streams[i].ContainsKey("width")) { info.Streams[i].Width = (int)streams[i]["width"]; } if (streams[i].ContainsKey("height")) { info.Streams[i].Height = (int)streams[i]["height"]; } if (streams[i].ContainsKey("codec_name")) { info.Streams[i].CodecName = (string)streams[i]["codec_name"]; } if (streams[i].ContainsKey("codec_long_name")) { info.Streams[i].CodecLongName = (string)streams[i]["codec_long_name"]; } if (streams[i].ContainsKey("codec_type")) { info.Streams[i].CodecType = (string)streams[i]["codec_type"]; } if (streams[i].ContainsKey("channel_layout")) { info.Streams[i].ChannelLayout = (string)streams[i]["channel_layout"]; } if (streams[i].ContainsKey("pix_fmt")) { info.Streams[i].PixelFormat = (string)streams[i]["pix_fmt"]; } if (streams[i].ContainsKey("sample_rate") && int.TryParse((string)streams[i]["sample_rate"], out var sample_rate)) { info.Streams[i].SampleRate = sample_rate; } if (streams[i].ContainsKey("index")) { info.Streams[i].Index = ((int)streams[i]["index"]).ToString(); } if (streams[i].ContainsKey("r_frame_rate")) { var stringFrameRate = (string)streams[i]["r_frame_rate"]; if (stringFrameRate.Contains('/')) { var split = stringFrameRate.Split('/'); if (split.Length == 2 && int.TryParse(split[0], out var firstRate) && int.TryParse(split[1], out var secondRate)) { info.Streams[i].FrameRate = (firstRate > 0 && secondRate > 0) ? firstRate / (float)secondRate : -1f; } } } } //Workaround if video stream bitrate is not set but in format if (!foundBitRate && info.Streams.Length > 0 && format.ContainsKey("bit_rate") && long.TryParse((string)format["bit_rate"], out var formatBitrate)) { info.Streams[0].BitRate = formatBitrate; } return(info); }
/// <summary> /// Add client to message loop /// </summary> /// <param name="socket">Connected client</param> /// <param name="user">Discord user</param> public static void ClientAdd(WebSocket socket, DW.SocketUser user) { sockets.TryAdd(socket, user); }
public static Dictionary <PluginPair, Query> Build(ref string text, Dictionary <string, PluginPair> nonGlobalPlugins) { if (text == null) { throw new ArgumentNullException(nameof(text)); } if (nonGlobalPlugins == null) { throw new ArgumentNullException(nameof(nonGlobalPlugins)); } // replace multiple white spaces with one white space var terms = text.Split(new[] { Query.TermSeparator }, StringSplitOptions.RemoveEmptyEntries); if (terms.Length == 0) { // nothing was typed return(null); } // This Dictionary contains the corresponding query for each plugin Dictionary <PluginPair, Query> pluginQueryPair = new Dictionary <PluginPair, Query>(); var rawQuery = string.Join(Query.TermSeparator, terms); // This is the query on removing extra spaces which would be executed by global Plugins text = rawQuery; string possibleActionKeyword = terms[0]; foreach (string pluginActionKeyword in nonGlobalPlugins.Keys) { // Using Ordinal since this is used internally if (possibleActionKeyword.StartsWith(pluginActionKeyword, StringComparison.Ordinal)) { if (nonGlobalPlugins.TryGetValue(pluginActionKeyword, out var pluginPair) && !pluginPair.Metadata.Disabled) { // The search string is the raw query excluding the action keyword string search = rawQuery.Substring(pluginActionKeyword.Length).Trim(); // To set the terms of the query after removing the action keyword if (possibleActionKeyword.Length > pluginActionKeyword.Length) { // If the first term contains the action keyword, then set the remaining string to be the first term terms[0] = possibleActionKeyword.Substring(pluginActionKeyword.Length); } else { // If the first term is the action keyword, then skip it. terms = terms.Skip(1).ToArray(); } // A new query is constructed for each plugin as they have different action keywords var query = new Query(rawQuery, search, new ReadOnlyCollection <string>(terms), pluginActionKeyword); pluginQueryPair.TryAdd(pluginPair, query); } } } // If the user has specified a matching action keyword, then do not // add the global plugins to the list. if (pluginQueryPair.Count == 0) { var globalplugins = PluginManager.GlobalPlugins; foreach (PluginPair globalPlugin in PluginManager.GlobalPlugins) { if (!pluginQueryPair.ContainsKey(globalPlugin)) { var query = new Query(rawQuery, rawQuery, new ReadOnlyCollection <string>(terms), string.Empty); pluginQueryPair.Add(globalPlugin, query); } } } return(pluginQueryPair); }
AccountEntry Process(AccountEntry entry) { if (entry.Spendable._Account != null && entry.Spendable._Account != this) { throw new InvalidOperationException("Entry already processed by another account"); } entry.Spendable._Account = this; try { if (entry.Reason == AccountEntryReason.Income || entry.Reason == AccountEntryReason.Outcome) { if (entry.BalanceChange < Money.Zero) { if (!_Unspent.Remove(entry.Spendable.OutPoint)) { return(null); } } if (entry.BalanceChange > Money.Zero) { if (!_Unspent.TryAdd(entry.Spendable.OutPoint, entry.Spendable)) { return(null); } } if (entry.BalanceChange == Money.Zero) { return(null); } } else if (entry.Reason == AccountEntryReason.Lock || entry.Reason == AccountEntryReason.Unlock) { if (entry.Reason == AccountEntryReason.Lock) { _Locked.Add(entry.Spendable.OutPoint); } else { _Locked.Remove(entry.Spendable.OutPoint); } } else if (entry.Reason == AccountEntryReason.ChainBlockChanged) { if (entry.BalanceChange < Money.Zero) { if (!_Unspent.Remove(entry.Spendable.OutPoint)) { return(null); } } if (entry.BalanceChange > Money.Zero) { if (!_Unspent.TryAdd(entry.Spendable.OutPoint, entry.Spendable)) { return(null); } } } _Balance += entry.BalanceChange; return(entry); } finally { #if DEBUG if (_Balance != Unspent.Select(o => o.TxOut.Value).Sum()) { throw new NotSupportedException("Something is going wrong"); } #endif } }
public void SetSettings(UserSettings userSettings) { UserSettings tmpSettings = new UserSettings(); UiLanguage = userSettings.CurentUILanguague; ChatFontSize = userSettings.FontSize; BackgroundColor = userSettings.BackgroundColor; ParagraphSpaceCount = userSettings.InsertSpaceCount; LineBreakeHeight = userSettings.LineBreakHeight; TranslationEngine = (TranslationEngine)userSettings.CurrentTranslationEngine; FFLanguage = userSettings.CurrentFFXIVLanguage; TranslateToLanguage = userSettings.CurrentTranslateToLanguage; IsChatClickThrough = userSettings.IsClickThrough; IsChatAlwaysOnTop = userSettings.IsAlwaysOnTop; IsHideSettingsToTray = userSettings.IsHideToTray; IsAutoHide = userSettings.IsAutoHide; IsDirecMemoryReading = userSettings.IsDirecMemoryReading; AutoHideTimeout = userSettings.AutoHideTimeout; if (userSettings.ShowHideChatKeys != null) { ShowHideChatKeys = new HotKeyCombination(userSettings.ShowHideChatKeys); } else { ShowHideChatKeys = new HotKeyCombination(tmpSettings.ShowHideChatKeys); } if (userSettings.ClickThoughtChatKeys != null) { ClickThoughtChatKeys = new HotKeyCombination(userSettings.ClickThoughtChatKeys); } else { ClickThoughtChatKeys = new HotKeyCombination(tmpSettings.ClickThoughtChatKeys); } if (userSettings.ClearChatKeys != null) { ClearChatKeys = new HotKeyCombination(userSettings.ClearChatKeys); } else { ClearChatKeys = new HotKeyCombination(tmpSettings.ClearChatKeys); } SettingsWindowSize = userSettings.SettingsWindowSize; ChatWindowRectangle = userSettings.ChatWindowLocation; if (userSettings.RecentBackgroundColors != null) { RecentBackgroundColors = userSettings.RecentBackgroundColors.Distinct().ToList(); } else { RecentBackgroundColors = tmpSettings.RecentBackgroundColors.Distinct().ToList(); } var tmpChatList = Helper.LoadJsonData <List <ChatMsgType> >(GlobalSettings.ChatCodesFilePath); var tmpChatCodes = new Dictionary <string, ChatMsgType>(); for (int i = 0; i < tmpChatList.Count; i++) { tmpChatCodes.TryAdd(tmpChatList[i].ChatCode, tmpChatList[i]); } var userCodes = userSettings.ChatCodes.Values.ToList(); for (int i = 0; i < userCodes.Count; i++) { if (tmpChatCodes.ContainsKey(userCodes[i].ChatCode)) { tmpChatCodes[userCodes[i].ChatCode] = userCodes[i]; } } ChatCodes = tmpChatCodes; IsFirstTime = userSettings.IsFirstTime; }
public void ReadSheet(Stream stream, ReadSheetDicOptions option) { Inspector.NotNull(stream, "Excel文件流不能为空"); Inspector.NotNull(option, $"{nameof(ReadSheetDicOptions)} can not be null"); Inspector.Validation(option.ExcelFields == null || option.ExcelFields.Length == 0 || option.ExcelFields.Count(t => string.IsNullOrWhiteSpace(t.field)) > 0, "Excel中的列头信息不能为空或存在为空的列名"); //匹配SheetName var sheetName = ""; { var sheetNames = this.GetSheetNames(stream, false); Inspector.Validation(option.ReadWay == ReadWay.SheetIndex && option.SheetIndex > sheetNames.Count(), $"指定的SheetIndex {option.SheetIndex} 无效,实际只存在{sheetNames.Count()}个Sheet"); Inspector.Validation(option.ReadWay == ReadWay.SheetName && !sheetNames.Contains(option.SheetName), $"指定的SheetName {option.SheetName} 不存在"); sheetName = option.ReadWay switch { ReadWay.SheetIndex => sheetNames.ElementAt(option.SheetIndex - 1), ReadWay.SheetName => option.SheetName }; } //Excel中的表头列信息(index:集合中元素的位置,cellRef:单元格的A1 B1中的A B这种) var fieldLoc = new List <(int index, string excelField, ColumnType columnType, bool allowNull, string cellRef)>(); { for (int index = 0; index < option.ExcelFields.Count(); index++) { Inspector.Validation(fieldLoc.Exists(t => t.excelField == option.ExcelFields[index].field?.Trim()), "指定读取的 ExcelFields 中存在相同的列名"); fieldLoc.Add((index, option.ExcelFields[index].field, option.ExcelFields[index].type, option.ExcelFields[index].allowNull, "")); } } using (var sheetDoc = SpreadsheetDocument.Open(stream, false)) { WorkbookPart workbookPart = sheetDoc.WorkbookPart; //1.目标Sheet的Rid是否存在 string rId = workbookPart.Workbook.Sheets?.Cast <Sheet>()?.FirstOrDefault(t => t.Name.Value == sheetName)?.Id?.Value; Inspector.NotNullOrWhiteSpace(rId, $"不存在名为 {sheetName} 的Sheet"); SharedStringTablePart shareStringPart; if (workbookPart.GetPartsOfType <SharedStringTablePart>().Count() > 0) { shareStringPart = workbookPart.GetPartsOfType <SharedStringTablePart>().First(); } else { shareStringPart = workbookPart.AddNewPart <SharedStringTablePart>(); } string[] shareStringItemValues = shareStringPart.GetItemValues().ToArray(); //2.反转Sheet顺序 foreach (var workSheetPart in workbookPart.WorksheetParts?.Reverse()) { //是否是指定Sheet的Rid,不是则忽略 string partRelationshipId = workbookPart.GetIdOfPart(workSheetPart); if (partRelationshipId != rId) { continue; } //读取失败的原始数据信息 (Dictionary <string, object> odata, List <(string rowIndex, string columnName, string cellValue, string errorMsg)> failInfos)failRowData = (new Dictionary <string, object>(), new List <(string rowIndex, string columnName, string cellValue, string errorMsg)>()); //创建Reader OpenXmlReader reader = OpenXmlReader.Create(workSheetPart); //工具类实例 var reflection = ReflectionHelper.NewInstance; while (reader.Read()) { if (reader.ElementType == typeof(Worksheet)) { reader.ReadFirstChild(); } if (reader.ElementType == typeof(Row)) { var row = (Row)reader.LoadCurrentElement(); //3.读取表头列,匹配字段信息 if (row.RowIndex == option.HeadRow) { foreach (Cell cell in row.Elements <Cell>()) { if (cell.CellReference != null && cell.CellReference.HasValue) { //excel中的表头列字段 string excelField = cell.GetValue(shareStringItemValues); if (fieldLoc.Exists(t => t.excelField == excelField)) { var fieldInfo = fieldLoc.FirstOrDefault(t => t.excelField == excelField); fieldInfo.cellRef = StringHelper.RemoveNumber(cell.CellReference); fieldLoc[fieldInfo.index] = fieldInfo; } } } //实体上定义了ExcelKit特性的字段未在Excel中匹配到 var unMatchedField = fieldLoc.Where(t => string.IsNullOrWhiteSpace(t.cellRef)); if (unMatchedField.Count() > 0) { var unmatchFields = string.Join("、", unMatchedField.Select(t => t.excelField)); var msg = $"指定的ExcelFields中的字段【{unmatchFields}】不存在于Excel中"; throw new ExcelKitException(msg); } continue; } if (row.RowIndex < option.DataStartRow) { continue; } if (option.DataEndRow.HasValue && row.RowIndex > option.DataEndRow) { break; } //读取到的每行数据 var rowData = new Dictionary <string, object>(); //excel原始数据 failRowData.odata.Clear(); //失败信息 failRowData.failInfos.Clear(); //是否读取成功 var readSuc = true; //4. row.Elements<Cell>()获取出来的会自动跳过为空的单元格 foreach (Cell cell in row.Elements <Cell>()) { //4.1 跳过cell引用为空的 if (cell.CellReference == null || !cell.CellReference.HasValue) { continue; } //4.2 当前循环的cell列位置(不含数字) var loopCellRef = StringHelper.RemoveNumber(cell.CellReference); //不存在或匹配列信息不一致的跳过 var fieldInfo = fieldLoc.FirstOrDefault(t => t.cellRef.Equals(loopCellRef, StringComparison.OrdinalIgnoreCase)); if (fieldInfo == (0, null, 0, false, null) || !loopCellRef.Equals(fieldInfo.cellRef, StringComparison.OrdinalIgnoreCase)) { continue; } //Excel中读取到的值 string readVal = null; try { readVal = cell.GetValue(shareStringItemValues); Inspector.Validation(!fieldInfo.allowNull && string.IsNullOrWhiteSpace(readVal), $"Excel中列 {fieldInfo.excelField} 为必填项"); object value = ColumnTypeMapping.Convert(readVal, fieldInfo.columnType, fieldInfo.allowNull); rowData.Add(fieldInfo.excelField, value); } catch (Exception ex) { readSuc = false; failRowData.failInfos.Add((row.RowIndex, fieldInfo.excelField, readVal?.ToString(), ex.Message)); } } //5.单元格为空缺失的key补齐(这样做key的顺序和原始的不一致了,有需求时可以使用header上面的cellRef排序解决,为了读取速度此处暂不做) var lackKeys = fieldLoc.Select(t => t.excelField).Except(rowData.Keys); foreach (var lackKey in lackKeys) { rowData.TryAdd(lackKey, null); } //读取成功执行 if (readSuc) { option.SucData?.Invoke(rowData, row.RowIndex.Value); } else { option.FailData?.Invoke(failRowData.odata, failRowData.failInfos); } } } } sheetDoc.Close(); } }
public static void Init(ResourceManager resources, McResourcePack resourcePack, IProgressReceiver progressReceiver = null) { ResourceManager = resources; ResourcePack = resourcePack; var otherRaw = ResourceManager.ReadStringResource("Alex.Resources.items3.json"); SecItemEntries = JsonConvert.DeserializeObject <SecondItemEntry[]>(otherRaw); var raw = ResourceManager.ReadStringResource("Alex.Resources.items2.json"); ItemEntry[] itemData = JsonConvert.DeserializeObject <ItemEntry[]>(raw); var ii = resources.Registries.Items.Entries; LoadModels(); Dictionary <string, Item> items = new Dictionary <string, Item>(); for (int i = 0; i < ii.Count; i++) { var entry = ii.ElementAt(i); progressReceiver?.UpdateProgress(i * (100 / ii.Count), $"Processing items...", entry.Key); var blockState = BlockFactory.GetBlockState(entry.Key); Item item; if (blockState != null) { item = new ItemBlock(blockState); } else { item = new Item(); } var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", "")); if (minetItem != null) { if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t)) { item.ItemType = t; } item.Material = minetItem.ItemMaterial; item.Meta = minetItem.Metadata; item.Id = minetItem.Id; } item.Name = entry.Key; item.DisplayName = entry.Key; var data = itemData.FirstOrDefault(x => x.name.Equals(entry.Key.Substring(10), StringComparison.InvariantCultureIgnoreCase)); if (data != null) { item.MaxStackSize = data.stackSize; item.DisplayName = data.displayName; } foreach (var it in ResourcePack.ItemModels) { if (it.Key.Contains(entry.Key.Replace("minecraft:", ""), StringComparison.InvariantCultureIgnoreCase)) { //Log.Info($"Model found: {entry.Key} = {it.Key}"); ItemModelRenderer renderer; if (ItemRenderers.TryGetValue(it.Key, out renderer)) { } else if (ItemRenderers.TryGetValue(entry.Key, out renderer)) { } if (renderer != null) { Log.Info($"Found renderer for {entry.Key}, textures: {it.Value.Textures.Count}"); item.Renderer = renderer; break; } } } /* if (ResourcePack.ItemModels.TryGetValue(entry.Key.Replace("minecraft:", "minecraft:item/"), out ResourcePackItem iii)) * { * ItemModelRenderer renderer; * if (ItemRenderers.TryGetValue(entry.Key, out renderer)) * { * * } * else if (ItemRenderers.TryGetValue(entry.Key, out renderer)) * * { * * } * * if (renderer != null) * { * Log.Info($"Found renderer for {entry.Key}, textures: {iii.Textures.Count}"); * } * * item.Renderer = renderer; * }*/ // Log.Info($"Loaded item: {entry.Key} (Renderer: {item.Renderer != null})"); items.TryAdd(entry.Key, item); } Items = new ReadOnlyDictionary <string, Item>(items); }
public Catalog MakeCatalog() { // Convert collections of items from Data Dragon globals DTOs Dictionary <string, LorVocabTerm> vocabTerms = ConvertDdItems <DdVocabTerm, LorVocabTerm>(Globals.VocabTerms, "vocabTerms", LorVocabTerm.TryFromDataDragon); Dictionary <string, LorKeyword> keywords = ConvertDdItems <DdKeyword, LorKeyword>(Globals.Keywords, "keywords", LorKeyword.TryFromDataDragon); Dictionary <string, LorFaction> regions = ConvertIndexedDdItems <DdRegion, LorFaction>(Globals.Regions, "regions", LorFaction.TryFromDataDragon, RegionIndices); Dictionary <string, LorSpellSpeed> spellSpeeds = ConvertDdItems <DdSpellSpeed, LorSpellSpeed>(Globals.SpellSpeeds, "spellSpeeds", LorSpellSpeed.TryFromDataDragon); Dictionary <string, LorRarity> rarities = ConvertDdItems <DdRarity, LorRarity>(Globals.Rarities, "rarities", LorRarity.TryFromDataDragon); Dictionary <string, LorSet> sets = ConvertIndexedDdItems <DdSet, LorSet>(Globals.Sets, "sets", LorSet.TryFromDataDragon, SetIndices); // Populate collections of [super/sub]types manually from list of cards var supertypes = new List <LorSupertype>(); var supertypeDic = new Dictionary <string, LorSupertype>(); foreach (string supertypeRef in DdCards .Select(c => c.Supertype) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => s !) .Distinct()) { string name = TextInfo.ToTitleCase(TextInfo.ToLower(supertypeRef)); var supertype = new LorSupertype(name); supertypes.Add(supertype); supertypeDic.Add(supertypeRef, new LorSupertype(name)); } var types = new List <LorType>(); var typeDic = new Dictionary <string, LorType>(); foreach (string typeRef in DdCards .Select(c => c.Type) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => s !) .Distinct()) { string name = TextInfo.ToTitleCase(TextInfo.ToLower(typeRef)); var type = new LorType(name); types.Add(type); typeDic.Add(typeRef, type); } var subtypes = new List <LorSubtype>(); var subtypeDic = new Dictionary <string, LorSubtype>(); foreach (string subtypeRef in DdCards .SelectMany(c => c.GetDistinctSubtypes()) .Distinct()) { string name = TextInfo.ToTitleCase(TextInfo.ToLower(subtypeRef)); var subtype = new LorSubtype(name); subtypes.Add(subtype); subtypeDic.Add(subtypeRef, subtype); } // First card pass to initialize cards and add them to lookup var cards = new Dictionary <string, ICard>(); foreach (DdCard ddCard in DdCards) { if (ddCard.CardCode is null) { string name = ddCard.Name ?? "[Unnamed card]"; Logger.LogWarning($"{name} does not have a card code. Ignoring card."); continue; } if (!CardCode.TryFromString(ddCard.CardCode, out CardCode? cardCode)) { Logger.LogWarning($"Could not parse the card code '{cardCode}'. Ignoring card."); continue; } var card = new BasicCard(cardCode !, Locale, Version, ddCard.Name); if (!cards.TryAdd(ddCard.CardCode, card)) { Logger.LogWarning($"Multiple cards have the card code '{cardCode}'. Ignoring this duplicate card."); continue; } AddPropToCard(card, ddCard.RegionRef, "RegionRef", regions, (c, v) => c.Region = v); AddPropToCard(card, ddCard.Supertype, "Supertype", supertypeDic, (c, v) => c.Supertype = v); AddPropToCard(card, ddCard.Type, "Type", typeDic, (c, v) => c.Type = v); AddPropToCard(card, ddCard.SpellSpeedRef, "SpellSpeedRef", spellSpeeds, (c, v) => c.SpellSpeed = v); AddPropToCard(card, ddCard.Set, "Set", sets, (c, v) => c.Set = v); AddPropToCard(card, ddCard.RarityRef, "RarityRef", rarities, (c, v) => c.Rarity = v); AddPropListToCard(card, ddCard.RegionRefs, "RegionRef", regions, (c, vs) => c.Regions = vs); AddPropListToCard(card, ddCard.Subtypes, "Subtype", subtypeDic, (c, vs) => c.Subtypes = vs); AddPropListToCard(card, ddCard.KeywordRefs, "KeywordRef", keywords, (c, vs) => c.Keywords = vs); card.Cost = ddCard.Cost; card.Attack = ddCard.Attack; card.Health = ddCard.Health; card.Collectible = ddCard.Collectible; card.Description = ddCard.Description; card.DescriptionRaw = ddCard.DescriptionRaw; card.LevelupDescription = ddCard.LevelupDescription; card.LevelupDescriptionRaw = ddCard.LevelupDescriptionRaw; card.FlavorText = ddCard.FlavorText; card.ArtistName = ddCard.ArtistName; if (ddCard.Assets != null && ddCard.Assets.Length > 0) { string?gamePath = ddCard.Assets[0].GameAbsolutePath; if (gamePath != null) { card.GameArtPath = new Uri(gamePath); } string?fullPath = ddCard.Assets[0].FullAbsolutePath; if (fullPath != null) { card.FullArtPath = new Uri(fullPath); } } } // Second card pass to fill in associated card references foreach (DdCard ddCard in DdCards) { if (ddCard.AssociatedCardRefs is null) { continue; } if (ddCard.CardCode is null) { continue; } string code = ddCard.CardCode !; if (!cards.TryGetValue(code, out ICard? card)) { continue; } var assoCards = new List <ICard>(); foreach (string assoCode in ddCard.AssociatedCardRefs) { if (cards.TryGetValue(assoCode, out ICard? assoCard)) { assoCards.Add(assoCard); } else { Logger.LogWarning($"{card} has an associated card with the code '{assoCode}' that isn't in the card collection. Ignoring this associated card."); } } // Small hack to cast the card to its known BasicCard type since C# can't make the cards dictionary covariant (card as BasicCard) !.AssociatedCards = assoCards; } // Return the finished product return(new Catalog(Locale, Version) { VocabTerms = vocabTerms, Keywords = keywords, Regions = regions, SpellSpeeds = spellSpeeds, Rarities = rarities, Sets = sets, Supertypes = supertypes, Types = types, Subtypes = subtypes, Cards = cards, }); }
public bool AddUser(User user) { return(users.TryAdd(user.Uuid, user)); }
public static void AddFlightPlan(FlightPlan flightPlan) { flightPlanDB.TryAdd(flightPlan.GetId(), flightPlan); }
public async Task <DataSet> ReadDocument(string fileName, bool isFirstRowHeader = false) { var fileExtension = Path.GetExtension(fileName); if (!fileExtension.IsSupportedExcelFile()) { throw new FileFormatException("The file format is not supported!"); } var dataSet = new DataSet(); if (fileExtension == SupportFormats.csv) { var table = new DataTable(); using (var stremReader = new StreamReader(fileName)) { var headers = stremReader.ReadLine().Split(','); foreach (string header in headers) { table.Columns.Add(header); } while (!stremReader.EndOfStream) { var rows = stremReader.ReadLine().Split(','); var dataRow = table.NewRow(); for (int i = 0; i < headers.Length; i++) { dataRow[i] = rows[i]; } table.Rows.Add(dataRow); } } dataSet.Tables.Add(table); return(dataSet); } else { try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false)) { var workbookPart = doc.WorkbookPart; #region Sheets processing foreach (var sheet in workbookPart.Workbook.Descendants <Sheet>()) { var table = new DataTable(sheet.Name); var dataList = new List <TableRowItem>(); var sheetColumns = new Dictionary <string, string>(); var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id)); var sheetData = worksheetPart.Worksheet.Elements <SheetData>().First(); dataSet.Tables.Add(table); if (sheetData.Elements <Row>().Any(x => x.RowIndex == null)) { throw new NotSupportedException("The version of this file is not supported!"); } #region Define header if (isFirstRowHeader) { foreach (var row in sheetData?.Elements <Row>()?.Where(x => x.RowIndex == 1)) { if (row.Elements <Cell>().Any()) { foreach (var cell in row.Elements <Cell>()) { var columnAddress = await GetColumnName(cell.CellReference.Value); var columnName = await GetCellValue(cell, workbookPart); sheetColumns.TryGetValue(columnName, out string colName); if (string.IsNullOrEmpty(colName)) { sheetColumns.TryAdd(columnAddress, columnName); } } } else { throw new MissingFieldException("The column name in the first row was not found!"); } } } else { foreach (var row in sheetData?.Elements <Row>()) { foreach (var cell in row.Elements <Cell>()) { var columnAddress = await GetColumnName(cell.CellReference.Value); sheetColumns.TryGetValue(columnAddress, out string colName); if (string.IsNullOrEmpty(colName)) { sheetColumns.TryAdd(columnAddress, columnAddress); } } } } #endregion #region Sort columns var columnsList = sheetColumns.Values.ToList(); if (!isFirstRowHeader) { columnsList.Sort(); } foreach (var col in columnsList) { table.Columns.Add(col); } #endregion #region Filling up dataSet foreach (var row in sheetData.Elements <Row>()) { var dtsTableRow = table.NewRow(); foreach (var cell in row.Elements <Cell>()) { var columnAddress = await GetColumnName(cell.CellReference.Value); var columnIndex = await GetColumnIndex(cell.CellReference.Value); sheetColumns.TryGetValue(columnAddress, out string columnName); int.TryParse(columnIndex, out int index); var cellValue = await GetCellValue(cell, workbookPart); var firstField = isFirstRowHeader ? 1 : 0; if (index > firstField) { dataList.Add(new TableRowItem { Index = index, Name = columnName, Value = cellValue }); } } } for (var i = isFirstRowHeader ? 2 : 1; i <= dataList.Max(x => x.Index); i++) { var dataRow = table.NewRow(); var tempList = dataList.Where(x => x.Index == i).ToList(); foreach (var item in tempList) { dataRow[item.Name] = item.Value; } table.Rows.Add(dataRow); } #endregion } #endregion } } } catch (Exception e) { throw e; } } return(dataSet); }
public void op_TryAdd_IDictionaryOfT_TKey_TValue_whenTrue() { var list = new Dictionary<string, string>(); Assert.True(list.TryAdd("example", string.Empty)); }
public bool Update(ConsentRequest req) { return(_requests.TryAdd(req.Id, req)); }
public async Task <User> AddFirebaseUser(UserCreateDto user) { User newUser = null; if (await this.FirebaseUserExistsByEmail(user.Email)) { Notify($"O usuário {user.Email} já existe"); return(newUser); } // if (!user.Roles.Any()) // { // Notify("Não é possível criar um usuário sem as definições de níveis de acesso"); // return newUser; // } UserRecordArgs args = new UserRecordArgs() { Email = user.Email, EmailVerified = user.EmailVerified, PhoneNumber = user.PhoneNumber, Password = user.Password, DisplayName = user.DisplayName, PhotoUrl = user.PhotoUrl, Disabled = false, }; var fbUser = await FirebaseAuth.DefaultInstance.CreateUserAsync(args); if (fbUser != null) { (string name, string lastName)fullName = this.ExtraxctName(fbUser.DisplayName); newUser = new User() { FirebaseUserId = fbUser.Uid, Email = fbUser.Email, CreationDate = DateTime.Now, FirstName = fullName.name, LastName = fullName.lastName, ProfileUrl = fbUser.PhotoUrl, CityHallId = user.CityHallId }; await Add(newUser); var claims = new Dictionary <string, object>() { { "app_user_id", newUser.Id }, { "user", true }, }; await _userRoleService.UpdateUserRole("user", newUser.Id, true); if (user.Roles?.Count > 0) { claims.TryAdd(user.Roles[0], true); await _userRoleService.UpdateUserRole(user.Roles[0], newUser.Id, true); } await _userRoleService.UpdateUserClaims(newUser.Id, claims); } return(newUser); }
public static void AddServer(Servers server) { serverDB.TryAdd(server.ServerId, server); }
/// <summary> /// 转为Html属性集合 /// </summary> public IDictionary<string, object> ToHtmlAttributes() { var result = new Dictionary<string, object>(); result["plugin"] = "ajaxForm"; var data = new Dictionary<string, object>(); data.TryAdd("target", this.Target); data.TryAdd("replaceTarget", this.ReplaceTarget); if (this.Method.HasValue) data.TryAdd("type", this.Method.Value == FormMethod.Post ? "POST" : "GET"); if (this.DataType.HasValue) { string dataType = "html"; switch (this.DataType) { case AjaxDataType.Html: break; case AjaxDataType.Xml: dataType = "xml"; break; case AjaxDataType.Json: dataType = "json"; break; case AjaxDataType.Script: dataType = "script"; break; default: break; } data.TryAdd("dataType", dataType); } data.TryAdd("beforeSubmitFn", this.BeforeSubmitCallBack); data.TryAdd("successFn", this.OnSuccessCallBack); data.TryAdd("errorFn", this.OnErrorCallBack); data.TryAdd("resetForm", this.ResetForm); data.TryAdd("clearForm", this.ClearForm); data.TryAdd("closeDialog", this.CloseDialog); data.TryAdd("data", this.ExtraData); data.TryAdd("url", this.Url); result.Add("data", Json.Encode(data)); return result; }
public async Task <EarnRuleModel> GetEarnRuleByIdAsync([FromQuery] string id) { var campaign = await _campaignsClient.Campaigns.GetByIdAsync(id); ThrowIfError(campaign.ErrorCode, campaign.ErrorMessage); var asset = _settingsService.GetTokenName(); // order conditions to have optional after first condition if (campaign.Conditions.Count > 0) { var orderedConditions = new List <MAVN.Service.Campaign.Client.Models.Condition.ConditionModel>(); var specialCondition = campaign.Conditions.FirstOrDefault(x => x.Type.Equals(ReferToRealEstateBonusType)); if (specialCondition != null) { orderedConditions.Add(specialCondition); } orderedConditions.AddRange(campaign.Conditions.Where(x => !x.Type.Equals(ReferToRealEstateBonusType))); } var result = _mapper.Map <EarnRuleModel>(campaign); result.Asset = asset; // dictionary by Localization var mobileContentsDictionary = new Dictionary <Localization, MobileContentResponse>(); foreach (var content in campaign.Contents) { if (mobileContentsDictionary.TryGetValue(content.Localization, out var existingMobileContent)) { FillMobileContent(existingMobileContent); } else { Enum.TryParse <MobileLocalization>(content.Localization.ToString(), out var mobileLanguage); var newMobileContent = new MobileContentResponse { MobileLanguage = mobileLanguage }; FillMobileContent(newMobileContent); mobileContentsDictionary.TryAdd(content.Localization, newMobileContent); } void FillMobileContent(MobileContentResponse mobileContent) { switch (content.RuleContentType) { case RuleContentType.Title: mobileContent.Title = content.Value; mobileContent.TitleId = content.Id; break; case RuleContentType.Description: mobileContent.Description = content.Value; mobileContent.DescriptionId = content.Id; break; case RuleContentType.UrlForPicture: mobileContent.ImageId = content.Id; mobileContent.ImageBlobUrl = content.Value; mobileContent.Image = new ImageResponse { Id = content.Image?.Id, RuleContentId = content.Id.ToString(), ImageBlobUrl = content.Image?.BlobUrl }; break; } } } result.MobileContents = mobileContentsDictionary.ToList().OrderBy(x => x.Key).Select(x => x.Value).ToList(); return(result); }
private void HandleExtensionSwitches(List <ExeXml.AddOn> addOns) { // first overwrite the default switch settings in the country file, if the user changed them (via config-settings sent by the run-tool) TakeExtensionSwitches(infoStore.runConfig.extensionSwitches); // then overwrite with any instructions from extensions, the means the priority of switches to be on or off is as follows: // highest: add-ons (via AddOn_ExtensionSwitch), next: user settings (via run-tool), lowest: default settings (via set-switches-dialog) TakeAddOnExtensionSwitches(addOns); // take care of a "feature" that is mainly there for compatibility with the version before March 2020, where the switches of functions within extension-policies were visible instead of set to switch // namly that such functions can be permanantly off instead of switchable List <ExeXml.Fun> permanentOffFunctions = TakeCareOfPermanentOffFunctions(); // lists for taking into account that pol/fun/par can be switched by more than one extension and that 'on' always wins List <string> onIds = new List <string>(); Dictionary <string, ExeXml.Fun> parsToRemove = new Dictionary <string, ExeXml.Fun>(); foreach (var extension in infoStore.country.extensions.Values) { foreach (var extPol in extension.polIds) { string polId = extPol.Key; bool isBasePol = extPol.Value == true; // true: a base-policy, that is switched off if the extension is on if (!infoStore.country.cao.pols.ContainsKey(polId)) { continue; } ExeXml.Pol pol = infoStore.country.cao.pols[polId]; bool?switchOn = null; if (extension.on == true) { switchOn = isBasePol ? false : true; // extension-switch is on: added-as-on ✔: on; added-as-off ✘: off } else if (!isBasePol) { switchOn = false; // extension-switch is off or n/a: added-as-on ✔: off; added-as-off ✘: do not touch } if (switchOn == true) { pol.on = true; } if (switchOn == false && !onIds.Contains(polId)) { pol.on = false; } // add the policy and all its functions and parameters, which do not have an own setting, to the switched-on (i.e. winning) elements if (switchOn == true) { onIds.AddUnique(polId); foreach (var f in pol.funs) { if (!extension.funIds.ContainsKey(f.Key)) { string funId = f.Key; ExeXml.Fun fun = f.Value; fun.on = true; onIds.AddUnique(funId); foreach (var parId in fun.pars.Keys) { if (!extension.parIds.ContainsKey(parId)) { if (parsToRemove.ContainsKey(parId)) { parsToRemove.Remove(parId); } onIds.AddUnique(parId); } } } } } } foreach (var extFun in extension.funIds) { string funId = extFun.Key; bool isBaseFun = extFun.Value == true; // true: a base-function, that is switched off if the extension is on ExeXml.Fun fun = null; foreach (var pol in infoStore.country.cao.pols) { var funs = from f in pol.Value.funs where f.Key == funId select f; if (!funs.Any()) { continue; } fun = funs.First().Value; if (fun.pars.Count == 0) { fun = null; // this takes care of functions which are set to n/a including all their parameters for this system, i.e. ignores them } break; } if (fun == null) { continue; } // see explanation above, however note: if parent-policy is switched off, all included functions are off as well // if parent-policy is switched on, included functions can still be switched off bool?switchOn = null; if (extension.on == true) { switchOn = isBaseFun ? false : true; // extension-switch is on: added-as-on ✔: on; added-as-off ✘: off } else if (!isBaseFun) { switchOn = false; // extension-switch is off or n/a: added-as-on ✔: off; added-as-off ✘: do not touch } if (switchOn == true) { fun.on = true; } if (switchOn == false && !onIds.Contains(funId)) { fun.on = false; } // add the function and all its parameters, which do not have an own setting, to the switched-on (i.e. winning) elements if (switchOn == true) { onIds.AddUnique(funId); foreach (var parId in fun.pars.Keys) { if (!extension.parIds.ContainsKey(parId)) { if (parsToRemove.ContainsKey(parId)) { parsToRemove.Remove(parId); } onIds.AddUnique(parId); } } } } foreach (var extPar in extension.parIds) { string parId = extPar.Key; bool isBasePar = extPar.Value == true; // other than for pol/fun we do not need the par, but its id and the parent-fun, because we need to delete the parameter in case ExeXml.Fun parentFun = null; foreach (var pol in infoStore.country.cao.pols) { foreach (var fun in pol.Value.funs) { if ((from p in fun.Value.pars where p.Key == parId select p).Any()) { parentFun = fun.Value; break; } } if (parentFun != null) { break; } } if (parentFun == null) { continue; } bool?keepPar = null; if (extension.on == true) { keepPar = isBasePar ? false : true; // extension-switch is on: added-as-on ✔: keep par, added-as-off ✘: remove par } else if (!isBasePar) { keepPar = false; // extension-switch is off or n/a: added-as-on ✔: remove par, added-as-off ✘: do not touch } if (keepPar == true && parsToRemove.ContainsKey(parId)) { parsToRemove.Remove(parId); } if (keepPar == false && !onIds.Contains(parId)) { parsToRemove.TryAdd(parId, parentFun); } if (keepPar == true) { onIds.AddUnique(parId); } } } foreach (var ptr in parsToRemove) { ptr.Value.pars.Remove(ptr.Key); // remove the respective parameters only after taking all extensions into account } foreach (ExeXml.Fun pof in permanentOffFunctions) { pof.on = false; } }
/// <summary> /// Tree属性集合 /// </summary> /// <returns></returns> public Dictionary<string, object> ToUnobtrusiveHtmlAttributes() { var result = new Dictionary<string, object>(); //先获取额外的Tree设置 if (AdditionalSetOptions != null) result = new Dictionary<string, object>(AdditionalSetOptions); //数据设置 Dictionary<string, object> data = new Dictionary<string, object>(); Dictionary<string, object> simpleData = new Dictionary<string, object>(); //设置默认支持事件 Dictionary<string, object> callBack = new Dictionary<string, object>(); #region 设置编辑属性 //判断是否开启可编辑状态 bool isRename = false, isRemove = false, enable = false, isCopy = false, isMove = false; Dictionary<string, object> edit = new Dictionary<string, object>(); Dictionary<string, object> drag = new Dictionary<string, object>(); //首先判断是否开启 拖拽功能 if (this.IsDrag) { //编辑设置开启 然后设置关闭 删除 改名 (默认)功能 enable = true; isCopy = true; isMove = true; } //添加drag设置 drag.TryAdd("isCopy", isCopy); drag.TryAdd("isMove", isMove); //判断是否开启可改名 if (this.IsRename) { //先判断是否已经设定 if (!enable) enable = true; isRename = true; } //判断是否开启删除 if (this.IsRemove) { if (!enable) enable = true; isRemove = true; } //判断是否被开启编辑功能 if (enable) { edit.TryAdd("enable", enable); //判断是否开启拖拽 edit.TryAdd("drag", drag); edit.TryAdd("showRemoveBtn", isRemove); edit.TryAdd("showRenameBtn", isRename); result.TryAdd("edit", edit); } #endregion 设置编辑属性 #region 设置数据属性 //设置启用简单数据 simpleData.TryAdd("enable", true); //修正根节点表示值根节点表示 simpleData.TryAdd("rootPId", RootId); //设置简单数据 data.TryAdd("simpleData", simpleData); //合并数据 result.TryAdd("data", data); #endregion 设置数据属性 #region 设置勾选框 //判断是否开启勾选框 if (this.SelectBoxType != null) { Dictionary<string, object> check = new Dictionary<string, object>(); //设置勾选框开启 check.TryAdd("enable", true); if (this.SelectBoxType == SelectBoxTypes.Checkbox) { //设置勾选框类型 check.TryAdd("chkStyle", this.SelectBoxType.ToString().ToLower()); } else { //设置勾选类型 check.TryAdd("chkStyle", this.SelectBoxType.ToString().ToLower()); if (this.RadioBoxType != null) { //设置单选按钮范围 check.TryAdd("radioType", this.RadioBoxType.ToString().ToLower()); } else { //设置单选默认按钮范围 Level check.TryAdd("radioType", RadioBoxTypes.Level.ToString().ToLower()); } } //合并勾选框 result.TryAdd("check", check); } #endregion 设置勾选框 #region 设置回调函数 //默认的回调事件添加 //展开前的回调函数 //判断是否开启单一路径功能 if (this.AdditionalCallBacks != null) { callBack = this.AdditionalCallBacks; if (callBack.ContainsKey("onExpand")) { callBack["addOnExpand"] = callBack["onExpand"]; } if (callBack.ContainsKey("beforeExpand")) { callBack["addBeforeExpand"] = callBack["beforeExpand"]; } } if (IsSinglePath) { callBack["beforeExpand"] = "|" + "beforeExpand" + "|"; //被展开时的回调函数 callBack["onExpand"] = "|" + "onExpand" + "|"; } //合并默认回调函数 if (callBack != null) result.TryAdd("callback", callBack); #endregion 设置回调函数 #region 设置异步加载 //判断是否启用异步加载 if (!string.IsNullOrEmpty(this.AsyncUrl)) { //异步加载设置 Dictionary<string, object> async = new Dictionary<string, object>(); //设置异步开启 async.TryAdd("enable", true); //设置异步提交参数数据类型 async.TryAdd("contentType", "application/json"); //设置自动提交父节点属性的参数 参数为parentId string[] autoParam = new string[] { "id=parentId" }; async.TryAdd("autoParam", autoParam); //设置获取数据的Url地址 async.TryAdd("url", this.AsyncUrl); //合并异步加载 result.TryAdd("async", async); } #endregion 设置异步加载 //整合设置 return result; }
public async Task <ITestResultReport> CreateReportAsync() { Logger.LogInformation($"Start to generate report by {nameof(TwinCountingReportGenerator)} for Sources [{this.expectedSource}] and [{this.actualSource}]"); ulong totalExpectCount = 0; ulong totalMatchCount = 0; ulong totalPatches = 0; ulong totalDuplicates = 0; Queue <string> unmatchedResults = new Queue <string>(); Dictionary <string, DateTime> propertiesUpdated = new Dictionary <string, DateTime>(); Dictionary <string, DateTime> propertiesReceived = new Dictionary <string, DateTime>(); while (await this.expectedTestResults.MoveNextAsync()) { Option <TwinTestResult> twinTestResult = this.GetTwinTestResult(this.expectedTestResults.Current); Logger.LogDebug($"Expected test results {twinTestResult}"); twinTestResult.ForEach( r => { foreach (var prop in r.Properties) { propertiesUpdated.TryAdd(prop.ToString(), this.expectedTestResults.Current.CreatedAt); } }); } while (await this.actualTestResults.MoveNextAsync()) { totalPatches++; Option <TwinTestResult> twinTestResult = this.GetTwinTestResult(this.actualTestResults.Current); Logger.LogDebug($"Actual test results {twinTestResult}"); twinTestResult.ForEach( r => { foreach (var prop in r.Properties) { bool added = propertiesReceived.TryAdd(prop.ToString(), this.actualTestResults.Current.CreatedAt); if (!added) { Logger.LogDebug($"Duplicate for {this.actualSource} {prop.ToString()}"); totalDuplicates++; } } }); } foreach (KeyValuePair <string, DateTime> desiredPropertyUpdate in propertiesUpdated) { totalExpectCount++; if (propertiesReceived.ContainsKey(desiredPropertyUpdate.Key)) { totalMatchCount++; } else { TestReportUtil.EnqueueAndEnforceMaxSize(unmatchedResults, $"{this.expectedSource} {desiredPropertyUpdate.Key}", this.unmatchedResultsMaxSize); } } foreach (KeyValuePair <string, DateTime> desiredPropertyReceived in propertiesReceived) { if (!propertiesUpdated.ContainsKey(desiredPropertyReceived.Key)) { Logger.LogError($"[{nameof(TwinCountingReportGenerator)}] Actual test result source has unexpected results."); TestReportUtil.EnqueueAndEnforceMaxSize(unmatchedResults, $"{this.actualSource} {desiredPropertyReceived.Key}", this.unmatchedResultsMaxSize); } } return(new TwinCountingReport( this.testDescription, this.topology, this.trackingId, this.expectedSource, this.actualSource, this.resultType, totalExpectCount, totalMatchCount, totalPatches, totalDuplicates, new List <string>(unmatchedResults).AsReadOnly())); }
private void Map(Type type, Stack <TagMapParent> parents, int messageTypeKey) { if (_mappedTypes.Contains(type) || type == typeof(object)) { return; } _mappedTypes.Add(type); var messageType = type.GetCustomAttribute <MessageTypeAttribute>(); if (messageType != null) { int key = GetTypeKey(Encoding.ASCII.GetBytes(messageType.Value)); _mapMessageType.TryAdd(key, type); } foreach (PropertyInfo property in type.GetProperties()) { FixTagAttribute?fixTagAttribute = property.GetCustomAttribute <FixTagAttribute>(); var repeatingGroup = property.GetCustomAttribute <RepeatingGroupAttribute>(); var isEnumerable = property.PropertyType.GetInterfaces() .Any(x => x == typeof(System.Collections.IEnumerable)) && property.PropertyType != typeof(string); Type?innerType = null; if (repeatingGroup != null) { AddRepeatingGroupLeaf(parents, property, repeatingGroup, GetInnerTypeOfEnumerable(property), repeatingGroup.Tag * messageTypeKey); } //If there is no fix tag attribute, we expand custom types and enumerated types with repeating group attribute if (fixTagAttribute is null) { if (!isEnumerable) { innerType = property.PropertyType; //Avoid recursion for obvious built in types. if (!AllowedType(innerType)) { parents.Push(CreateParentNode(property)); Map(innerType, parents, messageTypeKey); parents.Pop(); } } else if (isEnumerable && repeatingGroup != null) { //Finding the tpye of enumeration innerType = GetInnerTypeOfEnumerable(property); if (!AllowedType(innerType)) { parents.Push(CreateRepeatingParentNode(property, repeatingGroup, innerType)); Map(innerType, parents, messageTypeKey); parents.Pop(); } } } else if (fixTagAttribute != null) { var typeConverter = property.GetCustomAttribute <TypeConverterAttribute>(); TagMapLeaf value; //Enumerable: string[] can have a FixTag for repeating groups if (isEnumerable && repeatingGroup != null) { //Finding the tpye of enumeration innerType = GetInnerTypeOfEnumerable(property); if (AllowedType(innerType) || typeConverter != null) { value = AddEnumerableLeaf(parents, property, fixTagAttribute, repeatingGroup, typeConverter, fixTagAttribute.Tag * messageTypeKey, innerType); } else { throw new NotSupportedException("FixTagAttribute on enumerable must by primitive or string typed."); } } else if (!isEnumerable) { //Nullable<Types>, IsValueType, IsSerializable innerType = property.PropertyType; if (AllowedType(innerType) || AllowedType(GetInnerTypeOfNullable(property, typeof(Nullable <>))) || typeConverter != null) { value = AddLeafNode(parents, property, fixTagAttribute, typeConverter, fixTagAttribute.Tag * messageTypeKey); } else { throw new NotSupportedException("FixTagAttribute must have a TypeConverter or be a primitive or string typed."); } } } } }
/// <summary> /// Returns a list of grouped addresses which have had their common ownership made public by common use as inputs or as the resulting change in past transactions. /// </summary /// <remarks> /// Please see https://github.com/bitcoin/bitcoin/blob/726d0668ff780acb59ab0200359488ce700f6ae6/src/wallet/wallet.cpp#L3641 /// </remarks> /// <param name="walletName">The wallet in question.</param> /// <returns>The grouped list of base58 addresses.</returns> private List <List <string> > GetAddressGroupings(string walletName) { // Get the wallet to check. var wallet = this.walletManager.GetWallet(walletName); // Cache all the addresses in the wallet. var addresses = wallet.GetAllAddresses(); // Get the transaction data for this wallet. var txs = wallet.GetAllTransactions(); // Create a transaction dictionary for performant lookups. var txDictionary = new Dictionary <uint256, TransactionOutputData>(txs.Count()); foreach (var item in txs) { txDictionary.TryAdd(item.Id, item); } // Cache the wallet's set of internal (change addresses). var internalAddresses = wallet.GetAccounts().SelectMany(a => a.InternalAddresses); var addressGroupings = new List <List <string> >(); foreach (var transaction in txDictionary) { var tx = this.blockStore.GetTransactionById(transaction.Value.Id); if (tx.Inputs.Count > 0) { var addressGroupBase58 = new List <string>(); // Group all input addresses with each other. foreach (var txIn in tx.Inputs) { if (!IsTxInMine(addresses, txDictionary, txIn)) { continue; } // Get the txIn's previous transaction address. var prevTransactionData = txs.FirstOrDefault(t => t.Id == txIn.PrevOut.Hash); var prevTransaction = this.blockStore.GetTransactionById(prevTransactionData.Id); var prevTransactionScriptPubkey = prevTransaction.Outputs[txIn.PrevOut.N].ScriptPubKey; var addressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, prevTransactionScriptPubkey); if (string.IsNullOrEmpty(addressBase58)) { continue; } addressGroupBase58.Add(addressBase58); } // If any of the inputs were "mine", also include any change addresses associated to the transaction. if (addressGroupBase58.Any()) { foreach (var txOut in tx.Outputs) { if (IsChange(internalAddresses, txOut.ScriptPubKey)) { var txOutAddressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, txOut.ScriptPubKey); if (!string.IsNullOrEmpty(txOutAddressBase58)) { addressGroupBase58.Add(txOutAddressBase58); } } } addressGroupings.Add(addressGroupBase58); } } // Group lone addresses by themselves. foreach (var txOut in tx.Outputs) { if (IsAddressMine(addresses, txOut.ScriptPubKey)) { var grouping = new List <string>(); string addressBase58 = this.scriptAddressReader.GetAddressFromScriptPubKey(this.Network, txOut.ScriptPubKey); if (string.IsNullOrEmpty(addressBase58)) { continue; } grouping.Add(addressBase58); addressGroupings.Add(grouping); } } } // Merge the results into a distinct set of grouped addresses. var uniqueGroupings = new List <List <string> >(); foreach (var addressGroup in addressGroupings) { var addressGroupDistinct = addressGroup.Distinct(); List <string> existing = null; foreach (var address in addressGroupDistinct) { // If the address was found to be apart of an existing group add it here. // The assumption here is that if we have a grouping of [a,b], finding [a] would have returned // the existing set and we can just add the address to that set. if (existing != null) { var existingAddress = existing.FirstOrDefault(a => a == address); if (existingAddress == null) { existing.Add(address); } continue; } // Check if the address already exists in a group. // If it does not, add the distinct set into the unique groupings list, // thereby creating a new "grouping". existing = uniqueGroupings.FirstOrDefault(g => g.Contains(address)); if (existing == null) { uniqueGroupings.Add(new List <string>(addressGroupDistinct)); } } } return(uniqueGroupings.ToList()); }
/// <summary> /// Adds a list of features to which the provided directive is applied. /// </summary> /// <param name="directive">Directive to apply.</param> /// <param name="features">Features.</param> /// <param name="hostSources">List of source uri if the directive requires one.</param> /// <returns></returns> public SecurityHeadersBuilder AddFeaturePolicy(CommonPolicyDirective.Directive directive, FeaturePolicyConstants.HttpFeatures features, IList <Uri> hostSources = null) { if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Accelerometer)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Accelerometer, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.AmbientLightSensor)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.AmbientLightSensor, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Autoplay)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Autoplay, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Battery)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Battery, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Camera)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Camera, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.DisplayCapture)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.DisplayCapture, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.DocumentDomain)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.DocumentDomain, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.EncryptedMedia)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.EncryptedMedia, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.ExecutionWhileNotRendered)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.ExecutionWhileNotRendered, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.ExecutionWhileOutOfViewport)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.ExecutionWhileOutOfViewport, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Fullscreen)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Fullscreen, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Geolocation)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Geolocation, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Gyroscope)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Gyroscope, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Magnetometer)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Magnetometer, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Microphone)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Microphone, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Midi)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Midi, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Payment)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Payment, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.PictureInPicture)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.PictureInPicture, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.PublickeyCredentials)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.PublickeyCredentials, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Speaker)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Speaker, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.SyncXhr)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.SyncXhr, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.Usb)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.Usb, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.WakeLock)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.WakeLock, directive); } if (features.HasFlag(FeaturePolicyConstants.HttpFeatures.XrSpatialTracking)) { _features.TryAdd(FeaturePolicyConstants.HttpFeatures.XrSpatialTracking, directive); } _policy.SetHeaders[FeaturePolicyConstants.Header] = FeaturesToString(hostSources); return(this); }
private ChunkMesh GenerateSectionMesh(IWorld world, ScheduleType scheduled, Vector3 chunkPosition, ref ChunkSection section, int yIndex) { Dictionary <Vector3, ChunkMesh.EntryPosition> positions = new Dictionary <Vector3, ChunkMesh.EntryPosition>(); List <VertexPositionNormalTextureColor> solidVertices = new List <VertexPositionNormalTextureColor>(); List <int> animatedIndexes = new List <int>(); List <int> transparentIndexes = new List <int>(); List <int> solidIndexes = new List <int>(); var force = section.New || section.MeshCache == null || section.MeshPositions == null; var cached = section.MeshCache; var positionCache = section.MeshPositions; Dictionary <int, int> processedIndices = new Dictionary <int, int>(); for (var y = 0; y < 16; y++) { for (var x = 0; x < ChunkColumn.ChunkWidth; x++) { for (var z = 0; z < ChunkColumn.ChunkDepth; z++) { bool wasScheduled = section.IsScheduled(x, y, z); bool wasLightingScheduled = section.IsLightingScheduled(x, y, z); var blockPosition = new Vector3(x, y + (yIndex << 4), z) + chunkPosition; var isBorderBlock = (scheduled == ScheduleType.Border && (x == 0 || x == 15) || (z == 0 || z == 15)); var neighborsScheduled = HasScheduledNeighbors(world, blockPosition); var blockState = section.Get(x, y, z); var model = blockState.Model; if (blockState is BlockState state && state.IsMultiPart) { model = new CachedResourcePackModel(Game.Resources, MultiPartModels.GetBlockStateModels(world, blockPosition, state, state.MultiPartHelper)); // blockState.Block.Update(world, blockPosition); } if (blockState != null && ((force && blockState.Block.RequiresUpdate) || (wasScheduled && blockState.Block.RequiresUpdate))) { blockState = blockState.Block.BlockPlaced(world, blockState, blockPosition); section.Set(x, y, z, blockState); model = blockState.Model; } if ((blockState == null || !blockState.Block.Renderable) || (!section.New && !section.IsRendered(x, y, z) && !neighborsScheduled && !isBorderBlock)) { continue; } if (force || wasScheduled || neighborsScheduled || isBorderBlock) { var data = model.GetVertices(world, blockPosition, blockState.Block); if (data.vertices.Length == 0 || data.indexes.Length == 0) { section.SetRendered(x, y, z, false); } if (data.vertices == null || data.indexes == null || data.vertices.Length == 0 || data.indexes.Length == 0) { //section.SetRendered(x, y, z, false); continue; } bool transparent = blockState.Block.Transparent; bool animated = blockState.Block.Animated; if (data.vertices.Length > 0 && data.indexes.Length > 0) { section.SetRendered(x, y, z, true); int startVerticeIndex = solidVertices.Count; foreach (var vert in data.vertices) { solidVertices.Add(vert); } int startIndex = animated ? animatedIndexes.Count : (transparent ? transparentIndexes.Count : solidIndexes.Count); for (int i = 0; i < data.indexes.Length; i++) { var a = data.indexes[i]; if (animated) { animatedIndexes.Add(startVerticeIndex + a); } else if (transparent) { transparentIndexes.Add(startVerticeIndex + a); } else { solidIndexes.Add(startVerticeIndex + a); } } positions.TryAdd(new Vector3(x, y, z), new ChunkMesh.EntryPosition(transparent, animated, startIndex, data.indexes.Length)); } } else { if (positionCache.TryGetValue(new Vector3(x, y, z), out var pos)) { var indices = pos.Animated ? cached.AnimatedIndexes : (pos.Transparent ? cached.TransparentIndexes : cached.SolidIndexes); var indiceIndex = pos.Animated ? animatedIndexes.Count : (pos.Transparent ? transparentIndexes.Count : solidIndexes.Count); for (int index = 0; index < pos.Length; index++) { var indice = indices[pos.Index + index]; if (!processedIndices.TryGetValue(indice, out var newIndex)) { newIndex = solidVertices.Count; var vertice = cached.Vertices[indice]; solidVertices.Add(vertice); processedIndices.Add(indice, newIndex); } if (pos.Animated) { animatedIndexes.Add(newIndex); } else if (pos.Transparent) { transparentIndexes.Add(newIndex); } else { solidIndexes.Add(newIndex); } } positions.TryAdd(new Vector3(x, y, z), new ChunkMesh.EntryPosition(pos.Transparent, pos.Animated, indiceIndex, pos.Length)); } } if (wasScheduled) { section.SetScheduled(x, y, z, false); } if (wasLightingScheduled) { section.SetLightingScheduled(x, y, z, false); } } } } section.New = false; var mesh = new ChunkMesh(solidVertices.ToArray(), solidIndexes.ToArray(), transparentIndexes.ToArray(), animatedIndexes.ToArray()); section.MeshCache = mesh; section.MeshPositions = positions; return(mesh); }
/// <summary> /// 自定义皮肤设置 /// </summary> /// <param name="presentAreaKey"></param> /// <param name="ownerId"></param> /// <param name="isUseCustomStyle"></param> /// <returns></returns> public ActionResult _CustomSettings(string presentAreaKey = PresentAreaKeysOfBuiltIn.UserSpace, long ownerId = 0, bool isUseCustomStyle = false) { if (!ThemeService.Validate(presentAreaKey, ownerId)) return Content("没有设置皮肤的权限"); var customStyleEntity = new CustomStyleService().Get(presentAreaKey, ownerId); CustomStyle customStyle = null; if (customStyleEntity != null) { customStyle = customStyleEntity.CustomStyle; } //配色方案相关操作 IEnumerable<CustomStyle> colorSchemes = new CustomStyleService().GetColorSchemes(presentAreaKey); ViewData["colorSchemes"] = colorSchemes; if (customStyle == null) { customStyle = CustomStyle.New(); BackgroundImageStyle backgroundImageStyle = new BackgroundImageStyle(); customStyle.BackgroundImageStyle = backgroundImageStyle; Dictionary<string, string> definedColours = null; if (colorSchemes.Count() > 0) definedColours = colorSchemes.First().DefinedColours; else { definedColours = new Dictionary<string, string>(); definedColours[ColorLabel.PageBackground.ToString()] = "#f2e3bf"; definedColours[ColorLabel.ContentBackground.ToString()] = "#f8f0e6"; definedColours[ColorLabel.BorderBackground.ToString()] = "#ebe6d9"; definedColours[ColorLabel.MainTextColor.ToString()] = "#666"; definedColours[ColorLabel.SubTextColor.ToString()] = "#ccc"; definedColours[ColorLabel.MainLinkColor.ToString()] = "#cc6673"; definedColours[ColorLabel.SubLinkColor.ToString()] = "#efc0ca"; } customStyle.DefinedColours = definedColours; } Dictionary<string, object> customStyleCssBlock = new Dictionary<string, object>(); if (customStyle.IsUseBackgroundImage) { customStyleCssBlock.TryAdd("background-image", "url('" + customStyle.BackgroundImageStyle.Url + "')"); customStyleCssBlock.TryAdd("background-repeat", customStyle.BackgroundImageStyle.IsRepeat ? "repeat" : "no-repeat"); customStyleCssBlock.TryAdd("background-attachment", customStyle.BackgroundImageStyle.IsFix ? "fixed" : "scroll"); string position = "center"; switch (customStyle.BackgroundImageStyle.BackgroundPosition) { case BackgroundPosition.Left: position = "left"; break; case BackgroundPosition.Center: position = "center"; break; case BackgroundPosition.Right: position = "right"; break; default: position = "center"; break; } customStyleCssBlock.TryAdd("background-position", position + " top"); } ViewData["customStyleCssBlock"] = System.Web.Helpers.Json.Encode(customStyleCssBlock); List<SelectListItem> selectHeaderHeight = new List<SelectListItem> { new SelectListItem { Text = "20", Value = "20" }, new SelectListItem { Text = "60", Value = "60" }, new SelectListItem { Text = "100", Value = "100" } }; ViewData["HeaderHeight"] = new SelectList(selectHeaderHeight, "Value", "Text", customStyle.HeaderHeight); return View(customStyle); }
/// <summary> /// 删除按钮 /// </summary> /// <param name="htmlHelper">被扩展的hemlHelper实例</param> /// <param name="ajaxdeletebutton">异步执行删除按钮</param> /// <returns>MvcForm</returns> public static MvcHtmlString AjaxDeleteButton(this HtmlHelper htmlHelper, AjaxDeleteButton ajaxdeletebutton) { //定义属性字典 Dictionary<string, object> result = new Dictionary<string, object>(); //建立标签元素 TagBuilder builder = new TagBuilder("a"); //判断html属性字典是否有数据 //如果存在则导入到属性字典内 if (ajaxdeletebutton.HtmlAttributes != null) result = new Dictionary<string, object>(ajaxdeletebutton.HtmlAttributes); //定义data属性字典 Dictionary<string, object> data = new Dictionary<string, object>(); //把错误提示信息添加到data字典里 data.TryAdd("confirm", ajaxdeletebutton.Confirm); //将目标元素属性信息添加到data字典里 data.TryAdd("deleteTarget", ajaxdeletebutton.DeleteTarget); //将成功回调函数名称添加data字典(如果存在) if (!string.IsNullOrEmpty(ajaxdeletebutton.Success)) { data.TryAdd("SuccessFn", ajaxdeletebutton.Success); } //将失败回调函数名称添加data字典(如果存在) if (!string.IsNullOrEmpty(ajaxdeletebutton.Error)) { data.TryAdd("ErrorFn", ajaxdeletebutton.Error); } //添加用于ajax操作的标识 result["plugin"] = "AjaxDeleteButton"; //添加data 属性 result["data"] = Json.Encode(data); //将属性字典result导入到标签内属性内 builder.MergeAttributes(result); //添加标签的href属性 builder.MergeAttribute("href", ajaxdeletebutton.Url); //判断删除控件按钮文字是否有值 if (!string.IsNullOrEmpty(ajaxdeletebutton.Text)) builder.InnerHtml = ajaxdeletebutton.Text; else //判断删除控件按钮图标是否有值 if (ajaxdeletebutton.Icon != null) builder.InnerHtml = htmlHelper.Icon(ajaxdeletebutton.Icon.Value).ToString(); else return MvcHtmlString.Empty; //判断删除控件按钮提示信息是否有值 if (!string.IsNullOrEmpty(ajaxdeletebutton.Tooltip)) { builder.MergeAttribute("title", ajaxdeletebutton.Tooltip); } return MvcHtmlString.Create(builder.ToString()); }
public static bool AddProvider <T>(Func <VerificationCodeOption, T> provider) where T : IVerificationCodeProvider { return(providerList.TryAdd(typeof(T), (op) => { return provider(op); })); }
private static ClientMessageHeader ParseClientMessage(Stream clientStream) { var streamReader = new StreamReader(clientStream); { clientStream.Position = 0; var httpCmd = String.Empty; for (var i = 0; i < 10; i++) { httpCmd = streamReader.ReadLine(); if (String.IsNullOrEmpty(httpCmd)) { continue; } if (httpCmd.Count(c => c.Equals(' ')) >= 2) { break; } } if (String.IsNullOrEmpty(httpCmd)) { return null; } var splitBuffer = httpCmd.Split(new[] { ' ' }, 3); var method = splitBuffer[0]; var remoteUri = splitBuffer[1]; if (method.Equals("CONNECT", StringComparison.InvariantCultureIgnoreCase)) { remoteUri = "https://" + remoteUri; } var protocollVersion = splitBuffer[2]; splitBuffer = protocollVersion.Split(new[] { '/' }, 2); var protocol = splitBuffer[0]; var version = splitBuffer[1]; var headers = new Dictionary<string, string>(); while (true) { var headerline = streamReader.ReadLine(); if (String.IsNullOrEmpty(headerline)) { break; } var lineBuffer = headerline.Split(new[] { ':' }, 2); var key = lineBuffer[0].Trim(); var value = lineBuffer[1].Trim(); headers.TryAdd(key, value); } if (remoteUri.StartsWith("/")) { remoteUri = string.Format("https://{0}{1}", headers["Host"], remoteUri); } var message = new ClientMessageHeader { Method = method, RemoteUri = new Uri(remoteUri), Protocol = protocol, ProtocolVersion = Version.Parse(version), Headers = headers }; clientStream.Position = 0; return message; } }
private unsafe bool CacheGlyph(uint c, out GlyphEntry glyphEntry) { foreach (var face in faces) { if (face.TryCharIndex(c, out var glyph)) { if (face.HasColor()) { face.LoadGlyph(glyph, LoadFlags.RENDER);//NOT IMPLEMENTED face.LoadGlyph(glyph, LoadFlags.COLOR); } else { face.LoadGlyph(glyph, LoadFlags.RENDER); } var glyphSlot = face.GetGlyphSlot(); var w = glyphSlot.bitmap.width; var h = glyphSlot.bitmap.rows; var buffer = (byte *)glyphSlot.bitmap.buffer; if (glyphSlot.bitmap.pitch < 0) { continue; } var colorData = new Color[w * h]; var result = glyphSlot.bitmap.pixel_mode switch { FTPixelMode.FT_PIXEL_MODE_GRAY => FTPixelModeGrayPutColorData(colorData, w, h, buffer), FTPixelMode.FT_PIXEL_MODE_BGRA => FTPixelModeColorPutColorData(colorData, w, h, buffer), _ => throw new ArgumentException("Unsupported pixel mode") }; if (result) { if (spriteMaps.Count > 0 && spriteMaps[spriteMaps.Count - 1].Place(colorData, (int)w, (int)h, out var idx)) { glyphEntry = new GlyphEntry { sprite = new Sprite { mapId = spriteMaps.Count - 1, spriteIdx = idx }, height = (int)h, width = (int)w, leftOffset = glyphSlot.bitmap_left, topOffset = glyphSlot.bitmap_top }; spriteReferences.TryAdd(c, glyphEntry); } else { var newMap = new SpriteMap(graphicsDevice); if (newMap.Place(colorData, (int)w, (int)h, out idx)) { glyphEntry = new GlyphEntry { sprite = new Sprite { mapId = spriteMaps.Count, spriteIdx = idx }, height = (int)h, width = (int)w, leftOffset = glyphSlot.bitmap_left, topOffset = glyphSlot.bitmap_top }; spriteReferences.TryAdd(c, glyphEntry); spriteMaps.Add(newMap); } } } } } glyphEntry = default; return(false); }
public void op_TryAdd_IDictionaryOfT_KeyValuePair_whenTrue() { var list = new Dictionary<string, string>(); Assert.True(list.TryAdd(new KeyValuePair<string, string>("example", string.Empty))); }
public void SetExpectedResponse(string expectedUrl, string expectedResponse) { _expectedResponses.TryAdd(expectedUrl, expectedResponse); }
public void SetExpectedStatusCode(string expectedUrl, HttpStatusCode statusCode) { _expectedStatusCodes.TryAdd(expectedUrl, statusCode); }
/// <summary> /// Uploadify的Helper方法用于非附件上传 /// </summary> /// <param name="htmlHelper"></param> /// <param name="name">名称</param> /// <param name="allowedFileExtensions">允许的文件类型 /// 格式为(jpg,txt,doc)</param> /// <param name="fileSizeLimit">允许上传文件大小(单位KB)</param> /// <param name="uploadFileOptions">指定上传配置类</param> /// <param name="buttonOptions">指定按钮属性的类</param> /// <returns></returns> public static MvcHtmlString Uploadify(this HtmlHelper htmlHelper, string name, string allowedFileExtensions, int fileSizeLimit, UploadFileOptions uploadFileOptions, ButtonOptions buttonOptions = null) { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(allowedFileExtensions) || fileSizeLimit <= 0 || uploadFileOptions == null) { throw new ExceptionFacade("参数不能为空"); } if (fileSizeLimit <= 0) { throw new ExceptionFacade("参数不能小于等于0"); } htmlHelper.Script("~/Bundle/Scripts/Uploadify"); //data属性字典 Dictionary<string, object> data = new Dictionary<string, object>(); //定义属性字典 Dictionary<string, object> result = new Dictionary<string, object>(); //参数 Dictionary<string, object> formData = new Dictionary<string, object>(); //文件流标识名 string fileobjName = "Filedata"; #region uploadify设置 if (uploadFileOptions != null) { if (uploadFileOptions.AdditionalCallBacks != null) { result = new Dictionary<string, object>(uploadFileOptions.AdditionalCallBacks); } //定义上传文件标示名称 if (!string.IsNullOrEmpty(uploadFileOptions.FileObjName)) { result.TryAdd("fileObjName", uploadFileOptions.FileObjName); fileobjName = uploadFileOptions.FileObjName; } //设置是否自动上传 if (uploadFileOptions.IsAuto != null) { result.TryAdd("auto", uploadFileOptions.IsAuto); } //设置可多选文件属性 if (uploadFileOptions.IsMultiple != null) { result.TryAdd("multi", uploadFileOptions.IsMultiple); } //设置都否缓存SWF文件 if (uploadFileOptions.PreventCaching != null) { result.TryAdd("preventCaching", uploadFileOptions.PreventCaching); } //设置显示进度的样式 if (!string.IsNullOrEmpty(uploadFileOptions.ProgressData)) { result.TryAdd("progressData", uploadFileOptions.ProgressData); } //设置队列展示容器的ID if (!string.IsNullOrEmpty(uploadFileOptions.QueueId)) { result.TryAdd("queueID", uploadFileOptions.QueueId); } //设置队列可允许的个数 result.TryAdd("queueSizeLimit", uploadFileOptions.QueueSizeLimit); //设置完成后是否移除属性 if (uploadFileOptions.RemoveCompleted != null) { result.TryAdd("removeCompleted", uploadFileOptions.RemoveCompleted); } //设置移除的延时属性 if (uploadFileOptions.RemoveTimeout > 0) { result.TryAdd("removeTimeout", uploadFileOptions.RemoveTimeout); } //设置于服务器端的成功上传的延时属性 if (uploadFileOptions.SuccessTimeout > 0) { result.TryAdd("successTimeout", uploadFileOptions.SuccessTimeout); } //设置可上传的文件数量限制 result.TryAdd("uploadLimit", uploadFileOptions.UploadLimit); if (uploadFileOptions.AdditionalFormDatas != null) { formData = new Dictionary<string, object>(uploadFileOptions.AdditionalFormDatas); } else { formData.TryAdd("requestName", fileobjName); } result.TryAdd("formData", formData); //URL long userId = UserContext.CurrentUser != null ? UserContext.CurrentUser.UserId : 0; string uploadUrl = SiteUrls.Instance().UploadFile(userId); if (!string.IsNullOrEmpty(uploadFileOptions.UploaderUrl)) { uploadUrl = uploadFileOptions.UploaderUrl + ((uploadFileOptions.UploaderUrl.Contains("?") ? "&" : "?") + "CurrentUserIdToken=" + Utility.EncryptTokenForUploadfile(0.1, userId)); } result.TryAdd("uploader", uploadUrl); } //设置可允许上传的类型 属性 string fileTypeExts = FileTypeExts(allowedFileExtensions); if (string.IsNullOrEmpty(fileTypeExts)) fileTypeExts = uploadFileOptions.FileTypeExts; if (string.IsNullOrEmpty(fileTypeExts)) fileTypeExts = "*.*"; result.TryAdd("fileTypeExts", fileTypeExts); //设置文件限制大小属性 if (fileSizeLimit <= 0) fileSizeLimit = uploadFileOptions.FileSizeLimit; result.TryAdd("fileSizeLimit", fileSizeLimit); if (!string.IsNullOrEmpty(uploadFileOptions.FileTypeDescription)) result.TryAdd("fileTypeDesc", uploadFileOptions.FileTypeDescription); //设置SWF路径 string swfStr = SiteUrls.FullUrl("~/Scripts/jquery/uploadify/uploadify.swf"); result.TryAdd("swf", swfStr); #endregion uploadify设置 if (buttonOptions != null) { #region ButtonOptions设置 //添加按钮的额外样式 if (!string.IsNullOrEmpty(buttonOptions.CssClass)) { result.TryAdd("buttonClass", buttonOptions.CssClass); } //设置按钮的高度 if (buttonOptions.Height != 0) { result.TryAdd("height", buttonOptions.Height); } //设置按钮的宽度 if (buttonOptions.Width != 0) { result.TryAdd("width", buttonOptions.Width); } //设置按钮的显示背景图 if (!string.IsNullOrEmpty(buttonOptions.ImageUrl)) { result.TryAdd("buttonImage", buttonOptions.ImageUrl); } //设置按钮的文本 if (!string.IsNullOrEmpty(buttonOptions.Text)) { result.TryAdd("buttonText", buttonOptions.Text); } #endregion ButtonOptions设置 } TagBuilder builder = new TagBuilder("div"); //脚本操作标识 data["plugin"] = "uploadify"; data.TryAdd("data", Json.Encode(result)); builder.MergeAttributes(data); builder.MergeAttribute("id", name); return MvcHtmlString.Create(builder.ToString().Replace(""[", "").Replace("]"", "")); }
//SELECT METHODS public static MenuItems GetTreeMenu() { MenuItems mu = new MenuItems(); List<MenuItem> dbmi = new List<MenuItem>(); Queue<Tuple<string,CustTreeItems>> toAddParent = new Queue<Tuple<string,CustTreeItems>>(); dbmi.AddRange(DAL.DAL.ExecuteDataReader("S_AllControls_ControlName_PermissionName", FillMenuItem)); List<CustTreeItems> menulist = new List<CustTreeItems>(); Dictionary<string, CustTreeItems> itemsDictionary = new Dictionary<string, CustTreeItems>(); Dictionary<string, CustTreeItems> addPermissions = new Dictionary<string, CustTreeItems>(); foreach(var t in dbmi) { CustTreeItems c; if (!itemsDictionary.ContainsKey(t.Name)) { c = new CustTreeItems(); c.Name = t.Name; c.HasAccess = false; } else { c = itemsDictionary[t.Name]; } if (!string.IsNullOrEmpty(t.PermissionName)) { c.HasPermissions = true; c.Options.Add(new Permission(c, t.PermissionName, t.PermissionDescription, false)); } if (!string.IsNullOrEmpty(t.ParentName)) { c.HasParent = true; if (itemsDictionary.ContainsKey(t.ParentName)) { CustTreeItems parent = itemsDictionary[t.ParentName]; c.Parent = parent; int count = parent.Items.Where(x => x.Name == c.Name).Count(); if(count == 0) parent.Items.Add(c); itemsDictionary.TryAdd(t.Name, c); } else { toAddParent.Enqueue(Tuple.Create(t.ParentName,c)); } } else { itemsDictionary.TryAdd(t.Name, c); } itemsDictionary.TryAdd(t.Name, c); } //niet zo efficient maar mijn vermoedelijke efficientere manier liet het afweten //als parent in itemsdictionary -> bind //als parent niet in itemsdicionary -> enqueue en voer op het einde uit //in het beste scenario staat alles op volgorde, in het slechtste staat mijn parent steeds op het einde while(toAddParent.Count > 0) { Tuple<string, CustTreeItems> it = toAddParent.Dequeue(); CustTreeItems child = it.Item2; if (itemsDictionary.ContainsKey(it.Item1)) { CustTreeItems parent = itemsDictionary[it.Item1]; child.Parent = parent; int count = parent.Items.Where(x => x.Name == child.Name).Count(); if (count == 0) parent.Items.Add(child); itemsDictionary.TryAdd(it.Item1, child); } else { toAddParent.Enqueue(it); } } //foreach(MenuItem menuitem in dbmi) //{ // CustTreeItems cti; // if (itemsDictionary.ContainsKey(menuitem.Name)) // { // cti = itemsDictionary[menuitem.Name] ?? new CustTreeItems(menuitem.Name); // } // else // { // cti = new CustTreeItems(menuitem.Name); // } // cti.HasAccess = false; // if (!string.IsNullOrEmpty(menuitem.PermissionName)) // { // cti.HasPermissions = true; // cti.Options.Add(new Permission(cti, menuitem.PermissionName, menuitem.PermissionDescription, false)); // } // if (cti.HasParent = !string.IsNullOrEmpty(menuitem.ParentName)) // { // CustTreeItems parent; // if (itemsDictionary.TryGetValue(menuitem.ParentName, out parent)) // { // parent.Items.Add(cti); // cti.Parent = parent; // } // else // { // toAddParent.Add( Tuple.Create(menuitem.ParentName, cti) ); // } // } // foreach(var tuple in toAddParent) // { // if(tuple.Item1 == menuitem.Name) // { // CustTreeItems child = tuple.Item2; // child.Parent = cti; // cti.Items.Add(child); // break; // } // } // itemsDictionary.TryAdd(menuitem.Name, cti); //} ////itemsDictionary.Values.Where(treeitem => !treeitem.HasParent).ToList().ForEach(x => mu.Items.Add(x)); foreach (var v in itemsDictionary) { if (!v.Value.HasParent) { mu.Items.Add(v.Value); } } return mu; }