string.IndexOf(char)

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

4492 Examples 7

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

public NameValueCollection ParseQueryString(string url) {
            NameValueCollection nvc = new();

            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit == -1)
                return nvc;
            url = url.Substring(indexOfSplit + 1);

            string[] args = url.Split('&');
            foreach (string arg in args) {
                indexOfSplit = arg.IndexOf('=');
                if (indexOfSplit == -1)
                    continue;
                nvc[arg.Substring(0, indexOfSplit)] = arg.Substring(indexOfSplit + 1);
            }

            return nvc;
        }

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

private static void HandleRequest(HttpListenerContext c) {
            Logger.Log(LogLevel.VVV, "rc", $"Requested: {c.Request.RawUrl}");

            string url = c.Request.RawUrl;
            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit != -1)
                url = url.Substring(0, indexOfSplit);

            RCEndPoint endpoint =
                EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
                EndPoints.FirstOrDefault(ep => ep.Path == url) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path == "/404");
            endpoint.Handle(c);
        }

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

public string ToString(bool displayName, bool id)
            => $"{(id ? $"{{{ID}}} " : "")}{(Tag.IsNullOrEmpty() ? "" : $"[{Tag}] ")}{(displayName ? Player?.DisplayName : Player?.FullName) ?? "**SERVER**"}{(Target != null ? " @ " + Target.DisplayName : "")}:{(Text.IndexOf('\n') != -1 ? "\n" : " ")}{Text}";

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

public static NameValueCollection ParseQueryString(string url) {
            NameValueCollection nvc = new();

            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit == -1)
                return nvc;
            url = url.Substring(indexOfSplit + 1);

            string[] args = url.Split('&');
            foreach (string arg in args) {
                indexOfSplit = arg.IndexOf('=');
                if (indexOfSplit == -1)
                    continue;
                nvc[arg.Substring(0, indexOfSplit)] = arg.Substring(indexOfSplit + 1);
            }

            return nvc;
        }

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

private void HandleRequest(HttpRequestEventArgs c) {
            Logger.Log(LogLevel.VVV, "frontend", $"{c.Request.RemoteEndPoint} requested: {c.Request.RawUrl}");

            string url = c.Request.RawUrl;
            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit != -1)
                url = url.Substring(0, indexOfSplit);

            RCEndpoint? endpoint =
                EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
                EndPoints.FirstOrDefault(ep => ep.Path == url) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant());

            if (endpoint == null) {
                RespondContent(c, "frontend/" + url.Substring(1));
                return;
            }

            c.Response.Headers.Set("Cache-Control", "no-store, max-age=0, s-maxage=0, no-cache, no-transform");

            if (endpoint.Auth && !IsAuthorized(c)) {
                c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                RespondJSON(c, new {
                    Error = "Unauthorized."
                });
                return;
            }

            endpoint.Handle(this, c);
        }

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 0xd4d

static bool TryParseToken(string value, out uint tokenLo, out uint tokenHi) {
			int index = value.IndexOf('-');
			if (index >= 0) {
				var lo = value.Substring(0, index);
				var hi = value.Substring(index + 1);
				if (TryParseToken(lo, out tokenLo) && TryParseToken(hi, out tokenHi))
					return true;
			}
			else {
				if (TryParseToken(value, out tokenLo)) {
					tokenHi = tokenLo;
					return true;
				}
			}

			tokenLo = 0;
			tokenHi = 0;
			return false;
		}

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

public static string RemoveMatchingQuotes(string stringToTrim)
        {
            var firstQuoteIndex = stringToTrim.IndexOf('"');
            var lastQuoteIndex = stringToTrim.LastIndexOf('"');
            while (firstQuoteIndex != lastQuoteIndex)
            {
                stringToTrim = stringToTrim.Remove(firstQuoteIndex, 1);
                stringToTrim = stringToTrim.Remove(lastQuoteIndex - 1, 1); //-1 because we've shifted the indicies left by one
                firstQuoteIndex = stringToTrim.IndexOf('"');
                lastQuoteIndex = stringToTrim.LastIndexOf('"');
            }

            return stringToTrim;
        }

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

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

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

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static TypeSyntax GenerateType(Type type)
        {
            if (!type.IsGenericType)
                return GenerateQualifiedNameSyntax(type);


            var list = new List<SyntaxNodeOrToken>();
            foreach (var genericType in type.GetGenericArguments())
            {
                list.Add(genericType.IsGenericType ? GenerateType(genericType) : GenerateQualifiedNameSyntax(genericType.FullName));
                list.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }
            var typeArgumentList = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList<TypeSyntax>(list.Take(list.Count - 1)));
            //if (type.Namespace == typeof(Task).Namespace)
            return SyntaxFactory.GenericName(type.Name.Substring(0, type.Name.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
            //return SyntaxFactory.GenericName(type.FullName?.Substring(0, type.FullName.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
        }

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

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

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

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

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

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

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

public string GetTableAttribute()
	{
		var sb = new List<string>();

		if (GetCsName(this.FullTableName) != this.FullTableName)
		{
			if (this.FullTableName.IndexOf('.') == -1)
				sb.Add("Name = \"" + this.FullTableName + "\"");
			else
				sb.Add("Name = \"" + this.FullTableName + "\""); //Todo: QuoteSqlName
		}

		sb.Add("DisableSyncStructure = true");
		if (sb.Any() == false) return null;
		return "[Table(" + string.Join(", ", sb) + ")]";
	}

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

internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
        {
            if (type == null) return null;
            if (type == typeof(void)) return "void";
            if (type.IsGenericParameter) return type.Name;
            if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
            var sb = new StringBuilder();
            var nestedType = type;
            while (nestedType.IsNested)
            {
                sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
                nestedType = nestedType.DeclaringType;
            }
            if (isNameSpace && string.IsNullOrEmpty(nestedType.Namespace) == false)
                sb.Insert(0, ".").Insert(0, nestedType.Namespace);

            if (type.IsGenericType == false)
                return sb.Append(type.Name).ToString();

            var genericParameters = type.GetGenericArguments();
            if (type.IsNested && type.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any() == false)
                return sb.Append(type.Name).ToString();

            sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
            var genericTypeIndex = 0;
            foreach (var genericType in genericParameters)
            {
                if (genericTypeIndex++ > 0) sb.Append(", ");
                sb.Append(DisplayCsharp(genericType, true));
            }
            return sb.Append(">").ToString();
        }

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

public static string DisplayCsharp(this Type type, bool isNameSpace = true)
        {
            if (type == null) return null;
            if (type == typeof(void)) return "void";
            if (type.IsGenericParameter) return type.Name;
            if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
            var sb = new StringBuilder();
            var nestedType = type;
            while (nestedType.IsNested)
            {
                sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
                nestedType = nestedType.DeclaringType;
            }
            if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
                sb.Insert(0, ".").Insert(0, nestedType.Namespace);

            if (type.IsGenericType == false)
                return sb.Append(type.Name).ToString();

            var genericParameters = type.GetGenericArguments();
            if (type.IsNested && type.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any() == false)
                return sb.Append(type.Name).ToString();

            sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
            var genericTypeIndex = 0;
            foreach (var genericType in genericParameters)
            {
                if (genericTypeIndex++ > 0) sb.Append(", ");
                sb.Append(DisplayCsharp(genericType, true));
            }
            return sb.Append(">").ToString();
        }

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

internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
    {
        if (type == null) return null;
        if (type == typeof(void)) return "void";
        if (type.IsGenericParameter) return type.Name;
        if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
        var sb = new StringBuilder();
        var nestedType = type;
        while (nestedType.IsNested)
        {
            sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
            nestedType = nestedType.DeclaringType;
        }
        if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
            sb.Insert(0, ".").Insert(0, nestedType.Namespace);

        if (type.IsGenericType == false)
            return sb.Append(type.Name).ToString();

        var genericParameters = type.GetGenericArguments();
        if (type.IsNested && type.DeclaringType.IsGenericType)
        {
            var dic = genericParameters.ToDictionary(a => a.Name);
            foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
                if (dic.ContainsKey(nestedGenericParameter.Name))
                    dic.Remove(nestedGenericParameter.Name);
            genericParameters = dic.Values.ToArray();
        }
        if (genericParameters.Any() == false)
            return sb.Append(type.Name).ToString();

        sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
        var genericTypeIndex = 0;
        foreach (var genericType in genericParameters)
        {
            if (genericTypeIndex++ > 0) sb.Append(", ");
            sb.Append(DisplayCsharp(genericType, true));
        }
        return sb.Append(">").ToString();
    }

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

protected Cortege Parse(ref string raw, out LineAttr ltype)
        {
            int splitter = raw.IndexOf('=');

            if(splitter == -1)
            {
                ltype = LineAttr.InvalidOrUnknown;
                return default(Cortege);
            }

            string cprj = raw.Substring(splitter + 1);

            splitter    = raw.FirstNonWhiteSpace(splitter - 1, true) + 1;
            int rpos    = raw.LastIndexOf('.', splitter); // .ActiveCfg =
                                                          // .Build.0 =
                                                          // ------^

            if(splitter - rpos == 2) { // .0
                rpos = raw.LastIndexOf('.', rpos - 1);
            }

            int lpos        = raw.IndexOf('.');
            string pGuid    = raw.Substring(0, lpos);

            string csln     = raw.Substring(++lpos, rpos - lpos);
            string type     = raw.Substring(++rpos, splitter - rpos);

            ltype = GetAttribute(type.Trim());

            return new Cortege()
            {
                pGuid   = pGuid.Trim(),
                csln    = csln.Trim(),
                cprj    = cprj.Trim(),
            };
        }

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

public override bool Positioned(ISvc svc, RawText line)
        {
            if(svc.Sln.Exreplacedems == null) {
                svc.Sln.Exreplacedems = new Dictionary<string, string>();
            }

            string _line;
            while((_line = svc.ReadLine(this)) != null && _line.Trim() != "EndGlobalSection")
            {
                int pos = _line.IndexOf('=');
                if(pos < 0) // we will use non-strict processing
                {
                    svc.Sln.Exreplacedems[_line.Trim()] = null;
                    LSender.Send(this, $"Found extensible null record:{_line}", Message.Level.Info);
                    continue;
                }

                string key  = _line.Substring(0, pos).Trim();
                string val  = _line.Substring(pos + 1).Trim();

                svc.Sln.Exreplacedems[key] = val;
                LSender.Send(this, $"Found extensible key-value: `{key}` = `{val}`", Message.Level.Info);
            }

            return true;
        }

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

public override bool Positioned(ISvc svc, RawText line)
        {
            string _line;
            while((_line = svc.ReadLine(this)) != null && _line.Trim() != "EndGlobalSection")
            {
                int pos = _line.IndexOf('='); // Guids: src = dest
                if(pos < 0) {
                    LSender.Send(this, $"Incorrect NestedProjects records: '{_line}'", Message.Level.Warn);
                    return false;
                }

                string src  = _line.Substring(0, pos).Trim();
                string dest = _line.Substring(pos + 1).Trim();

                LSender.Send(this, $"NestedProjects '{src}' -> '{dest}'", Message.Level.Info);

                var parent = svc.Sln.SolutionFolderList.Where(f => f.header.pGuid == dest).First();

                svc.Sln.SolutionFolderList.Where(f => f.header.pGuid == src)
                    .ForEach(f => f.header.parent.Value = parent);

                svc.Sln.ProjecreplacedemList.Where(p => p.pGuid == src)
                    .ForEach(p => p.parent.Value = parent);
            }

            return true;
        }

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

private static string ExtractName(string raw, out int delimiter)
        {
            if(raw == null)
            {
                delimiter = -1;
                return null;
            }

            delimiter = raw.IndexOf(DELIM);
            if(delimiter == -1) return raw;

            return raw.Substring(0, delimiter);
        }

19 View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension

static string CleanupLine(string line, int lineNumber)
		{
			int commentIndex = line.IndexOf(';');

			if (commentIndex > -1)
				line = line.Remove(commentIndex);

			int start = -1;

			while ((start = line.IndexOf('(')) != -1)
			{
				int end = line.IndexOf(')');

				if (end < start)
					throw new ParseException("mismatched parentheses", lineNumber);

				line = line.Remove(start, end - start);
			}

			return line;
		}

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

private static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

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

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/pname"))
                {
                    Process[] process = Process.GetProcessesByName(arguments["/pname"]);
                    if (process.Length > 0)
                    {
                        for (int i = 0; i < process.Length; i++)
                        {
                            Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
                            Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
                            Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
                            dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
                    }
                }
                else if (arguments.ContainsKey("/pid"))
                {
                    int procid = Convert.ToInt32(arguments["/pid"]);
                    Process process = Process.GetProcessById(procid);
                    Console.WriteLine($"[+] Dumping {process.ProcessName} process");
                    Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
                    Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
                    dump(process.Handle, (uint)process.Id, process.ProcessName);
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

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

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

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

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

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

public void InitManager()
        {
            AudioManager.Instance.SetVolume(GameDataManager.Instance.userSetData.audio, Objects.AudioSource);
            string name = Enum.GetName(typeof(ResolutionType), GameDataManager.Instance.userSetData.resolutionType).Substring(10);
            int width = int.Parse(name.Substring(0, name.IndexOf('x')));
            int height = int.Parse(name.Substring(name.IndexOf('x') + 1));
            if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.FullScreen)
            {
                LccUtil.SetResolution(true, width, height);
            }
            else if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.Window)
            {
                LccUtil.SetResolution(false, width, height);
            }
            else if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.BorderlessWindow)
            {
                LccUtil.SetResolution(false, width, height);
                StartCoroutine(DisplayMode.SetNoFrame(width, height));
            }
            QualitySettings.SetQualityLevel(6, true);
        }

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

private void ProcessNumber (string number)
        {
            if (number.IndexOf ('.') != -1 ||
                number.IndexOf ('e') != -1 ||
                number.IndexOf ('E') != -1) {

                double n_double;
                if (Double.TryParse (number, out n_double)) {
                    token = JsonToken.Double;
                    token_value = n_double;

                    return;
                }
            }

            int n_int32;
            if (Int32.TryParse (number, out n_int32)) {
                token = JsonToken.Int;
                token_value = n_int32;

                return;
            }

            long n_int64;
            if (Int64.TryParse (number, out n_int64)) {
                token = JsonToken.Long;
                token_value = n_int64;

                return;
            }

            ulong n_uint64;
            if (UInt64.TryParse(number, out n_uint64))
            {
                token = JsonToken.Long;
                token_value = n_uint64;

                return;
            }

            // Shouldn't happen, but just in case, return something
            token = JsonToken.Int;
            token_value = 0;
        }

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

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null) return false;
#if WINRT || COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if(!declaredTypeInfo.IsGenericType) return false;

#if WINRT || COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if WINRT || PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : EventSourceReader.cs
License : MIT License
Project Creator : 3ventic

private async Task ReaderAsync()
        {
            try
            {
                if (string.Empty != LastEventId)
                {
                    if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
                    {
                        Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
                    }
                    
                    Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
                }
                using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Headers.TryGetValues("content-type", out IEnumerable<string> ctypes) || ctypes?.Contains("text/event-stream") == false)
                    {
                        throw new ArgumentException("Specified URI does not return server-sent events");
                    }

                    Stream = await response.Content.ReadreplacedtreamAsync();
                    using (var sr = new StreamReader(Stream))
                    {
                        string evt = DefaultEventType;
                        string id = string.Empty;
                        var data = new StringBuilder(string.Empty);

                        while (true)
                        {
                            string line = await sr.ReadLineAsync();
                            if (line == string.Empty)
                            {
                                // double newline, dispatch message and reset for next
                                if (data.Length > 0)
                                {
                                    MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
                                }
                                data.Clear();
                                id = string.Empty;
                                evt = DefaultEventType;
                                continue;
                            }
                            else if (line.First() == ':')
                            {
                                // Ignore comments
                                continue;
                            }

                            int dataIndex = line.IndexOf(':');
                            string field;
                            if (dataIndex == -1)
                            {
                                dataIndex = line.Length;
                                field = line;
                            }
                            else
                            {
                                field = line.Substring(0, dataIndex);
                                dataIndex += 1;
                            }

                            string value = line.Substring(dataIndex).Trim();

                            switch (field)
                            {
                                case "event":
                                    // Set event type
                                    evt = value;
                                    break;
                                case "data":
                                    // Append a line to data using a single \n as EOL
                                    data.Append($"{value}\n");
                                    break;
                                case "retry":
                                    // Set reconnect delay for next disconnect
                                    int.TryParse(value, out ReconnectDelay);
                                    break;
                                case "id":
                                    // Set ID
                                    LastEventId = value;
                                    id = LastEventId;
                                    break;
                                default:
                                    // Ignore other fields
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Disconnect(ex);
            }
        }

19 View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod

protected void SplitUri(string uri, out string url, out string[] queryParams)
        {
            int pos = uri.IndexOf('?');
            if (pos == -1)
            {
                url = uri;
                queryParams = new string[0];
            }
            else
            {
                url = uri.Substring(0, pos);
                queryParams = uri.Substring(pos + 1).Split('&');
            }
        }

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

public void Write (double number)
        {
            DoValidation (Condition.Value);
            PutNewline ();

            string str = Convert.ToString (number, number_format);
            Put (str);

            if (str.IndexOf ('.') == -1 &&
                str.IndexOf ('E') == -1)
                writer.Write (".0");

            context.ExpectingValue = false;
        }

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

bool ParseString(string srcString, SwitchForm[] switchForms)
		{
			int len = srcString.Length;
			if (len == 0)
				return false;
			int pos = 0;
			if (!IsItSwitchChar(srcString[pos]))
				return false;
			while (pos < len)
			{
				if (IsItSwitchChar(srcString[pos]))
					pos++;
				const int kNoLen = -1;
				int matchedSwitchIndex = 0;
				int maxLen = kNoLen;
				for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++)
				{
					int switchLen = switchForms[switchIndex].IDString.Length;
					if (switchLen <= maxLen || pos + switchLen > len)
						continue;
					if (String.Compare(switchForms[switchIndex].IDString, 0,
							srcString, pos, switchLen, true) == 0)
					{
						matchedSwitchIndex = switchIndex;
						maxLen = switchLen;
					}
				}
				if (maxLen == kNoLen)
					throw new Exception("maxLen == kNoLen");
				SwitchResult matchedSwitch = _switches[matchedSwitchIndex];
				SwitchForm switchForm = switchForms[matchedSwitchIndex];
				if ((!switchForm.Multi) && matchedSwitch.ThereIs)
					throw new Exception("switch must be single");
				matchedSwitch.ThereIs = true;
				pos += maxLen;
				int tailSize = len - pos;
				SwitchType type = switchForm.Type;
				switch (type)
				{
					case SwitchType.PostMinus:
						{
							if (tailSize == 0)
								matchedSwitch.WithMinus = false;
							else
							{
								matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus);
								if (matchedSwitch.WithMinus)
									pos++;
							}
							break;
						}
					case SwitchType.PostChar:
						{
							if (tailSize < switchForm.MinLen)
								throw new Exception("switch is not full");
							string charSet = switchForm.PostCharSet;
							const int kEmptyCharValue = -1;
							if (tailSize == 0)
								matchedSwitch.PostCharIndex = kEmptyCharValue;
							else
							{
								int index = charSet.IndexOf(srcString[pos]);
								if (index < 0)
									matchedSwitch.PostCharIndex = kEmptyCharValue;
								else
								{
									matchedSwitch.PostCharIndex = index;
									pos++;
								}
							}
							break;
						}
					case SwitchType.LimitedPostString:
					case SwitchType.UnLimitedPostString:
						{
							int minLen = switchForm.MinLen;
							if (tailSize < minLen)
								throw new Exception("switch is not full");
							if (type == SwitchType.UnLimitedPostString)
							{
								matchedSwitch.PostStrings.Add(srcString.Substring(pos));
								return true;
							}
							String stringSwitch = srcString.Substring(pos, minLen);
							pos += minLen;
							for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++)
							{
								char c = srcString[pos];
								if (IsItSwitchChar(c))
									break;
								stringSwitch += c;
							}
							matchedSwitch.PostStrings.Add(stringSwitch);
							break;
						}
				}
			}
			return true;

		}

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

static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms,
			string commandString, ArrayList indices)
		{
			indices.Clear();
			int numUsedChars = 0;
			for (int i = 0; i < numForms; i++)
			{
				CommandSubCharsSet charsSet = forms[i];
				int currentIndex = -1;
				int len = charsSet.Chars.Length;
				for (int j = 0; j < len; j++)
				{
					char c = charsSet.Chars[j];
					int newIndex = commandString.IndexOf(c);
					if (newIndex >= 0)
					{
						if (currentIndex >= 0)
							return false;
						if (commandString.IndexOf(c, newIndex + 1) >= 0)
							return false;
						currentIndex = j;
						numUsedChars++;
					}
				}
				if (currentIndex == -1 && !charsSet.EmptyAllowed)
					return false;
				indices.Add(currentIndex);
			}
			return (numUsedChars == commandString.Length);
		}

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

public void Start()
		{
			if(m_webSocket != null)
				return;

			const string httpScheme = "https://";
			const string wsScheme = "wss://";
			const string webSocketUrl = "websocket.btcc.com/socket.io/";

			#region handshake

			string polling;
			using (var wc = new HttpClient())
			{
				polling = wc.GetStringAsync(httpScheme + webSocketUrl + "?transport=polling").Result;
				if (string.IsNullOrEmpty(polling))
				{
					throw new BTCChinaException("BtcChinaWebSocketApi.Start", "", "failed to download config");
				}
			}

			var config = polling.Substring(polling.IndexOf('{'), polling.IndexOf('}') - polling.IndexOf('{') + 1);
			var wsc = JsonConvert.DeserializeObject<WsConfigHelper>(config);

			#endregion handshake

			//set timers
			m_pingTimeoutTimer = new Timer(_ =>
			{
				if (m_pong)
				{
					m_pong = false; //waiting for another ping
				}
				else
				{
					Log.Error("[BtcChina] Ping Timeout!");
					if (TimeoutReceived != null)
					{
						TimeoutReceived(this, new EventArgs());
					}
				}
			}, null, Timeout.Infinite, Timeout.Infinite);

			m_pingIntervalTimer = new Timer(_ =>
			{
				m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}", (int)EngineioMessageType.PING));
				m_pingTimeoutTimer.Change(wsc.PingTimeout, Timeout.Infinite);
				m_pong = false;
			}, null, wsc.PingInterval, wsc.PingInterval);

			//setup websocket connections and events
			m_webSocket = new WebSocket(wsScheme + webSocketUrl + "?transport=websocket&sid=" + wsc.Sid);
			m_webSocket.Opened += btc_Opened;
			m_webSocket.Error += btc_Error;
			m_webSocket.MessageReceived += btc_MessageReceived;
			m_webSocket.DataReceived += btc_DataReceived;
			m_webSocket.Closed += btc_Closed;

			Log.Info("[BtcChina] Opening websockets...");
			m_webSocket.Open();
		}

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

private void btc_MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			int eioMessageType;
			if (int.TryParse(e.Message.Substring(0, 1), out eioMessageType))
			{
				switch ((EngineioMessageType)eioMessageType)
				{
					case EngineioMessageType.PING:
						//replace incoming PING with PONG in incoming message and resend it.
						m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}", (int)EngineioMessageType.PONG, e.Message.Substring(1, e.Message.Length - 1)));
						break;
					case EngineioMessageType.PONG:
						m_pong = true;
						break;

					case EngineioMessageType.MESSAGE:
						int sioMessageType;
						if (int.TryParse(e.Message.Substring(1, 1), out sioMessageType))
						{
							switch ((SocketioMessageType)sioMessageType)
							{
								case SocketioMessageType.CONNECT:
									//Send "42["subscribe",["marketdata_cnybtc","marketdata_cnyltc","marketdata_btcltc"]]"
									m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", (int)EngineioMessageType.MESSAGE,
																	   (int)SocketioMessageType.EVENT,
//																	   "[\"subscribe\",[\"marketdata_cnybtc\",\"marketdata_cnyltc\",\"grouporder_cnybtc\"]]"
																	   "[\"subscribe\",[\"grouporder_cnybtc\"]]"
																	   )
																	   );

									break;

								case SocketioMessageType.EVENT:
									if (e.Message.Substring(4, 5) == "trade")//listen on "trade"
										Log.Info("[BtcChina] TRADE: " + e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1));
									else
										if (e.Message.Substring(4, 10) == "grouporder")//listen on "trade")
										{
											Log.Info("[BtcChina] grouporder event");

											var json = e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1);
											var objResponse = JsonConvert.DeserializeObject<WsGroupOrderMessage>(json);
											OnMessageGroupOrder(objResponse.GroupOrder);
										}
										else
										{
											Log.Warn("[BtcChina] Unknown message: " + e.Message.Substring(0, 100));
										}
									break;

								default:
									Log.Error("[BtcChina] error switch socket.io messagetype: " + e.Message);
									break;
							}
						}
						else
						{
							Log.Error("[BtcChina] error parse socket.io messagetype!");
						}
						break;

					default:
						Log.Error("[BtcChina] error switch engine.io messagetype");
						break;
				}
			}
			else
			{
				Log.Error("[BtcChina] error parsing engine.io messagetype!");
			}
		}

19 View Source File : V2Loader.cs
License : MIT License
Project Creator : Abdesol

static void CheckElementName(XmlReader reader, string name)
		{
			if (name != null) {
				if (name.Length == 0)
					throw Error(reader, "The empty string is not a valid name.");
				if (name.IndexOf('/') >= 0)
					throw Error(reader, "Element names must not contain a slash.");
			}
		}

19 View Source File : XmlFoldingStrategy.cs
License : MIT License
Project Creator : Abdesol

static void CreateCommentFold(TextDoreplacedent doreplacedent, List<NewFolding> foldMarkers, XmlReader reader)
		{
			string comment = reader.Value;
			if (comment != null) {
				int firstNewLine = comment.IndexOf('\n');
				if (firstNewLine >= 0) {

					// Take off 4 chars to get the actual comment start (takes
					// into account the <!-- chars.

					int startOffset = GetOffset(doreplacedent, reader) - 4;
					int endOffset = startOffset + comment.Length + 7;

					string foldText = String.Concat("<!--", comment.Substring(0, firstNewLine).TrimEnd('\r'), "-->");
					foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText });
				}
			}
		}

19 View Source File : SimCluster.cs
License : MIT License
Project Creator : abdullin

static string GetNetwork(string machine) {
            if (machine.IndexOf('.') < 0) {
                return machine;
            }

            return string.Join('.', machine.Split('.').Skip(1));
        }

19 View Source File : GenericTypeExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static string GetGenericTypeName(this Type type)
        {
            var typeName = string.Empty;

            if (type.IsGenericType)
            {
                var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
                typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
            }
            else
            {
                typeName = type.Name;
            }

            return typeName;
        }

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static MixedRealityToolkitModuleType GetModuleFromPackageFolder(string packageFolder)
        {
            if (!packageFolder.StartsWith("MixedRealityToolkit"))
            {
                // There are no mappings for folders that do not start with "MixedRealityToolkit"
                return MixedRealityToolkitModuleType.None;
            }

            int separatorIndex = packageFolder.IndexOf('.');
            packageFolder = (separatorIndex != -1) ? packageFolder.Substring(separatorIndex + 1) : "Core";

            MixedRealityToolkitModuleType moduleType;
            return moduleNameMap.TryGetValue(packageFolder, out moduleType) ? moduleType : MixedRealityToolkitModuleType.None;
        }

19 View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy

public List<string> GetDevices()
	{
		string outputString;
		string errorString;

		RunCommand(new string[] { "devices" }, null, out outputString, out errorString);
		string[] devices = outputString.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

		List<string> deviceList = new List<string>(devices);
		deviceList.RemoveAt(0);

		for(int i = 0; i < deviceList.Count; i++)
		{
			string deviceName = deviceList[i];
			int index = deviceName.IndexOf('\t');
			if (index >= 0)
				deviceList[i] = deviceName.Substring(0, index);
			else
				deviceList[i] = "";

		}

		return deviceList;
	}

19 View Source File : _Host.cshtml.cs
License : Apache License 2.0
Project Creator : acblog

public async Task<string> Getreplacedle()
        {
            string path = HttpContext.Request.Path.ToString().Trim('/');
            {
                int indFrag = path.IndexOf('#');
                if (indFrag != -1)
                    path = path.Remove(indFrag);
            }
            string[] pathSegs = path.Split('/');

            List<string> result = new List<string>
            {
                "AcBlog"
            };

            if (pathSegs.Length > 0)
            {
                switch (pathSegs[0])
                {
                    case "posts":
                        await GeneratePostreplacedle(pathSegs[1..], result, "Posts");
                        break;
                    case "articles":
                        await GeneratePostreplacedle(pathSegs[1..], result, "Articles");
                        break;
                    case "slides":
                        await GeneratePostreplacedle(pathSegs[1..], result, "Slides");
                        break;
                    case "notes":
                        await GeneratePostreplacedle(pathSegs[1..], result, "Notes");
                        break;
                    case "categories":
                        // await GenerateCategoryreplacedle(pathSegs[1..], result);
                        break;
                    case "keywords":
                        // await GenerateKeywordreplacedle(pathSegs[1..], result);
                        break;
                }
            }

            result.Reverse();

            return string.Join(" - ", result);
        }

19 View Source File : DoubleExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string FormatChance(this double chance)
        {
            if (chance == 1)
            {
                return "100%";
            }
            if (chance == 0)
            {
                return "0%";
            }
            double r = (chance * 100);
            string p = r.ToString("F99").TrimEnd('0');
            if (!p.StartsWith("0."))
            {
                int extra = 2;
                if (p.IndexOf(".0") > -1 || p.EndsWith("."))
                {
                    extra = 0;
                }
                return p.Substring(0, p.IndexOf('.') + extra) + "%";
            }
            int i = p.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });
            if (i < 0)
            {
                return "0%";
            }
            return p.Substring(0, i + 1) + "%";
        }

19 View Source File : StringExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool StartsWithVowel(this string s)
        {
            if (string.IsNullOrEmpty(s))
                return false;

            char firstLetter = s.ToLower()[0];
            bool isVowel = "aeiou".IndexOf(firstLetter) >= 0;

            return isVowel;
        }

19 View Source File : EventManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string GetEventName(string eventFormat)
        {
            var idx = eventFormat.IndexOf('@');     // strip comment
            if (idx == -1)
                return eventFormat;

            var eventName = eventFormat.Substring(0, idx);
            return eventName;
        }

19 View Source File : QuestManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string GetQuestName(string questFormat)
        {
            var idx = questFormat.IndexOf('@');     // strip comment
            if (idx == -1)
                return questFormat;

            var questName = questFormat.Substring(0, idx);
            return questName;
        }

19 View Source File : Sheet.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public string RevitScaleWithoutFormatting()
        {
            var result = scale.Trim();
            var i = 0;
            if (result.Contains(":"))
            {
                i = result.IndexOf(':');
            }
            else
            {
                return "0";
            }
            return string.IsNullOrEmpty(result.Trim()) ? "0" : result.Substring(i + 2).Trim();
        }

19 View Source File : ProcessExtensions.cs
License : MIT License
Project Creator : actions

public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable)
        {
            var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions));
            Dictionary<string, string> env = new Dictionary<string, string>();

            if (Directory.Exists("/proc"))
            {
                string envFile = $"/proc/{process.Id}/environ";
                trace.Info($"Read env from {envFile}");
                string envContent = File.ReadAllText(envFile);
                if (!string.IsNullOrEmpty(envContent))
                {
                    // on linux, environment variables are seprated by '\0'
                    var envList = envContent.Split('\0', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var envStr in envList)
                    {
                        // split on the first '='
                        var keyValuePair = envStr.Split('=', 2);
                        if (keyValuePair.Length == 2)
                        {
                            env[keyValuePair[0]] = keyValuePair[1];
                            trace.Verbose($"PID:{process.Id} ({keyValuePair[0]}={keyValuePair[1]})");
                        }
                    }
                }
            }
            else
            {
                // On OSX, there is no /proc folder for us to read environment for given process,
                // So we have call `ps e -p <pid> -o command` to print out env to STDOUT,
                // However, the output env are not format in a parseable way, it's just a string that concatenate all envs with space,
                // It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs.
                // So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space)
                trace.Info($"Read env from output of `ps e -p {process.Id} -o command`");
                List<string> psOut = new List<string>();
                object outputLock = new object();
                using (var p = hostContext.CreateService<IProcessInvoker>())
                {
                    p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)
                    {
                        if (!string.IsNullOrEmpty(stdout.Data))
                        {
                            lock (outputLock)
                            {
                                psOut.Add(stdout.Data);
                            }
                        }
                    };

                    p.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr)
                    {
                        if (!string.IsNullOrEmpty(stderr.Data))
                        {
                            lock (outputLock)
                            {
                                trace.Error(stderr.Data);
                            }
                        }
                    };

                    int exitCode = p.ExecuteAsync(workingDirectory: hostContext.GetDirectory(WellKnownDirectory.Root),
                                                  fileName: "ps",
                                                  arguments: $"e -p {process.Id} -o command",
                                                  environment: null,
                                                  cancellationToken: CancellationToken.None).GetAwaiter().GetResult();
                    if (exitCode == 0)
                    {
                        trace.Info($"Successfully dump environment variables for {process.Id}");
                        if (psOut.Count > 0)
                        {
                            string psOutputString = string.Join(" ", psOut);
                            trace.Verbose($"ps output: '{psOutputString}'");

                            int varStartIndex = psOutputString.IndexOf(variable, StringComparison.Ordinal);
                            if (varStartIndex >= 0)
                            {
                                string rightPart = psOutputString.Substring(varStartIndex + variable.Length + 1);
                                if (rightPart.IndexOf(' ') > 0)
                                {
                                    string value = rightPart.Substring(0, rightPart.IndexOf(' '));
                                    env[variable] = value;
                                }
                                else
                                {
                                    env[variable] = rightPart;
                                }

                                trace.Verbose($"PID:{process.Id} ({variable}={env[variable]})");
                            }
                        }
                    }
                }
            }

            if (env.TryGetValue(variable, out string envVariable))
            {
                return envVariable;
            }
            else
            {
                return null;
            }
        }

19 View Source File : ActionCommand.cs
License : MIT License
Project Creator : actions

public static bool TryParseV2(string message, HashSet<string> registeredCommands, out ActionCommand command)
        {
            command = null;
            if (string.IsNullOrEmpty(message))
            {
                return false;
            }

            try
            {
                // the message needs to start with the keyword after trim leading space.
                message = message.TrimStart();
                if (!message.StartsWith(_commandKey))
                {
                    return false;
                }

                // Get the index of the separator between the command info and the data.
                int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
                if (endIndex < 0)
                {
                    return false;
                }

                // Get the command info (command and properties).
                int cmdIndex = _commandKey.Length;
                string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);

                // Get the command name
                int spaceIndex = cmdInfo.IndexOf(' ');
                string commandName =
                    spaceIndex < 0
                    ? cmdInfo
                    : cmdInfo.Substring(0, spaceIndex);

                if (registeredCommands.Contains(commandName))
                {
                    // Initialize the command.
                    command = new ActionCommand(commandName);
                }
                else
                {
                    return false;
                }

                // Set the properties.
                if (spaceIndex > 0)
                {
                    string propertiesStr = cmdInfo.Substring(spaceIndex + 1).Trim();
                    string[] splitProperties = propertiesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string propertyStr in splitProperties)
                    {
                        string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
                        if (pair.Length == 2)
                        {
                            command.Properties[pair[0]] = UnescapeProperty(pair[1]);
                        }
                    }
                }

                command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
                return true;
            }
            catch
            {
                command = null;
                return false;
            }
        }

19 View Source File : ActionCommand.cs
License : MIT License
Project Creator : actions

public static bool TryParse(string message, HashSet<string> registeredCommands, out ActionCommand command)
        {
            command = null;
            if (string.IsNullOrEmpty(message))
            {
                return false;
            }

            try
            {
                // Get the index of the prefix.
                int prefixIndex = message.IndexOf(Prefix);
                if (prefixIndex < 0)
                {
                    return false;
                }

                // Get the index of the separator between the command info and the data.
                int rbIndex = message.IndexOf(']', prefixIndex);
                if (rbIndex < 0)
                {
                    return false;
                }

                // Get the command info (command and properties).
                int cmdIndex = prefixIndex + Prefix.Length;
                string cmdInfo = message.Substring(cmdIndex, rbIndex - cmdIndex);

                // Get the command name
                int spaceIndex = cmdInfo.IndexOf(' ');
                string commandName =
                    spaceIndex < 0
                    ? cmdInfo
                    : cmdInfo.Substring(0, spaceIndex);

                if (registeredCommands.Contains(commandName))
                {
                    // Initialize the command.
                    command = new ActionCommand(commandName);
                }
                else
                {
                    return false;
                }

                // Set the properties.
                if (spaceIndex > 0)
                {
                    string propertiesStr = cmdInfo.Substring(spaceIndex + 1);
                    string[] splitProperties = propertiesStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string propertyStr in splitProperties)
                    {
                        string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
                        if (pair.Length == 2)
                        {
                            command.Properties[pair[0]] = Unescape(pair[1]);
                        }
                    }
                }

                command.Data = Unescape(message.Substring(rbIndex + 1));
                return true;
            }
            catch
            {
                command = null;
                return false;
            }
        }

19 View Source File : Logging.cs
License : MIT License
Project Creator : actions

public void Write(string message)
        {
            // lazy creation on write
            if (_pageWriter == null)
            {
                Create();
            }

            string line = $"{DateTime.UtcNow.ToString("O")} {message}";
            _pageWriter.WriteLine(line);

            _totalLines++;
            if (line.IndexOf('\n') != -1)
            {
                foreach (char c in line)
                {
                    if (c == '\n')
                    {
                        _totalLines++;
                    }
                }
            }

            _byteCount += System.Text.Encoding.UTF8.GetByteCount(line);
            if (_byteCount >= PageSize)
            {
                NewPage();
            }
        }

See More Examples