string.Trim()

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

15004 Examples 7

19 View Source File : MessageController.cs
License : Apache License 2.0
Project Creator : 0nise

public static MessageModel main(String message,string fromQQ) {
            string resultContent = "\n无数据";
            string content = message;
            MessageModel messageModel = null;
            if (message == null || message == "" || message.Length == 0)
            {
                messageModel = new MessageModel(sendMessage: MessageConstant.HELP_CONTENT, isAdmin: false, code: "");
                return messageModel;
            }
            resultContent = "\n无数据";
            message = executeCodeReplace(message);
            message = message.Trim();
            if (message.Length == 0 || message == "")
            {
                messageModel = new MessageModel(sendMessage: MessageConstant.HELP_CONTENT, isAdmin: false, code: "");
                return messageModel;
            }
            else if (message.Contains(MessageConstant.RANDOM_CONTENT_replacedLE)) {
                // 标题查询随机文章
                message = message.Replace(MessageConstant.RANDOM_CONTENT_replacedLE, "").Trim();
                resultContent = DBHelperMySQL.GetContentRandomByreplacedle(message);
                // 标题查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_CONTENT_replacedLE);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_replacedLE)) {
                // 标题查询最新文章
                message = message.Replace(MessageConstant.DESC_CONTENT_replacedLE, "").Trim();
                string clreplacedContent = "";
                if (message.Length == 0 || message == "" || "".Equals(message) || message == null)
                {
                    // 调用每日最新
                    resultContent = DBHelperMySQL.getContentDateByToday();
                    // 标题查询最新课程
                    clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle("");
                }
                else
                {
                    resultContent = DBHelperMySQL.getContentDateByreplacedle(message);
                    clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle(message);
                }
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_replacedLE);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_AUTHOR)) {
                // 作者查询最新文章
                message = message.Replace(MessageConstant.DESC_CONTENT_AUTHOR, "").Trim();
                resultContent = DBHelperMySQL.getContentDateByAuthor(message);
                // 作者查询最新课程
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByAuthor(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_AUTHOR);
            } else if (message.Contains(MessageConstant.RANDOM_CONTENT_AUTHOR)) {
                // 作者查询随机文章
                message = message.Replace(MessageConstant.RANDOM_CONTENT_AUTHOR, "").Trim();
                resultContent = DBHelperMySQL.getContentRandomByAuthor(message);
                // 作者查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByAuthor(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_CONTENT_AUTHOR);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_TODAY) || message.Contains(MessageConstant.DESC_CONTENT))
            {
                // 今日最新
                message = message.Replace(MessageConstant.DESC_CONTENT_TODAY, "").Trim();
                resultContent = DBHelperMySQL.getContentDateByToday();
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle("");
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_TODAY);
            } else if (message.Contains(MessageConstant.GONG_GAO)) {
                // 公告处理
                bool flag = DBHelperMySQL.isAdmin(fromQQ);
                // 判断是否管理员
                if (flag) {
                    message = message.Replace(MessageConstant.GONG_GAO, "来自i春秋机器人的智能推送\n");
                    resultContent = message;
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: true, code: MessageConstant.GONG_GAO);
                }
                else {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.GONG_GAO);
                }
            }
            else if (message.Contains(MessageConstant.AITE_ALL))
            {
                // 艾特全体处理
                bool flag = DBHelperMySQL.isAdmin(fromQQ);
                if (flag)
                {
                    message = message.Replace(MessageConstant.AITE_ALL, "来自i春秋机器人的智能推送\n");
                    resultContent = message;
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: true, code: MessageConstant.AITE_ALL);
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.AITE_ALL);
                }
            }
            else if (message.Contains(MessageConstant.HELP) || message.Contains(MessageConstant.HELP_TWO))
            {
                // Help 帮助等指令
                resultContent = MessageConstant.HELP_CONTENT;
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HELP_TWO);
            } else if (message.Contains(MessageConstant.DESC_VIDEO)) {
                // 标题查询最新教程
                message = message.Replace(MessageConstant.DESC_VIDEO, "").Trim();
                resultContent = DBHelperMySQL.getCourseDateByreplacedle(message);
                // 标题查询最新课程
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_VIDEO);
            }
            else if (message.Contains(MessageConstant.RANDOM_VIDEO))
            {
                // 标题查询随机教程
                message = message.Replace(MessageConstant.RANDOM_VIDEO, "").Trim();
                resultContent = DBHelperMySQL.getCourseRandomByreplacedle(message);
                // 标题查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_VIDEO);
            }
            else if (message.Contains(MessageConstant.TEST))
            {
                // 测试命令
                resultContent = " [CQ:image,file=photo.jpg]";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.TEST);
            } else if (message.Contains(MessageConstant.SELECT_MONEY)) {
                string tmpStr = message.Replace(MessageConstant.SELECT_MONEY, "").Trim();
                // 判断是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                string money = "";
                if (tmpStr.Length > 0 && isAdmin)
                {
                    // 查询余额
                    money = DBHelperMySQL.getBlankMoney(tmpStr);
                }
                else
                {
                    // 查询余额
                    money = DBHelperMySQL.getBlankMoney(fromQQ);
                }
                if (money == "" || money == null || money.Length == 0)
                {
                    resultContent = "没有数据,请联系QQ:758841765 给予昵称QQ等信息。";
                }
                else
                {
                    resultContent = "\n当前余额为 " + money;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.SELECT_MONEY);
            }
            else if (message.Contains(MessageConstant.HISTORY_MONEY))
            {
                // 提现记录
                string historyMoney = DBHelperMySQL.getBlankHistory(fromQQ);
                // 查询当前余额
                string money = DBHelperMySQL.getBlankMoney(fromQQ);
                if (money == "" || money == null || money.Length == 0) {
                    resultContent = "没有数据,请联系QQ:758841765 给予昵称QQ等信息。";
                }
                else {
                    resultContent = "\n当前余额为 " + money + "\n";
                    // 查询历史记录
                    resultContent += "提现记录\n";
                    resultContent += "金额\t\t时间\n" + historyMoney;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HISTORY_MONEY);
            }
            else if (message.Contains(MessageConstant.APPLY_MONEY))
            {
                // 申请提现
                resultContent = "请联系【坏蛋】,QQ号:286894635。\n[CQ:at,qq=286894635]";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.APPLY_MONEY);
            } else if (message.Contains(MessageConstant.ABOUT)) {
                resultContent = "i春秋社区机器人,研发人员为:0nise,产品设计为:坏蛋!";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.ABOUT);
            } else if (message.Contains(MessageConstant.UPDATE_MONEY)) {
                // 更新金额
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin) {
                    try
                    {
                        decimal tmpMoney = 0.0M;
                        // 提现
                        if (message.Contains(MessageConstant.PUT_FORWARD))
                        {
                            int moneyIndex = message.IndexOf(MessageConstant.PUT_FORWARD + ":");
                            int index = message.IndexOf(MessageConstant.UPDATE_MONEY);
                            if (moneyIndex >= 0 && index >= 0)
                            {
                                decimal money = Convert.ToDecimal(message.Substring(moneyIndex).Replace("提现:", "").Replace(" ", ""));
                                if (money > tmpMoney)
                                {
                                    string qq = message.Replace(message.Substring(moneyIndex), "").Replace(MessageConstant.UPDATE_MONEY, "").Replace(" ", "");
                                    resultContent = DBHelperMySQL.updateBlank(qq, money,"0");
                                }
                                else
                                {
                                    resultContent = "提现金额必须大于0!";
                                }
                            }
                        }
                        // 加钱
                        else if (message.Contains(MessageConstant.ADD_MONEY))
                        {
                            int moneyIndex = message.IndexOf(MessageConstant.ADD_MONEY + ":");
                            int index = message.IndexOf(MessageConstant.ADD_MONEY);
                            if (moneyIndex >= 0 && index >= 0)
                            {
                                decimal money = Convert.ToDecimal(message.Substring(moneyIndex).Replace("加钱:", "").Replace(" ", ""));
                                if (money > tmpMoney)
                                {
                                    string qq = message.Replace(message.Substring(moneyIndex), "").Replace(MessageConstant.UPDATE_MONEY, "").Replace(" ", "");
                                    resultContent = DBHelperMySQL.updateBlank(qq, money,"1");
                                }
                                else
                                {
                                    resultContent = "加钱金额必须大于0!";
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        resultContent = "更新失败。";
                    }
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.UPDATE_MONEY);
            }
            else if (message.Contains(MessageConstant.TODAY_COUNT))
            {
                // 今日使用数量
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    int count = DBHelperMySQL.getToday();
                    resultContent = "今日使用人数达"+count+"人";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.TODAY_COUNT);
            }
            else if (message.Contains(MessageConstant.USER_TOTAL))
            {
                // 总人数
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    int count = DBHelperMySQL.getUserTotal();
                    DateTime dt = DateTime.Now;
                    // 获取日期
                    string date = dt.ToLongDateString().ToString();
                    resultContent = "截止" + date + ",机器人历史使用人数达"+count+"人。";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.USER_TOTAL);
            }
            else if (message.Contains(MessageConstant.THIS_WEEK))
            {
                // 七日使用
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    Hashtable hashtable = DBHelperMySQL.getThisWeek();
                    resultContent = "";
                    foreach (Object item in hashtable.Keys)
                    {
                        string dateData =  item.ToString();
                        string count = hashtable[item].ToString();
                        resultContent += dateData + " 使用人数为:" + count + "人;\n";
                    }
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.USER_TOTAL);
            }
            else if (message.Contains(MessageConstant.QUN_TOTAL))
            {
                // 群数量
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    resultContent = "群数量";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.QUN_TOTAL);
            }
            else if (message.Contains(MessageConstant.MONEY_DESC))
            {
                // 财富榜
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                // 检索是否为做作家团
                if (DBHelperMySQL.exitsUser(fromQQ) || isAdmin)
                {
                    resultContent = DBHelperMySQL.Top30Money();
                }
                else
                {
                    resultContent = "您不是作家团成员!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.MONEY_DESC);
            }
            else
            {
                // 其他内容
                resultContent = MessageConstant.HELP_CONTENT;
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: "");
            }

            if (resultContent == "" || resultContent == null || resultContent.Length == 0) {
                messageModel.SendMessage = "\n无数据";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HELP);
            }
            // 记录用户操作数据
            DBHelperMySQL.addUserData(fromQQ, content, resultContent);
            return messageModel;
        }

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

public static Dictionary<string, string> ParseOptions(string s)
        {
            Dictionary<string, string> argDict = new Dictionary<string, string>();

            string tmp = "";
            bool putTmp = false;
            string opt = null;

            if (string.IsNullOrEmpty(s))
                return argDict;

            string[] breaks = s.Split(' ');

            foreach (string item in breaks)
            {
                if (item.StartsWith("\""))
                {
                    tmp = item;
                    putTmp = true;
                }
                else if (item.EndsWith("\""))
                {
                    putTmp = false;

                    if (opt != null)
                    {
                        argDict.Add(opt, tmp + item);
                        opt = null;
                    }
                    else
                        argDict.Add(tmp + item, "");

                    tmp = "";
                }
                else
                {
                    if (putTmp)
                        tmp += item;
                    else
                    {
                        var value = item.Trim();

                        if (value.Length > 0)
                        {
                            if (value.StartsWith("-"))
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, "");
                                }

                                opt = value;

                            }
                            else
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, value);
                                    opt = null;
                                }
                                else
                                    argDict.Add(value, "");
                            }
                        }
                    }
                }

            }

            if (opt != null)
                argDict.Add(opt, "");

            breaks = null;

            return argDict;
        }

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

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

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

public static Config Get()
        {
            string key, val;
            string[] optLines;

            string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            if (!File.Exists(workDir + "\\.config"))
                return conf;

            if (conf != null)
                return conf;


            conf = new Config();

            optLines = File.ReadAllLines(workDir + "\\.config");

            if (optLines == null)
                return conf;

            foreach (var item in optLines)
            {
                var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (part != null && part.Length == 2)
                {
                    key = part[0].Trim();
                    val = part[1].Trim();

                    switch (key)
                    {
                        case "memcached_port":
                            conf.MemcachedPort = TryConv<int>(val, 11211);
                            break;
                        case "memcached_path":
                            conf.MemcachedPath = val;
                            break;
                        case "sbmon_path":
                            conf.SbmonPath = val;
                            break;
                        case "log_level":
                            conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
                            break;
                        case "dbpwd":
                            conf.DbPreplacedword = val;
                            break;
                        case "test_mode":
                            conf.TestMode = TryConv<bool>(val, true);
                            break;
                        case "html_replacedet_root":
                            conf.HtmlContentRoot = val;
                            break;
                        case "cacheset_salt":
                            conf.CacheSetSalt = val;
                            break;
                        case "records_per_page":
                            conf.RecordCountPerPage = TryConv<int>(val, 40);
                            break;
                        case "basliks_per_page":
                            conf.BaslikCountPerPage = TryConv<int>(val, 15);
                            break;
                    }
                }
            }
            
            optLines = null;

            return conf;
        }

19 View Source File : MessageController.cs
License : Apache License 2.0
Project Creator : 0nise

public static MessageModel main(String message,string fromQQ) {
            string resultContent = "\n无数据";
            string content = message;
            MessageModel messageModel = null;
            if (message == null || message == "" || message.Length == 0)
            {
                messageModel = new MessageModel(sendMessage: MessageConstant.HELP_CONTENT, isAdmin: false, code: "");
                return messageModel;
            }
            resultContent = "\n无数据";
            message = executeCodeReplace(message);
            message = message.Trim();
            if (message.Length == 0 || message == "")
            {
                messageModel = new MessageModel(sendMessage: MessageConstant.HELP_CONTENT, isAdmin: false, code: "");
                return messageModel;
            }
            else if (message.Contains(MessageConstant.RANDOM_CONTENT_replacedLE)) {
                // 标题查询随机文章
                message = message.Replace(MessageConstant.RANDOM_CONTENT_replacedLE, "").Trim();
                resultContent = DBHelperMySQL.GetContentRandomByreplacedle(message);
                // 标题查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_CONTENT_replacedLE);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_replacedLE)) {
                // 标题查询最新文章
                message = message.Replace(MessageConstant.DESC_CONTENT_replacedLE, "").Trim();
                string clreplacedContent = "";
                if (message.Length == 0 || message == "" || "".Equals(message) || message == null)
                {
                    // 调用每日最新
                    resultContent = DBHelperMySQL.getContentDateByToday();
                    // 标题查询最新课程
                    clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle("");
                }
                else
                {
                    resultContent = DBHelperMySQL.getContentDateByreplacedle(message);
                    clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle(message);
                }
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_replacedLE);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_AUTHOR)) {
                // 作者查询最新文章
                message = message.Replace(MessageConstant.DESC_CONTENT_AUTHOR, "").Trim();
                resultContent = DBHelperMySQL.getContentDateByAuthor(message);
                // 作者查询最新课程
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByAuthor(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_AUTHOR);
            } else if (message.Contains(MessageConstant.RANDOM_CONTENT_AUTHOR)) {
                // 作者查询随机文章
                message = message.Replace(MessageConstant.RANDOM_CONTENT_AUTHOR, "").Trim();
                resultContent = DBHelperMySQL.getContentRandomByAuthor(message);
                // 作者查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByAuthor(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_CONTENT_AUTHOR);
            }
            else if (message.Contains(MessageConstant.DESC_CONTENT_TODAY) || message.Contains(MessageConstant.DESC_CONTENT))
            {
                // 今日最新
                message = message.Replace(MessageConstant.DESC_CONTENT_TODAY, "").Trim();
                resultContent = DBHelperMySQL.getContentDateByToday();
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle("");
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_CONTENT_TODAY);
            } else if (message.Contains(MessageConstant.GONG_GAO)) {
                // 公告处理
                bool flag = DBHelperMySQL.isAdmin(fromQQ);
                // 判断是否管理员
                if (flag) {
                    message = message.Replace(MessageConstant.GONG_GAO, "来自i春秋机器人的智能推送\n");
                    resultContent = message;
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: true, code: MessageConstant.GONG_GAO);
                }
                else {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.GONG_GAO);
                }
            }
            else if (message.Contains(MessageConstant.AITE_ALL))
            {
                // 艾特全体处理
                bool flag = DBHelperMySQL.isAdmin(fromQQ);
                if (flag)
                {
                    message = message.Replace(MessageConstant.AITE_ALL, "来自i春秋机器人的智能推送\n");
                    resultContent = message;
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: true, code: MessageConstant.AITE_ALL);
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                    messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.AITE_ALL);
                }
            }
            else if (message.Contains(MessageConstant.HELP) || message.Contains(MessageConstant.HELP_TWO))
            {
                // Help 帮助等指令
                resultContent = MessageConstant.HELP_CONTENT;
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HELP_TWO);
            } else if (message.Contains(MessageConstant.DESC_VIDEO)) {
                // 标题查询最新教程
                message = message.Replace(MessageConstant.DESC_VIDEO, "").Trim();
                resultContent = DBHelperMySQL.getCourseDateByreplacedle(message);
                // 标题查询最新课程
                string clreplacedContent = DBHelperMySQL.getClreplacedDateByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.DESC_VIDEO);
            }
            else if (message.Contains(MessageConstant.RANDOM_VIDEO))
            {
                // 标题查询随机教程
                message = message.Replace(MessageConstant.RANDOM_VIDEO, "").Trim();
                resultContent = DBHelperMySQL.getCourseRandomByreplacedle(message);
                // 标题查询随机课程
                string clreplacedContent = DBHelperMySQL.getClreplacedRandomByreplacedle(message);
                if (clreplacedContent.Length > 0 && !"".Equals(clreplacedContent))
                {
                    resultContent += clreplacedContent;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.RANDOM_VIDEO);
            }
            else if (message.Contains(MessageConstant.TEST))
            {
                // 测试命令
                resultContent = " [CQ:image,file=photo.jpg]";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.TEST);
            } else if (message.Contains(MessageConstant.SELECT_MONEY)) {
                // 查询余额
                string money = DBHelperMySQL.getBlankMoney(fromQQ);
                if (money == "" || money == null || money.Length == 0)
                {
                    resultContent = "没有数据,请联系QQ:758841765 给予昵称QQ等信息。";
                }
                else
                {
                    resultContent = "\n当前余额为 " + money;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.SELECT_MONEY);
            }
            else if (message.Contains(MessageConstant.HISTORY_MONEY))
            {
                // 提现记录
                string historyMoney = DBHelperMySQL.getBlankHistory(fromQQ);
                // 查询当前余额
                string money = DBHelperMySQL.getBlankMoney(fromQQ);
                if (money == "" || money == null || money.Length == 0) {
                    resultContent = "没有数据,请联系QQ:758841765 给予昵称QQ等信息。";
                }
                else {
                    resultContent = "\n当前余额为 " + money + "\n";
                    // 查询历史记录
                    resultContent += "提现记录\n";
                    resultContent += "金额\t\t时间\n" + historyMoney;
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HISTORY_MONEY);
            }
            else if (message.Contains(MessageConstant.APPLY_MONEY))
            {
                // 申请提现
                resultContent = "请联系【坏蛋】,QQ号:286894635。\n[CQ:at,qq=286894635]";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.APPLY_MONEY);
            } else if (message.Contains(MessageConstant.ABOUT)) {
                resultContent = "i春秋社区机器人,研发人员为:0nise!";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.ABOUT);
            } else if (message.Contains(MessageConstant.UPDATE_MONEY)) {
                // 更新金额
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin) {
                    try
                    {
                        int moneyIndex = message.IndexOf("提现:");
                        int index = message.IndexOf(MessageConstant.UPDATE_MONEY);
                        if (moneyIndex >= 0 && index >= 0)
                        {
                           decimal money = Convert.ToDecimal(message.Substring(moneyIndex).Replace("提现:", "").Replace(" ",""));
                           string qq = message.Replace(message.Substring(moneyIndex), "").Replace(MessageConstant.UPDATE_MONEY, "").Replace(" ", "");
                           resultContent = DBHelperMySQL.updateBlank(qq,money);
                        }
                    }
                    catch (Exception)
                    {
                        resultContent = "更新失败。";
                    }
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.UPDATE_MONEY);
            }
            else if (message.Contains(MessageConstant.TODAY_COUNT))
            {
                // 今日使用数量
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    int count = DBHelperMySQL.getToday();
                    resultContent = "今日使用人数达"+count+"人";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.TODAY_COUNT);
            }
            else if (message.Contains(MessageConstant.USER_TOTAL))
            {
                // 总人数
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    int count = DBHelperMySQL.getUserTotal();
                    DateTime dt = DateTime.Now;
                    // 获取日期
                    string date = dt.ToLongDateString().ToString();
                    resultContent = "截止" + date + ",机器人历史使用人数达"+count+"人。";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.USER_TOTAL);
            }
            else if (message.Contains(MessageConstant.THIS_WEEK))
            {
                // 七日使用
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    Hashtable hashtable = DBHelperMySQL.getThisWeek();
                    resultContent = "";
                    foreach (Object item in hashtable.Keys)
                    {
                        string dateData =  item.ToString();
                        string count = hashtable[item].ToString();
                        resultContent += dateData + " 使用人数为:" + count + "人;\n";
                    }
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.USER_TOTAL);
            }
            else if (message.Contains(MessageConstant.QUN_TOTAL))
            {
                // 群数量
                // 判定是否为管理员
                bool isAdmin = DBHelperMySQL.isAdmin(fromQQ);
                if (isAdmin)
                {
                    resultContent = "群数量";
                }
                else
                {
                    resultContent = "您不是管理员!请联系坏蛋,QQ286894635!";
                }
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: isAdmin, code: MessageConstant.QUN_TOTAL);
            }
            else
            {
                // 其他内容
                resultContent = MessageConstant.HELP_CONTENT;
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: "");
            }

            if (resultContent == "" || resultContent == null || resultContent.Length == 0) {
                messageModel.SendMessage = "\n无数据";
                messageModel = new MessageModel(sendMessage: resultContent, isAdmin: false, code: MessageConstant.HELP);
            }
            // 记录用户操作数据
            DBHelperMySQL.addUserData(fromQQ, content, resultContent);
            return messageModel;
        }

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

public static MTexture GetIcon(string emote, float time) {
            Atlas atlas;
            if ((atlas = GetIconAtlas(ref emote)) == null)
                return null;

            List<string> iconPaths = new(emote.Split(' '));
            if (iconPaths.Count > 1 && int.TryParse(iconPaths[0], out int fps)) {
                iconPaths.RemoveAt(0);
            } else {
                fps = 7; // Default FPS.
            }

            List<MTexture> icons = iconPaths.SelectMany(iconPath => {
                iconPath = iconPath.Trim();
                List<MTexture> subs = atlas.orig_GetAtlreplacedubtextures(iconPath);
                if (subs.Count != 0)
                    return subs;
                if (atlas.Has(iconPath))
                    return new List<MTexture>() { atlas[iconPath] };
                if (iconPath.ToLowerInvariant() == "end")
                    return new List<MTexture>() { null };
                return new List<MTexture>();
            }).ToList();

            if (icons.Count == 0)
                return null;

            if (icons.Count == 1)
                return icons[0];

            int index = (int) Math.Floor(time * fps);

            if (index >= icons.Count - 1 && icons[icons.Count - 1] == null)
                return icons[icons.Count - 2];

            return icons[index % icons.Count];
        }

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

public override void ParseAndRun(ChatCMDEnv env) {
            CelesteNetPlayerSession? session = env.Session;
            if (session == null)
                return;

            Channels channels = env.Server.Channels;

            Channel? c;

            if (int.TryParse(env.Text, out int page) ||
                string.IsNullOrWhiteSpace(env.Text)) {

                if (channels.All.Count == 0) {
                    env.Send($"No channels. See {Chat.Settings.CommandPrefix}{ID} on how to create one.");
                    return;
                }

                const int pageSize = 8;

                StringBuilder builder = new();

                page--;
                int pages = (int) Math.Ceiling(channels.All.Count / (float) pageSize);
                if (page < 0 || pages <= page)
                    throw new Exception("Page out of range.");

                if (page == 0)
                    builder
                        .Append("You're in ")
                        .Append(session.Channel.Name)
                        .AppendLine();

                for (int i = page * pageSize; i < (page + 1) * pageSize && i < channels.All.Count; i++) {
                    c = channels.All[i];
                    builder
                        .Append(c.PublicName)
                        .Append(" - ")
                        .Append(c.Players.Count)
                        .Append(" players")
                        .AppendLine();
                }

                builder
                    .Append("Page ")
                    .Append(page + 1)
                    .Append("/")
                    .Append(pages);

                env.Send(builder.ToString().Trim());

                return;
            }

            Tuple<Channel, Channel> tuple = channels.Move(session, env.Text);
            if (tuple.Item1 == tuple.Item2) {
                env.Send($"Already in {tuple.Item2.Name}");
            } else {
                env.Send($"Moved to {tuple.Item2.Name}");
            }
        }

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

public virtual ChatCMDArg Parse() {
            // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

            if (int.TryParse(String, out Int)) {
                Type = ChatCMDArgType.Int;
                Long = IntRangeFrom = IntRangeTo = Int;
                ULong = (ulong) Int;

            } else if (long.TryParse(String, out Long)) {
                Type = ChatCMDArgType.Long;
                ULong = (ulong) Long;

            } else if (ulong.TryParse(String, out ULong)) {
                Type = ChatCMDArgType.ULong;

            } else if (float.TryParse(String, out Float)) {
                Type = ChatCMDArgType.Float;
            }

            if (Type == ChatCMDArgType.String) {
                string[] split;
                int from, to;
                if ((split = String.Split('-')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = to;
                    }
                } else if ((split = String.Split('+')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = from + to;
                    }
                }
            }

            return this;
        }

19 View Source File : GoPhishIntegration.cs
License : GNU General Public License v3.0
Project Creator : 0dteam

public static string setReportURL(string headers)
        {
            // Extract GoPhish Custom Header (X-GOPHISH-ASMN: USERID0123)
            var match = new Regex(WebExpID).Match(headers);

            foreach (var group in match.Groups)
            {
                if(group.ToString().Trim()!=string.Empty)
                {
                    // Extract User ID from the header (USERID0123)
                    string user_id = group.ToString().Replace(WebExpPrefix, string.Empty);

                    // Build reporting URL, something like this -> https[:]//GOPHISHURL:PORT/report?rid=USERID
                    string report_url = URLrequest.Replace(@"USERID", user_id);
                    return report_url;
                }
            }

            // else, no header was found -> No report tracking URL
            return "NaN";
        }

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

public static Suser GetSuser(string suser)
        {

            string query = string.Format(GET_SUSER_SQL, suser.Trim().ToLower());
            Suser suserObject = null;

            if (!CacheManager.TryGetCachedQueryResult<Suser>(query,out suserObject))
            {
                SqlServerIo sql = SqlServerIo.Create();
                
                if (sql.Execute(false, query))
                {
                    if (sql.Read())
                    {
                        suserObject = new Suser(
                            0,
                            sql.GetValueOfColumn<string>("Suser"),
                            sql.GetValueOfColumn<string>("Preplacedword")
                            );

                    }
                    
                }

                SqlServerIo.Release(sql);
                
            }
            
            return suserObject;
        }

19 View Source File : GroupMessageReceivedMahuaEvent.cs
License : Apache License 2.0
Project Creator : 0nise

public void ProcessGroupMessage(GroupMessageReceivedContext context)
        {
            String message = context.Message;
            message = message.Trim();
            if (message == "" || message.Length == 0 || message == null)
            {
                return;
            }
            String myQQ = _mahuaApi.GetLoginQq();
            String aiteQQ = "[CQ:at,qq=" + myQQ + "]";
            if (message.Contains(aiteQQ)) {
                String sendMessage = "[CQ:at,qq=" + context.FromQq + "]\n";
                message = message.Replace(aiteQQ, "").Replace("\"\"","").Replace("“","").Replace("”","").Trim();
                IDatabase redis = RedisHelper.getRedis();
                if (redis.StringGet(context.FromQq).IsNull == false)
                {
                    string tmpStr = "为防止造成刷屏,您每次使用机器人的时间间隔" + Constants.sleepTime + "秒哦!";
                    sendMessage += tmpStr;
                    _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
                }
                else
                {
                    redis.StringSet(context.FromQq, "flag");
                    redis.KeyExpire(context.FromQq, new TimeSpan(10000000 * Convert.ToInt16(Constants.sleepTime)));
                    MessageModel messageModel = MessageController.main(message, context.FromQq);
                    // 发送消息
                    string tmpStr = messageModel.SendMessage;
                    if (messageModel.IsAdmin)
                    {
                        // 群数量
                        if (MessageConstant.QUN_TOTAL.Equals(messageModel.Code))
                        {
                            ModelWithSourceString<IEnumerable<GroupInfo>> modelWithSourceString = _mahuaApi.GetGroupsWithModel();
                            IEnumerable<GroupInfo> groupInfo = modelWithSourceString.Model;
                            int count = 0;
                            foreach (var item in groupInfo)
                            {
                                count++;
                            }
                            _mahuaApi.SendGroupMessage(context.FromGroup, "群数量:" + count.ToString());
                        }
                        else
                        {
                            if (tmpStr != "" && tmpStr.Length > 0)
                            {
                                sendMessage += tmpStr;
                                _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
                            }
                        }
                    }
                    else
                    {
                        if (tmpStr != "" && tmpStr.Length > 0)
                        {
                            sendMessage += tmpStr;
                            _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
                        }
                    }
                }
            }
        }

19 View Source File : GroupMessageReceivedMahuaEvent.cs
License : Apache License 2.0
Project Creator : 0nise

public void ProcessGroupMessage(GroupMessageReceivedContext context)
        {
            String message = context.Message;
            message = message.Trim();
            if (message == "" || message.Length == 0 || message == null)
            {
                return;
            }
            String myQQ = _mahuaApi.GetLoginQq();
            String aiteQQ = "[CQ:at,qq=" + myQQ + "]";
            if (message.Contains(aiteQQ)) {
                String sendMessage = "[CQ:at,qq=" + context.FromQq + "]";
                message = message.Replace(aiteQQ, "").Replace("\"\"","").Replace("“","").Replace("”","").Trim();
                IDatabase redis = RedisHelper.getRedis();
                // 判断用户是否在缓冲中
                if (redis.StringGet(context.FromQq).IsNull)
                {
                    redis.StringSet(context.FromQq, "flag");
                    redis.KeyExpire(context.FromQq, new TimeSpan(10000000 * Convert.ToInt16(Constants.sleepTime)));
                }
                else {
                    string tmpStr = "为防止造成刷屏,您每次使用机器人的时间间隔"+ Constants.sleepTime + "秒哦!";
                    sendMessage += tmpStr;
                    _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
                    return;
                };
                if (message == null || message =="" || message.Length == 0) {
                    //
                }
                else
                {
                    MessageModel messageModel = MessageController.main(message, context.FromQq);
                    // 发送消息
                    string tmpStr = messageModel.SendMessage;
                    if (messageModel.IsAdmin) {
                        // 群数量
                        if (MessageConstant.QUN_TOTAL.Equals(messageModel.Code))
                        {
                            ModelWithSourceString<IEnumerable<GroupInfo>> modelWithSourceString = _mahuaApi.GetGroupsWithModel();
                            IEnumerable<GroupInfo> groupInfo = modelWithSourceString.Model;
                            int count = 0;
                            foreach (var item in groupInfo)
                            {
                                count ++;
                            }
                            _mahuaApi.SendGroupMessage(context.FromQq, "群数量:" + count.ToString());
                        }
                        else
                        {
                            if (tmpStr != "" && tmpStr.Length > 0)
                            {
                                sendMessage += tmpStr;
                                _mahuaApi.SendGroupMessage(context.FromQq, sendMessage);
                            }
                        }
                    }
                    else
                    {
                        if (tmpStr != "" && tmpStr.Length > 0)
                        {
                            sendMessage += tmpStr;
                            _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
                        }
                    }
                }
            }
        }

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 : CelesteNetEmoteComponent.cs
License : MIT License
Project Creator : 0x0ade

public void Send(string text) {
            Client.SendAndHandle(new DataEmote {
                Player = Client.PlayerInfo,
                Text = text?.Trim()
            });
        }

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

public void RebuildList() {
            if (MDraw.DefaultFont == null || Client == null || Channels == null)
                return;

            DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();

            List<Blob> list = new() {
                new Blob {
                    Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
                    Color = ColorCountHeader
                }
            };

            StringBuilder builder = new();


            switch (Mode) {
                case ListMode.Clreplacedic:
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        builder.Append(player.DisplayName);

                        DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
                        if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
                            builder
                                .Append(" #")
                                .Append(channel.Name);
                        }

                        if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                            AppendState(builder, state);

                        builder.AppendLine();
                    }

                    list.Add(new() {
                        Text = builder.ToString().Trim(),
                        ScaleFactor = 1f
                    });
                    break;

                case ListMode.Channels:
                    HashSet<DataPlayerInfo> listed = new();

                    DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));

                    if (own != null) {
                        list.Add(new() {
                            Text = own.Name,
                            Color = ColorChannelHeaderOwn
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p))) 
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 0.5f
                        });
                    }

                    foreach (DataChannelList.Channel channel in Channels.List) {
                        if (channel == own)
                            continue;

                        list.Add(new() {
                            Text = channel.Name,
                            Color = ColorChannelHeader
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }

                    bool wrotePrivate = false;

                    builder.Clear();
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        if (!wrotePrivate) {
                            wrotePrivate = true;
                            list.Add(new() {
                                Text = "!<private>",
                                Color = ColorChannelHeaderPrivate
                            });
                        }

                        builder.AppendLine(player.DisplayName);
                    }

                    if (wrotePrivate) {
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }
                    break;
            }

            List = list;
        }

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

public string GetCommandPage(ChatCMDEnv env, int page = 0) {
            const int pageSize = 8;

            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

            int pages = (int) Math.Ceiling(Chat.Commands.All.Count / (float) pageSize);
            if (page < 0 || pages <= page)
                throw new Exception("Page out of range.");

            for (int i = page * pageSize; i < (page + 1) * pageSize && i < Chat.Commands.All.Count; i++) {
                ChatCMD cmd = Chat.Commands.All[i];
                builder
                    .Append(prefix)
                    .Append(cmd.ID)
                    .Append(" ")
                    .Append(cmd.Args)
                    .AppendLine();
            }

            builder
                .Append("Page ")
                .Append(page + 1)
                .Append("/")
                .Append(pages);

            return builder.ToString().Trim();
        }

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

public override object? Run(string uid) {
            if ((uid = uid?.Trim() ?? "").IsNullOrEmpty())
                return null;

            Frontend.Server.UserData.Delete<BanInfo>(uid);
            Frontend.BroadcastCMD(true, "update", "/userinfos");

            return null;
        }

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

public void ReadTeapot(out string[] features, out uint token) {
            features = Dummy<string>.EmptyArray;
            token = 0;
            using StreamReader reader = new(TCPReaderStream, Encoding.UTF8, false, 1024, true);
            for (string line; !string.IsNullOrWhiteSpace(line = reader?.ReadLine() ?? "");) {
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConFeatures)) {
                    features = line.Substring(CelesteNetUtils.HTTPTeapotConFeatures.Length).Trim().Split(CelesteNetUtils.ConnectionFeatureSeparators);
                }
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConToken)) {
                    token = uint.Parse(line.Substring(CelesteNetUtils.HTTPTeapotConToken.Length).Trim());
                }
            }
        }

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

static void Repack(string input, string[] extras, string output, string name = null) {
            Console.Error.WriteLine($"Repacking: {input} -> {output}");
            if (name == null)
                name = Path.GetFileName(output);

            string outputTmp = Path.Combine(Path.GetDirectoryName(output), name);
            if (File.Exists(outputTmp))
                File.Delete(outputTmp);

            List<string> args = new List<string>();
            args.Add($"/out:{outputTmp}");
            args.Add(input);
            foreach (string dep in extras)
                if (!string.IsNullOrWhiteSpace(dep))
                    args.Add(dep.Trim());

            RepackOptions options = new RepackOptions(args);
            ILRepack repack = new ILRepack(options);
            repack.Repack();

            if (output != outputTmp) {
                if (File.Exists(output))
                    File.Delete(output);
                File.Move(outputTmp, output);
            }
        }

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

public string Help_GetCommandSnippet(ChatCMDEnv env, ChatCMD cmd) {
            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

            builder
                .Append(prefix)
                .Append(cmd.ID)
                .Append(" ")
                .Append(cmd.Args)
                .AppendLine()
                .AppendLine(cmd.Help);

            return builder.ToString().Trim();
        }

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

public override object? Run(dynamic? input) {
            JArray? uidsRaw = (JArray?) input?.UIDs;
            string[]? uids = uidsRaw?.Select(t => t.ToString()).ToArray();
            string? reason = (string?) input?.Reason;
            if (uids == null || uids.Length == 0 ||
                (reason = reason?.Trim() ?? "").IsNullOrEmpty())
                return null;

            BanInfo ban = new() {
                UID = uids[0],
                Reason = reason,
                From = DateTime.UtcNow
            };

            CelesteNetPlayerSession[] players;
            using (Frontend.Server.ConLock.R())
                players = Frontend.Server.Sessions.ToArray();

            foreach (string uid in uids) {
                foreach (CelesteNetPlayerSession player in players) {
                    if (player.UID != uid && player.ConUID != uid)
                        continue;

                    if (ban.Name.IsNullOrEmpty())
                        ban.Name = player.PlayerInfo?.FullName ?? "";

                    ChatModule chat = Frontend.Server.Get<ChatModule>();
                    new DynamicData(player).Set("leaveReason", chat.Settings.MessageBan);
                    player.Dispose();
                    player.Con.Send(new DataDisconnectReason { Text = "Banned: " + reason });
                    player.Con.Send(new DataInternalDisconnect());
                }
            }

            foreach (string uid in uids)
                Frontend.Server.UserData.Save(uid, ban);
            Frontend.BroadcastCMD(true, "update", "/userinfos");

            return null;
        }

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

private static async MaybeEx<(string arg1, string arg2)> SplitString(string str, bool async)
        {
            if (async)
            {
                await Task.Delay(10);
            }

            str = await ValidateString(str);

            var arr = str?.Split(',');
            if (arr == null || arr.Length != 2)
            {
                return await MaybeEx<(string arg1, string arg2)>.Nothing();
            }

            return (arr[0].Trim(), arr[1].Trim());
        }

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

private static async Maybe<(string arg1, string arg2)> SplitString(string str, bool async)
        {
            if (async)
            {
                await Task.Delay(10);
            }

            str = await ValidateString(str);

            var arr = str?.Split(',');
            if (arr == null || arr.Length != 2)
            {
                return await Maybe<(string arg1, string arg2)>.Nothing();
            }

            return (arr[0].Trim(), arr[1].Trim());
        }

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

private static string RemoveCommentsAndWhiteSpace(string line)
        {
            int commentIndex = line.IndexOf(";", StringComparison.Ordinal);
            if (commentIndex >= 0)
            {
                return line.Substring(0, commentIndex).Trim();
            }
            else
            {
                return line.Trim();
            }
        }

19 View Source File : IrdParser.cs
License : MIT License
Project Creator : 13xforever

public static Ird Parse(byte[] content)
        {
            if (content == null)
                throw new ArgumentNullException(nameof(content));

            if (content.Length < 200)
                throw new ArgumentException("Data is too small to be a valid IRD structure", nameof(content));

            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                using (var compressedStream = new MemoryStream(content, false))
                using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var decompressedStream = new MemoryStream())
                {
                    gzip.CopyTo(decompressedStream);
                    content = decompressedStream.ToArray();
                }
            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                throw new FormatException("Not a valid IRD file");

            var result = new Ird();
            using (var stream = new MemoryStream(content, false))
            using (var reader = new BinaryReader(stream, Encoding.UTF8))
            {
                reader.ReadInt32(); // magic
                result.Version = reader.ReadByte();
                result.ProductCode = Encoding.ASCII.GetString(reader.ReadBytes(9));
                result.replacedleLength = reader.ReadByte();
                result.replacedle = Encoding.UTF8.GetString(reader.ReadBytes(result.replacedleLength));
                result.UpdateVersion = Encoding.ASCII.GetString(reader.ReadBytes(4)).Trim();
                result.GameVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                result.AppVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                if (result.Version == 7)
                    result.Id = reader.ReadInt32();
                result.HeaderLength = reader.ReadInt32();
                result.Header = reader.ReadBytes(result.HeaderLength);
                result.FooterLength = reader.ReadInt32();
                result.Footer = reader.ReadBytes(result.FooterLength);
                result.RegionCount = reader.ReadByte();
                result.RegionMd5Checksums = new List<byte[]>(result.RegionCount);
                for (var i = 0; i < result.RegionCount; i++)
                    result.RegionMd5Checksums.Add(reader.ReadBytes(16));
                result.FileCount = reader.ReadInt32();
                result.Files = new List<IrdFile>(result.FileCount);
                for (var i = 0; i < result.FileCount; i++)
                {
                    var file = new IrdFile();
                    file.Offset = reader.ReadInt64();
                    file.Md5Checksum = reader.ReadBytes(16);
                    result.Files.Add(file);
                }
                result.Unknown = reader.ReadInt32();
                if (result.Version == 9)
                    result.Pic = reader.ReadBytes(115);
                result.Data1 = reader.ReadBytes(16);
                result.Data2 = reader.ReadBytes(16);
                if (result.Version < 9)
                    result.Pic = reader.ReadBytes(115);
                result.Uid = reader.ReadInt32();
                var dataLength = reader.BaseStream.Position;
                result.Crc32 = reader.ReadUInt32();

                var crc32 = Crc32Algorithm.Compute(content, 0, (int)dataLength);
                if (result.Crc32 != crc32)
                    throw new InvalidDataException($"Corrupted IRD data, expected {result.Crc32:x8}, but was {crc32:x8}");
            }
            return result;
        }

19 View Source File : IrdClient.cs
License : MIT License
Project Creator : 13xforever

private static string Getreplacedle(string html)
        {
            if (string.IsNullOrEmpty(html))
                return null;

            var idx = html.LastIndexOf("</span>");
            var result = html.Substring(idx + 7).Trim();
            if (string.IsNullOrEmpty(result))
                return null;

            return result;
        }

19 View Source File : IrdClient.cs
License : MIT License
Project Creator : 13xforever

public async Task<SearchResult> SearchAsync(string query, CancellationToken cancellationToken)
        {
            try
            {
                var requestUri = new Uri(BaseUrl + "/data.php").SetQueryParameters(new Dictionary<string, string>
                    {
                        ["draw"] = query.Length.ToString(),

                        ["columns[0][data]"] = "id",
                        ["columns[0][name]"] = "",
                        ["columns[0][searchable]"] = "true",
                        ["columns[0][orderable]"] = "true",
                        ["columns[0][search][value]"] = "",
                        ["columns[0][search][regex]"] = "false",

                        ["columns[1][data]"] = "replacedle",
                        ["columns[1][name]"] = "",
                        ["columns[1][searchable]"] = "true",
                        ["columns[1][orderable]"] = "true",
                        ["columns[1][search][value]"] = "",
                        ["columns[1][search][regex]"] = "false",

                        ["order[0][column]"] = "0",
                        ["order[0][dir]"] = "asc",

                        ["start"] = "0",
                        ["length"] = "10",

                        ["search[value]"] = query.Trim(100),

                        ["_"] = DateTime.UtcNow.Ticks.ToString(),
                    });
                    try
                    {
                        var responseBytes = await client.GetByteArrayAsync(requestUri).ConfigureAwait(false);
                        var result = Deserialize(responseBytes);
                        result.Data = result.Data ?? new List<SearchResulreplacedem>(0);
                        foreach (var item in result.Data)
                        {
                            item.Filename = GetIrdFilename(item.Filename);
                            item.replacedle = Getreplacedle(item.replacedle);
                        }
                        return result;
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Failed to make API call to IRD Library");
                        return null;
                    }
            }
            catch (Exception e)
            {
                Log.Error(e);
                return null;
            }
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

private List<string> EnumeratePhysicalDrivesLinux()
        {
            var cdInfo = "";
            try
            {
                cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
            }
            catch (Exception e)
            {
                Log.Debug(e, e.Message);
            }
            var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
                    .Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
                    .Distinct()
                    .ToList();

        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

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 : DbAdapterAbstract.cs
License : MIT License
Project Creator : 17MKH

public string AppendQuote(string value)
    {
        var val = value?.Trim();
        if (val != null && SqlLowerCase)
            val = val.ToLower();

        return $"{LeftQuote}{val}{RightQuote}";
    }

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

private string Handle_Payload()
        {
            //对用户输入的payload进行一些转换处理,方便下一步的加密
            string raw_input = textBox1.Text.Trim().Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); //支持多种linux win换行符
            string payload_pattern_csharp = @"\{(.+?)\}";
            string payload_pattern_c = @"=.*"";$";
            string[] raw_payload_array;
            if (Regex.IsMatch(raw_input, payload_pattern_c))
            {
                //c语言格式的shellcode,转成 csharp 格式
                raw_input = raw_input.Replace("\"", "").Replace("\\", ",0").Replace(";", "").Replace("=", "{").Replace("{,", "{ ") + " }";
            }
            string raw_payload = Regex.Matches(raw_input, payload_pattern_csharp)[0].Value.Replace("{", "").Replace("}", "").Trim();
            raw_payload = raw_payload.TrimStart(',');
            raw_payload_array = raw_payload.Split(',');
            List<byte> byte_payload_list = new List<byte>();

            foreach (string i in raw_payload_array)
            {
                byte_payload_list.Add(string_to_int(i));
            }
            byte[] payload_result = byte_payload_list.ToArray();

            //加密payload并转换为字符串,准备写入文件
            byte[] encrypted_payload = Encrypter.Encrypt(KEY, payload_result);
            string string_encrypted_payload = string.Join(",", encrypted_payload);
            //MessageBox.Show(string_encrypted_payload);
            return string_encrypted_payload;
        }

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

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

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

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if(!string.IsNullOrWhiteSpace(cmdstr)){
                string[] cmdArr = cmdstr.Split('\n');
                foreach(string cmd in cmdArr){
                    monitorForm.RunShell(cmd.Trim(), true, true);
                    Thread.Sleep(100);
                }
            }            
        }

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

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if (!string.IsNullOrWhiteSpace(cmdstr))
            {
                string[] cmdArr = cmdstr.Split('\n');
                foreach (string cmd in cmdArr)
                {
                    monitorForm.RunShell(cmd.Trim(), true);
                    Thread.Sleep(100);
                }
            }  
        }

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

private void button1_Click(object sender, EventArgs e)
        {
            string name = stb_name.Text;
            string cmdstr = cmd.Text;
            if(string.IsNullOrWhiteSpace(name)){
                MessageBox.Show(this, "请定义一个名称");
                return;
            }
            if (string.IsNullOrWhiteSpace(cmdstr))
            {
                MessageBox.Show(this, "请输入要执行的命令");
                return;
            }
            List<TaskShell> cmdList = new List<TaskShell>();
            string[] cmds = cmdstr.Split('\n');
            TaskShell task = null;
            foreach(string c in cmds){
                if (!string.IsNullOrWhiteSpace(c.Trim()))
                {
                    task = new TaskShell();
                    task.Uuid = Guid.NewGuid().ToString("N");
                    task.Name = "";
                    task.Shell = c.Trim();
                    cmdList.Add(task);
                }                
            }
            bool isnew = false;
            if(shell == null){
                shell = new CmdShell();
                shell.Uuid = Guid.NewGuid().ToString("N");
                shell.Target = uuid;
                isnew = true;
            }            
            shell.Name = name;
            shell.Type = "自定义脚本";
            shell.TaskType = TaskType.Default;
            shell.ShellList = cmdList;
            if (isnew)
            {
                config.CustomShellList.Add(shell);
            }

            AppConfig.Instance.SaveConfig(2);

            this.Close();
        }

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

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

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

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if (!string.IsNullOrWhiteSpace(cmdstr))
            {
                string[] cmdArr = cmdstr.Split('\n');
                foreach (string cmd in cmdArr)
                {
                    monitorForm.RunShell(cmd.Trim(), true, true);
                    Thread.Sleep(100);
                }
            }  
        }

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

private void 添加同级节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_treeView.SelectedItems.Count > 0)
            {
                TreeListViewItem parentNode = _treeView.SelectedItems[0];
                YmlItem parentObj = (YmlItem)parentNode.Tag;

                TreeListViewItem viewItem = new TreeListViewItem();
                YmlItem obj = new YmlItem()
                {
                    Key = "",
                    Value = "",
                    Level = parentObj.Level,
                    Common = "",
                    Uuid = Guid.NewGuid().ToString("N"),
                    ImageIndex = parentObj.ImageIndex == 2 ? 1 : parentObj.ImageIndex,
                    Parent = parentObj.Parent,
                    SpcCount = parentObj.SpcCount
                };
                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 (parentNode.Parent != null)
                {
                    parentNode.Parent.Items.Add(viewItem);
                }
                else
                {
                    _treeView.Items.Add(viewItem);
                }                

                YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
                form.ShowDialog(this);

                string value = viewItem.SubItems[1].Text;
                if (string.IsNullOrWhiteSpace(value))
                {
                    string key = viewItem.SubItems[0].Text;
                    if (key.Trim().StartsWith("#"))
                    {
                        obj.ImageIndex = 2;
                    }
                    else
                    {
                        obj.ImageIndex = 3;
                    }
                    viewItem.ImageIndex = obj.ImageIndex;
                }
                btn_save.Enabled = true;
            }            
        }

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

private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_treeView.SelectedItems.Count > 0)
            {
                TreeListViewItem parentNode = _treeView.SelectedItems[0];
                YmlItem parentObj = (YmlItem) parentNode.Tag;

                TreeListViewItem viewItem = new TreeListViewItem();
                YmlItem obj = new YmlItem()
                {
                    Key = "",
                    Value = "",
                    Level = parentObj.Level + 1,
                    Common = "",
                    Uuid = Guid.NewGuid().ToString("N"),
                    ImageIndex = 1,
                    Parent = parentObj,
                    SpcCount = (parentObj.Level + 1) * 4
                };
                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);
                parentNode.Items.Add(viewItem);

                string parentId = parentObj.Uuid;
                YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
                form.ShowDialog(this);

                string value = viewItem.SubItems[1].Text;
                if (string.IsNullOrWhiteSpace(value))
                {
                    string key = viewItem.SubItems[0].Text;
                    if (key.Trim().StartsWith("#"))
                    {
                        obj.ImageIndex = 2;                        
                    } else {
                        obj.ImageIndex = 3;
                    }
                    viewItem.ImageIndex = obj.ImageIndex;
                }
                btn_save.Enabled = true;
            }
        }

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

private void IceDeployVersionForm_Load(object sender, EventArgs e)
        {
            stb_remote_pdir.Text = ice.IceSrvDir;
            if(ice.Project != null){
                if(null != ice.Project.LocalCodePath){
                    stb_local_pdir.Text = ice.Project.LocalCodePath;
                }
                if (null != ice.Project.LocalIceXmlPath)
                {
                    stb_icexml.Text = ice.Project.LocalIceXmlPath;
                }
                if (null != ice.Project.MavenSetting)
                {
                    stb_maven_xml.Text = ice.Project.MavenSetting;
                }
            }

            stb_local_pdir.SkinTxt.TextChanged += stb_local_pdir_TextChanged;

            stb_local_pdir.SkinTxt.AllowDrop = true;
            stb_local_pdir.SkinTxt.DragDrop += stb_local_pdir_DragDrop;
            stb_local_pdir.SkinTxt.DragEnter += stb_local_pdir_DragEnter;

            stb_icexml.SkinTxt.AllowDrop = true;
            stb_icexml.SkinTxt.DragDrop += stb_icexml_DragDrop;
            stb_icexml.SkinTxt.DragEnter += stb_icexml_DragEnter;


            stb_maven_xml.SkinTxt.AllowDrop = true;
            stb_maven_xml.SkinTxt.DragDrop += stb_maven_xml_DragDrop;
            stb_maven_xml.SkinTxt.DragEnter += stb_maven_xml_DragEnter;

            if (stb_maven_xml.Text == "")
            {
                try
                {
                    CmdResult result = Command.run("mvn -v");
                    if (result.isFailed())
                    {
                        errorLabel.Text = "检测到未安装Maven或者未设置Maven环境变量,需手动打包";
                    }
                    else if (result.isSuccess())
                    {
                        // Maven home: F:\Server\apache-maven-3.3.9\bin\..
                        int index = result.result.IndexOf("Maven home:");
                        if (index != -1)
                        {
                            int len = result.result.IndexOf("..", index);
                            string line = result.result.Substring(index, len - index);
                            len = "Maven home:".Length;
                            mavenHome = line.Substring(len, line.IndexOf("bin\\") - len);
                            mavenHome = Utils.PathWinToLinux(mavenHome.Trim());
                            if (File.Exists(mavenHome + "conf/settings.xml"))
                            {
                                stb_maven_xml.Text = mavenHome + "conf/settings.xml";
                            }
                            else
                            {
                                errorLabel.Text = mavenHome + "conf/settings.xml 未找到,请手动指定";
                            }
                        }
                    }
                }
                catch(Exception ex) {
                    Console.WriteLine(ex.Message);
                }
            }            
        }

19 View Source File : DDZGamePlayController.cs
License : Apache License 2.0
Project Creator : 2881099

[HttpPost("GetOrAddPlayer")]
        async public Task<APIReturn> GetOrAddPlayer([FromForm] string nick)
        {
            nick = nick?.Trim();
            if (string.IsNullOrEmpty(nick)) throw new ArgumentException(nameof(nick));

            await CheckPlayer(false);
            if (CurrentPlayer == null)
            {
                if (await Player.Where(a => a.Nick == nick).AnyAsync())
                    return APIReturn.失败.SetMessage("玩家名已存在");

                CurrentPlayer = await new Player { Id = PlayerId, Nick = nick, Score = 1000 }.InsertAsync();
            }
            else
            {
                CurrentPlayer.Nick = nick;
                await CurrentPlayer.SaveAsync();
            }
            return APIReturn.成功.SetData("player", CurrentPlayer);
        }

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

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

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

void RefershClusterNodes()
            {
                foreach (var testConnection in _clusterConnectionStrings)
                {
                    RegisterClusterNode(testConnection);
                    //尝试求出其他节点,并缓存slot
                    try
                    {
                        var cnodes = AdapterCall<string>("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
                        foreach (var cnode in cnodes)
                        {
                            if (string.IsNullOrEmpty(cnode)) continue;
                            var dt = cnode.Trim().Split(' ');
                            if (dt.Length < 9) continue;
                            if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
                            if (dt[7] != "connected") continue;

                            var endpoint = dt[1];
                            var at40 = endpoint.IndexOf('@');
                            if (at40 != -1) endpoint = endpoint.Remove(at40);

                            if (endpoint.StartsWith("127.0.0.1"))
                                endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
                            else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
                                endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
                            ConnectionStringBuilder connectionString = testConnection.ToString();
                            connectionString.Host = endpoint;
                            RegisterClusterNode(connectionString);

                            for (var slotIndex = 8; slotIndex < dt.Length; slotIndex++)
                            {
                                var slots = dt[slotIndex].Split('-');
                                if (ushort.TryParse(slots[0], out var tryslotStart) &&
                                    ushort.TryParse(slots[1], out var tryslotEnd))
                                {
                                    for (var slot = tryslotStart; slot <= tryslotEnd; slot++)
                                        _slotCache.AddOrUpdate(slot, connectionString.Host, (k1, v1) => connectionString.Host);
                                }
                            }
                        }
                        break;
                    }
                    catch
                    {
                        _ib.TryRemove(testConnection.Host, true);
                    }
                }

                if (_ib.GetKeys().Length == 0)
                    throw new RedisClientException($"All \"clusterConnectionStrings\" failed to connect");
            }

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

public static ConnectionStringBuilder Parse(string connectionString)
        {
            var ret = new ConnectionStringBuilder();
            if (string.IsNullOrEmpty(connectionString)) return ret;

            //支持密码中带有逗号,将原有 split(',') 改成以下处理方式
            var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
            ret.Host = vs[0].Trim();

            for (var a = 1; a < vs.Length; a += 2)
            {
                var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
                switch (kv[0])
                {
                    case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
                    case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
                    case "userid":
                    case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
                    case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
                    case "database":
                    case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;

                    case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
                    case "name":
                    case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
                    case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;

                    case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
                    case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
                    case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
                    case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;

                    case "poolsize":
                    case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
                    case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
                    case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
                }
            }
            return ret;
        }

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

public static List<YmlItem> FormatYmlToTree(string content)
        {
            List<YmlItem> lists = new List<YmlItem>();
            string[] lines = content.Split('\n');
            YmlItem item = null;
            string startStr = "";
            List<YmlItem> levels = new List<YmlItem>();
            int index1 = -1, index2 = -1, index = 0;
            foreach(string line in lines){
                if(string.IsNullOrWhiteSpace(line)){
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 2;
                    item.Key = "#" + line;
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    lists.Add(item);
                    continue;
                }
                if(line.TrimStart().StartsWith("#")){
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 2;
                    item.Key = line;
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    lists.Add(item);
                }
                else
                {
                    item = new YmlItem();
                    item.Uuid = "T" + (index++);
                    item.ImageIndex = 0;
                    item.Key = "";
                    item.Value = "";
                    item.Level = 0;
                    item.Common = "";

                    item.SpcCount = StartSpaceCount(line);
                    if (item.SpcCount == 0)
                    {
                        levels.Clear();
                        item.Level = 0;
                    }
                    else
                    {
                        // level
                        for (int i = levels.Count - 1; i >= 0; i-- )
                        {
                            if (levels[i].SpcCount < item.SpcCount)
                            {
                                item.Level = levels[i].Level + 1;
                                item.Parent = levels[i];
                                break;
                            }
                        }
                    }
                    levels.Add(item);

                    index2 = line.IndexOf("#");
                    if (index2 > 0)
                    {
                        startStr = line.Substring(0, index2);
                        item.Common = line.Substring(index2);
                    }
                    else
                    {
                        startStr = line;
                    }

                    index1 = startStr.IndexOf(":");
                    if (index1 > 0)
                    {
                        item.Key = startStr.Substring(0, index1).TrimStart();
                        item.Value = startStr.Substring(index1 + 1).Trim();
                    }
                    else
                    {
                        item.Key = startStr.TrimStart();
                        item.Common = "--格式错误--";
                    }

                    if (!string.IsNullOrWhiteSpace(item.Value))
                    {
                        item.ImageIndex = 1;
                    }

                    lists.Add(item);
                }
            }

            return lists;
        }

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

public static Color getTextColor(string str)
        {
            Color color = Color.DarkCyan;
            if(!string.IsNullOrWhiteSpace(str)){
                if (str.Trim() == "true" || str.Trim() == "false")
                {
                    color = Color.Red;
                }
                else
                {
                    Match m = Regex.Match(str.Trim(), @"^(-?\d+)(\.\d+)?$");
                    if (m.Success)
                    {
                        color = Color.YellowGreen;
                    }
                }
            }            
            return color;
        }

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

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

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

public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
			if (bat == null || bat.Any() == false) return ("", "", "");
            if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
			var proc = new System.Diagnostics.Process();
			proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
				CreateNoWindow = true,
				FileName = "cmd.exe",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				WorkingDirectory = cddir
			};
			proc.Start();
			foreach (var cmd in bat)
				proc.StandardInput.WriteLine(cmd);
			proc.StandardInput.WriteLine("exit");
			var outStr = proc.StandardOutput.ReadToEnd();
			var errStr = proc.StandardError.ReadToEnd();
			proc.Close();
			var idx = outStr.IndexOf($">{bat[0]}");
			if (idx != -1) {
				idx = outStr.IndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Substring(idx + 1);
			}
			idx = outStr.LastIndexOf(">exit");
			if (idx != -1) {
				idx = outStr.LastIndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Remove(idx);
			}
			outStr = outStr.Trim();
			if (outStr == "") outStr = null;
			if (errStr == "") errStr = null;
			return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
		}

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

public string GetColumnAttribute(DbColumnInfo col, bool isInsertValueSql = false)
	{
		var sb = new List<string>();

		if (GetCsName(col.Name) != col.Name)
			sb.Add("Name = \"" + col.Name + "\"");

		if (col.CsType != null)
		{
			var dbinfo = fsql.CodeFirst.GetDbInfo(col.CsType);
			if (dbinfo != null && string.Compare(dbinfo.dbtypeFull.Replace("NOT NULL", "").Trim(), col.DbTypeTextFull, true) != 0)
			{
				#region StringLength 反向
				switch (fsql.Ado.DataType)
				{
					case DataType.MySql:
					case DataType.OdbcMySql:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "longtext": sb.Add("StringLength = -2"); break;
							case "text": sb.Add("StringLength = -1"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.SqlServer:
					case DataType.OdbcSqlServer:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "nvarchar(max)": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.PostgreSQL:
					case DataType.OdbcPostgreSQL:
					case DataType.OdbcKingbaseES:
					case DataType.ShenTong:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Oracle:
					case DataType.OdbcOracle:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "nclob": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar2\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Dameng:
					case DataType.OdbcDameng:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar2\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Sqlite:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.MsAccess:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "longtext": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
				}
				#endregion
			}
			if (col.IsPrimary)
				sb.Add("IsPrimary = true");
			if (col.IsIdenreplacedy)
				sb.Add("IsIdenreplacedy = true");

			if (dbinfo != null && dbinfo.isnullable != col.IsNullable)
			{
				if (col.IsNullable && fsql.DbFirst.GetCsType(col).Contains("?") == false && col.CsType.IsValueType)
					sb.Add("IsNullable = true");
				if (col.IsNullable == false && fsql.DbFirst.GetCsType(col).Contains("?") == true)
					sb.Add("IsNullable = false");
			}

			if (isInsertValueSql)
			{
				var defval = GetColumnDefaultValue(col, false);
				if (defval == null) //c#默认属性值,就不需要设置 InsertValueSql 了
				{
					defval = GetColumnDefaultValue(col, true);
					if (defval != null)
					{
						sb.Add("InsertValueSql = \"" + defval.Replace("\"", "\\\"") + "\"");
						sb.Add("CanInsert = false");
					}
				}
				else
					sb.Add("CanInsert = false");
			}
		}
		if (sb.Any() == false) return null;
		return "[Column(" + string.Join(", ", sb) + ")]";
	}

See More Examples