string.IndexOf(string)

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

4041 Examples 7

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

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

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

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

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

19 View Source File : SQLite.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

public bool ReadTable(string TableName)
        {
            int index = -1;
            int length = this.master_table_entries.Length - 1;
            for (int i = 0; i <= length; i++)
            {
                if (this.master_table_entries[i].item_name.ToLower().CompareTo(TableName.ToLower()) == 0)
                {
                    index = i;
                    break;
                }
            }
            if (index == -1)
            {
                return false;
            }
            string[] strArray = this.master_table_entries[index].sql_statement.Substring(this.master_table_entries[index].sql_statement.IndexOf("(") + 1).Split(new char[] { ',' });
            int num6 = strArray.Length - 1;
            for (int j = 0; j <= num6; j++)
            {
                strArray[j] = (strArray[j]).TrimStart();
                int num4 = strArray[j].IndexOf(" ");
                if (num4 > 0)
                {
                    strArray[j] = strArray[j].Substring(0, num4);
                }
                if (strArray[j].IndexOf("UNIQUE") == 0)
                {
                    break;
                }
                this.field_names = (string[])Utils.CopyArray((Array)this.field_names, new string[j + 1]);
                this.field_names[j] = strArray[j];
            }
            return this.ReadTableFromOffset((ulong)((this.master_table_entries[index].root_num - 1L) * this.page_size));
        }

19 View Source File : StringExtensionMethods.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static string AfterFirst(this string str, string sub)
    {
        var idx = str.IndexOf(sub);
        return idx < 0 ? "" : str.Substring(idx + sub.Length);
    }

19 View Source File : StringExtensionMethods.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static string BeforeFirst(this string str, string sub)
    {
        var idx = str.IndexOf(sub);
        return idx < 0 ? "" : str.Substring(0, idx);
    }

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

void SrvPath_TextChanged(object sender, EventArgs e)
        {
            string path = stb_ice_srvpath.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                string appname = stb_ice_appname.Text;

                if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
                {
                    try
                    {
                        if (get_ice_port_run)
                        {
                            return;
                        }
                        get_ice_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = string.Format("{0}config/{1}.xml", path, appname);
                        string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
                            if (list != null && list.Count > 0)
                            {
                                List<Hashtable> appList = null, nodeList = null;
                                List<Hashtable> serverList = null;
                                string ports = "", nodeName = "", serverName = "";
                                foreach (Hashtable one in list)
                                {
                                    if (one["NodeName"].ToString() == "application")
                                    {
                                        appList = (List<Hashtable>)one["ChildList"];
                                        foreach (Hashtable two in appList)
                                        {
                                            if (two["NodeName"].ToString() == "node")
                                            {
                                                nodeName = two["name"].ToString();
                                                nodeList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in nodeList)
                                                {
                                                    if (four["NodeName"].ToString() == "server-instance")
                                                    {
                                                        ports += "," + four["serverport"].ToString();
                                                    }
                                                }

                                            }

                                            if (two["NodeName"].ToString() == "server-template")
                                            {
                                                serverList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in serverList)
                                                {
                                                    if (four["NodeName"].ToString() == "icebox")
                                                    {
                                                        serverName = four["id"].ToString();
                                                        serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
                                                        break;
                                                    }
                                                }
                                            }

                                            if (ports != "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                                                
                                stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
                                {
                                    stb_ice_servername.Text = serverName;
                                    stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
                                });
                            }
                            get_ice_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

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

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

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

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

            }
        }

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

private string getFileExt(string filename)
        {
            string ext = "";
            if (null != filename && filename.IndexOf(".") != -1)
            {
                ext = filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() + "文件";
            }
            return ext;
        }

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

private string getFileOwner(string str, int size)
        {
            string user = "";
            if (null != str && str.Length > 5 && str.IndexOf(" ") != -1)
            {
                string[] arrs = str.Split(' ');
                if (arrs.Length > size)
                {
                    int i = 0, j = 0;
                    foreach (string s in arrs)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            i++;
                            if (i >= size)
                            {
                                user = arrs[j];
                                break;
                            }
                        }
                        j++;
                    }
                }
            }
            return user;
        }

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

public void CheckIceServerResult(string s)
        {
            monitorForm.RunShell("quit", false);
            if (s != null && s.IndexOf("active (pid =") != -1)
            {
                SetStatus(1);

                // 检测监控项
                StartCheckItems();
            }
            else
            {
                SetStatus(0);
            }
        }

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

public void CheckItem(string uri, ListViewItem item)
        {
            try
            {
                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetLisreplacedemStatus(item, 1);
                        }
                        else
                        {
                            // 异常
                            SetLisreplacedemStatus(item, 2);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 异常
                        SetLisreplacedemStatus(item, 2);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem(uri, item);
                }
                logger.Error("http请求异常:" + e.Message, e);
            }
        }

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

public void CheckNginxResult(string s)
        {
            if(s != null && s.IndexOf(" master process ") != -1){
                SetStatus(1);

                // 检车监控项
                StartCheckItems();
            }
            else
            {
                SetStatus(0);
            }
        }

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

public void CheckItem()
        {
            try
            {
                button5.Enabled = false;
                button5.Text = "检测中..";

                timer = resetTimer;
                progressBar1.Value = timer;

                string uri = l_pro_visit_url.Text;
                //HttpUtil.get(uri, new DownloadStringCompletedEventHandler(AsyncDownloadCompleted));

                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetStatus(1);
                        }
                        else
                        {
                            // 异常
                            SetStatus(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        SetStatus(0);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }                    
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
                logger.Error("http请求异常:" + e.Message, e);
            }

            button5.Enabled = true;
            button5.Text = "立即检测";
        }

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

private void AsyncDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                // 返回结果在 e.Result 里
                string html = e.Result;
                if (e.Error == null || string.IsNullOrWhiteSpace(html))
                {
                    // 正常
                    SetStatus(1);
                    return;
                }
                else if (e.Error != null)
                {
                    string error = e.Error.Message;
                    logger.Error("异步Http请求异常:" + error, e.Error);
                }
                // 异常
                SetStatus(0);
            }
            catch (Exception ex)
            {
                if (ex.InnerException.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (ser, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
            }
        }

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

public static List<YmlLine> FormatYml(string content, bool beautify = false)
        {
            List<YmlLine> list = new List<YmlLine>();
            string[] lines = content.Split('\n');
            YmlLine ylText = null;
            int index1 = -1, index2 = -1, count = 0, num = 0;
            string startStr = null, endStr = null, line = "";
            string key = null, value = null, mh = ":";
            List<int> levels = new List<int>();
            for(int i = 0, k = lines.Length; i < k; i++){
                line = lines[i];

                if(line.TrimStart().StartsWith("#")){
                    ylText = new YmlLine()
                    {
                        Text = line + "\n",
                        Color = Color.Gray
                    };
                    list.Add(ylText);
                }
                else
                {
                    // 非整行注释

                    // 美化
                    if (beautify)
                    {
                        count = StartSpaceCount(line);
                        if (count == 0)
                        {
                            levels.Clear();
                        }
                        // level
                        if (!levels.Contains(count))
                        {
                            levels.Add(count);
                            levels.Sort();
                        }
                        num = levels.IndexOf(count) * 4;
                        if (num > count)
                        {
                            line = GetSpace(num - count) + line;
                        }
                    }                    

                    // 行中有井号,但不是首位#
                    index2 = line.IndexOf("#");
                    if(index2 > 0){
                        startStr = line.Substring(0, index2);

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value,
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            ylText = new YmlLine()
                            {
                                Text = "#" + startStr,
                                Color = Color.Gray
                            };
                            list.Add(ylText);
                        }

                        // 注释掉的部分
                        endStr = line.Substring(index2);
                        ylText = new YmlLine()
                        {
                            Text = endStr + "\n",
                            Color = Color.Gray
                        };
                        list.Add(ylText);
                    }
                    else
                    {
                        // 行中无井号
                        startStr = line;

                        index1 = startStr.IndexOf(":");
                        if (index1 > 0)
                        {
                            // key
                            key = startStr.Substring(0, index1);
                            ylText = new YmlLine()
                            {
                                Text = key,
                                Color = Color.OrangeRed
                            };
                            list.Add(ylText);
                            // :
                            ylText = new YmlLine()
                            {
                                Text = mh,
                                Color = Color.Violet
                            };
                            list.Add(ylText);
                            // value
                            value = startStr.Substring(index1 + 1);
                            ylText = new YmlLine()
                            {
                                Text = value + "\n",
                                Color = getTextColor(value)
                            };
                            list.Add(ylText);
                        }
                        else
                        {
                            // 行中无井号,且是不合规的配置值
                            if (string.IsNullOrWhiteSpace(line))
                            {
                                ylText = new YmlLine()
                                {
                                    Text = line + "\n",
                                    Color = Color.OrangeRed
                                };
                            }
                            else
                            {
                                ylText = new YmlLine()
                                {
                                    Text = "#" + line + "\n",
                                    Color = Color.Gray
                                };
                            }                            
                            list.Add(ylText);                            
                        }
                    }
                }
            }
            return list;
        }

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

public static YmlError ValidateYml(string content)
        {
            YmlError result = null;
            string[] lines = content.Split('\n');
            int index1 = -1, index2 = -1, lineIndex = 1, index = 0;
            string startStr = null;
            foreach (string line in lines)
            {
                if (!line.TrimStart().StartsWith("#"))
                {
                    if (line.IndexOf("	") != -1 && line.Substring(0, line.IndexOf("	")).IndexOf("#") == -1)
                    {
                        result = new YmlError();
                        result.line = lineIndex;
                        result.index = content.IndexOf("	", index);
                        result.msg = string.Format("第{0}行,位置{1}包含Tab符", lineIndex, line.IndexOf("	"));
                        break;
                    }
                    else if (!string.IsNullOrWhiteSpace(line))
                    {
                        index2 = line.IndexOf("#");
                        if (index2 > 0)
                        {
                            startStr = line.Substring(0, index2);
                            index1 = startStr.IndexOf(":");
                            if (index1 <= 0)
                            {
                                result = new YmlError();
                                result.line = lineIndex;
                                result.index = index;
                                result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
                                break;
                            }
                        }
                        else
                        {
                            index1 = line.IndexOf(":");
                            if (index1 <= 0)
                            {
                                result = new YmlError();
                                result.line = lineIndex;
                                result.index = index;
                                result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
                                break;
                            }
                        }
                    }
                }
                
                lineIndex++;
                index += line.Length;
            }        
            return result;
        }

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

public static List<Message> FormatMessage(List<Message> msgList, string message)
        {
            if (msgList == null)
            {
                msgList = new List<Message>();
            }
            Message msg = null;
            if (message.IndexOf(T0m) == -1 && message.IndexOf(Tm) == -1 && message.IndexOf(TK) == -1)
            {
                msg = new Message();
                msg.Text = message;
                msgList.Add(msg);
            }
            else
            {
                message = message.Replace(TK, "");
                message = message.Replace(Tm, T0m);

                string[] arrs = message.Split(new string[] { T0m }, StringSplitOptions.None);
                string str = null;
                int index = -1;
                foreach (string line in arrs)
                {
                    str = line.Replace("\r\n", "\n");
                    if ((index = str.IndexOf(T0131)) != -1)
                    {
                        SplitMsg(msgList, str, index, T0131, Color.IndianRed, Color.Empty);                        
                    }
                    else if ((index = str.IndexOf(T0132)) != -1)
                    {
                        SplitMsg(msgList, str, index, T0132, Color.LawnGreen, Color.Empty);
                    }
                    else if ((index = str.IndexOf(T0134)) != -1)
                    {
                        SplitMsg(msgList, str, index, T0134, Color.RoyalBlue, Color.Empty);
                    }
                    else if ((index = str.IndexOf(T0136)) != -1)
                    {
                        SplitMsg(msgList, str, index, T0136, Color.PowderBlue, Color.Empty);
                    }
                    else if ((index = str.IndexOf(T3042)) != -1)
                    {
                        SplitMsg(msgList, str, index, T3042, Color.CadetBlue, Color.Green);
                    }
                    else
                    {
                        msg = new Message();
                        msg.Text = str;
                        msgList.Add(msg);
                    }
                }
            }            
            return msgList;
        }

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

private static string GetParameterTypeName(Type type)
        {
            string typeName = type.FullName;
            if (type.GenericTypeArguments?.Length > 0)
            {
                //Nullable`1
                typeName = typeName.Substring(0, typeName.IndexOf("`"));              
                typeName += "{";
                for (int i = 0; i < type.GenericTypeArguments.Length; i++)
                {
                    if (i > 0)
                    {
                        typeName += ",";
                    }
                    typeName += GetParameterTypeName(type.GenericTypeArguments[i]);
                }
                typeName += "}";
            }
            return typeName;
        }

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

public void CheckItem()
        {
            button5.Enabled = false;
            button5.Text = "检测中..";
            try
            {
                timer = resetTimer;
                progressBar1.Value = timer;

                string uri = l_visit_url.Text;

                RequestHttpWebRequest req = new RequestHttpWebRequest();
                req.GetResponseAsync(new RequestInfo(uri), x =>
                {
                    try
                    {
                        if (x.StatusCode == HttpStatusCode.OK || x.StatusCode == HttpStatusCode.Found)
                        {
                            // 正常
                            SetStatus(1);
                        }
                        else
                        {
                            // 异常
                            SetStatus(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        SetStatus(0);
                        logger.Error("http请求异常:" + ex.Message, ex);
                    }
                });
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("未能为 SSL/TLS 安全通道建立信任关系") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                    CheckItem();
                }
                logger.Error("http请求异常:" + e.Message, e);
            }
            button5.Enabled = true;
            button5.Text = "立即检测";
        }

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

public void LoadProjectList()
        {
            ThreadPool.QueueUserWorkItem((a) => {
                List<JObject> itemList = new List<JObject>();
                // 1、获取webapps下的项目
                ArrayList files = (ArrayList)monitorForm.RunSftpShell(string.Format("ls {0}webapps/", l_tomcat_path.Text), false, false);
                if (files != null)
                {
                    string dirname = "";
                    JObject json = null;
                    Object obj = null;
                    for (int ii = 0; ii < files.Count; ii++)
                    {
                        obj = files[ii];
                        if (obj is ChannelSftp.LsEntry)
                        {
                            dirname = ((ChannelSftp.LsEntry)obj).getFilename();
                            if (dirname.IndexOf(".") == -1 && dirname.IndexOf(":") == -1)
                            {
                                json = new JObject();
                                json.Add("name", dirname);
                                json.Add("url", l_visit_url.Text + (dirname == "ROOT" ? "" : "/" + dirname));
                                json.Add("path", l_tomcat_path.Text + "webapps/" + dirname);
                                itemList.Add(json);
                            }
                        }
                    }
                }
                // 2、获取server.xml中的映射配置
                List<JObject> itemList2 = loadTomcatServerProject();
                foreach (JObject p in itemList2)
                {
                    itemList.Add(p);
                }
                // 渲染列表
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    projects.Items.Clear();
                    ListViewItem item = null;
                    ListViewItem.ListViewSubItem subItem = null;
                    foreach (JObject pro in itemList)
                    {
                        item = new ListViewItem();
                        item.Tag = pro;
                        item.Name = pro["name"].ToString();
                        item.Text = pro["url"].ToString();

                        subItem = new ListViewItem.ListViewSubItem();
                        subItem.Text = pro["path"].ToString();
                        item.SubItems.Add(subItem);
                    
                        projects.Items.Add(item);
                    }
                });
            });
        }

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

private void 行注释ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = ymlEditor.GetFirstCharIndexOfCurrentLine();
            int line = ymlEditor.GetLineFromCharIndex(index);
            int start = ymlEditor.SelectionStart;
            string lineStr = ymlEditor.Lines[line];
            if(lineStr.TrimStart().StartsWith("#")){
                ymlEditor.SelectionStart = index + lineStr.IndexOf("#");
                ymlEditor.SelectionLength = 1;
                ymlEditor.SelectedText = "";
            }
            else
            {
                ymlEditor.SelectionStart = start;
                ymlEditor.SelectionLength = 0;
                ymlEditor.SelectedText = "#";
            }
            ymlEditor.Focus();
        }

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

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

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

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

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

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

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

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

                    lists.Add(item);
                }
            }

            return lists;
        }

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

private static ParamModel GetParam(PropertyInfo pi, int index = 0)
        {
            PTypeModel ptype = GetPType(pi.PropertyType);

            string piId = null;
            if (pi.DeclaringType != null)
            {
                string declaringTypeName = pi.DeclaringType.ToString();
                if (declaringTypeName.IndexOf("`") != -1)
                {   //泛型属性Id结构如下:P:Jc.Core.Robj`1.Result
                    declaringTypeName = declaringTypeName.Substring(0, declaringTypeName.IndexOf("`") + 2);
                }
                piId = $"P:{declaringTypeName}.{pi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = pi.Name,
                Id = piId,
                PType = ptype,
                CustomAttrList = pi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };
            if(pi.CustomAttributes.Count()>0)
            {

            }
            return param;
        }

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

internal static string GetTypeName(Type type)
        {
            string typeName = type.Name;
            if (type.GenericTypeArguments?.Length > 0)
            {
                //Nullable`1
                typeName = typeName.Substring(0,typeName.IndexOf("`"));
                if(typeName== "Nullable")
                {
                    typeName = type.GenericTypeArguments[0].Name + "?";
                }
                else
                {
                    typeName += "<";
                    for (int i = 0; i < type.GenericTypeArguments.Length; i++)
                    {
                        if (i == 0)
                        {
                            typeName += GetTypeName(type.GenericTypeArguments[i]);
                        }
                        else
                        {
                            typeName += "," + GetTypeName(type.GenericTypeArguments[i]);
                        }
                    }
                    typeName += ">";
                }
            }
            return typeName;
        }

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

private string getFileOwner(string str)
        {
            string user = "";
            if (null != str && str.Length > 5 && str.IndexOf(" ") != -1)
            {                
                string[] arrs = str.Split(' ');
                if(arrs.Length > 3){
                    int i = 0, j = 0;
                    foreach(string s in arrs){
                        if(!string.IsNullOrWhiteSpace(s)){
                            i++;
                            if(i >= 3){
                                user = arrs[j];
                                break;
                            }
                        }
                        j++;
                    }                    
                }
            }
            return user;
        }

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

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

            stb_local_pdir.SkinTxt.TextChanged += stb_local_pdir_TextChanged;

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

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


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

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

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

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

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

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

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

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

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

public static string TranslateUrl(string url, string baseDir) {
				if (string.IsNullOrEmpty(baseDir))
				{
					baseDir = AppContext.BaseDirectory + "/";
					if (url.StartsWith(AppContext.BaseDirectory)) url = url.Substring(AppContext.BaseDirectory.Length).TrimStart('/');
				}
				if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir);
				if (url.StartsWith("~/")) url = url.Substring(1);
				if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/')));
				if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\')));
				if (url.IndexOf(":\\") != -1) return url;
				return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url));
			}

19 View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件 
                string result = clipboardData.TrimEx();// Utils.GetClipboardData();
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return null;
                }

                if (result.StartsWith(Global.vmessProtocol))
                {
                    int indexSplit = result.IndexOf("?");
                    if (indexSplit > 0)
                    {
                        vmessItem = ResolveStdVmess(result) ?? ResolveVmess4Kitsunebi(result);
                    }
                    else
                    {
                        vmessItem.configType = (int)EConfigType.Vmess;
                        result = result.Substring(Global.vmessProtocol.Length);
                        result = Utils.Base64Decode(result);

                        //转成Json
                        VmessQRCode vmessQRCode = Utils.FromJson<VmessQRCode>(result);
                        if (vmessQRCode == null)
                        {
                            msg = UIRes.I18N("FailedConversionConfiguration");
                            return null;
                        }

                        vmessItem.network = Global.DefaultNetwork;
                        vmessItem.headerType = Global.None;

                        vmessItem.configVersion = Utils.ToInt(vmessQRCode.v);
                        vmessItem.remarks = Utils.ToString(vmessQRCode.ps);
                        vmessItem.address = Utils.ToString(vmessQRCode.add);
                        vmessItem.port = Utils.ToInt(vmessQRCode.port);
                        vmessItem.id = Utils.ToString(vmessQRCode.id);
                        vmessItem.alterId = Utils.ToInt(vmessQRCode.aid);
                        vmessItem.security = Utils.ToString(vmessQRCode.scy);

                        if (!Utils.IsNullOrEmpty(vmessQRCode.scy))
                        {
                            vmessItem.security = vmessQRCode.scy;
                        }
                        else
                        {
                            vmessItem.security = Global.DefaultSecurity;
                        }
                        if (!Utils.IsNullOrEmpty(vmessQRCode.net))
                        {
                            vmessItem.network = vmessQRCode.net;
                        }
                        if (!Utils.IsNullOrEmpty(vmessQRCode.type))
                        {
                            vmessItem.headerType = vmessQRCode.type;
                        }

                        vmessItem.requestHost = Utils.ToString(vmessQRCode.host);
                        vmessItem.path = Utils.ToString(vmessQRCode.path);
                        vmessItem.streamSecurity = Utils.ToString(vmessQRCode.tls);
                        vmessItem.sni = Utils.ToString(vmessQRCode.sni);
                    }

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else if (result.StartsWith(Global.ssProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveSSLegacy(result);
                    if (vmessItem == null)
                    {
                        vmessItem = ResolveSip002(result);
                    }
                    if (vmessItem == null)
                    {
                        return null;
                    }
                    if (vmessItem.address.Length == 0 || vmessItem.port == 0 || vmessItem.security.Length == 0 || vmessItem.id.Length == 0)
                    {
                        return null;
                    }

                    vmessItem.configType = (int)EConfigType.Shadowsocks;
                }
                else if (result.StartsWith(Global.socksProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Socks;
                    result = result.Substring(Global.socksProtocol.Length);
                    //remark
                    int indexRemark = result.IndexOf("#");
                    if (indexRemark > 0)
                    {
                        try
                        {
                            vmessItem.remarks = Utils.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
                        }
                        catch { }
                        result = result.Substring(0, indexRemark);
                    }
                    //part decode
                    int indexS = result.IndexOf("@");
                    if (indexS > 0)
                    {
                    }
                    else
                    {
                        result = Utils.Base64Decode(result);
                    }

                    string[] arr1 = result.Split('@');
                    if (arr1.Length != 2)
                    {
                        return null;
                    }
                    string[] arr21 = arr1[0].Split(':');
                    //string[] arr22 = arr1[1].Split(':');
                    int indexPort = arr1[1].LastIndexOf(":");
                    if (arr21.Length != 2 || indexPort < 0)
                    {
                        return null;
                    }
                    vmessItem.address = arr1[1].Substring(0, indexPort);
                    vmessItem.port = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
                    vmessItem.security = arr21[0];
                    vmessItem.id = arr21[1];
                }
                else if (result.StartsWith(Global.trojanProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Trojan;

                    Uri uri = new Uri(result);
                    vmessItem.address = uri.IdnHost;
                    vmessItem.port = uri.Port;
                    vmessItem.id = uri.UserInfo;

                    var qurery = HttpUtility.ParseQueryString(uri.Query);
                    vmessItem.sni = qurery["sni"] ?? "";

                    var remarks = uri.Fragment.Replace("#", "");
                    if (Utils.IsNullOrEmpty(remarks))
                    {
                        vmessItem.remarks = "NONE";
                    }
                    else
                    {
                        vmessItem.remarks = Utils.UrlDecode(remarks);
                    }
                }
                else if (result.StartsWith(Global.vlessProtocol))
                {
                    vmessItem = ResolveStdVLESS(result);

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else
                {
                    msg = UIRes.I18N("NonvmessOrssProtocol");
                    return null;
                }
            }
            catch
            {
                msg = UIRes.I18N("Incorrectconfiguration");
                return null;
            }

            return vmessItem;
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool IsIP(string ip)
        {
            //如果为空
            if (IsNullOrEmpty(ip))
            {
                return false;
            }

            //清除要验证字符串中的空格
            //ip = ip.TrimEx();
            //可能是CIDR
            if (ip.IndexOf(@"/") > 0)
            {
                string[] cidr = ip.Split('/');
                if (cidr.Length == 2)
                {
                    if (!IsNumberic(cidr[0]))
                    {
                        return false;
                    }
                    ip = cidr[0];
                }
            }


            //模式字符串
            string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";

            //验证
            return IsMatch(ip, pattern);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 3583Bytes

private static void RunEngine()
	{
		bool ShowBoard = false;

		var engine = new Engine();



		Console.WriteLine("Chess Core");
		Console.WriteLine("Created by Adam Berent");
		Console.WriteLine("Version: 1.0.1");
		Console.WriteLine("");
		Console.WriteLine("Type quit to exit");
		Console.WriteLine("Type show to show board");
		Console.WriteLine("");
		Console.WriteLine("feature setboard=1");


		while (true)
		{
			try
			{
				if (ShowBoard)
				{
					DrawBoard(engine);
				}

				if (engine.WhoseMove != engine.HumanPlayer)
				{
					MakeEngineMove(engine);
				}
				else
				{
					Console.WriteLine();

					string move = Console.ReadLine();

					if (String.IsNullOrEmpty(move))
					{
						continue;
					}

					move = move.Trim();


					if (move == "new")
					{
						engine.NewGame();
						continue;
					}
					if (move == "quit")
					{
						return;
					}
					if (move == "xboard")
					{
						continue;
					}
					if (move == "show")
					{
						ShowBoard = !ShowBoard;

						continue;
					}
					if (move.StartsWith("edit"))
					{
						continue;
					}
					if (move == "hint")
					{
						continue;
					}
					if (move == "bk")
					{
						continue;
					}
					if (move == "undo")
					{
						engine.Undo();
						continue;
					}
					if (move == "remove")
					{
						continue;
					}
					if (move == "remove")
					{
						continue;
					}
					if (move == "hard")
					{
						engine.GameDifficulty = Engine.Difficulty.Hard;
						continue;
					}
					if (move == "easy")
					{
						continue;
					}
					if (move.StartsWith("accepted"))
					{
						continue;
					}
					if (move.StartsWith("rejected"))
					{
						continue;
					}
					if (move.StartsWith("variant"))
					{
						continue;
					}
					if (move == "random")
					{
						continue;
					}
					if (move == "force")
					{
						continue;
					}
					if (move == "go")
					{
						continue;
					}
					if (move == "playother")
					{
						if (engine.WhoseMove == ChessPieceColor.White)
						{
							engine.HumanPlayer = ChessPieceColor.Black;
						}
						else if (engine.WhoseMove == ChessPieceColor.Black)
						{
							engine.HumanPlayer = ChessPieceColor.White;
						}

						continue;
					}
					if (move == "white")
					{
						engine.HumanPlayer = ChessPieceColor.Black;

						if (engine.WhoseMove != engine.HumanPlayer)
						{
							MakeEngineMove(engine);
						}
						continue;
					}
					if (move == "black")
					{
						engine.HumanPlayer = ChessPieceColor.White;

						if (engine.WhoseMove != engine.HumanPlayer)
						{
							MakeEngineMove(engine);
						}
						continue;
					}

					if (move.StartsWith("level"))
					{
						continue;
					}
					if (move.StartsWith("st"))
					{
						continue;
					}
					if (move.StartsWith("sd"))
					{
						continue;
					}
					if (move.StartsWith("time"))
					{
						continue;
					}
					if (move.StartsWith("otim"))
					{
						continue;
					}
					if (move.StartsWith("otim"))
					{
						continue;
					}
					if (move == "?")
					{
						continue;
					}
					if (move.StartsWith("ping"))
					{
						if (move.IndexOf(" ") > 0)
						{
							string pong = move.Substring(move.IndexOf(" "), move.Length - move.IndexOf(" "));

							Console.WriteLine("pong " + pong);
						}
						continue;
					}

					if (move.StartsWith("result"))
					{
						continue;
					}

					if (move.StartsWith("setboard"))
					{
						if (move.IndexOf(" ") > 0)
						{
							string fen = move.Substring(move.IndexOf(" "), move.Length - move.IndexOf(" ")).Trim();

							engine.InitiateBoard(fen);
						}

						continue;
					}

					if (move.StartsWith("setboard"))
					{
						continue;
					}
					if (move.StartsWith("edit"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("1/2-1/2"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("0-1"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("1-0"))
					{
						engine.NewGame();
						continue;
					}

					if (move.Length < 4)
					{
						continue;
					}

					if (move.Length > 5)
					{
						continue;
					}

					string src = move.Substring(0, 2);
					string dst = move.Substring(2, 2);


					byte srcCol;
					byte srcRow;
					byte dstRow;
					byte dstCol;

					try
					{
						srcCol = GetColumn(src);
						srcRow = GetRow(src);
						dstRow = GetRow(dst);
						dstCol = GetColumn(dst);
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
						continue;
					}

					if (!engine.IsValidMove(srcCol, srcRow, dstCol, dstRow))
					{
						Console.WriteLine("Invalid Move");
						continue;
					}

					engine.MovePiece(srcCol, srcRow, dstCol, dstRow);

					MakeEngineMove(engine);
					    

					if (engine.StaleMate)
					{
						if (engine.InsufficientMaterial)
						{
							Console.WriteLine("1/2-1/2 {Draw by insufficient material}");
						}
						else if (engine.RepeatedMove)
						{
							Console.WriteLine("1/2-1/2 {Draw by repereplacedion}");
						}
						else if (engine.FiftyMove)
						{
							Console.WriteLine("1/2-1/2 {Draw by fifty move rule}");
						}
						else
						{
							Console.WriteLine("1/2-1/2 {Stalemate}");
						}
						engine.NewGame();
					}
					else if (engine.GetWhiteMate())
					{
						Console.WriteLine("0-1 {Black mates}");
						engine.NewGame();
					}
					else if (engine.GetBlackMate())
					{
						Console.WriteLine("1-0 {White mates}");
						engine.NewGame();
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
				return;
			}
		}
	}

19 View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private static VmessItem ResolveVmess4Kitsunebi(string result)
        {
            VmessItem vmessItem = new VmessItem
            {
                configType = (int)EConfigType.Vmess
            };
            result = result.Substring(Global.vmessProtocol.Length);
            int indexSplit = result.IndexOf("?");
            if (indexSplit > 0)
            {
                result = result.Substring(0, indexSplit);
            }
            result = Utils.Base64Decode(result);

            string[] arr1 = result.Split('@');
            if (arr1.Length != 2)
            {
                return null;
            }
            string[] arr21 = arr1[0].Split(':');
            string[] arr22 = arr1[1].Split(':');
            if (arr21.Length != 2 || arr21.Length != 2)
            {
                return null;
            }

            vmessItem.address = arr22[0];
            vmessItem.port = Utils.ToInt(arr22[1]);
            vmessItem.security = arr21[0];
            vmessItem.id = arr21[1];

            vmessItem.network = Global.DefaultNetwork;
            vmessItem.headerType = Global.None;
            vmessItem.remarks = "Alien";
            vmessItem.alterId = 0;

            return vmessItem;
        }

19 View Source File : DOTweenAnimation.cs
License : MIT License
Project Creator : 39M

public static TargetType TypeToDOTargetType(Type t)
        {
            string str = t.ToString();
            int dotIndex = str.LastIndexOf(".");
            if (dotIndex != -1) str = str.Substring(dotIndex + 1);
            if (str.IndexOf("Renderer") != -1 && (str != "SpriteRenderer")) str = "Renderer";
            return (TargetType)Enum.Parse(typeof(TargetType), str);
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 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 View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
        {
            Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
            Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
            string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
            {
                item.Delete();
            }
            List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
            foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                replacedetBundleBuildList.Add(new replacedetBundleBuild()
                {
                    replacedetBundleName = item.replacedetBundleName,
                    replacedetNames = item.replacedetNames,
                });
            }
            replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
                BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
                item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
                replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
            }
            replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
            FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
            if (replacedetBundleSetting.isCopyStreamingreplacedets)
            {
                string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
                foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
                {
                    if (Path.GetExtension(item.Name) == ".meta") continue;
                    File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
                }
            }
            replacedetDatabase.Refresh();
        }

19 View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc

public static List<replacedetBundleData> BuildreplacedetBundleData(replacedetBundleRule[] replacedetBundleRules)
        {
            List<replacedetBundleData> replacedetBundleDataList = new List<replacedetBundleData>();
            List<string> replacedetNameList = new List<string>();
            foreach (replacedetBundleRule item in replacedetBundleRules)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        string replacedetName = fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
                        string md5 = MD5Util.ComputeMD5(replacedetName);
                        replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, new string[] { replacedetName }));
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetNameList.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"));
                        }
                        if (replacedetNameList.Count > 0)
                        {
                            string replacedetName = directoryInfo.FullName.Substring(directoryInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
                            string md5 = MD5Util.ComputeMD5(replacedetName);
                            replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, replacedetNameList.ToArray()));
                            replacedetNameList.Clear();
                        }
                    }
                }
            }
            return replacedetBundleDataList;
        }

19 View Source File : LogConfigUtil.cs
License : MIT License
Project Creator : 404Lcc

public static string GetFilePath(string data)
        {
            int start = data.IndexOf("(at ") + 4;
            int end = data.LastIndexOf(':');
            return data.Substring(start, end - start);
        }

19 View Source File : StringExpand.cs
License : MIT License
Project Creator : 404Lcc

public static PanelType ToPanelType(this string name)
        {
            name = name.Substring(0, name.IndexOf("Panel"));
            return (PanelType)Enum.Parse(typeof(PanelType), name);
        }

19 View Source File : HolidayUtil.cs
License : MIT License
Project Creator : 6tail

private static string findForward(string key)
        {
            int start = DATA_IN_USE.IndexOf(key);
            if (start < 0)
            {
                return null;
            }
            string right = DATA_IN_USE.Substring(start);
            int n = right.Length % SIZE;
            if (n > 0)
            {
                right = right.Substring(n);
            }
            while ((!right.StartsWith(key)) && right.Length >= SIZE)
            {
                right = right.Substring(SIZE);
            }
            return right;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8bitbytes

public static int Main()
        {
            bool done = false;
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            string received_data;
            byte[] receive_byte_array;
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast");
                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Console.WriteLine("data follows \n{0}\n\n", received_data);
                    if (received_data.IndexOf("?") > -1)
                    {
                        var resp = processRequestReponseMessage(received_data);
                        SendMessage(listener, resp, groupEP);
                    }
                    else
                    {
                        processCommand(received_data);
                        SendMessage(listener, "OK", groupEP);
                    }
                }
            }
            catch (Exception e)
            {
                writeErrorMessage(e.ToString());
                SendMessage(listener, e.Message, groupEP);
            }
            listener.Close();
            return 0;
        }

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 91Act

public static int ParseCommand(CommandForm[] commandForms, string commandString,
			out string postString)
		{
			for (int i = 0; i < commandForms.Length; i++)
			{
				string id = commandForms[i].IDString;
				if (commandForms[i].PostStringMode)
				{
					if (commandString.IndexOf(id) == 0)
					{
						postString = commandString.Substring(id.Length);
						return i;
					}
				}
				else
					if (commandString == id)
				{
					postString = "";
					return i;
				}
			}
			postString = "";
			return -1;
		}

19 View Source File : KissMangaHelper.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static string GetName(string mUrl)
        {
            var doreplacedent = new HtmlWeb().Load(mUrl);
            int startIndex = doreplacedent.DoreplacedentNode.InnerHtml.IndexOf("\"bigChar\">") + 10;
            int length = 150; // Hope no replacedle is longer than 150 characters
            string crop = doreplacedent.DoreplacedentNode.InnerHtml.Substring(startIndex, length);

            int end = crop.IndexOf("</strong>");
            return crop.Substring(0, end);
        }

19 View Source File : FrmBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void BtnAdd_Click(object sender, EventArgs e)
        {
            string url = gfxBrowser.Url.ToString();
            string name = string.Empty;
            string num = string.Empty;
            switch (cmboSource.SelectedItem.ToString().ToLower())
            {
                case "mangadex":
                    name = url.Split('/')[5];
                    num = url.Split('/')[4];
                    url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;

                    Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);

                    FrmEdit editor = new FrmEdit(m, false);
                    DialogResult result = editor.ShowDialog();

                    if (result == DialogResult.OK)
                    {
                        // cleanup
                        foreach (Chapter ch in m.GetChapters())
                        {
                            try
                            {
                                string s = ch.GetChapterRoot().ToString();
                                Directory.Delete(ch.GetChapterRoot().ToString());
                            } catch (Exception) { }
                        }

                        WFClient.dbm.GetMangaDB().Add(m);

                        String[] dls = m.GetDLChapters();
                        if (dls == null || dls[0].Equals("-1"))
                        {
                            foreach (Chapter c in m.GetSetPrunedChapters(false))
                            {
                                WFClient.dlm.AddToQueue(new MangaDexDownload(c));
                            }
                        } else
                        {   // Only download selected chapters
                            foreach (Chapter c in m.GetSetPrunedChapters(false))
                            {
                                if (dls.Contains(c.GetNum()))
                                {
                                    WFClient.dlm.AddToQueue(new MangaDexDownload(c));
                                }
                            }
                        }
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    } else
                    {

                    }
                    break;
                case "kissmanga":

                    // MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
                    // break;
                    // TODO

                    string kName = KissMangaHelper.GetName(url);
                    string kHash = KissMangaHelper.GetHash(url);

                    // Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);

                    Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);

                    FrmEdit editor1 = new FrmEdit(km, false);
                    DialogResult result1 = editor1.ShowDialog();

                    if (result1 == DialogResult.OK)
                    {
                        // cleanup
                        foreach (Chapter ch in km.GetChapters())
                        {
                            try
                            {
                                string s = ch.GetChapterRoot().ToString();
                                Directory.Delete(ch.GetChapterRoot().ToString());
                            }
                            catch (Exception) { }
                        }

                        WFClient.dbm.GetMangaDB().Add(km);

                        String[] dls = km.GetDLChapters();
                        if (dls == null || dls[0].Equals("-1"))
                        {
                            foreach (Chapter c in km.GetSetPrunedChapters(false))
                            {
                                WFClient.dlm.AddToQueue(new KissMangaDownload(c));
                            }
                        }
                        else
                        {   // Only download selected chapters
                            foreach (Chapter c in km.GetSetPrunedChapters(false))
                            {
                                if (dls.Contains(c.GetNum()))
                                {
                                    WFClient.dlm.AddToQueue(new KissMangaDownload(c));
                                }
                            }
                        }
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    }
                    else
                    {

                    }
                    break;
                case "nhentai": 
                    num = url.Split('/')[4];
                    name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);

                    JObject hJson = new JObject(
                        new JProperty("hentai",
                            new JObject(
                                new JProperty("replacedle", name),
                                new JProperty("num",  num),
                                new JProperty("url",  url))));

                    DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));

                    Hentai h = new Nhentai(hDir, hJson.ToString());

                    FrmEdit edit = new FrmEdit(h, false);
                    DialogResult rezult = edit.ShowDialog();

                    if (rezult == DialogResult.OK)
                    {
                        WFClient.dbm.GetMangaDB().Add(h);

                        Chapter ch = h.GetChapters()[0];
                        WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
                        // Start downloading the first one
                        WFClient.dlm.DownloadNext();
                    } 
                    break;
            }
            MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
        }

19 View Source File : FrmHentaiBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private string Getreplacedle()
        {
            string fullreplacedle = browser.Doreplacedentreplacedle;
            return fullreplacedle.Substring(0, fullreplacedle.IndexOf("nhentai:") - 3);
        }

19 View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : a4004

private async void Search()
        {
            await Task.Delay(1000);

            WaitFm.Debug("Searching for devices...");

            int threshold = 1;
Rescan:
            while (SerialBusManager.SerialPorts.Count() < threshold)
            {
                await Task.Delay(1000);
                WaitFm.Debug($"Searching for devices... {(threshold - 1 == 1 ? "[1 device is connected, but you've chosen to not use it]" : (threshold - 1 > 1 ? $"[{threshold - 1} devices are connected, but you've chosen not to use them]" : ""))}");
            }

            WaitFm.Debug($"Detected {SerialBusManager.SerialDevices[threshold - 1]} on {SerialBusManager.SerialPorts[threshold - 1]}");

            CreateRequest($"Found new device ({SerialBusManager.SerialPorts[threshold - 1]})",
                SerialBusManager.SerialDevices[threshold - 1], "Use this device", "Don't use this device", out int option);

            if (option == 2)
            {
                threshold++;
                WaitFm.Debug($"The device was rejected by the user, device threshold is now {threshold} (was {threshold - 1})", Event.Warning);
                goto Rescan;
            }
            else if (option == 1)
            {
                Program.Settings.SelectedPort = SerialBusManager.SerialPorts[threshold - 1];
                Program.Settings.SelectedName = SerialBusManager.SerialDevices[threshold - 1];

                WaitFm.replacedle("Connecting to your device");

                if (!Program.Settings.PortFix)
                    WaitFm.Caption($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}");
                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out string output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);

                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }
                else
                {
                    if (ShellManager.RunCommand(out string output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }

                
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");
        }

19 View Source File : ProCamsLensDataTable.cs
License : Apache License 2.0
Project Creator : A7ocin

public void LoadLensData()
	{
		_filmFormats = new List<FilmFormatData>();
		
		// Load in the data from Resources/CinemaSuite_LensData.txt
		Textreplacedet textreplacedet = (Textreplacedet)(Resources.Load("CinemaSuite_LensData", typeof(Textreplacedet)));
		if(textreplacedet == null)
		{
			Debug.LogError("File 'CinemaSuite_LensData.txt' is not found in Resources folder. Unable to load lens data.");
			return;
		}
		
		FilmFormatData currentFormat = null;
		
		string[] lines = textreplacedet.text.Split("\n"[0]);
		int numLines = lines.Length;
		for(int i = 0; i < numLines; ++i)
		{
			//Debug.Log("Line: " + i + "= " + lines[i]);
			
			string line = lines[i].Trim();
			if(line.StartsWith("#"))
			{
				continue;	
			}
			
			int length = line.Length;
			
			if(currentFormat == null)
			{
				// Look for "Name="
				if(line.StartsWith("Name="))
				{
					// New section

					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string name = line.Substring(index).Trim();
						if(name.Length != 0)
						{
							// Create new film format with valid name
							currentFormat = new FilmFormatData();
							currentFormat._formatName = name;
						}
					}
				}
				else if(length != 0)
				{
					Debug.LogError("Invalid data at line: " + i);
				}
			}
			else
			{
				// Look for film format section entries
				
				if(length == 0)
				{
					// End of section
					_filmFormats.Add(currentFormat);
					//Debug.Log ("Added film format " + currentFormat._formatName);
					currentFormat = null;
				}
				else if(line.StartsWith("Aspect="))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string strAspect = line.Substring(index).Trim();
						int colon = strAspect.IndexOf(":");
						if(colon > 0 && colon < length)
						{
							string first = strAspect.Substring(0, colon).Trim();
							string second = strAspect.Substring(colon + 1).Trim();
							float w = 0;
							float h = 0;
							
							if(!float.TryParse(first, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out w) || w <= 0)
							{
								Debug.LogError("Invalid number: " + first + " at line " + (i + 1));
								return;
							}
							if(!float.TryParse(second, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h) || h <= 0)
							{
								Debug.LogError("Invalid number: " + second + " at line " + (i + 1));
								return;
							}
							currentFormat._aspect = w / h;
							//Debug.Log ("Aspect: " + currentFormat._aspect);
						}
					}
				}
				else if(line.StartsWith("ScreenSize"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// ScreenSize=DI,1024
						string[] strSizes = line.Substring(index).Split(","[0]);
						if(strSizes == null || strSizes.Length != 2)
						{
							Debug.LogError("Invalid screen size entry at line " + (i + 1));
							return;
						}
						
						string sizeName = strSizes[0].Trim();
						int sizeValue = 0;
						if(!int.TryParse(strSizes[1].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out sizeValue) || sizeValue <= 0)
						{
							Debug.LogError("Invalid screen size at line " + (i + 1));
							return;
						}
						currentFormat._screenSizes.Add(new ScreenSize(sizeName, sizeValue));
						//Debug.Log ("Screensize: " + sizeName + ", " + sizeValue);
					}
				}
				else if(line.StartsWith("FocalLength"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// FocalLength=Cooke S4/i - T2,12mm,4.980,00.000,00.000
						string[] strData = line.Substring(index).Split(","[0]);
						if(strData == null || strData.Length != 5)
						{
							Debug.LogError("Invalid data for focal length at line " + (i + 1));
							return;
						}
						
						string lensKit = strData[0].Trim();
						if(lensKit.Length == 0)
						{
							Debug.LogError("Invalid lens kit name at line " + (i + 1));
							return;
						}
						
						int focal = 0;
						if(!int.TryParse(strData[1].TrimEnd('m'), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out focal) || focal <= 0)
						{
							Debug.LogError("Invalid focal length at line " + (i + 1));
							return;
						}
						
						float nodal = 0;
						if(!float.TryParse(strData[2].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out nodal) || nodal < 0)
						{
							Debug.LogError("Invalid nodal offset at line " + (i + 1));
							return;
						}
						
						float realFOV = 0;
						if(!float.TryParse(strData[3].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out realFOV) || realFOV <= 0)
						{
							Debug.LogError("Invalid real FOV at line " + (i + 1));
							return;
						}
						
						float unityFOV = 0;
						if(!float.TryParse(strData[4].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out unityFOV) || unityFOV <= 0)
						{
							Debug.LogError("Invalid Unity FOV at line " + (i + 1));
							return;
						}
						
						currentFormat.AddFocalLengthData(lensKit, focal, nodal, realFOV, unityFOV);
						//Debug.Log ("Focal Data: " + lensKit + ", " + focal + ", " + nodal + ", " + realFOV + ", " + unityFOV);
					}
				}
			}
		}
	}

19 View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : a4004

private async void Flash()
        {
            await Task.Delay(1000);
FileMode:
            CreateRequest("Device software installation", "You are installing software on your device, you can choose where to get it from.", 
                "Get the latest image from the Internet (Recommended)", "Use a local image on this PC", out int option);

            if (option == 2)
            {
                Invoke(new Action(() =>
                {
                    OpenFileDialog fileDialog = new OpenFileDialog()
                    {
                        Multiselect = false,
                        SupportMultiDottedExtensions = true,
                        Filter = "Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|All files (*.*)|*.*",
                        replacedle = "Choose a software image file",
                    };

                    if (fileDialog.ShowDialog() == DialogResult.OK)
                        Program.Settings.Bin = fileDialog.FileName;
                }));

                if (Program.Settings.Bin == default)
                    goto FileMode;
            }
            else if (option == 1)
            {
                if (!CreateSelRequest(out string file))
                    goto FileMode;
                else
                {
                    WaitFm.Debug($"User selected file: {file}");

                    WaitFm.replacedle("Downloading software");
                    WaitFm.Caption("");

                    WaitFm.Debug($"Downloading {file}...");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading {Path.GetFileName(file)} from github.com ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug($"Successfully downloaded {Path.GetFileName(file)} from github.com", Event.Success);
                        };

                        await client.DownloadFileTaskAsync(file, Path.GetFileName(file));
                        Program.Settings.Bin = Path.GetFileName(file);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Download failed due to an error: {ex.Message}", Event.Critical);
                        await CreateMessage("A problem was encountered", "The required file could not be downloaded. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }          
                }

                WaitFm.replacedle("Getting ready");
                await Task.Delay(1000);
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");

            CreateRequest("Flash Operation", "The program is about to install software to your Espressif device. " +
                    "Existing data on the device will be PERMANENTLY DELETED, are you sure?", "Allow software installation",
                    "Cancel flash operation, no changes will be made", out int result);

            if (result == 2)
            {
                WaitFm.Debug("User cancelled the flash operation.", Event.Critical);
                await CreateMessage("Software installation aborted", "You've chosen to cancel the installation " +
                    "of software to your Espressif device. No changes have been made. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else if (result == 1)
            {
                WaitFm.Debug("Flash operation started.");
                WaitFm.replacedle("Installing software");

                WaitFm.Caption("Checking device connection");
                WaitFm.Debug("Checking device connection...");

                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                string output = string.Empty;

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }

                WaitFm.Caption("Erasing flash memory");
                WaitFm.Debug("Erasing flash memory chip...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }

                WaitFm.Caption("Writing new software image");
                WaitFm.Debug("Writing new software image...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Flash complete!", Event.Success);
                        WaitFm.Caption("Installed.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }


                await Task.Delay(500);

                await CreateMessage("Installation complete", $"The software package {Program.Settings.Bin} has been successfully" +
                    $" installed on your device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else
            {
                WaitFm.Debug("Failsafe: the selection was invalid.", Event.Critical);
                await CreateMessage("Software installation aborted", "A problem was encountered with the selection. " +
                    "No changes have been made to your Espressif device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
        }

19 View Source File : AssetBundleManager.cs
License : Apache License 2.0
Project Creator : A7ocin

static public bool AreBundlesDownloading(string replacedetBundleName = "")
		{
			if (replacedetBundleName == "")
			{
				return (m_DownloadingBundles.Count > 0 && m_InProgressOperations.Count > 0);
			}
			else
			{
				if (m_DownloadingBundles.Contains(replacedetBundleName))
				{
					return true;
				}
				else
				{
					foreach (string key in m_DownloadingBundles)
					{
						if (key.IndexOf(replacedetBundleName + "/") > -1)
						{
							return true;
						}
					}
					return false;
				}
			}
		}

See More Examples