string.Contains(string)

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

14848 Examples 7

19 Source : Configuration.ValueConfig.cs
with GNU Affero General Public License v3.0
from 0ceal0t

private bool DrawCombo(string id, T[] comboOptions, T currentValue, out T value) {
            value = currentValue;
            if (ImGui.BeginCombo(id, $"{currentValue}", ImGuiComboFlags.HeightLargest)) {
                if (ShowSearch) {
                    ImGui.SetNexreplacedemWidth(ImGui.GetWindowContentRegionWidth() - 50);
                    ImGui.InputText("Search##Combo", ref SearchInput, 256);
                }

                if (ShowSearch) ImGui.BeginChild("Child##Combo", new Vector2(ImGui.GetWindowContentRegionWidth(), 200), true);

                var idx = 0;
                foreach (T option in comboOptions) {
                    if (ShowSearch && !string.IsNullOrEmpty(SearchInput)) {
                        var optionString = option.ToString();
                        if (!optionString.ToLower().Contains(SearchInput.ToLower())) continue;
                    }

                    if (ImGui.Selectable($"{option}##Combo{idx}", option.Equals(currentValue))) {
                        value = option;

                        if (ShowSearch) ImGui.EndChild();
                        ImGui.EndCombo();
                        return true;
                    }
                    idx++;
                }

                if (ShowSearch) ImGui.EndChild();
                ImGui.EndCombo();
            }
            return false;
        }

19 Source : MessageController.cs
with Apache License 2.0
from 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 Source : MessageController.cs
with Apache License 2.0
from 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 Source : GroupMessageReceivedMahuaEvent.cs
with Apache License 2.0
from 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 Source : GroupMessageReceivedMahuaEvent.cs
with Apache License 2.0
from 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 Source : XnaToFnaUtil.Processor.cs
with zlib License
from 0x0ade

public void CheckAndDestroyLock(MethodDefinition method, int instri) {
            Instruction instr = method.Body.Instructions[instri];

            /* replaced UGLY HACK DO NOT I SAY DO NOT USE THIS EVERYWHERE
             * *ahem*
             * """Fix""" some games *cough* DUCK GAME *cough* looping for CONTENT to LOAD.
             * I deserve to be hanged for this.
             * -ade
             */
            if (instri >= 1 &&
                (instr.OpCode == OpCodes.Brfalse || instr.OpCode == OpCodes.Brfalse_S ||
                 instr.OpCode == OpCodes.Brtrue || instr.OpCode == OpCodes.Brtrue_S) &&
                ((Instruction) instr.Operand).Offset < instr.Offset && instr.Previous.Operand != null) {
                // Check if field load / method call contains "load" or "content"
                string name =
                    (instr.Previous.Operand as FieldReference)?.Name ??
                    (instr.Previous.Operand as MethodReference)?.Name ??
                    instr.Previous.Operand.ToString();
                name = name.ToLowerInvariant();
                if (instri - method.Body.Instructions.IndexOf((Instruction) instr.Operand) <= 3 &&
                    name != null && (name.Contains("load") || name.Contains("content"))) {
                    // Replace previous, possible volatile and this with nop
                    Log($"[PostProcess] [HACK!!!] NOPing possible content loading waiting loop in {method.GetFindableID()}");
                    if (instr.Previous?.Previous.OpCode == OpCodes.Volatile)
                        instr.Previous.Previous.OpCode = OpCodes.Nop;
                    instr.Previous.OpCode = OpCodes.Nop;
                    instr.Previous.Operand = null;
                    instr.OpCode = OpCodes.Nop;
                    instr.Operand = null;
                }
            }

            /* OH FOR replaced SAKE THIS IS EVEN WORSE
             * *ahem*
             * """Fix""" some games *cough* DUCK GAME *cough* locking up the main thread with a lock while LOADing CONTENT.
             * I deserve to be hanged for this, too.
             * -ade
             */
            if (instri >= 3 && instr.OpCode == OpCodes.Call &&
                ((MethodReference) instr.Operand).GetFindableID() ==
                    "System.Void System.Threading.Monitor::Enter(System.Object,System.Boolean&)") {
                // Check for content / load in context
                if (method.DeclaringType.FullName.ToLowerInvariant().Contains("content") ||
                    method.Name.ToLowerInvariant().Contains("load") || method.Name.ToLowerInvariant().Contains("content")) {
                    // "The input must be false.", MSDN says.
                    Log($"[PostProcess] [HACK!!!] Destroying possible content loading lock in {method.GetFindableID()}");
                    DestroyMonitorLock(method, instri);
                } else {
                    // Check for the previous load field, maximally 4 (dup, st, ld in between) behind.
                    for (int i = instri; 0 < i && instri - 4 <= i; i--) {
                        string name =
                            (method.Body.Instructions[i].Operand as FieldReference)?.Name ??
                            (method.Body.Instructions[i].Operand as MethodReference)?.Name ??
                            method.Body.Instructions[i].Operand?.ToString();
                        name = name?.ToLowerInvariant();
                        if (name != null && (name.Contains("load") || name.Contains("content"))) {
                            // "The input must be false.", MSDN says.
                            Log($"[PostProcess] [HACK!!!] Destroying possible content loading lock in {method.GetFindableID()}");
                            DestroyMonitorLock(method, instri);
                            break;
                        }
                    }
                }
            }
        }

19 Source : MaybeExTest.cs
with MIT License
from 0x1000000

public static MaybeEx<string> ValidateString(string s)
            => string.IsNullOrWhiteSpace(s) || !s.Contains(',')
                ? MaybeEx<string>.Nothing()
                : s;

19 Source : MaybeTest.cs
with MIT License
from 0x1000000

public static Maybe<string> ValidateString(string s)
            => string.IsNullOrWhiteSpace(s) || !s.Contains(',')
                ? Maybe<string>.Nothing()
                : s;

19 Source : Program.cs
with MIT License
from 0x1000000

private static void Generate(string projDir, string relativePath, IReadOnlyList<NodeModel> model, Action<IReadOnlyList<NodeModel>, StringBuilder> generator)
        {
            var path = Path.Combine(projDir, relativePath);

            StringBuilder newContentBuilder = new StringBuilder();

            bool skip = false;
            foreach (var line in File.ReadLines(path))
            {
                if (line.Contains("//CodeGenEnd"))
                {
                    generator.Invoke(model, newContentBuilder);
                    skip = false;
                }

                if (!skip)
                {
                    newContentBuilder.AppendLine(line);
                }

                if (line.Contains("//CodeGenStart"))
                {
                    skip = true;
                }
            }

            File.WriteAllText(path, newContentBuilder.ToString());
        }

19 Source : Program.cs
with MIT License
from 0x1000000

public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
        {
            List<NodeModel> result = new List<NodeModel>();
				
            var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);

            files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));

            var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
            var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);

            foreach (var tree in trees)
            {
                var semantic = cSharpCompilation.GetSemanticModel(tree);

                foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
                {
                    var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
                    
                    var isSuitable = clreplacedSymbol != null 
                                 && !clreplacedSymbol.IsAbstract 
                                 && clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
                                 && IsExpr(clreplacedSymbol) 
                                 && clreplacedSymbol.Name.StartsWith("Expr");
                        
                    if (!isSuitable)
                    {
                        continue;
                    }

                    var properties = GetProperties(clreplacedSymbol);

                    var subNodes = new List<SubNodeModel>();
                    var modelProps = new List<SubNodeModel>();

                    foreach (var constructor in clreplacedSymbol.Constructors)
                    {
                        foreach (var parameter in constructor.Parameters)
                        {
                            INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;

                            var correspondingProperty = properties.FirstOrDefault(prop =>
                                string.Equals(prop.Name,
                                    parameter.Name,
                                    StringComparison.CurrentCultureIgnoreCase));

                            if (correspondingProperty == null)
                            {
                                throw new Exception(
                                    $"Could not find a property for the constructor arg: '{parameter.Name}'");
                            }

                            var ta = replacedyzeSymbol(ref pType);

                            var subNodeModel = new SubNodeModel(correspondingProperty.Name,
                                parameter.Name,
                                pType.Name,
                                ta.ListName,
                                ta.IsNullable,
                                ta.HostTypeName);
                            if (ta.Expr)
                            {
                                subNodes.Add(subNodeModel);
                            }
                            else
                            {
                                modelProps.Add(subNodeModel);
                            }

                        }
                    }

                    result.Add(new NodeModel(clreplacedSymbol.Name,
                        modelProps.Count == 0 && subNodes.Count == 0,
                        subNodes,
                        modelProps));
                }
            }

            result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));

            return result;

            bool IsExpr(INamedTypeSymbol symbol)
            {
                if (symbol.Name == "IExpr")
                {
                    return true;
                }
                while (symbol != null)
                {
                    if (symbol.Interfaces.Any(HasA))
                    {
                        return true;
                    }
                    symbol = symbol.BaseType;
                }

                return false;


                bool HasA(INamedTypeSymbol iSym)
                {
                    if (iSym.Name == "IExpr")
                    {
                        return true;
                    }

                    return IsExpr(iSym);
                }
            }

            List<ISymbol> GetProperties(INamedTypeSymbol symbol)
            {
                List<ISymbol> result = new List<ISymbol>();
                while (symbol != null)
                {
                    result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                    symbol = symbol.BaseType;
                }

                return result;
            }

            Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
            {
                string listName = null;
                string hostType = null;
                if (typeSymbol.ContainingType != null)
                {
                    var host = typeSymbol.ContainingType;
                    hostType = host.Name;
                }

                var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;

                if (nullable && typeSymbol.Name == "Nullable")
                {
                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                if (typeSymbol.IsGenericType)
                {
                    if (typeSymbol.Name.Contains("List"))
                    {
                        listName = typeSymbol.Name;
                    }

                    if (typeSymbol.Name == "Nullable")
                    {
                        nullable = true;
                    }

                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
            }
        }

19 Source : Processes.cs
with GNU General Public License v3.0
from 0x2b00b1e5

public static Process GetMainWindowreplacedleByName(string query)
        {

            Process replacedle = null;
            Process[] p = Process.GetProcesses();
            string replacedle = string.Empty;
            for (var i = 0; i < p.Length; i++)
            {
                replacedle = p[i].MainWindowreplacedle;

                if (replacedle.Contains(query))
                    return p[i];
                
            }
            return replacedle;
        }

19 Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5

public static FLInfo GetFLInfo()
        {
            FLInfo i = new FLInfo();
            //Get replacedle
            string fullreplacedle;
            if (Process.GetProcessesByName("FL").Length >= 1)
            {
                fullreplacedle = Processes.GetMainWindowsTilteByProcessName("FL");
            }
            else if (Process.GetProcessesByName("FL64").Length >= 1)
            {
                fullreplacedle = Processes.GetMainWindowsTilteByProcessName("FL64");
            }
            else
            {
                fullreplacedle = null;
            }
            // Check if project is new/unsaved
                //if yes, return null
                //if not, return name
            if (!fullreplacedle.Contains("-"))
            {
                i.projectName = null;
                i.appName = fullreplacedle;
            }
                
            else
            {
                string[] splitbyminus = fullreplacedle.Split('-');
                i.projectName = splitbyminus[0];
                i.appName = splitbyminus[1];
            }
            //return
            return i;

        }

19 Source : RawFileType.cs
with MIT License
from 0xC0000054

private static Doreplacedent GetRAWImageDoreplacedent(string file)
        {
            Doreplacedent doc = null;

            string options = GetDCRawOptions();
            // Set the -Z - option to tell the LibRaw dcraw-emu example program
            // that the image data should be written to standard output.
            string arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} -Z - \"{1}\"", options, file);
            ProcessStartInfo startInfo = new ProcessStartInfo(ExecutablePath, arguments)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
            bool useTIFF = options.Contains("-T");

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();

                if (useTIFF)
                {
                    using (Bitmap image = new Bitmap(process.StandardOutput.BaseStream))
                    {
                        doc = Doreplacedent.FromImage(image);
                    }
                }
                else
                {
                    using (PixMapReader reader = new PixMapReader(process.StandardOutput.BaseStream, leaveOpen: true))
                    {
                        doc = reader.DecodePNM();
                    }
                }

                process.WaitForExit();
            }

            return doc;
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

private static List<string> GetAllProfiles(string DirectoryPath)
        {
            List<string> loginDataFiles = new List<string>
            {
                DirectoryPath + @"\Default\Login Data",
                DirectoryPath + @"\Login Data"
            }; 

            if (Directory.Exists(DirectoryPath))
            {
                foreach (string dir in Directory.GetDirectories(DirectoryPath))
                {
                    if (dir.Contains("Profile"))
                        loginDataFiles.Add(dir + @"\Login Data");
                }
            }

            return loginDataFiles;
        }

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

static void WriteToRegKey(string host, string username, string preplacedword, string keypath, string valuename)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connect to to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("SetStringValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = reginfo[1];
                inParams["sValueName"] = valuename;
                inParams["sValue"] = datavals;
                ManagementBaseObject outParams = registry.InvokeMethod("SetStringValue", inParams, null);
                if(Convert.ToInt32(outParams["ReturnValue"]) == 0)
                {
                    Console.WriteLine("[+] Created {0} {1} and put content inside", keypath, valuename);
                }
                else
                {
                    Console.WriteLine("[-] An error occured, please check values");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error      :  {0}", ex.Message));
                return;
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

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

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

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

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

        }

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

static void RemoveRegValue(string host, string username, string preplacedword, string keypath, string keyname)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+]  WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("DeleteValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = keypath;
                inParams["sValueName"] = keyname;
                ManagementBaseObject outParams1 = registry.InvokeMethod("DeleteValue", inParams, null);
                Console.WriteLine("[+] Deleted value at {0} {1}", keypath, keyname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }

19 Source : GodTier.cs
with GNU General Public License v3.0
from 1330-Studios

[HarmonyPrefix]
            public static bool Prefix(ref UpgradeScreen __instance, ref string towerId) {
                foreach (var tower in towers)
                    if (towerId.Contains(tower.Item1.baseId)) {
                        towerId = "DartMonkey";
                    }
                foreach (var paragon in paragons)
                    if (towerId.Contains(paragon.Item3)) {
                        towerId = paragon.Item3;
                        __instance.currTowerId = paragon.Item3;
                        __instance.hasTower = true;
                    }

                return true;
            }

19 Source : GodTier.cs
with GNU General Public License v3.0
from 1330-Studios

[HarmonyPrefix]
            public static bool Prefix(ref UpgradeScreen __instance, ref string towerId) {
                foreach (var tower in towers)
                    if (towerId.Contains(tower.Item1.baseId)) {
                        towerId = "DartMonkey";
                    }
                foreach (var paragon in paragons)
                    if (towerId.Contains(paragon.Item3)) {
                        towerId = paragon.Item3;
                        __instance.currTowerId = paragon.Item3;
                        __instance.hasTower = true;
                    }

                return true;
            }

19 Source : IPHelper.cs
with MIT License
from 1100100

public static string ReplaceIpPlaceholder(this string text)
        {
            if (!text.Contains(LocalIp))
                return text;
            return text.Replace(LocalIp, GetLocalInternetIp().ToString());
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : RedumpProvider.cs
with MIT License
from 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            var result = new HashSet<DiscKeyInfo>();
            try
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
                if (embeddedResources.Any())
                    Log.Trace("Loading embedded redump keys");
                else
                    Log.Warn("No embedded redump keys found");
                foreach (var res in embeddedResources)
                {
                    using var resStream = replacedembly.GetManifestResourceStream(res);
                    using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
                    foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
                                                                    || e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        using var keyStream = zipEntry.Open();
                        using var memStream = new MemoryStream();
                        await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
                        var discKey = memStream.ToArray();
                        if (zipEntry.Length > 256/8*2)
                        {
                            Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
                            continue;
                        }
                        if (discKey.Length > 16)
                        {
                            discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                        }

                        try
                        {
                            result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, $"Invalid disc key format: {discKey}");
                        }
                    }
                }
                if (result.Any())
                    Log.Info($"Found {result.Count} embedded redump keys");
                else
                    Log.Warn($"Failed to load any embedded redump keys");
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to load embedded redump keys");
            }

            Log.Trace("Loading cached redump keys");
            var diff = result.Count;
            try
            {
                if (Directory.Exists(discKeyCachePath))
                {
                    var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
                    foreach (var dkeyFile in matchingDiskKeys)
                    {
                        try
                        {
                            try
                            {
                                var discKey = File.ReadAllBytes(dkeyFile);
                                if (discKey.Length > 16)
                                {
                                    try
                                    {
                                        discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
                                    }
                                }
                                result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
                            }
                            catch (InvalidDataException)
                            {
                                File.Delete(dkeyFile);
                                continue;
                            }
                            catch (Exception e)
                            {
                                Log.Warn(e);
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Failed to load redump keys from local cache");
            }
            diff = result.Count - diff;
            Log.Info($"Found {diff} cached disc keys");
            return result;
        }

19 Source : TypeUtils.cs
with MIT License
from 1996v

public static bool IsAnonymousType(this Type type)
        {
            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                   && type.Name.Contains("AnonymousType")
                   && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
                   && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private bool hasNonChar(string str)
        {
            if(str != null){
                return str.Contains(",") || str.Contains("|") || str.Contains(";")
                    || str.Contains("\"") || str.Contains("'") || str.Contains(":");
            }
            return false;
        }

19 Source : Core.cs
with MIT License
from 1y0n

public static string Shellcode_Handle(string raw)
        {
            string result = "";
            //去掉所有换行 → 匹配出shellcode → 去掉所有空格 → 去掉引号、分号、括号 → 转换格式
            raw = raw.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");

            if (raw.Contains(@"\x"))
            {
                //c 类型的shellcode
                string pattern = @"=.*$";
                string temp = Regex.Match(raw, pattern).Value;
                result = temp.Replace(@"""", "").Replace(" ", "").Replace("=", "").Replace(";", "");
            }
            else if ((raw.Contains(@",0x")) || (raw.Contains(@", 0x")))
            {
                //c# 类型的shellcode
                string pattern = @"{.*}";
                string temp = Regex.Match(raw, pattern).Value;
                result = temp.Replace("{", "").Replace(" ", "").Replace("}", "").Replace(";", "");
            }
            else 
            {
                return "";
            }
            //转换成 c# 格式
            if (result.Contains(@"\x"))
            {
                result = result.Replace(@"\x", ",0x").TrimStart(',');
            }
            return result;
        }

19 Source : Utils.cs
with Apache License 2.0
from 214175590

public static string getLinuxName(string name)
        {
            if(name.Contains(" ")){
                return "\"" + name + "\"";
            }
            return name;
        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

public void checkTimedTask()
        {
            var now = DateTime.Now;
            String[] dts = null;
            string week = "";
            foreach (CmdShell cmds in seConfig.CustomShellList)
            {
                if (cmds.Target == itemConfig.ice.Uuid)
                {
                    if (cmds.TaskType == TaskType.Timed)
                    {
                        if (null != cmds.ShellList)
                        {
                            dts = null;
                            foreach (TaskShell task in cmds.ShellList)
                            {
                                dts = task.DateTime.Split('|');
                                if (dts[0] == "0")
                                {// 一次
                                    if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "1")
                                {// 每天
                                    if (now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "2")
                                {// 每周
                                    week = DateTime.Now.DayOfWeek.ToString("d");
                                    if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "3")
                                {// 每月
                                    if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "4")
                                {// 每年
                                    if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => {

                string srvdir = itemConfig.ice.IceSrvDir;
                if (null != srvdir)
                {
                    if (!srvdir.EndsWith("/"))
                    {
                        srvdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{icesrv_dir}"))
                {
                    shell = shell.Replace("{icesrv_dir}", srvdir);
                }

                if (shell.Contains("{server_name}"))
                {
                    shell = shell.Replace("{server_name}", l_server_name.Text);
                }

                if (shell.Contains("{adminsh}"))
                {
                    shell = shell.Replace("{adminsh}", srvdir + "bin/admin.sh");
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590

public void checkTimedTask()
        {
            var now = DateTime.Now;
            String[] dts = null;
            string week = "";
            foreach (CmdShell cmds in seConfig.CustomShellList)
            {
                if (cmds.Target == itemConfig.tomcat.Uuid)
                {
                    if (cmds.TaskType == TaskType.Timed)
                    {
                        if (null != cmds.ShellList)
                        {
                            dts = null;
                            foreach (TaskShell task in cmds.ShellList)
                            {
                                dts = task.DateTime.Split('|');
                                if (dts[0] == "0")
                                {// 一次
                                    if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "1")
                                {// 每天
                                    if (now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "2")
                                {// 每周
                                    week = DateTime.Now.DayOfWeek.ToString("d");
                                    if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "3")
                                {// 每月
                                    if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "4")
                                {// 每年
                                    if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.nginx.NginxPath;
                if (null != shdir)
                {
                    if (shdir.EndsWith("/"))
                    {
                        shdir = shdir.Substring(0, shdir.Length - 1);
                    }
                    shdir = shdir.Substring(0, shdir.LastIndexOf("/") + 1);
                }

                string shell = task.Shell;
                if (shell.Contains("{nginx_dir}"))
                {
                    shell = shell.Replace("{nginx_dir}", shdir);
                }

                if (shell.Contains("{nginx}"))
                {
                    shell = shell.Replace("{nginx}", itemConfig.nginx.NginxPath);
                }

                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : SpringBootMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => { 

                string shdir = itemConfig.spring.ShFileDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{sh_bin_dir}"))
                {
                    shell = shell.Replace("{sh_bin_dir}", shdir);
                }

                if (shell.Contains("{project_dir}"))
                {
                    shell = shell.Replace("{project_dir}", l_source_path.Text);
                }

                if (shell.Contains("{build_sh_file}"))
                {
                    shell = shell.Replace("{build_sh_file}", itemConfig.spring.BuildFileName);
                }

                if (shell.Contains("{ctl_sh_file}"))
                {
                    shell = shell.Replace("{ctl_sh_file}", itemConfig.spring.CrlFileName);
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : SpringBootMonitorForm.cs
with Apache License 2.0
from 214175590

public void checkTimedTask()
        {
            var now = DateTime.Now;
            String[] dts = null;
            string week = "";
            foreach (CmdShell cmds in seConfig.CustomShellList)
            {
                if (cmds.Target == itemConfig.spring.Uuid)
                {
                    if (cmds.TaskType == TaskType.Timed)
                    {
                        if (null != cmds.ShellList)
                        {
                            dts = null;
                            foreach (TaskShell task in cmds.ShellList)
                            {
                                dts = task.DateTime.Split('|');
                                if (dts[0] == "0")
                                {// 一次
                                    if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "1")
                                {// 每天
                                    if (now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "2")
                                {// 每周
                                    week = DateTime.Now.DayOfWeek.ToString("d");
                                    if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "3")
                                {// 每月
                                    if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                                else if (dts[0] == "4")
                                {// 每年
                                    if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
                                    {
                                        // 执行
                                        runTaskShell(cmds, task);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.tomcat.TomcatDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{tomcat_dir}"))
                {
                    shell = shell.Replace("{tomcat_dir}", shdir);
                }

                if (shell.Contains("{tomcat_webapps}"))
                {
                    shell = shell.Replace("{tomcat_webapps}", shdir + "webapps/");
                }

                if (shell.Contains("{tomcat_logs}"))
                {
                    shell = shell.Replace("{tomcat_logs}", shdir + "logs/");
                }

                if (shell.Contains("{tomcat_startup}"))
                {
                    shell = shell.Replace("{tomcat_startup}", shdir + "bin/startup.sh");
                }

                if (shell.Contains("{tomcat_shutdown}"))
                {
                    shell = shell.Replace("{tomcat_shutdown}", shdir + "bin/shutdown.sh");
                }
                
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : RazorModel.cs
with MIT License
from 2881099

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

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

		var dbinfo = fsql.CodeFirst.GetDbInfo(col.CsType);
		if (dbinfo != null && string.Compare(dbinfo.dbtypeFull.Replace("NOT NULL", "").Trim(), col.DbTypeTextFull, true) != 0)
			sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
		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 (sb.Any() == false) return null;
		return "[Column(" + string.Join(", ", sb) + ")]";
	}

19 Source : RazorModel.cs
with MIT License
from 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) + ")]";
	}

19 Source : FileManager.cs
with GNU General Public License v3.0
from 2dust

public static bool ZipExtractToFile(string fileName, string ignoredName)
        {
            try
            {
                using (ZipArchive archive = ZipFile.OpenRead(fileName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.Length == 0)
                        {
                            continue;
                        }
                        try
                        {
                            if (!Utils.IsNullOrEmpty(ignoredName) && entry.Name.Contains(ignoredName))
                            {
                                continue;
                            }
                            entry.ExtractToFile(Utils.GetPath(entry.Name), true);
                        }
                        catch (IOException ex)
                        {
                            Utils.SaveLog(ex.Message, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                return false;
            }
            return true;
        }

19 Source : VRHeightOffset.cs
with MIT License
from 39M

void Start() {
    if (VRDevice.isPresent && VRSettings.enabled && _deviceOffsets != null) {
#if UNITY_5_4_OR_NEWER
      string deviceName = VRSettings.loadedDeviceName;
#else
      string deviceName = VRDevice.family;
#endif
      var deviceHeightPair = _deviceOffsets.FirstOrDefault(d => deviceName.ToLower().Contains(d.DeviceName.ToLower()));
      if (deviceHeightPair != null) {
        transform.Translate(Vector3.up * deviceHeightPair.HeightOffset);
      }
    }
  }

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

public static Dictionary<string, dynamic> DeserializeYamlFile(string ruleFilePath, Options o)
        {
            var contents = File.ReadAllText(ruleFilePath);
            if (!contents.Contains("tags"))
            {
                Console.WriteLine($"Ignoring rule {ruleFilePath} (no tags)");
                return null;
            }
            if (o.Warning)
                contents = contents.Replace(Environment.NewLine + Environment.NewLine,
                        Environment.NewLine)
                    .Remove(0, contents.IndexOf("tags", StringComparison.Ordinal));
            if (contents.Contains("---"))
                contents = contents.Remove(contents.IndexOf("---", StringComparison.Ordinal));
            var deserializer = new YamlDotNet.Serialization.Deserializer();
            var dict = deserializer.Deserialize<Dictionary<string, dynamic>>(contents);
            return dict;
        }

19 Source : PlyHeader.cs
with MIT License
from 3DBear

private List<string> GetProperties(IList<string> header, int elementIndex)
        {
            var properties = new List<string>();
            for (int i = elementIndex + 1; i < header.Count; i++)
            {
                var property = header[i];
                if (property.Contains("property"))
                {
                    properties.Add(property);
                }
                else
                {
                    break;
                }
            }
            return properties;
        }

19 Source : RiggedHand.cs
with MIT License
from 39M

private void replacedignRiggedFingersByName(){
      List<string> palmStrings = new List<string> { "palm"};
      List<string> thumbStrings = new List<string> { "thumb", "tmb" };
      List<string> indexStrings = new List<string> { "index", "idx"};
      List<string> middleStrings = new List<string> { "middle", "mid"};
      List<string> ringStrings = new List<string> { "ring"};
      List<string> pinkyStrings = new List<string> { "pinky", "pin"};
      //find palm by name
      //Transform palm = null;
      Transform thumb = null;
      Transform index = null;
      Transform middle = null;
      Transform ring = null;
      Transform pinky = null;
      Transform[] children = transform.GetComponentsInChildren<Transform>();
      if (palmStrings.Any(w => transform.name.ToLower().Contains(w))){
        base.palm = transform;
      }
      else{
        foreach (Transform t in children) {
          if (palmStrings.Any(w => t.name.ToLower().Contains(w)) == true) {
            base.palm = t;

          }
        }
      }
      if (!palm) {
        palm = transform;
      }
      if (palm) {
        foreach (Transform t in children) {
          RiggedFinger preExistingRiggedFinger;
          preExistingRiggedFinger = t.GetComponent<RiggedFinger>();
          string lowercaseName = t.name.ToLower();
          if (!preExistingRiggedFinger) {
            if (thumbStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
              thumb = t;
              RiggedFinger newRiggedFinger = thumb.gameObject.AddComponent<RiggedFinger>();
              newRiggedFinger.fingerType = Finger.FingerType.TYPE_THUMB;
            }
            if (indexStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
              index = t;
              RiggedFinger newRiggedFinger = index.gameObject.AddComponent<RiggedFinger>();
              newRiggedFinger.fingerType = Finger.FingerType.TYPE_INDEX;
            }
            if (middleStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
              middle = t;
              RiggedFinger newRiggedFinger = middle.gameObject.AddComponent<RiggedFinger>();
              newRiggedFinger.fingerType = Finger.FingerType.TYPE_MIDDLE;
            }
            if (ringStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
              ring = t;
              RiggedFinger newRiggedFinger = ring.gameObject.AddComponent<RiggedFinger>();
              newRiggedFinger.fingerType = Finger.FingerType.TYPE_RING;
            }
            if (pinkyStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
              pinky = t;
              RiggedFinger newRiggedFinger = pinky.gameObject.AddComponent<RiggedFinger>();
              newRiggedFinger.fingerType = Finger.FingerType.TYPE_PINKY;
            }
          }
        }
      }
    }

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

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

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

private void ParseStatus(string line)
        {
            MatchCollection statusMatch = StatusEx.Matches(line);

            if (statusMatch.Count == 0)
            {
                NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
                return;
            }

            bool posUpdate = false;
            bool overrideUpdate = false;
            bool pinStateUpdate = false;
            bool resetPins = true;

            foreach (Match m in statusMatch)
            {
                if (m.Index == 1)
                {
                    Status = m.Groups[1].Value;
                    continue;
                }

                if (m.Groups[1].Value == "Ov")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedOverride = int.Parse(parts[0]);
                        RapidOverride = int.Parse(parts[1]);
                        SpindleOverride = int.Parse(parts[2]);
                        overrideUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "WCO")
                {
                    try
                    {
                        string OffsetString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = OffsetString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                OffsetString = string.Join(",", parts);
                            }
                        }

                        WorkOffset = Vector3.Parse(OffsetString);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (SyncBuffer && m.Groups[1].Value == "Bf")
                {
                    try
                    {
                        int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
                        int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;

                        if (used < 0)
                            used = 0;

                        BufferState = used;
                        RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "Pn")
                {
                    resetPins = false;

                    string states = m.Groups[2].Value;

                    bool stateX = states.Contains("X");
                    if (stateX != PinStateLimitX)
                        pinStateUpdate = true;
                    PinStateLimitX = stateX;

                    bool stateY = states.Contains("Y");
                    if (stateY != PinStateLimitY)
                        pinStateUpdate = true;
                    PinStateLimitY = stateY;

                    bool stateZ = states.Contains("Z");
                    if (stateZ != PinStateLimitZ)
                        pinStateUpdate = true;
                    PinStateLimitZ = stateZ;

                    bool stateP = states.Contains("P");
                    if (stateP != PinStateProbe)
                        pinStateUpdate = true;
                    PinStateProbe = stateP;
                }

                else if (m.Groups[1].Value == "F")
                {
                    try
                    {
                        FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "FS")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
                        SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }
            }

            SyncBuffer = false; //only run this immediately after button press

            //run this later to catch work offset changes before parsing position
            Vector3 NewMachinePosition = MachinePosition;

            foreach (Match m in statusMatch)
            {
                if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
                {
                    try
                    {
                        string PositionString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = PositionString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                PositionString = string.Join(",", parts);
                            }
                        }

                        NewMachinePosition = Vector3.Parse(PositionString);

                        if (m.Groups[1].Value == "WPos")
                            NewMachinePosition += WorkOffset;

                        if (NewMachinePosition != MachinePosition)
                        {
                            posUpdate = true;
                            MachinePosition = NewMachinePosition;
                        }
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

            }

            if (posUpdate && Connected && PositionUpdateReceived != null)
                PositionUpdateReceived.Invoke();

            if (overrideUpdate && Connected && OverrideChanged != null)
                OverrideChanged.Invoke();

            if (resetPins)  //no pin state received in status -> all zero
            {
                pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe;  //was any pin set before

                PinStateLimitX = false;
                PinStateLimitY = false;
                PinStateLimitZ = false;
                PinStateProbe = false;
            }

            if (pinStateUpdate && Connected && PinStateChanged != null)
                PinStateChanged.Invoke();

            if (Connected && StatusReceived != null)
                StatusReceived.Invoke(line);
        }

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

private void UpdateStatus(string line)
        {
            if (!Connected)
                return;

            if (line.Contains("$J="))
                return;

            if (line.StartsWith("[TLO:"))
            {
                try
                {
                    CurrentTLO = double.Parse(line.Substring(5, line.Length - 6), Constants.DecimalParseFormat);
                    RaiseEvent(PositionUpdateReceived);
                }
                catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
                return;
            }

            try
            {
                //we use a Regex here so G91.1 etc don't get recognized as G91
                MatchCollection mc = GCodeSplitter.Matches(line);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match m = mc[i];

                    if (m.Groups[1].Value != "G")
                        continue;

                    double code = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);

                    if (code == 17)
                        Plane = ArcPlane.XY;
                    if (code == 18)
                        Plane = ArcPlane.YZ;
                    if (code == 19)
                        Plane = ArcPlane.ZX;

                    if (code == 20)
                        Unit = ParseUnit.Imperial;
                    if (code == 21)
                        Unit = ParseUnit.Metric;

                    if (code == 90)
                        DistanceMode = ParseDistanceMode.Absolute;
                    if (code == 91)
                        DistanceMode = ParseDistanceMode.Incremental;

                    if (code == 49)
                        CurrentTLO = 0;

                    if (code == 43.1)
                    {
                        if (mc.Count > (i + 1))
                        {
                            if (mc[i + 1].Groups[1].Value == "Z")
                            {
                                CurrentTLO = double.Parse(mc[i + 1].Groups[2].Value, Constants.DecimalParseFormat);
                                RaiseEvent(PositionUpdateReceived);
                            }

                            i += 1;
                        }
                    }
                }
            }
            catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
        }

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

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {
            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

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

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {

            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

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

public static void BuildLink()
        {
            List<replacedembly> replacedemblieList = new List<replacedembly>();
            replacedemblieList.Add(typeof(Object).replacedembly);
            replacedemblieList.Add(typeof(UnityEngine.Object).replacedembly);
            replacedemblieList.Add(typeof(Transform).replacedembly);
            replacedemblieList.Add(typeof(GameObject).replacedembly);
            replacedemblieList.Add(typeof(Image).replacedembly);
            replacedemblieList.Add(typeof(Init).replacedembly);
            string[] filePaths = Directory.GetFiles("replacedets", "*.dll", SearchOption.AllDirectories);
            foreach (string item in filePaths)
            {
                if (item.ToLower().Contains("editor") || item.ToLower().Contains("plugins"))
                {
                    continue;
                }
                replacedemblieList.Add(replacedembly.LoadFrom(item));
            }
            replacedemblieList = replacedemblieList.Distinct().ToList();
            XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
            XmlElement linkerElement = xmlDoreplacedent.CreateElement("linker");
            foreach (replacedembly item in replacedemblieList)
            {
                XmlElement replacedemblyElement = xmlDoreplacedent.CreateElement("replacedembly");
                replacedemblyElement.SetAttribute("fullname", item.GetName().Name);
                foreach (Type typeItem in item.GetTypes())
                {
                    if (typeItem.FullName == "Win32")
                    {
                        continue;
                    }
                    XmlElement typeElement = xmlDoreplacedent.CreateElement("type");
                    typeElement.SetAttribute("fullname", typeItem.FullName);
                    typeElement.SetAttribute("preserve", "all");
                    //增加子节点
                    replacedemblyElement.AppendChild(typeElement);
                }
                linkerElement.AppendChild(replacedemblyElement);
            }
            xmlDoreplacedent.AppendChild(linkerElement);
            string path = "replacedets/link.xml";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            xmlDoreplacedent.Save(path);
        }

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

public static bool IsHotfix(string[] datas, out int index)
        {
            index = -1;
            for (int i = datas.Length - 1; i > 0; i--)
            {
                Regex regex = new Regex(@"IL_[\s\S]*[\s\S]*[\s\S]*[\s\S]*: call");
                Match match = regex.Match(datas[i]);
                if (match.Success)
                {
                    index = i + 1;
                    break;
                }
            }
            //不是热更
            if (index == -1)
            {
                for (int i = datas.Length - 1; i > 0; i--)
                {
                    bool isLog = false;
                    foreach (LogConfig item in logConfigList)
                    {
                        if (datas[i].Contains(item.name))
                        {
                            isLog = true;
                            break;
                        }
                    }
                    if (isLog)
                    {
                        index = i + 1;
                        break;
                    }
                }
                return false;
            }
            return true;
        }

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

public static void Draw(object obj, int indentLevel)
        {
            EditorGUILayout.BeginVertical();
            EditorGUI.indentLevel = indentLevel;
            string replacedemblyName = string.Empty;
            switch (Path.GetFileNameWithoutExtension(obj.GetType().replacedembly.ManifestModule.Name))
            {
                case "Unity.Model":
                    replacedemblyName = "Unity.Model";
                    break;
                case "Unity.Hotfix":
                    replacedemblyName = "Unity.Hotfix";
                    break;
                case "ILRuntime":
                    replacedemblyName = "Unity.Hotfix";
                    break;
            }
            if (replacedemblyName == "Unity.Model")
            {
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Model.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
            }
            else
            {
#if ILRuntime
                FieldInfo[] fieldInfos = ILRuntimeManager.Instance.appdomain.LoadedTypes[obj.ToString()].ReflectionType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    if (item.FieldType is ILRuntimeWrapperType)
                    {
                        //基础类型绘制
                        Type type = ((ILRuntimeWrapperType)item.FieldType).RealType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (listObjectTypes.ContainsKey((obj, item)))
                        {
                            ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if (type.GetInterface("IList") != null)
                        {
                            ListObjectType listObjectType = new ListObjectType();
                            if (value == null)
                            {
                                continue;
                            }
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            listObjectTypes.Add((obj, item), listObjectType);
                            continue;
                        }
                        foreach (IObjectType objectTypeItem in objectList)
                        {
                            if (!objectTypeItem.IsType(type))
                            {
                                continue;
                            }
                            string fieldName = item.Name;
                            if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                            {
                                continue;
                            }
                            if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                            {
                                fieldName = fieldName.Substring(1, fieldName.Length - 17);
                            }
                            value = objectTypeItem.Draw(type, fieldName, value, null);
                            item.SetValue(obj, value);
                        }
                    }
                    else
                    {
                        //自定义类型绘制
                        Type type = item.FieldType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (objectObjectTypes.ContainsKey((obj, item)))
                        {
                            ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "ILRuntime.dll")
                        {
                            ObjectObjectType objectObjectType = new ObjectObjectType();
                            if (value == null)
                            {
                                object instance = ILRuntimeManager.Instance.appdomain.Instantiate(type.ToString());
                                objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                                item.SetValue(obj, instance);
                            }
                            else
                            {
                                objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            }
                            objectObjectTypes.Add((obj, item), objectObjectType);
                            continue;
                        }
                    }
                }
#else
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Hotfix.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
#endif
                EditorGUI.indentLevel = indentLevel;
                EditorGUILayout.EndVertical();
            }
        }

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

public static List<string> ReadCSPROJ(string path, ref List<string> defineList, ref List<string> dllFilePathList)
        {
            List<string> csFilePathList = new List<string>();
            List<string> csprojPathList = new List<string>();
            XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
            xmlDoreplacedent.Load(path);
            XmlNode xmlNode = null;
            foreach (XmlNode item in xmlDoreplacedent.ChildNodes)
            {
                if (item.Name == "Project")
                {
                    xmlNode = item;
                    break;
                }
            }
            foreach (XmlNode item in xmlNode.ChildNodes)
            {
                if (item.Name == "PropertyGroup")
                {
                    foreach (XmlNode childItem in item.ChildNodes)
                    {
                        if (childItem.Name == "DefineConstants")
                        {
                            //宏引用
                            string define = childItem.InnerText;
                            defineList.AddRange(define.Split(';'));
                        }
                    }
                }
                if (item.Name == "ItemGroup")
                {
                    foreach (XmlNode childItem in item.ChildNodes)
                    {
                        if (childItem.Name == "Reference")
                        {
                            //dll引用
                            string dllFilePath = childItem.FirstChild.InnerText.Replace("\\", "/");
                            dllFilePathList.Add(dllFilePath);
                        }
                        if (childItem.Name == "Compile")
                        {
                            //cs引用
                            string csFilePath = childItem.Attributes[0].Value.Replace("\\", "/");
                            csFilePathList.Add(csFilePath);
                        }
                        if (childItem.Name == "ProjectReference")
                        {
                            //工程引用
                            string csprojFilePath = childItem.Attributes[0].Value;
                            csprojPathList.Add(csprojFilePath);
                        }
                    }
                }
            }
            //遍历工程引用
            foreach (string item in csprojPathList)
            {
                if (item.ToLower().Contains("editor"))
                {
                    continue;
                }
                ReadCSPROJ(item, ref defineList, ref dllFilePathList);
                string dllFilePath = "Library/Scriptreplacedemblies/" + item.Replace(".csproj", ".dll");
                if (File.Exists(dllFilePath))
                {
                    dllFilePathList.Add(dllFilePath);
                }
            }
            defineList = defineList.Distinct().ToList();
            //移除相关宏
            for (int i = defineList.Count - 1; i >= 0; i--)
            {
                if (defineList[i].Contains("UNITY_EDITOR"))
                {
                    defineList.RemoveAt(i);
                }
            }
            dllFilePathList = dllFilePathList.Distinct().ToList();
            return csFilePathList;
        }

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

public static string GetPath(PathType type, params string[] folders)
        {
            string path = string.Empty;
            string subPath = string.Empty;
            switch (type)
            {
                case PathType.DataPath:
                    path = Application.dataPath;
                    break;
                case PathType.StreamingreplacedetsPath:
                    path = Application.streamingreplacedetsPath;
                    break;
                case PathType.PersistentDataPath:
                    path = Application.persistentDataPath;
                    break;
            }
            if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
            {
                if (type == PathType.PersistentDataPath && folders.Length == 1 && folders[0].Contains("/"))
                {
                    return GetPath(path, folders[0]);
                }
            }
            else
            {
                if (folders.Length == 1 && folders[0].Contains("/"))
                {
                    return GetPath(path, folders[0]);
                }
            }
            for (int i = 0; i < folders.Length; i++)
            {
                if (i == folders.Length - 1)
                {
                    subPath = $"{subPath}{folders[i]}";
                }
                else
                {
                    subPath = $"{subPath}{folders[i]}/";
                }
                if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
                {
                    if (type == PathType.PersistentDataPath && !string.IsNullOrEmpty(subPath))
                    {
                        DirectoryUtil.CreateDirectory($"{path}/{subPath}");
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(subPath))
                    {
                        DirectoryUtil.CreateDirectory($"{path}/{subPath}");
                    }
                }
            }
            return $"{path}/{subPath}";
        }

See More Examples