System.Collections.Generic.Dictionary.ContainsKey(string)

Here are the examples of the csharp api System.Collections.Generic.Dictionary.ContainsKey(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

18078 Examples 7

19 Source : DynamicProxyExtensions.cs
with MIT License
from 2881099

internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
        {
            if (type == null) return null;
            if (type == typeof(void)) return "void";
            if (type.IsGenericParameter) return type.Name;
            if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
            var sb = new StringBuilder();
            var nestedType = type;
            while (nestedType.IsNested)
            {
                sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
                nestedType = nestedType.DeclaringType;
            }
            if (isNameSpace && string.IsNullOrEmpty(nestedType.Namespace) == false)
                sb.Insert(0, ".").Insert(0, nestedType.Namespace);

            if (type.IsGenericType == false)
                return sb.Append(type.Name).ToString();

            var genericParameters = type.GetGenericArguments();
            if (type.IsNested && type.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any() == false)
                return sb.Append(type.Name).ToString();

            sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
            var genericTypeIndex = 0;
            foreach (var genericType in genericParameters)
            {
                if (genericTypeIndex++ > 0) sb.Append(", ");
                sb.Append(DisplayCsharp(genericType, true));
            }
            return sb.Append(">").ToString();
        }

19 Source : Form1.cs
with MIT License
from 2881099

private void superTabControl1_TabItemClose(object sender, SuperTabStripTabItemCloseEventArgs e)
        {
            if (e.Tab.Text == "首页")
            {
                e.Cancel = true;
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(superTabControl1, "默认页不允许关闭", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
            }
            if (pairs.ContainsKey(e.Tab.Text)) pairs.Remove(e.Tab.Text);
            if (pairs.Count == 0) buttonItem19.Enabled = false;

        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void Main(string[] args)
        {

            int ruleCount = 0;
            int gradientMax = 0;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(o =>
                {
                    LoadConfig(o);
                    if (!o.Suricata)
                    {
                        LoadMismatchSearchMatrix(o);
                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
                        {
                            try
                            {
                                var dict = DeserializeYamlFile(ruleFilePath, o);
                                if (dict != null && dict.ContainsKey("tags"))
                                {
                                    ruleCount++;
                                    var tags = dict["tags"];
                                    var categories = new List<string>();
                                    string lastEntry = null;
                                    foreach (string tag in tags)
                                    {
                                        //If its the technique id entry, then this adds the file name to the techniques map
                                        if (tag.ToLower().StartsWith("attack.t"))
                                        {
                                            var techniqueId = tag.Replace("attack.", "").ToUpper();
                                            if (!techniques.ContainsKey(techniqueId))
                                                techniques[techniqueId] = new List<string>();
                                            techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
                                            if (techniques.Count > gradientMax)
                                                gradientMax = techniques.Count;
                                            //then if there are any categories so far, it checks for a mismatch for each one
                                            if (categories.Count > 0 && o.Warning)
                                            {
                                                foreach (string category in categories)
                                                    if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
                                                        mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
                                            }
                                        }
                                        else
                                        {
                                            //if its the start of a new technique block, then clean categories and adds first category
                                            if (lastEntry == null || lastEntry.StartsWith("attack.t"))
                                                categories = new List<string>();
                                            categories.Add(
                                                tag.Replace("attack.", "")
                                                .Replace("_", "-")
                                                .ToLower());
                                        }
                                        lastEntry = tag;
                                    }
                                }
                            }
                            catch (YamlException e)
                            {
                                Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
                            }
                        }

                        WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
                        PrintWarnings();
                    }
                    else
                    {

                        List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();

                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
                        {
                            res.Add(ParseRuleFile(ruleFilePath));
                        }

                        WriteSuricataFileResult(o,
                            res
                                .SelectMany(dict => dict)
                                .ToLookup(pair => pair.Key, pair => pair.Value)
                                .ToDictionary(group => group.Key,
                                              group => group.SelectMany(list => list).ToList()));
                    }

                });
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void LoadMismatchSearchMatrix(Options o)
        {
            if (o.Warning)
            {
                foreach (var x in (JsonConvert.DeserializeObject<JObject>(new WebClient().DownloadString(o.MitreMatrix))["objects"] as JArray)!
                    .Where(x => x["external_references"] != null && x["external_references"].Any(y => y["source_name"] != null && x["kill_chain_phases"] != null)))
                {
                    var techId = x["external_references"]
                        .First(x => x["source_name"].ToString() == "mitre-attack")["external_id"]
                        .ToString();
                    if (!mismatchSearchMatrix.ContainsKey(techId))
                        mismatchSearchMatrix.Add(techId,
                            x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString()).ToList()
                        );
                    else
                    {
                        mismatchSearchMatrix[techId] = mismatchSearchMatrix[techId].Concat(x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString())).ToList();
                    }
                }
            }
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static Dictionary<string, List<string>> ParseRuleFile(string ruleFilePath)
        {
            Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
            var contents = new StringReader(File.ReadAllText(ruleFilePath));
            string line = contents.ReadLine();
                while (line != null)
                {
                    try
                    {
                        //if the line contains a mitre_technique
                        if (line.Contains("mitre_technique_id "))
                        {
                            List<string> techniques = new List<string>();
                            //get all indexes from all technique ids and add them all to a list
                            IEnumerable<int> indexes = Regex.Matches(line, "mitre_technique_id ").Cast<Match>().Select(m => m.Index + "mitre_technique_id ".Length);
                            foreach (int index in indexes) 
                                techniques.Add(line.Substring(index, line.IndexOfAny(new [] { ',', ';' }, index) - index));
                            int head = line.IndexOf("msg:\"") + "msg:\"".Length;
                            int tail = line.IndexOf("\"", head);
                            string msg = line.Substring(head, tail - head);
                            head = line.IndexOf("sid:") + "sid:".Length;
                            tail = line.IndexOfAny(new char[] { ',', ';' }, head);
                            string sid = line.Substring(head, tail - head);
                            //for each found technique add the sid along with the message to the content
                            foreach( string technique in techniques)
                            {
                                if (res.ContainsKey(technique))
                                    res[technique].Add($"{sid} - {msg}");
                                else
                                    res.Add(technique, new List<string> { $"{sid} - {msg}" });
                            }
                        }
                        line = contents.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(line);
                        Console.WriteLine(e.Message);
                        line = contents.ReadLine();
                }
                }
                return res;
            }

19 Source : SlackSender.cs
with GNU Affero General Public License v3.0
from 3CORESec

private async Task<string> SendAlert(string path, (string, Dictionary<string, dynamic>) res, string sourceIp, string ts = null)
        {
            var _path = paths.ContainsKey(path) ? paths[path] : path;
            var message = $"Trapdoor triggered in: {_path}";
            var temp = await GenerateAlert(res, sourceIp);
            if (!string.IsNullOrEmpty(ts))
                return _sender.EditNotification(temp.Item2, message, ts);
            return _sender.SendNotification(temp.Item2, message);
        }

19 Source : JsonSender.cs
with GNU Affero General Public License v3.0
from 3CORESec

public override async Task<string> SendAlert((string, Dictionary<string, dynamic>) res, string sourceIp, string path, string guid)
        {
            try
            {
                path = path.Split("/")[1];
                var _path = paths.ContainsKey(path)? paths[path] : path;
                var message = $"Trapdoor triggered in: {_path}";
                var temp = await GenerateAlert(res, sourceIp, message);
                var content = new StringContent(temp, Encoding.UTF8, "application/json");
                await _client.PostAsync(send_link, content);
                return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

19 Source : Model.cs
with GNU Affero General Public License v3.0
from 3drepo

public string SharedIdtoUniqueId(string sharedId)
        {
            if (sharedIdToUniqueId == null) FetchTree();
            
            return sharedIdToUniqueId.ContainsKey(sharedId) ? sharedIdToUniqueId[sharedId] : null;
        }

19 Source : Model.cs
with GNU Affero General Public License v3.0
from 3drepo

public Dictionary<string, object>[] GetMetadataInfo(string nodeId)
        {
            if (meshInfo == null) FetchTree();
            Dictionary<string, object>[] res = null;
            if (meshInfo.ContainsKey(nodeId) && meshInfo[nodeId].meta != null && meshInfo[nodeId].meta.Length > 0)
            {
                res = new Dictionary<string, object>[meshInfo[nodeId].meta.Length];
                for(int i = 0; i < meshInfo[nodeId].meta.Length; ++i)
                {
                    res[i] = repoHttpClient.GetMetadataById(teamspace, modelId, meshInfo[nodeId].meta[i]).metadata;
                }
            }

            return res;
        }

19 Source : Model.cs
with GNU Affero General Public License v3.0
from 3drepo

public string GetSubMeshId(string supermesh, int index)
        {
            string ret = null;

            if (superMeshes.ContainsKey(supermesh) && superMeshes[supermesh].indexToId.Length > index)
            {
                ret = superMeshes[supermesh].indexToId[index];
            }

            return ret;
        }

19 Source : Model.cs
with GNU Affero General Public License v3.0
from 3drepo

public MeshLocation[] GetMeshLocation(string meshId)
        {
            if(meshToLocations.ContainsKey(meshId))
            {
                return meshToLocations[meshId].ToArray();
            } else
            {                
                return new MeshLocation[] { };
            }
        }

19 Source : ModelManager.cs
with GNU Affero General Public License v3.0
from 3drepo

private SuperMeshInfo ProcessSuperMeshInfo(replacedetMapping replacedetMapping, Dictionary<string, List<MeshLocation>> meshLocations, Dictionary<string, Bounds> meshBboxEntries)
        {
            SuperMeshInfo info = new SuperMeshInfo();
            info.nSubMeshes = replacedetMapping.mapping.Length;
            info.indexToId = new string[info.nSubMeshes];

            if (replacedetMapping.mapping.Length > 0)
            {
                var supermeshId = replacedetMapping.mapping[0].usage[0];
                info.name = supermeshId.Remove(supermeshId.LastIndexOf('_'));

                for(int i = 0; i < replacedetMapping.mapping.Length; ++i)
                {
                    var meshId = replacedetMapping.mapping[i].name;
                    info.indexToId[i] = meshId;
                    if (!meshLocations.ContainsKey(meshId))
                    {
                        meshLocations[meshId] = new List<MeshLocation>();
                    }
                    meshLocations[meshId].Add(new MeshLocation(supermeshId, i));
                    Bounds bbox = new Bounds();
                    bbox.SetMinMax(ArrayToVector3d(replacedetMapping.mapping[i].min), ArrayToVector3d(replacedetMapping.mapping[i].max));
                    if (!meshBboxEntries.ContainsKey(meshId))
                    {
                        meshBboxEntries[meshId] = bbox;                        
                    } else
                    {
                        meshBboxEntries[meshId].Encapsulate(bbox);
                    }
                    

                }
            }

            return info;
        }

19 Source : HttpClient.cs
with GNU Affero General Public License v3.0
from 3drepo

protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
        {
            AppendApiKey(ref uri);

            // put together the json object with the login form data
            string parameters = JsonMapper.ToJson(data);
            byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = postDataBuffer.Length;
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("POST " + uri + " data: " + parameters);

            Stream postDataStream = request.GetRequestStream();

            postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
            postDataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);
            string responseData = responseReader.ReadToEnd();

            Cookie responseCookie = response.Cookies[0];
            string responseDomain = responseCookie.Domain;

            // Only replacedume one cookie per domain
            if (!cookieDict.ContainsKey(responseDomain))
            {
                cookieDict.Add(responseCookie.Domain, responseCookie);
                responseCookie.Domain = "." + responseCookie.Domain;
            }

            Uri myUri = new Uri(uri);

            foreach (KeyValuePair<string, Cookie> entry in cookieDict)
            {
                int uriHostLength = myUri.Host.Length;

                if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
                {
                    cookies.Add(myUri, entry.Value);
                }
            }

            return JsonMapper.ToObject<T_out>(responseData);
        }

19 Source : XProjectEnv.cs
with MIT License
from 3F

protected IDictionary<string, string> DefProperties(IConfPlatform conf, IDictionary<string, string> properties)
        {
            var ret = new Dictionary<string, string>(properties);

            void _set(string k, string v)
            {
                if(v != null) {
                    ret[k] = v;
                }

                if(!ret.ContainsKey(k)) {
                    ret[k] = PropertyNames.UNDEFINED;
                }
            };

            _set(PropertyNames.CONFIG, conf?.ConfigurationByRule);
            _set(PropertyNames.PLATFORM, conf?.PlatformByRule);

            return ret;
        }

19 Source : SettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void ComboBoxSerialPort_DropDownOpened(object sender, EventArgs e)
		{
			ComboBoxSerialPort.Items.Clear();

			Dictionary<string, string> ports = new Dictionary<string, string>();

			try
			{
				ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
				foreach (ManagementObject queryObj in searcher.Get())
				{
					string id = queryObj["DeviceID"] as string;
					string name = queryObj["Name"] as string;

					ports.Add(id, name);
				}
			}
			catch (ManagementException ex)
			{
				MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
			}

			// fix error of some boards not being listed properly
			foreach (string port in SerialPort.GetPortNames())
			{
				if (!ports.ContainsKey(port))
				{
					ports.Add(port, port);
				}
			}

			foreach (var port in ports)
			{
				ComboBoxSerialPort.Items.Add(new ComboBoxItem() { Content = port.Value, Tag = port.Key });
			}
		}

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

private static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/pname"))
                {
                    Process[] process = Process.GetProcessesByName(arguments["/pname"]);
                    if (process.Length > 0)
                    {
                        for (int i = 0; i < process.Length; i++)
                        {
                            Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
                            Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
                            Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
                            dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
                    }
                }
                else if (arguments.ContainsKey("/pid"))
                {
                    int procid = Convert.ToInt32(arguments["/pid"]);
                    Process process = Process.GetProcessById(procid);
                    Console.WriteLine($"[+] Dumping {process.ProcessName} process");
                    Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
                    Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
                    dump(process.Handle, (uint)process.Id, process.ProcessName);
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

19 Source : AObjectBase.cs
with MIT License
from 404Lcc

public void AutoReference(Transform transform, Dictionary<string, FieldInfo> fieldInfoDict)
        {
            string name = transform.name.ToLower();
            if (fieldInfoDict.ContainsKey(name))
            {
                if (fieldInfoDict[name].FieldType.Equals(typeof(GameObject)))
                {
                    fieldInfoDict[name].SetValue(this, transform.gameObject);
                }
                else if (fieldInfoDict[name].FieldType.Equals(typeof(Transform)))
                {
                    fieldInfoDict[name].SetValue(this, transform);
                }
                else
                {
                    fieldInfoDict[name].SetValue(this, transform.GetComponent(fieldInfoDict[name].FieldType));
                }
            }
            for (int i = 0; i < transform.childCount; i++)
            {
                AutoReference(transform.GetChild(i), fieldInfoDict);
            }
        }

19 Source : ProtobufPropertyHelper.cs
with MIT License
from 404Lcc

void RegisterMemberTypeInternal(string metaIndex, Type type)
        {
            if (!m_types.ContainsKey(metaIndex))
            {
				m_types.Add(metaIndex,type);
            }
            else
                throw new SystemException(string.Format("PropertyMeta : {0} is registered!",metaIndex));
        }

19 Source : HotKeys.cs
with MIT License
from 3RD-Dimension

public static void LoadHotKeys()
        {           
            hotkeyCode.Clear();
            hotkeyDescription.Clear();

            if (!File.Exists(HotKeyFile))
            {
               MainWindow.Logger.Error("Hotkey file not found, going to create default");
                CheckCreateFile.CreateDefaultXML();               
            }
 
            XmlReader r = XmlReader.Create(HotKeyFile);   // "hotkeys.xml");

            while (r.Read())
            {
                if (!r.IsStartElement())
                    continue;

                switch (r.Name)
                {
                    case "Hotkeys":
                        // Get Hotkey Version Number, used for modifying or updating to newer hotkey files (ie if new features are added)
                        if (r["HotkeyFileVer"].Length > 0)
                        {                           
                            CurrentHotKeyFileVersion = Convert.ToInt32(r["HotkeyFileVer"]); // Current Hotkey File Version
                        }
                        break;
                    case "bind":
                        if ((r["keyfunction"].Length > 0) && (r["keycode"] != null))
                        {
                            if (!hotkeyCode.ContainsKey(r["keyfunction"]))
                                hotkeyCode.Add(r["keyfunction"], r["keycode"]);
                            hotkeyDescription.Add(r["keyfunction"], r["key_description"]);
                        }
                        break;
                }              
            }
            r.Close();

            // Check if CurrentFileVersion and NewFileVersion is different and if so, Update the file then reload by running ths process again.
            MainWindow.Logger.Info("Hotkey file found, checking if needing update/modification");
            if (CurrentHotKeyFileVersion < CheckCreateFile.HotKeyFileVer) // If CurrentHotKeyFileVersion does not equal HotKeyFileVer then update is required
            {
                 CheckCreateFile.CheckAndUpdateXMLFile(CurrentHotKeyFileVersion);
             }           
        }

19 Source : AssetManager.cs
with MIT License
from 404Lcc

private replacedetData LoadreplacedetData<T>(string name, string suffix, bool isKeep, bool isreplacedetBundle, params string[] types) where T : Object
        {
            string path = GetreplacedetPath(name, types);
            if (replacedetDict.ContainsKey(path))
            {
                return replacedetDict[path];
            }
            else
            {
                replacedetData replacedetData = new replacedetData();
                Object replacedet = null;
#if replacedetBundle
                if (isreplacedetBundle)
                {
#if !UNITY_EDITOR
                    replacedet = replacedetBundleManager.Instance.Loadreplacedet($"replacedets/Bundles/{path}{suffix}").Loadreplacedet<T>($"replacedets/Bundles/{path}{suffix}");
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Bundles/{path}{suffix}");
#endif
                }
                else
                {
#if !UNITY_EDITOR
                    replacedet = Resources.Load<T>(path);
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
                }
#else
#if !UNITY_EDITOR
                replacedet = Resources.Load<T>(path);
#else
                replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
#endif
                if (replacedet == null) return null;
                replacedetData.replacedet = replacedet;
                replacedetData.types = types;
                replacedetData.name = name;
                replacedetData.suffix = suffix;
                replacedetData.isKeep = isKeep;
                replacedetData.isreplacedetBundle = isreplacedetBundle;
                replacedetDict.Add(path, replacedetData);
                return replacedetData;
            }
        }

19 Source : AssetManager.cs
with MIT License
from 404Lcc

private async Task<replacedetData> LoadreplacedetDataAsync<T>(string name, string suffix, bool isKeep, bool isreplacedetBundle, params string[] types) where T : Object
        {
            await Task.Run(() => { });
            string path = GetreplacedetPath(name, types);
            if (replacedetDict.ContainsKey(path))
            {
                return replacedetDict[path];
            }
            else
            {
                replacedetData replacedetData = new replacedetData();
                Object replacedet = null;
#if replacedetBundle
                if (isreplacedetBundle)
                {
#if !UNITY_EDITOR
                    AsyncOperationHandle<T> handler = Addressables.LoadreplacedetAsync<T>($"replacedets/Bundles/{path}{suffix}");
                    await handler.Task;
                    replacedet = handler.Result;
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Bundles/{path}{suffix}");
#endif
                }
                else
                {
#if !UNITY_EDITOR
                    replacedet = Resources.Load<T>(path);
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
                }
#else
#if !UNITY_EDITOR
                replacedet = Resources.Load<T>(path);
#else
                replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
#endif
                if (replacedet == null) return null;
                replacedetData.replacedet = replacedet;
                replacedetData.types = types;
                replacedetData.name = name;
                replacedetData.suffix = suffix;
                replacedetData.isKeep = isKeep;
                replacedetData.isreplacedetBundle = isreplacedetBundle;
                replacedetDict.Add(path, replacedetData);
                return replacedetData;
            }
        }

19 Source : AssetManager.cs
with MIT License
from 404Lcc

public void Unloadreplacedet(string name, params string[] types)
        {
            string path = GetreplacedetPath(name, types);
            if (replacedetDict.ContainsKey(path))
            {
                replacedetData replacedetData = replacedetDict[path];
                Unloadreplacedet(replacedetData);
                replacedetDict.Remove(path);
            }
        }

19 Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz

public Task<AuditoriumDto> GetAuditoriumSeatingFor(string showId)
        {
            if (_repository.ContainsKey(showId))
            {
                return Task.FromResult(_repository[showId]);
            }

            return Task.FromResult(new AuditoriumDto());
        }

19 Source : ReservationsProvider.cs
with Apache License 2.0
from 42skillz

public Task<ReservedSeatsDto> GetReservedSeats(string showId)
        {
            if (_repository.ContainsKey(showId))
            {
                return Task.FromResult(_repository[showId]);
            }

            return Task.FromResult(new ReservedSeatsDto());
        }

19 Source : TrainRepository.cs
with MIT License
from 42skillz

public Train GetTrain(string trainId)
        {
            lock (this.syncRoot)
            {
                if (!_trains.ContainsKey(trainId))
                {
                    // First time, we create the train with default value
                    var train = new Train(trainId);
                    foreach (var c in "ABCDEFGHIJKL")
                    {
                        var coach = new Coach(c.ToString());

                        for (var i = 1; i < 42; i++)
                        {
                            var seat = new Seat(coach.Name, i.ToString(), string.Empty);
                            coach.Seats.Add(seat);
                        }

                        train.Add(coach);
                    }

                    _trains.Add(trainId, train);
                }
            }

            lock (this.syncRoot)
            {
                return _trains[trainId];
            }
        }

19 Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz

public AuditoriumDto GetAuditoriumLayoutFor(string showId)
        {
            if (_repository.ContainsKey(showId)) return _repository[showId];

            return new AuditoriumDto();
        }

19 Source : ReservationsProvider.cs
with Apache License 2.0
from 42skillz

public ReservedSeatsDto GetReservedSeats(string showId)
        {
            if (_repository.ContainsKey(showId)) return _repository[showId];

            return new ReservedSeatsDto();
        }

19 Source : Richtext.cs
with MIT License
from 499116344

public T Get<T>(string name, T value = default(T))
        {
            if (_data.ContainsKey(name))
            {
                return (T) _data[name];
            }

            return value;
        }

19 Source : CommandTree.cs
with MIT License
from 5minlab

private void _add(string[] commands, int command_index, CommandAttribute cmd) {
            if (commands.Length == command_index) {
                m_command = cmd;
                return;
            }

            string token = commands[command_index];
            if (!m_subcommands.ContainsKey(token)) {
                m_subcommands[token] = new CommandTree();
            }
            m_subcommands[token]._add(commands, command_index + 1, cmd);
        }

19 Source : CommandTree.cs
with MIT License
from 5minlab

public string _complete(string[] partialCommand, int index, string result) {
            if (partialCommand.Length == index && m_command != null) {
                // this is a valid command... so we do nothing
                return result;
            } else if (partialCommand.Length == index) {
                // This is valid but incomplete.. print all of the subcommands
                Shell.LogCommand(result);
                foreach (string key in m_subcommands.Keys.OrderBy(m => m)) {
                    Shell.Log(result + " " + key);
                }
                return result + " ";
            } else if (partialCommand.Length == (index + 1)) {
                string partial = partialCommand[index];
                if (m_subcommands.ContainsKey(partial)) {
                    result += partial;
                    return m_subcommands[partial]._complete(partialCommand, index + 1, result);
                }

                // Find any subcommands that match our partial command
                List<string> matches = new List<string>();
                foreach (string key in m_subcommands.Keys.OrderBy(m => m)) {
                    if (key.StartsWith(partial)) {
                        matches.Add(key);
                    }
                }

                if (matches.Count == 1) {
                    // Only one command found, log nothing and return the complete command for the user input
                    return result + matches[0] + " ";
                } else if (matches.Count > 1) {
                    // list all the options for the user and return partial
                    Shell.LogCommand(result + partial);
                    foreach (string match in matches) {
                        Shell.Log(result + match);
                    }
                }
                return result + partial;
            }

            string token = partialCommand[index];
            if (!m_subcommands.ContainsKey(token)) {
                return result;
            }
            result += token + " ";
            return m_subcommands[token]._complete(partialCommand, index + 1, result);
        }

19 Source : CommandTree.cs
with MIT License
from 5minlab

private void _run(string[] commands, int index) {
            if (commands.Length == index) {
                RunCommand(emptyArgs);
                return;
            }

            string token = commands[index].ToLower();
            if (!m_subcommands.ContainsKey(token)) {
                RunCommand(commands.Skip(index).ToArray());
                return;
            }
            m_subcommands[token]._run(commands, index + 1);
        }

19 Source : AnyDictionary.cs
with MIT License
from 5minlab

internal bool ContainsKey(string k) {
            return dict.ContainsKey(k);
        }

19 Source : SimpleJSON.cs
with MIT License
from 71

public override void Add(string aKey, JSONNode aItem)
        {
            if (aItem == null)
                aItem = JSONNull.CreateOrGet();

            if (!string.IsNullOrEmpty(aKey))
            {
                if (m_Dict.ContainsKey(aKey))
                    m_Dict[aKey] = aItem;
                else
                    m_Dict.Add(aKey, aItem);
            }
            else
                m_Dict.Add(Guid.NewGuid().ToString(), aItem);
        }

19 Source : SimpleJSON.cs
with MIT License
from 71

public override JSONNode Remove(string aKey)
        {
            if (!m_Dict.ContainsKey(aKey))
                return null;
            JSONNode tmp = m_Dict[aKey];
            m_Dict.Remove(aKey);
            return tmp;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public override void Add(string aKey, JSONNode aItem)
        {
            if (!string.IsNullOrEmpty(aKey))
            {
                if (m_Dict.ContainsKey(aKey))
                    m_Dict[aKey] = aItem;
                else
                    m_Dict.Add(aKey, aItem);
            }
            else
                m_Dict.Add(Guid.NewGuid().ToString(), aItem);
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public override JSONNode Remove(string aKey)
        {
            if (!m_Dict.ContainsKey(aKey))
                return null;
            JSONNode tmp = m_Dict[aKey];
            m_Dict.Remove(aKey);
            return tmp;        
        }

19 Source : UnityARAnchorManager.cs
with MIT License
from 734843327

public void RemoveAnchor(ARPlaneAnchor arPlaneAnchor)
		{
			if (planeAnchorMap.ContainsKey (arPlaneAnchor.identifier)) {
				ARPlaneAnchorGameObject arpag = planeAnchorMap [arPlaneAnchor.identifier];
				GameObject.Destroy (arpag.gameObject);
				planeAnchorMap.Remove (arPlaneAnchor.identifier);
			}
		}

19 Source : UnityARAnchorManager.cs
with MIT License
from 734843327

public void UpdateAnchor(ARPlaneAnchor arPlaneAnchor)
		{
			if (planeAnchorMap.ContainsKey (arPlaneAnchor.identifier)) {
				ARPlaneAnchorGameObject arpag = planeAnchorMap [arPlaneAnchor.identifier];
				UnityARUtility.UpdatePlaneWithAnchorTransform (arpag.gameObject, arPlaneAnchor);
				arpag.planeAnchor = arPlaneAnchor;
				planeAnchorMap [arPlaneAnchor.identifier] = arpag;
                bound=arpag.gameObject.GetComponentInChildren<MeshRenderer>().bounds;
			}
		}

19 Source : Object.Extension.cs
with MIT License
from 7Bytes-Studio

public static object Invoke(this object instance,string methodName,Type[] argTypes,object[] args)
        {
            if (null == instance) return null;
            var type = instance.GetType();
            var key = type.FullName + methodName;
            var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
            if (!s_MethodInfoDic.ContainsKey(key))
            {
                s_MethodInfoDic.Add(key, type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, argTypes, new ParameterModifier[] { new ParameterModifier(argTypes.Length) }));
            }
            return s_MethodInfoDic[key].Invoke(instance, args);
        }

19 Source : Object.Extension.cs
with MIT License
from 7Bytes-Studio

public static object Invoke(this object instance, string methodName, params object[] args)
        {
            if (null == instance) return null;
            var type = instance.GetType();
            var key = type.FullName + methodName;
            var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;

            if (!s_MethodInfoDic.ContainsKey(key))
            {
                s_MethodInfoDic.Add(key, type.GetMethod(methodName, bindingFlags));
            }

            return s_MethodInfoDic[key].Invoke(instance,args);
        }

19 Source : Utility.Unique.cs
with MIT License
from 7Bytes-Studio

public static int GetId(string text)
            {
                if (!s_IdDic.ContainsKey(text))
                {
                    lock (s_Lock)
                    {
                        s_IdDic.Add(text, s_CurrentId++);
                    }
                }
                return s_IdDic[text];
            }

19 Source : Event.EventTopic.partial.cs
with MIT License
from 7Bytes-Studio

public static EventTopic Create(object creator,string topicName)
            {
                if (!s_DictionaryEventTopic.ContainsKey(topicName))
                {
                    var eventTopic = new EventTopic();
                    eventTopic.Creator = creator;
                    eventTopic.UniqueTopicName = topicName;
                    eventTopic.CreateTime = DateTime.Now;
                    eventTopic.ThreadId = Thread.CurrentThread.ManagedThreadId;
                    s_DictionaryEventTopic.Add(topicName,eventTopic);
                    return eventTopic;
                }
                throw new Exception(string.Format("事件主题:{0}已经创建过了,请务重复创建。"));
            }

19 Source : Event.EventTopic.partial.cs
with MIT License
from 7Bytes-Studio

public static EventTopic GetEventTopic(string topicName)
            {
                if (s_DictionaryEventTopic.ContainsKey(topicName))
                {
                    return s_DictionaryEventTopic[topicName];
                }
                return null;
            }

19 Source : Iterator.cs
with MIT License
from 7Bytes-Studio

public static bool HasIterator(string name)
        {
            return s_Dic.ContainsKey(name);
        }

19 Source : Iterator.cs
with MIT License
from 7Bytes-Studio

public static bool Start(string name, IEnumerator enumerator)
        {
            if (!s_Dic.ContainsKey(name))
            {
                s_Dic.Add(name,enumerator);
                s_IteratorStartCallback.Invoke(name,enumerator);
                return true;
            }
            return false;
        }

19 Source : Iterator.cs
with MIT License
from 7Bytes-Studio

public static void Cancel(string name)
        {
            if (s_Dic.ContainsKey(name))
            {
                var enumerator = s_Dic[name];
                s_Dic.Remove(name);
                s_IteratorCancelCallback.Invoke(name,enumerator);
            }
        }

19 Source : RedisDb.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<Dictionary<string,T>> HashGetAll<T>(string key)
        {
            var arr = await db.HashGetAllAsync(key);
           // _logger.LogDebug($"key={key},arr={Newtonsoft.Json.JsonConvert.SerializeObject(arr)}");
            var dic = new Dictionary<string, T>();

            try
            {
                foreach (var item in arr)
                {
                    if (!item.Value.IsNullOrEmpty && !dic.ContainsKey(item.Name))
                    {
                        dic.Add(item.Name, JsonConvert.DeserializeObject<T>(item.Value));
                    }
                }
            }
            catch (Exception ex) 
            {
                _logger.LogError($"Exception={ex}");
            }

            return dic;
        }

19 Source : ConfigDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task UpdateConfigs(Dictionary<string, string> configDic, Dictionary<string, string> oldConfigDic)
        {
            var configs = GetAppConfigValue(configDic, typeof(AppConfig));
            foreach (var config in configs)
            {
                if (!oldConfigDic.ContainsKey(config.Key))
                {
                    _redisDb.HashSet("configurations", config.Key, config.Value);
                }
                else if (oldConfigDic[config.Key] != config.Value)
                {
                    _redisDb.HashSet("configurations", config.Key, config.Value);
                }
            }
            await Task.CompletedTask;
        }

19 Source : RecurringQueue.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<Dictionary<string,T>> Subscribe<T>()
        {
            var list = new Dictionary<string, T>();
            var channel = typeof(T).Name.ToLower();
            var key = $"{queueName}_{channel}";
            var dic = await _redisDb.HashGetAll<QueueData<T>>(key);
            if (dic == null || dic.Count == 0)
            {
                return default;
            }

            bool hasChange = false;
            Random rnd = new Random();
            foreach (var item in dic)
            {
                var uniqueId = item.Key;
                var itemValue = item.Value;
                if (itemValue.DelayTime.Subtract(DateTime.Now).TotalMilliseconds > 0)
                {
                    //没到时间
                    continue;
                }


                var delay = itemValue.DelayMax > itemValue.DelayMin ? rnd.Next(itemValue.DelayMin, itemValue.DelayMax) : itemValue.DelayMin;
                if (delay < 2000)
                {
                    delay = 2000;
                } 
                //下次消费时间
                itemValue.DelayTime = DateTime.Now.AddMilliseconds(delay);

                if (!list.ContainsKey(uniqueId))
                {
                    list.Add(uniqueId, itemValue.Data);
                }
                await _redisDb.HashSet(key, uniqueId, itemValue);
                hasChange = true;
            }

            if (hasChange)
            {
                await RemoveCache(channel);
            }

            return list;
        }

See More Examples