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 View Source File : HealthMonitor.cs
License : MIT License
Project Creator : 0ffffffffh

private string RebuildArgList(string argList, string extras)
        {
            if (string.IsNullOrEmpty(extras))
                return argList;

            StringBuilder sb = new StringBuilder();
            string s;
            Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
            Dictionary<string, string> extraDict = Helper.ParseOptions(extras);

            foreach (var key in extraDict.Keys)
            {
                if (eArgs.ContainsKey(key))
                {
                    eArgs[key] = extraDict[key];
                }
                else
                {
                    eArgs.Add(key, extraDict[key]);
                }
            }


            extraDict.Clear();
            extraDict = null;

            foreach (var key in eArgs.Keys)
            {
                sb.AppendFormat("{0} {1} ", key, eArgs[key]);
            }

            s = sb.ToString().TrimEnd();

            eArgs.Clear();
            eArgs = null;

            sb.Clear();
            sb = null;

            return s;
        }

19 View Source File : CacheManager.cs
License : MIT License
Project Creator : 0ffffffffh

internal static void RemoveKeysetContext(KeysetId setId)
        {
            lock (setLock)
            {
                if (CacheSetKeys.ContainsKey(setId.SetId))
                    CacheSetKeys.Remove(setId.SetId);
            }
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private void HandlePost(HttpListenerContext ctx, Dictionary<string,string> postForm)
        {
            if (postForm == null)
            {
                return;
            }

            if (postForm.ContainsKey("nick") && postForm.ContainsKey("pwd"))
            {
                HandleAddSuser(ctx, postForm["nick"], postForm["pwd"]);
            }
            else
            {
                ReplyIndex(ctx, "gerekli bir $eyler unuttun.");
            }
        }

19 View Source File : InternalTalk.cs
License : MIT License
Project Creator : 0ffffffffh

public Dictionary<string, string> Parse(byte[] data, int length)
        {
            Dictionary<string, string> talkInfo = new Dictionary<string, string>();

            string s = Encoding.ASCII.GetString(data,0,length);

            var items = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            Log.Verbose(s);
            foreach (var item in items)
            {
                var kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (!talkInfo.ContainsKey(kv[0].ToLower()))
                    talkInfo.Add(kv[0].ToLower(), kv[1]);

            }

            return talkInfo;
        }

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override string Create(string uid) {
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (global.UIDs.ContainsKey(key));
                global.UIDs[key] = uid;

                Save(uid, new PrivateUserInfo {
                    Key = key,
                    KeyFull = keyFull
                });

                SaveRaw(GlobalPath, global);

                return key;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static T GetVal<T>(Dictionary<string,string> opts, string key, T failIdent)
        {
            string v;
            if (!opts.ContainsKey(key))
            {
                return failIdent;
            }

            v = opts[key];

            try
            {
                return (T)Convert.ChangeType(v, typeof(T));
            }
            catch
            {
                return failIdent;
            }
        }

19 View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh

public bool HasItem(string key)
        {
            return items.ContainsKey(key.ToLower());
        }

19 View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade

public void Send(string text) {
            text = text?.Trim();
            if (string.IsNullOrEmpty(text))
                return;

            lock (Log) {
                if (Pending.ContainsKey(text))
                    return;
                DataChat msg = new() {
                    Player = Client.PlayerInfo,
                    Text = text
                };
                Pending[text] = msg;
                Log.Add(msg);
                LogSpecial.Add(msg);
                Client.Send(msg);
            }
        }

19 View Source File : DataContext.cs
License : MIT License
Project Creator : 0x0ade

public void RescanDataTypes(Type[] types) {
            foreach (Type type in types) {
                if (type.IsAbstract)
                    continue;

                if (typeof(DataType).IsreplacedignableFrom(type)) {
                    RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);

                    string? id = null;
                    string? source = null;
                    for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty() && source.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
                        id = parent.GetField("DataID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
                        source = parent.GetField("DataSource", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
                    }

                    if (id.IsNullOrEmpty()) {
                        Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataID");
                        continue;
                    }

                    if (source.IsNullOrEmpty()) {
                        Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but no DataSource");
                        continue;
                    }

                    if (IDToDataType.ContainsKey(id)) {
                        Logger.Log(LogLevel.WRN, "data", $"Found data type {type.FullName} but conflicting ID {id}");
                        continue;
                    }

                    Logger.Log(LogLevel.INF, "data", $"Found data type {type.FullName} with ID {id}");
                    IDToDataType[id] = type;
                    DataTypeToID[type] = id;
                    DataTypeToSource[type] = source;

                } else if (typeof(MetaType).IsreplacedignableFrom(type)) {
                    RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);

                    string? id = null;
                    for (Type parent = type; parent != typeof(object) && id.IsNullOrEmpty(); parent = parent.BaseType ?? typeof(object)) {
                        id = parent.GetField("MetaID", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as string;
                    }

                    if (id.IsNullOrEmpty()) {
                        Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but no MetaID");
                        continue;
                    }

                    if (IDToMetaType.ContainsKey(id)) {
                        Logger.Log(LogLevel.WRN, "data", $"Found meta type {type.FullName} but conflicting ID {id}");
                        continue;
                    }

                    Logger.Log(LogLevel.INF, "data", $"Found meta type {type.FullName} with ID {id}");
                    IDToMetaType[id] = type;
                    MetaTypeToID[type] = id;
                }
            }
        }

19 View Source File : TestFileSystem.cs
License : MIT License
Project Creator : 0x1000000

public bool DirectoryExists(string path)
        {
            return this._directories.ContainsKey(path);
        }

19 View Source File : TestFileSystem.cs
License : MIT License
Project Creator : 0x1000000

public bool FileExists(string path)
        {
            return this._files.ContainsKey(path);
        }

19 View Source File : GameConversationsController.cs
License : MIT License
Project Creator : 0xbustos

public void AddConversation()
        {
            PendingStatus unlockedStatus = this.model.ConversationsToAdd[0];
            this.model.ConversationsToAdd.RemoveAt( 0 );
            Dictionary<string, List<PendingStatus>> conversations = this.model.PendingConversations;
            if (!conversations.ContainsKey( unlockedStatus.ConversationName ))
            {
                conversations[unlockedStatus.ConversationName] = new List<PendingStatus>();
            }

            List<PendingStatus> pending = conversations[unlockedStatus.ConversationName];
            PendingStatus match = pending.Where( status => status.ConversationName == unlockedStatus.StatusName ).FirstOrDefault();
            if (match == null)
            {
                pending.Add( unlockedStatus );
                pending.OrderBy( status => status.Importance );
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu

public void Add(string argument, string value)
        {
            if (!_parameters.ContainsKey(argument))
                _parameters.Add(argument, new Collection<string>());

            _parameters[argument].Add(value);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu

public void AddSingle(string argument, string value)
        {
            if (!_parameters.ContainsKey(argument))
                _parameters.Add(argument, new Collection<string>());
            else
                throw new ArgumentException(string.Format("Argument {0} has already been defined", argument));

            _parameters[argument].Add(value);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return;
            }

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

            string username = "";
            string preplacedword = "";

            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Usage();
                    return;
                }
                else
                {
                    username = arguments["username"];
                    preplacedword = arguments["preplacedword"];
                }
            }
            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Usage();
                return;
            }
            if (arguments.ContainsKey("computername"))
            {
                string[] computerNames = arguments["computername"].Split(',');
                string eventName = "Debug";
                string location = "local";
                string droplocation = @"C:\Windows\Temp";
                string wnamespace = "root\\CIMv2";
                string filename = string.Empty;
                string valuename = string.Empty;
                string keypath = string.Empty;
                string clreplacedname = string.Empty;
                foreach (string computerName in computerNames)
                {
                    if (arguments.ContainsKey("eventname"))
                    {
                        eventName = arguments["eventname"];
                    }
                    if (arguments.ContainsKey("location"))
                    {
                        location = arguments["location"];
                    }
                    if (arguments.ContainsKey("droplocation"))
                    {
                        droplocation = arguments["droplocation"];
                    }
                    if (arguments.ContainsKey("filename"))
                    {
                        filename = arguments["filename"];
                    }
                    if (arguments.ContainsKey("clreplacedname"))
                    {
                        clreplacedname = arguments["clreplacedname"];
                    }
                    if (arguments.ContainsKey("keypath"))
                    {
                        keypath = arguments["keypath"];
                    }
                    if (arguments.ContainsKey("valuename"))
                    {
                        valuename = arguments["valuename"];
                    }
                    if (arguments.ContainsKey("wminamespace"))
                    {
                        wnamespace = arguments["wminamespace"];
                    }

                    if (arguments.ContainsKey("writetype"))
                    {
                        if (arguments["writetype"].ToLower() == "wmi")
                        {
                            GetFileContent(location, droplocation, filename, "flat");
                            WriteToFileWMI(computerName, eventName, username, preplacedword);
                        }
                        else if (arguments["writetype"].ToLower() == "smb")
                        {
                            WriteToFileSMB(computerName, droplocation, filename, location);
                        }
                        else if(arguments["writetype"].ToLower() == "registry")
                        {
                            if (valuename == string.Empty)
                            {
                                Console.WriteLine("[-] Valuename is required");
                                return;
                            }
                            GetFileContent(location, droplocation, filename, "nonflat");
                            WriteToRegKey(computerName, username, preplacedword, keypath, valuename);
                        }
                        else if (arguments["writetype"].ToLower() == "wmiclreplaced")
                        {
                            GetFileContent(location, droplocation, filename, "nonflat");
                            WriteToWMIClreplaced(computerName, username, preplacedword, wnamespace, clreplacedname);
                        }
                        else if (arguments["writetype"].ToLower() == "removewmiclreplaced")
                        {
                            RemoveWMIClreplaced(computerName, username, preplacedword, wnamespace, clreplacedname);
                        }
                        else if (arguments["writetype"].ToLower() == "removeregkey")
                        {
                            RemoveRegValue(computerName, username, preplacedword, keypath, valuename);
                        }
                        else
                        {
                            Usage();
                            return;
                        }
                    }
                    else
                    {
                        Usage();
                    }
                }
            }
            else
            {
                Usage();
                return;
            }
        }

19 View Source File : ExcelDCOM.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

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

            if(!arguments.ContainsKey("computername"))
            {
                Console.WriteLine("[-] Error: computername arg is required");
                return;
            }
            else
            {
                string arch = "x86";
                string target = arguments["computername"];
                if (arguments.ContainsKey("arch"))
                {
                    if(arguments["arch"].ToLower() == "x64" || arguments["arch"] == "64")
                    {
                        arch = "x64";
                    }
                }
                ExecExcelDCOM(target, arch);
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

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

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

19 View Source File : UserServiceTable.cs
License : Apache License 2.0
Project Creator : 0xFireball

public UserServices GetOrCreate(string username)
        {
            lock (ServiceTable)
            {
                if (ServiceTable.ContainsKey(username))
                {
                    return ServiceTable[username];
                }
                var ret = new UserServices(username, ServerContext.Configuration.UserMaxConcurrentUploads);
                ServiceTable[username] = ret;
                return ret;
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                HowTo();
                return;
            }
            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            if (arguments.ContainsKey("command"))
            {
                CleanSingle(arguments["command"]);
            }
            else if (args[0].ToLower() == "clearall")
            {
                Clereplacedl();
            }
            else if (args[0].ToLower() == "query")
            {
                QueryReg();
            }
            else
            {
                HowTo();
                return;
            }
        }

19 View Source File : CacheBuilder.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

public static Texture2D Get(string key) {
            if (builtBytes.ContainsKey(key)) {
                var text = LoadTextureFromBytes(builtBytes[key]);
                return text;
            }

            var bytes = Convert.FromBase64String(built[key]);
            builtBytes.Add(key, bytes);
            var textNew = LoadTextureFromBytes(Convert.FromBase64String(built[key]));
            return textNew;
        }

19 View Source File : GodTier.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

[HarmonyPostfix]
                internal static void fix(ref UpgradeButton __instance) {
                    if (__instance == null) return;
                    if (__instance.upgradeStatus != UpgradeButton.UpgradeStatus.Purchasable) {
                        __instance.purchaseArrowGlow.active = false;
                        __instance.backgroundActive = new("Ui[GreenArrowBtn]");
                        __instance.background.overrideSprite = null;
                    }
                    if (__instance.upgrade == null) return;
                    if (__instance.upgrade.name == null) return;
                    __instance.purchaseArrowGlow.active = CustomUpgrades.ContainsKey(__instance.upgrade.name);
                    if (CustomUpgrades.ContainsKey(__instance.upgrade.name)) {
                        string resourceName = "";
                        Sprite resourceSprite = null;
                        switch (CustomUpgrades[__instance.upgrade.name]) {
                            case UpgradeBG.AntiVenom: {
                                    resourceName = "AntiVenomUBG";
                                    resourceSprite = LoadSprite(LoadTextureFromBytes(GodlyTowers.Properties.Resources.AVenomUBG));
                                    break;
                                }
                            case UpgradeBG.MiniPekka: {
                                    resourceName = "MiniPekkaUBG";
                                    resourceSprite = LoadSprite(LoadTextureFromBytes(GodlyTowers.Properties.Resources.MPUBG));
                                    break;
                                }
                        }
                        __instance.backgroundActive = new(resourceName);
                        __instance.background.overrideSprite = resourceSprite;
                    } else {
                        __instance.backgroundActive = new("Ui[GreenArrowBtn]");
                        __instance.background.overrideSprite = null;
                    }

                    return;
                }

19 View Source File : ImageLoading.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

public static Sprite LoadSpriteFromPNG(String identifier, byte[] encoded, float PixelsPerUnit = 100.0f,
            SpriteMeshType spriteType = SpriteMeshType.Tight, uint extrude = 0, Vector2 pivot = default) {
            if (cachedSprites.ContainsKey(identifier))
                return cachedSprites[identifier];

            try {
                var SpriteTexture = LoadTextureFromBytes(encoded);
                var s = Sprite.Create(SpriteTexture, new(0, 0, SpriteTexture.width, SpriteTexture.height), pivot, PixelsPerUnit, extrude, spriteType);
                return s;
            } catch (Exception) {
                throw spriteCantBeCreatedException;
            }
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ReplaceVariable(Dictionary<string, string> variables, string text)
        {
            var matches = Regex.Matches(text, @"\${(?<key>.*?)}");
            foreach (Match item in matches)
            {
                var key = item.Groups["key"].Value;
                if (variables.ContainsKey(key))
                {
                    var value = variables[key];
                    text = text.Replace("${" + key + "}", value);
                }
            }
            return Regex.Replace(text, @"\s+", " ").Trim(' ');
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public string Build<T>(string id, T parameter) where T : clreplaced
        {
            if (!_commands.ContainsKey(id))
            {
                return null;
            }
            var cmd = _commands[id];
            return cmd.Resolve(cmd, parameter);
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Resolve(XmlDoreplacedent doreplacedent)
        {
            if (doreplacedent.DoreplacedentElement.Name != "commands")
            {
                return;
            }
            lock (this)
            {
                var @namespace = doreplacedent.DoreplacedentElement
                    .GetAttribute("namespace") ?? string.Empty;
                //解析全局变量
                var globalVariables = ResolveVariables(doreplacedent.DoreplacedentElement);
                //获取命令节点
                var elements = doreplacedent.DoreplacedentElement
                    .Cast<XmlNode>()
                    .Where(a => a.Name != "var" && a is XmlElement);
                foreach (XmlElement item in elements)
                {
                    var id = item.GetAttribute("id");
                    id = string.IsNullOrEmpty(@namespace) ? $"{id}" : $"{@namespace}.{id}";
                    //解析局部变量
                    var localVariables = ResolveVariables(item);
                    //合并局部和全局变量,局部变量可以覆盖全局变量
                    var variables = new Dictionary<string, string>(globalVariables);
                    foreach (var ariable in localVariables)
                    {
                        if (variables.ContainsKey(ariable.Key))
                        {
                            variables[ariable.Key] = ariable.Value;
                        }
                        else
                        {
                            variables.Add(ariable.Key, ariable.Value);
                        }
                    }
                    //替换变量
                    var xml = ReplaceVariable(variables, item.OuterXml);
                    var doc = new XmlDoreplacedent();
                    doc.LoadXml(xml);
                    //通过变量解析命令
                    var cmd = ResolveCommand(doc.DoreplacedentElement);
                    if (_commands.ContainsKey(id))
                    {
                        _commands[id] = cmd;
                    }
                    else
                    {
                        _commands.Add(id, cmd);
                    }
                }
            }
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private void ResovleParameter(T enreplacedy)
        {
            var serializer = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(typeof(T));
            var values = serializer(enreplacedy);
            foreach (var item in values)
            {
                if (_parameters.ContainsKey(item.Key))
                {
                    _parameters[item.Key] = item.Value;
                }
                else
                {
                    _parameters.Add(item.Key, item.Value);
                }
            }
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResovleInsert(bool idenreplacedy)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .Where(a => !a.IsComplexType)
                .Where(a => !a.IsDefault || (_parameters.ContainsKey(a.CsharpName) && _parameters[a.CsharpName] != null));//如果是默认字段
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            var parameterNames = string.Join(",", intcolumns.Select(s => $"@{s.CsharpName}"));
            var sql = $"INSERT INTO {table}({columnNames}) VALUES ({parameterNames})";
            if (idenreplacedy)
            {
                sql = $"{sql};SELECT @@IDENreplacedY";
            }
            return sql;
        }

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

private Expression CreateExpression(ParameterExpression parameter, string expression)
        {
            var expressions1 = Factorization(expression);
            var expressions2 = new Dictionary<string, Expression>();
            foreach (var item in expressions1)
            {
                var subexpr = item.Value.Trim('(', ')');
                var @opterator = ResovleOperator(item.Value);
                var opt = GetExpressionType(@opterator);
                if (opt == ExpressionType.Not)
                {
                    Expression exp;
                    var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                    if (expressions2.ContainsKey(text))
                    {
                        exp = expressions2[text];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text))
                    {
                        var property = parameter.Type.GetProperty(text);
                        exp = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp = Expression.Constant(Convert.ToBoolean(text));
                    }
                    expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
                }
                else
                {
                    var text1 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
                        .Trim();
                    var text2 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
                        .Trim();
                    string temp = null;
                    Expression exp1, exp2;
                    //永远将变量放在第一个操作数
                    if (parameter.Type.GetProperties().Any(a => a.Name == text2))
                    {
                        temp = text1;
                        text1 = text2;
                        text2 = temp;
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text1))
                    {
                        exp1 = expressions2[text1];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        //是否为变量
                        var property = parameter.Type.GetProperty(text1);
                        exp1 = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp1 = ResovleConstantExpression(text1);
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text2))
                    {
                        exp2 = expressions2[text2];
                    }
                    //如果第一个操作数是变量
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        var constantType = parameter.Type.GetProperty(text1).PropertyType;
                        exp2 = ResovleConstantExpression(text2, constantType);
                    }
                    else
                    {
                        exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
                    }
                    expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
                }
            }
            return expressions2.Last().Value;
        }

19 View Source File : XmlQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

public void AddDbParameter(string name,object value)
        {
            if (_parameters == null)
            {
                _parameters = new Dictionary<string, object>();
            }
            if (_parameters.ContainsKey(name))
            {
                _parameters[name] = value;
            }
            else
            {
                _parameters.Add(name,value);
            }
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Resolve(XmlDoreplacedent doreplacedent)
        {
            if (doreplacedent.DoreplacedentElement.Name != "commands")
            {
                return;
            }
            lock (this)
            {
                var @namespace = doreplacedent.DoreplacedentElement
                    .GetAttribute("namespace") ?? string.Empty;
                //解析全局变量
                var globalVariables = ResolveVariables(doreplacedent.DoreplacedentElement);
                //获取命令节点
                var elements = doreplacedent.DoreplacedentElement
                    .Cast<XmlNode>()
                    .Where(a => a.Name != "var" && a is XmlElement);
                foreach (XmlElement item in elements)
                {
                    var id = item.GetAttribute("id");
                    id = string.IsNullOrEmpty(@namespace) ? $"{id}" : $"{@namespace}.{id}";
                    //解析局部变量
                    var localVariables = ResolveVariables(item);
                    //合并局部和全局变量,局部变量可以覆盖全局变量
                    var variables = new Dictionary<string, string>(globalVariables);
                    foreach (var ariable in localVariables)
                    {
                        if (variables.ContainsKey(ariable.Key))
                        {
                            variables[ariable.Key] = ariable.Value;
                        }
                        else
                        {
                            variables.Add(ariable.Key, ariable.Value);
                        }
                    }
                    //替换变量
                    var xml = ReplaceVariable(variables, item.OuterXml);
                    var doc = new XmlDoreplacedent();
                    doc.LoadXml(xml);
                    //通过变量解析命令
                    var cmd = ResolveCommand(doc.DoreplacedentElement);
                    if (_commands.ContainsKey(id))
                    {
                        _commands[id] = cmd;
                    }
                    else
                    {
                        _commands.Add(id, cmd);
                    }
                }
            }
        }

19 View Source File : RouteAnalyzer.cs
License : MIT License
Project Creator : 188867052

private string ConvertType(string type)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>()
            {
                { typeof(object).FullName, "object" },
                { typeof(object[]).FullName, "object[]" },
                { typeof(int).FullName, "int" },
                { typeof(int[]).FullName, "int[]" },
                { typeof(int?).FullName, "int?" },
                { typeof(decimal).FullName, "decimal" },
                { typeof(decimal[]).FullName, "decimal[]" },
                { typeof(decimal?).FullName, "decimal?" },
                { typeof(byte).FullName, "byte" },
                { typeof(byte[]).FullName, "byte[]" },
                { typeof(byte?).FullName, "byte?" },
                { typeof(bool).FullName, "bool" },
                { typeof(bool[]).FullName, "bool[]" },
                { typeof(bool?).FullName, "bool?" },
                { typeof(string).FullName, "string" },
                { typeof(string[]).FullName, "string[]" },
                { typeof(DateTime).FullName, "DateTime" },
                { typeof(DateTime[]).FullName, "DateTime[]" },
                { typeof(DateTime?).FullName, "DateTime?" },
            };

            if (dictionary.ContainsKey(type))
            {
                return dictionary[type];
            }

            return type;
        }

19 View Source File : KeysUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static String getKeyChar(int keyValue, bool shift = false)
        {
            string chars = "";
            string c = "k" + keyValue;
            bool caps = Win32.CapsLockStatus;
            if(caps || shift){
                c = "k" + keyValue;
            }
            if (KEY_DICT.ContainsKey(c))
            {
                chars = KEY_DICT[c];
            }
            return chars;
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void TransfersFileProgress(string id, long precent, long c, long max, int elapsed)
        {
            try
            {
                int start = 0, end = Convert.ToInt32(DateTime.Now.ToString("ffff"));
                if(TIMEDIC.ContainsKey(id)){
                    start = TIMEDIC[id];
                    TIMEDIC[id] = end;
                } else {
                    TIMEDIC.Add(id, end);
                }
                long startByte = 0, endByte = c;
                if (BYTEDIC.ContainsKey(id))
                {
                    startByte = BYTEDIC[id];
                    BYTEDIC[id] = endByte;
                } else {
                    BYTEDIC.Add(id, endByte);
                }
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    TransferItem obj = null;
                    foreach (ListViewItem item in listView3.Items)
                    {
                        if (item.Name == id)
                        {
                            obj = (TransferItem)item.Tag;
                        
                            obj.Progress = precent;
                            item.SubItems[1].Text = TransferStatus.Transfers.ToString();
                            item.SubItems[2].Text = precent + "%";
                            item.SubItems[6].Text = Utils.CalculaSpeed(startByte, endByte, max, start, end);
                            item.SubItems[7].Text = Utils.CalculaTimeLeft(startByte, endByte, max, start, end);
                            break;
                        }
                    }
                });
            }
            catch(Exception ex) {
                logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
                ChangeTransferItemStatus("R2L", id, TransferStatus.Failed);
            }
            
        }

19 View Source File : AssemblyHelper.cs
License : MIT License
Project Creator : 279328316

public static replacedemblyNoteModel GetreplacedemblyNote(string xmlFilePath)
        {
            if (filereplacedemblyDic.ContainsKey(xmlFilePath))
            {
                return filereplacedemblyDic[xmlFilePath];
            }
            FileInfo fileInfo = new FileInfo(xmlFilePath);
            if (!File.Exists(xmlFilePath))
            {
                return null;
            }
            replacedemblyNoteModel replacedemblyNoteModel = null;
            lock (filereplacedemblyDic)
            {
                if (filereplacedemblyDic.ContainsKey(xmlFilePath))
                {
                    return filereplacedemblyDic[xmlFilePath];
                }

                XmlHelper xmlHelper = new XmlHelper(xmlFilePath);
                replacedemblyNoteModel = xmlHelper.DeserializeNode<replacedemblyNoteModel>("replacedembly");
                replacedemblyNoteModel.ModuleName = fileInfo.Name.Replace(".xml", ".dll");

                XmlNode memberListNode = xmlHelper.GetNode("members");
                XmlNode memberNode = memberListNode.FirstChild;
                while (memberNode != null)
                {
                    MemberNoteModel memberModel = GetMember(memberNode);
                    replacedemblyNoteModel.MemberList.Add(memberModel);
                    memberNode = memberNode.NextSibling;
                }
                if (!filereplacedemblyDic.ContainsKey(xmlFilePath))
                {
                    filereplacedemblyDic.Add(xmlFilePath, replacedemblyNoteModel);
                }
            }
            return replacedemblyNoteModel;
        }

19 View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = listView1.SelectedItems[0];
                foreach (ListViewItem item2 in listView1.Items)
                {
                    item2.ForeColor = Color.Black;
                }
                item.ForeColor = Color.Red;

                YmlFile file = (YmlFile)item.Tag;
                string path = file.localPath + file.localName;
                string content = YSTools.YSFile.readFileToString(path);
                if ((file.remotePath + file.remoteName) == "")
                {
                    file_label.Text = file.localPath + file.localName;
                }
                else
                {
                    file_label.Text = file.remotePath + file.remoteName;
                }                

                // 渲染
                if (tabControl1.SelectedIndex == 0)
                {
                    if (resContent != content || _treeView.Items.Count == 0)
                    {
                        resContent = content;
                        btn_save.Enabled = false;
                        btn_tree.Text = "展开全部节点";

                        // 树形
                        _treeView.Items.Clear();
                        List<YmlItem> lists = YmlFormatUtil.FormatYmlToTree(content);
                        TreeListViewItem viewItem = null, parenreplacedem = null;
                        Dictionary<string, TreeListViewItem> _cache = new Dictionary<string, TreeListViewItem>();
                        foreach (YmlItem obj in lists)
                        {
                            viewItem = new TreeListViewItem();
                            viewItem.Tag = obj;
                            viewItem.Text = obj.Key;
                            viewItem.ImageIndex = obj.ImageIndex;

                            viewItem.SubItems.Add(obj.Value);
                            viewItem.SubItems.Add("" + obj.Level);
                            viewItem.SubItems.Add(obj.Common);

                            if (obj.Level == 0)
                            {
                                _treeView.Items.Add(viewItem);
                            }
                            else if (_cache.ContainsKey(obj.Parent.Uuid))
                            {
                                parenreplacedem = _cache[obj.Parent.Uuid];
                                if (null != parenreplacedem)
                                {
                                    parenreplacedem.Items.Add(viewItem);
                                }
                            }
                            else
                            {
                                _treeView.Items.Add(viewItem);
                            }

                            _cache.Add(obj.Uuid, viewItem);
                        }

                        Validate(item, content);
                    }                   

                }
                else
                {
                    if (resContent != content || ymlEditor.Text == "")
                    {
                        // YML编辑器
                        ymlEditor.Text = "";
                        List<YmlLine> list = YmlFormatUtil.FormatYml(content);
                        foreach (YmlLine line in list)
                        {
                            ymlEditor.SelectionColor = line.Color;
                            ymlEditor.SelectionFont = line.Font;
                            ymlEditor.AppendText(line.Text);
                        }

                        ymlEditor.ClearUndo();

                        Validate(item, content);
                    }
                }

            }
        }

19 View Source File : YmlNodeForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void RenderTree()
        {
            // 树形
            _treeView.Items.Clear();
            TreeListViewItem viewItem = null, parenreplacedem = null;
            Dictionary<string, TreeListViewItem> _cache = new Dictionary<string, TreeListViewItem>();
            foreach (YmlItem obj in lists)
            {
                if (obj.ImageIndex == 1 || obj.ImageIndex == 2)
                {
                    continue;
                }
                viewItem = new TreeListViewItem();
                viewItem.Tag = obj;
                viewItem.Text = obj.Key;
                viewItem.ImageIndex = obj.ImageIndex;

                viewItem.SubItems.Add(obj.Value);

                if (obj.Level == 0)
                {
                    _treeView.Items.Add(viewItem);
                }
                else if (_cache.ContainsKey(obj.Parent.Uuid))
                {
                    parenreplacedem = _cache[obj.Parent.Uuid];
                    if (null != parenreplacedem)
                    {
                        parenreplacedem.Items.Add(viewItem);
                    }
                }
                else
                {
                    _treeView.Items.Add(viewItem);
                }

                _cache.Add(obj.Uuid, viewItem);
            }
            _treeView.ExpandAll();
        }

19 View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316

public static PTypeModel GetPTypeModel(string typeId)
        {
            PTypeModel ptype = null;
            if (PTypeDic.ContainsKey(typeId))
            {
                PTypeModel sourcePType = PTypeDic[typeId];
                SetPTypeNote(sourcePType);

                //new 新对象,因为属性列表需要过滤 IsJsonIgnore != true
                ptype = new PTypeModel() {
                    Id = sourcePType.Id,
                    TypeName = sourcePType.TypeName,
                    Summary = sourcePType.Summary,
                    SourceType = sourcePType.SourceType,
                    IsIEnumerable = sourcePType.IsIEnumerable,
                    EnumItemId = sourcePType.EnumItemId,
                    EnumItemName = sourcePType.EnumItemName,
                    PiList = sourcePType.PiList?.Where(pi => pi.IsJsonIgnore != true).ToList()
                };
            }
            return ptype;
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public 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.IsNullOrWhiteSpace(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 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
    {
        var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
        var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
        foreach (var field in fields)
        {
            if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
            else dict.Add(field.Name, field);
        }
        return dict;
    });

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

void EditTemplates(bool replaced)
        {

            string path = string.Empty;
            var form = new FrmRazorTemplates(replaced);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (pairs.ContainsKey(form.TemplatesName))
                {
                    var item = superTabControl1.Tabs.Cast<SuperTabItem>()
                        .Where(a => a.Text == form.TemplatesName).FirstOrDefault();
                    superTabControl1.SelectedTab = item;
                    return;
                }
                var superItem = superTabControl1.CreateTab(form.TemplatesName);
                var ucEditor = new UCEditor(form.TemplatesPath);
                pairs.Add(form.TemplatesName, ucEditor);
                superTabControl1.SelectedTab = superItem;
                ucEditor.Dock = DockStyle.Fill;
                superTabControl1.SelectedPanel.Controls.Add(ucEditor);
            }
        }

19 View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099

[JSFunction]
        public async Task CodeGenerate(string id)
        {
            if (stateKeyValues.ContainsKey(id))
            {
                InvokeJS("Helper.ui.message.error('当前任务未结束,请稍后再试.');");
            }
            else
            {
                if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
                {
                    stateKeyValues.Add(id, true);
                    var model = Curd.TaskBuild.Select.WhereDynamic(gid)
                       .LeftJoin(a => a.Templates.Id == a.TemplatesId)
                       .IncludeMany(a => a.TaskBuildInfos, b => b.Include(p => p.DataBaseConfig))
                       .ToOne();
                    var res = await new CodeGenerate().Setup(model);
                    InvokeJS($"Helper.ui.message.info('[{model.TaskName}]{res}');");
                    stateKeyValues.Remove(id);
                }
                else
                {
                    InvokeJS("Helper.ui.alert.error('生成失败','参数不是有效的.');");
                }

            }
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToInterface(this MethodInfo method, bool isAlign = true)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            //if (method.IsPublic) sb.Append("public ");
            //if (method.Isreplacedembly) sb.Append("internal ");
            //if (method.IsFamily) sb.Append("protected ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsStatic) sb.Append("static ");
            //if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            //if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            if (isAlign)
                sb.Append("        ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");

            if (isAlign)
                sb.Append(";\r\n\r\n");

            return sb.ToString();
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToProxy(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            var isResult = false;

            if (isAsync)
            {
                sb.AppendLine($"            await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isAsync)
            {
                sb.AppendLine($"            await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.After(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

public TemplateReturnInfo RenderFile2(StringBuilder sb, IDictionary options, string filename, string refererFilename) {
			if (filename[0] == '/' || string.IsNullOrEmpty(refererFilename)) refererFilename = _viewDir;
			//else refererFilename = Path.GetDirectoryName(refererFilename);
			string filename2 = Utils.TranslateUrl(filename, refererFilename);
			Console.WriteLine(filename2);
			ITemplateOutput tpl;
			if (_cache.TryGetValue(filename2, out tpl) == false) {
				string tplcode = File.Exists(filename2) == false ? string.Concat("文件不存在 ", filename) : Utils.ReadTextFile(filename2);
				tpl = Parser(tplcode, _usings, options);
				lock (_cache_lock) {
					if (_cache.ContainsKey(filename2) == false) {
						_cache.Add(filename2, tpl);
					}
				}
			}
			try {
				return tpl.OuTpUt(sb, options, filename2, this);
			} catch (Exception ex) {
				TemplateReturnInfo ret = sb == null ?
					new TemplateReturnInfo { Sb = new StringBuilder(), Blocks = new Dictionary<string, int[]>() } :
					new TemplateReturnInfo { Sb = sb, Blocks = new Dictionary<string, int[]>() };
				ret.Sb.Append(refererFilename);
				ret.Sb.Append(" -> ");
				ret.Sb.Append(filename);
				ret.Sb.Append("\r\n");
				ret.Sb.Append(ex.Message);
				ret.Sb.Append("\r\n");
				ret.Sb.Append(ex.StackTrace);
				return ret;
			}
		}

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

static string DisplayCsharp(this MethodInfo method, bool isOverride)
    {
        if (method == null) return null;
        var sb = new StringBuilder();
        if (method.IsPublic) sb.Append("public ");
        if (method.Isreplacedembly) sb.Append("internal ");
        if (method.IsFamily) sb.Append("protected ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsStatic) sb.Append("static ");
        if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
        if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
        sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

        var genericParameters = method.GetGenericArguments();
        if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
        {
            var dic = genericParameters.ToDictionary(a => a.Name);
            foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                if (dic.ContainsKey(nestedGenericParameter.Name))
                    dic.Remove(nestedGenericParameter.Name);
            genericParameters = dic.Values.ToArray();
        }
        if (genericParameters.Any())
            sb.Append("<")
                .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                .Append(">");

        sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
        return sb.ToString();
    }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static Dictionary<string, T> MapToHash<T>(this object[] list, Encoding encoding)
    {
        if (list == null) return null;
        if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even");
        var dic = new Dictionary<string, T>();
        for (var a = 0; a < list.Length; a += 2)
        {
            var key = list[a].ToInvariantCultureToString();
            if (dic.ContainsKey(key)) continue;
            var val = list[a + 1];
            if (val == null) dic.Add(key, default(T));
            else dic.Add(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding));
        }
        return dic;
    }

19 View Source File : DynamicProxyExtensions.cs
License : MIT License
Project Creator : 2881099

internal static string DisplayCsharp(this MethodInfo method, bool isOverride)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            if (method.IsPublic) sb.Append("public ");
            if (method.Isreplacedembly) sb.Append("internal ");
            if (method.IsFamily) sb.Append("protected ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsStatic) sb.Append("static ");
            if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
            return sb.ToString();
        }

19 View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099

public void SendMessage(Guid senderClientId, IEnumerable<Guid> receiveClientId, object message, bool receipt = false)
    {
        receiveClientId = receiveClientId.Distinct().ToArray();
        Dictionary<string, ImSendEventArgs> redata = new Dictionary<string, ImSendEventArgs>();

        foreach (var uid in receiveClientId)
        {
            string server = SelectServer(uid);
            if (redata.ContainsKey(server) == false) redata.Add(server, new ImSendEventArgs(server, senderClientId, message, receipt));
            redata[server].ReceiveClientId.Add(uid);
        }
        var messageJson = JsonConvert.SerializeObject(message);
        foreach (var sendArgs in redata.Values)
        {
            OnSend?.Invoke(this, sendArgs);
            _redis.Publish($"{_redisPrefix}Server{sendArgs.Server}",
                JsonConvert.SerializeObject((senderClientId, sendArgs.ReceiveClientId, messageJson, sendArgs.Receipt)));
        }
    }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToMethod(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public static ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            var isResult = false;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 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.IsNullOrWhiteSpace(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();
    }

See More Examples