string.Split(char[], int)

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

557 Examples 7

19 View Source File : SaslDigestMd5.cs
License : MIT License
Project Creator : araditc

private static NameValueCollection ParseDigestChallenge(string challenge) {
			challenge.ThrowIfNull("challenge");
			NameValueCollection coll = new NameValueCollection();
			string[] parts = challenge.Split(',');
			foreach (string p in parts) {
				string[] kv = p.Split(new char[] { '=' }, 2);
				if (kv.Length == 2)
					coll.Add(kv[0], kv[1].Trim('"'));
			}
			return coll;
		}

19 View Source File : OAuth2TestServer.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<Transaction> SendAsync(
            string uri,
            string cookieHeader = null,
            string postBody = null,
            AuthenticationHeaderValue authenticateHeader = null)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, uri);
            if (!string.IsNullOrEmpty(cookieHeader))
            {
                request.Headers.Add("Cookie", cookieHeader);
            }
            if (authenticateHeader != null)
            {
                request.Headers.Authorization = authenticateHeader;
            }
            if (!string.IsNullOrEmpty(postBody))
            {
                request.Method = HttpMethod.Post;
                request.Content = new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded");
            }

            var transaction = new Transaction
            {
                Request = request,
                Response = await HttpClient.SendAsync(request),
            };
            if (transaction.Response.Headers.Contains("Set-Cookie"))
            {
                transaction.SetCookie = transaction.Response.Headers.GetValues("Set-Cookie").SingleOrDefault();
            }
            if (!string.IsNullOrEmpty(transaction.SetCookie))
            {
                transaction.CookieNameValue = transaction.SetCookie.Split(new[] { ';' }, 2).First();
            }
            transaction.ResponseText = await transaction.Response.Content.ReadreplacedtringAsync();

            if (transaction.Response.Content != null &&
                transaction.Response.Content.Headers.ContentType != null &&
                transaction.Response.Content.Headers.ContentType.MediaType == "text/xml")
            {
                transaction.ResponseElement = XElement.Parse(transaction.ResponseText);
            }

            if (transaction.Response.Content != null &&
                transaction.Response.Content.Headers.ContentType != null &&
                transaction.Response.Content.Headers.ContentType.MediaType == "application/json")
            {
                transaction.ResponseToken = JToken.Parse(transaction.ResponseText);
            }

            return transaction;
        }

19 View Source File : ServerSms.cs
License : Apache License 2.0
Project Creator : AlexWan

private string[] _smsc_send_cmd(string cmd, string arg, string[] files = null)
        {
            arg = "login=" + _urlencode(SmscLogin) + "&psw=" + _urlencode(SmscPreplacedword) + "&fmt=1&charset=" + SmscCharset + "&" + arg;

            string url = (SmscHttps ? "https" : "http") + "://smsc.ru/sys/" + cmd + ".php" + (SmscPost ? "" : "?" + arg);

            string ret;
            int i = 0;
            HttpWebRequest request;
            StreamReader sr;
            HttpWebResponse response;

            do
            {
                if (i > 0)
                    System.Threading.Thread.Sleep(2000 + 1000 * i);

                if (i == 2)
                    url = url.Replace("://smsc.ru/", "://www2.smsc.ru/");

                request = (HttpWebRequest)WebRequest.Create(url);

                if (SmscPost) {
                    request.Method = "POST";

                    string postHeader, boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                    byte[] postHeaderBytes, boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"), tbuf;
                    StringBuilder sb = new StringBuilder();
                    int bytesRead;

                    byte[] output = new byte[0];

                    if (files == null) {
                        request.ContentType = "application/x-www-form-urlencoded";
                        output = Encoding.UTF8.GetBytes(arg);
                        request.ContentLength = output.Length;
                    }
                    else {
                        request.ContentType = "multipart/form-data; boundary=" + boundary;

                        string[] par = arg.Split('&');
                        int fl = files.Length;

                        for (int pcnt = 0; pcnt < par.Length + fl; pcnt++)
                        {
                            sb.Clear();

                            sb.Append("--");
                            sb.Append(boundary);
                            sb.Append("\r\n");
                            sb.Append("Content-Disposition: form-data; name=\"");

                            bool pof = pcnt < fl;
                            String[] nv = new String[0];

                            if (pof)
                            {
                                sb.Append("File" + (pcnt + 1));
                                sb.Append("\"; filename=\"");
                                sb.Append(Path.GetFileName(files[pcnt]));
                            }
                            else {
                                nv = par[pcnt - fl].Split('=');
                                sb.Append(nv[0]);
                            }

                            sb.Append("\"");
                            sb.Append("\r\n");
                            sb.Append("Content-Type: ");
                            sb.Append(pof ? "application/octet-stream" : "text/plain; charset=\"" + SmscCharset + "\"");
                            sb.Append("\r\n");
                            sb.Append("Content-Transfer-Encoding: binary");
                            sb.Append("\r\n");
                            sb.Append("\r\n");

                            postHeader = sb.ToString();
                            postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

                            output = _concatb(output, postHeaderBytes);

                            if (pof)
                            {
                                FileStream fileStream = new FileStream(files[pcnt], FileMode.Open, FileAccess.Read);

                                // Write out the file contents
                                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];

                                bytesRead = 0;
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    tbuf = buffer;
                                    Array.Resize(ref tbuf, bytesRead);

                                    output = _concatb(output, tbuf);
                                }
                            }
                            else {
                                byte[] vl = Encoding.UTF8.GetBytes(nv[1]);
                                output = _concatb(output, vl);
                            }

                            output = _concatb(output, Encoding.UTF8.GetBytes("\r\n"));
                        }
                        output = _concatb(output, boundaryBytes);

                        request.ContentLength = output.Length;
                    }

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(output, 0, output.Length);
                }

                try
                {
                    response = (HttpWebResponse)request.GetResponse();

                    sr = new StreamReader(response.GetResponseStream());
                    ret = sr.ReadToEnd();
                }
                catch (WebException) {
                    ret = "";
                }
            }
            while (ret == "" && ++i < 4);

            if (ret == "") {
                if (SmscDebug)
                    _print_debug("Ошибка чтения адреса: " + url);

                ret = ","; // bogus response / фиктивный ответ
            }

            char delim = ',';

            if (cmd == "status")
            {
                string[] par = arg.Split('&');

                for (i = 0; i < par.Length; i++)
                {
                    string[] lr = par[i].Split("=".ToCharArray(), 2);

                    if (lr[0] == "id" && lr[1].IndexOf("%2c") > 0) // comma in id - multiple request / запятая в id - множественный запрос
                        delim = '\n';
                }
            }

            return ret.Split(delim);
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : anoyetta

private static replacedembly CefSharpResolver(object sender, ResolveEventArgs args)
        {
            if (args.Name.StartsWith("CefSharp", StringComparison.OrdinalIgnoreCase))
            {
                var replacedemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll";
                var archSpecificPath = Path.Combine(
                    AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                    Environment.Is64BitProcess ? "x64" : "x86",
                    replacedemblyName);

                return File.Exists(archSpecificPath) ?
                    replacedembly.LoadFile(archSpecificPath) :
                    null;
            }

            return null;
        }

19 View Source File : AuthenticationChallenge.cs
License : MIT License
Project Creator : andruzzzhka

internal static AuthenticationChallenge Parse (string value)
    {
      var chal = value.Split (new[] { ' ' }, 2);
      if (chal.Length != 2)
        return null;

      var schm = chal[0].ToLower ();
      return schm == "basic"
             ? new AuthenticationChallenge (
                 AuthenticationSchemes.Basic, ParseParameters (chal[1]))
             : schm == "digest"
               ? new AuthenticationChallenge (
                   AuthenticationSchemes.Digest, ParseParameters (chal[1]))
               : null;
    }

19 View Source File : MKMPriceAsFormula.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public bool Parse(string formula)
    {
      string formulaOrig = formula;
      formula = formula.Trim();
      var separators = new char[] { '*', '-', '+' };
      // parse the first operand, there must be at least one and the formula cannot start with an operand
      string operand = formula.Split(separators, 2)[0];
      if (!parseAndAddOperand(operand.Trim()))
      {
        MKMHelpers.LogError("parsing price formula", "failed to parse operand " + operand + " in formula " + formulaOrig
          + ", it cannot be used.", true);
        return false;
      }
      formula = formula.Substring(operand.Length);
      while (formula.Length > 0)
      {
        char oper = formula[0]; // the next symbol is surely the operand
        switch (oper)
        {
          case '*':
            operators.Add(mult);
            break;
          case '-':
            operators.Add(subtract);
            break;
          case '+':
            operators.Add(adding);
            break;
        }
        formula = formula.Substring(1);
        // there must be another operand after operator, otherwise it is an error
        operand = formula.Split(separators, 2)[0];
        if (!parseAndAddOperand(operand.Trim()))
        {
          MKMHelpers.LogError("parsing price formula", "failed to parse operand " + operand + " in formula " + formulaOrig
            + ", it cannot be used.", false);
          return false;
        }
        formula = formula.Substring(operand.Length);
        formula.Trim();
      }
      return true;
    }

19 View Source File : Locale.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public bool TryResolve(string key, [NotNullWhen(true)] out string? result, params object[] args)
        {
            var parts = key.Split(new[] { '.' }, 2);
            string section;
            string vKey;

            if (parts.Length == 1)
            {
                section = IniFile.EmptySection;
                vKey = parts[0];
            }
            else if (parts.Length > 1)
            {
                section = parts[0];
                vKey = parts[1];
            }
            else
            {
                result = null;
                return false;
            }

            if (!_iniFile.TryGetValue(section, vKey, out result)) return false;

            const string pattern = @"__(\d+)__";
            const string replacePattern = "{$1}";
            result = Regex.Replace(result, pattern, replacePattern);

            result = string.Format(result, args);
            return true;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ADeltaX

private void UpdateSuggestedList(string text)
        {
            //TODO: BROKEN

            var filter = text;

            if (filter.StartsWith(@"Computer\", StringComparison.InvariantCultureIgnoreCase))
                filter = filter.Remove(0, @"Computer\".Length);

            listViewSuggestion.ItemsSource = null;

            if (string.IsNullOrEmpty(filter))
            {
                IList<string> str = new List<string>();

                foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    str.Add(@"Computer\" + x.Name);

                listViewSuggestion.ItemsSource = str;
            }
            else
            {
                var splitted = filter.Split(new char[] { '\\' }, 2);
                if (splitted.Length >= 2)
                {
                    splitted[1] = splitted[1].Trim();

                    List<RegistryHive> registries = new List<RegistryHive>();

                    foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    {
                        if (x.Name.Equals(splitted[0], StringComparison.InvariantCultureIgnoreCase))
                            registries.Add(x.AttachedHive);
                    }

                    IList<string> str = new List<string>();
                    var subSplitted = splitted[1].Split(new char[] { '\\' });

                    var subIncorporated = string.Join("\\", subSplitted, 0, subSplitted.Length - 1);

                    foreach (var reg in registries)
                    {

                        var key = reg.Root.OpenSubKey(splitted[1] == "" ? "\\" : subIncorporated);
                        if (key != null)
                            foreach (var subKey in key.SubKeys)
                                str.Add(@"Computer\" + splitted[0] + subKey.Name); //TODO

                    }

                    if (subSplitted.Length >= 1 && !string.IsNullOrEmpty(subSplitted[0]))
                        str = str.Where(x => x.StartsWith(@"Computer\" + splitted[0] + "\\" + splitted[1], StringComparison.InvariantCultureIgnoreCase)).ToList();

                    listViewSuggestion.ItemsSource = str;
                }
                else
                {
                    IList<string> str = new List<string>();

                    foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    {
                        if (x.Name.StartsWith(splitted[0], StringComparison.InvariantCultureIgnoreCase))
                            str.Add(@"Computer\" + x.Name);
                    }

                    listViewSuggestion.ItemsSource = str;
                }
            }
        }

19 View Source File : BasicCredentials.cs
License : Apache License 2.0
Project Creator : authlete

static BasicCredentials BuildFromParameter(string base64String)
        {
            if (base64String == null)
            {
                // UserId = null, Preplacedword = null
                return new BasicCredentials(null, null);
            }

            // Decode the Base64 string.
            string plainText = Base64Decode(base64String);

            // Split "UserId:Preplacedword" into "UserId" and "Preplacedword".
            string[] substrings = plainText.Split(SEPARATOR, 2);

            string userId   = null;
            string preplacedword = null;

            // User ID
            if (1 <= substrings.Length)
            {
                userId = substrings[0];
            }

            // Preplacedword
            if (2 <= substrings.Length)
            {
                preplacedword = substrings[1];
            }

            return new BasicCredentials(userId, preplacedword);
        }

19 View Source File : BasicAuthenticationHandler.cs
License : MIT License
Project Creator : AElfProject

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var endpoint = Context.GetEndpoint();
            if (endpoint?.Metadata?.GetMetadata<IAuthorizeData>() == null)
            {
                return Task.FromResult(AuthenticateResult.NoResult());
            }
            
            if (string.IsNullOrWhiteSpace(_basicAuthOptions.UserName) || string.IsNullOrWhiteSpace(_basicAuthOptions.Preplacedword))
            {
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = Error.NeedBasicAuth;
                return Task.FromResult(AuthenticateResult.Fail(Error.NeedBasicAuth));
            }
            
            if (!Request.Headers.ContainsKey("Authorization"))
                return Task.FromResult(AuthenticateResult.Fail("Missing Authorization Header"));

            string userName;
            string preplacedword;
            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                userName = credentials[0];
                preplacedword = credentials[1];
            }
            catch
            {
                return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
            }

            if (userName != _basicAuthOptions.UserName || preplacedword != _basicAuthOptions.Preplacedword)
                return Task.FromResult(AuthenticateResult.Fail("Invalid Username or Preplacedword"));

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userName),
                new Claim(ClaimTypes.Name, userName),
            };
            var idenreplacedy = new ClaimsIdenreplacedy(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(idenreplacedy);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return Task.FromResult(AuthenticateResult.Success(ticket));
        }

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

private void RemoveFromlist(TwitchUser requestor, string request)
        {
            string[] parts = request.Split(new char[] { ' ', ',' }, 2);
            if (parts.Length < 2)
            {
                //     NewCommands[Addtolist].ShortHelp();
                QueueChatMessage("Usage text... use the official help method");
                return;
            }

            try
            {

                listcollection.remove(ref parts[0], ref parts[1]);
                QueueChatMessage($"Removed {parts[1]} from {parts[0]}");

            }
            catch
            {
                QueueChatMessage($"list {parts[0]} not found.");
            }
        }

19 View Source File : HttpListenerRequest.cs
License : MIT License
Project Creator : andruzzzhka

internal void SetRequestLine (string requestLine)
    {
      var parts = requestLine.Split (new[] { ' ' }, 3);
      if (parts.Length < 3) {
        _context.ErrorMessage = "Invalid request line (parts)";
        return;
      }

      var method = parts[0];
      if (method.Length == 0) {
        _context.ErrorMessage = "Invalid request line (method)";
        return;
      }

      var target = parts[1];
      if (target.Length == 0) {
        _context.ErrorMessage = "Invalid request line (target)";
        return;
      }

      var rawVer = parts[2];
      if (rawVer.Length != 8) {
        _context.ErrorMessage = "Invalid request line (version)";
        return;
      }

      if (rawVer.IndexOf ("HTTP/") != 0) {
        _context.ErrorMessage = "Invalid request line (version)";
        return;
      }

      Version ver;
      if (!rawVer.Substring (5).TryCreateVersion (out ver)) {
        _context.ErrorMessage = "Invalid request line (version)";
        return;
      }

      if (ver.Major < 1) {
        _context.ErrorMessage = "Invalid request line (version)";
        return;
      }

      if (!method.IsHttpMethod (ver)) {
        _context.ErrorMessage = "Invalid request line (method)";
        return;
      }

      _httpMethod = method;
      _rawUrl = target;
      _protocolVersion = ver;
    }

19 View Source File : SteamVR_PlayArea.cs
License : MIT License
Project Creator : ajayyy

public static bool GetBounds( Size size, ref HmdQuad_t pRect )
	{
		if (size == Size.Calibrated)
		{
			var initOpenVR = (!SteamVR.active && !SteamVR.usingNativeSupport);
			if (initOpenVR)
			{
				var error = EVRInitError.None;
				OpenVR.Init(ref error, EVRApplicationType.VRApplication_Utility);
			}

			var chaperone = OpenVR.Chaperone;
			bool success = (chaperone != null) && chaperone.GetPlayAreaRect(ref pRect);
			if (!success)
				Debug.LogWarning("Failed to get Calibrated Play Area bounds!  Make sure you have tracking first, and that your space is calibrated.");

			if (initOpenVR)
				OpenVR.Shutdown();

			return success;
		}
		else
		{
			try
			{
				var str = size.ToString().Substring(1);
				var arr = str.Split(new char[] {'x'}, 2);

				// convert to half size in meters (from cm)
				var x = float.Parse(arr[0]) / 200;
				var z = float.Parse(arr[1]) / 200;

				pRect.vCorners0.v0 =  x;
				pRect.vCorners0.v1 =  0;
				pRect.vCorners0.v2 = -z;

				pRect.vCorners1.v0 = -x;
				pRect.vCorners1.v1 =  0;
				pRect.vCorners1.v2 = -z;

				pRect.vCorners2.v0 = -x;
				pRect.vCorners2.v1 =  0;
				pRect.vCorners2.v2 =  z;

				pRect.vCorners3.v0 =  x;
				pRect.vCorners3.v1 =  0;
				pRect.vCorners3.v2 =  z;

				return true;
			}
			catch {}
		}

		return false;
	}

19 View Source File : VariableCollection.cs
License : MIT License
Project Creator : aprilyush

public void SetValue(string varExp, object value)
        {
            if (string.IsNullOrEmpty(varExp)) throw new ArgumentNullException("varExp");
            string[] exps = varExp.Split(".".ToCharArray(), 2);

            Variable var = this[exps[0]];
            if (var != null)
            {
                if (exps.Length == 1)
                {
                    var.Value = value;
                }
                else if (exps.Length == 2)
                {
                    var.SetExpValue(exps[1], value);
                }
            }
        }

19 View Source File : RegistryKey.cs
License : MIT License
Project Creator : ADeltaX

public RegistryKey OpenSubKey(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return this;
            }

            string[] split = path.Split(new[] { '\\' }, 2);
            int cellIndex = FindSubKeyCell(split[0]);

            if (cellIndex < 0)
            {
                return null;
            }
            KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex);
            if (split.Length == 1)
            {
                return new RegistryKey(_hive, cell);
            }
            return new RegistryKey(_hive, cell).OpenSubKey(split[1]);
        }

19 View Source File : SPL.Helper.cs
License : GNU General Public License v3.0
Project Creator : ArduinoIoTDev

public static ArrayList GetStringList(string inputStr)
        {
            string[] arr;
            arr = inputStr.Split(new Char[] { ' ', ',', '\t' }, 200);

            ArrayList newArr = new ArrayList();

            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] != string.Empty)
                {
                    newArr.Add(arr[i]);
                }
            }


            return newArr;
        }

19 View Source File : GitHubRepository.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private List<AvailablePlugin> ParseReleases(string releasesData, string replacedetUrl, string repoName)
        {
            var results = new List<AvailablePlugin>();

            var reader = new System.IO.StringReader(releasesData);

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                var parts = line.Split(new char[] { ' ' }, 3);
                var sha1Hash = parts[0];
                var fileName = parts[1];
                var displayName = parts[2];

                var versionString = fileName.Split('-').Last().Replace(".zip", string.Empty);
                var version = new Version(versionString);

                var downloadUrl = replacedetUrl + fileName;

                results.Add(new AvailablePlugin(displayName, downloadUrl, sha1Hash, version, repoName, this));
            }

            return results;
        }

19 View Source File : OAuth2TestServer.cs
License : Apache License 2.0
Project Creator : aspnet

public NameValueCollection ParseRedirectQueryString()
            {
                Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
                Response.Headers.Location.Query.ShouldStartWith("?");
                string querystring = Response.Headers.Location.Query.Substring(1);
                var nvc = new NameValueCollection();
                foreach (var pair in querystring
                    .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => x.Split(new[] { '=' }, 2).Select(Uri.UnescapeDataString)))
                {
                    if (pair.Count() == 2)
                    {
                        nvc.Add(pair.First(), pair.Last());
                    }
                }
                return nvc;
            }

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

internal static bool IsMSBuildForUnityEnabled()
        {
            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return false;
            }

            // Load the manifest file.
            string manifestFileContents = File.ReadAllText(manifestPath);
            if (string.IsNullOrWhiteSpace(manifestFileContents))
            {
                return false;
            }

            // Read the package manifest a line at a time.
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line.Contains(MSBuildPackageName))
                        {
                            // Split the line into packageName : packageVersion
                            string[] lineComponents = line.Split(new char[] { ':' }, 2);

                            return IsAppropriateMBuildVersion(MSBuildPackageVersion, lineComponents[1]);
                        }
                    }
                }
            }

            return false;
        }

19 View Source File : VerySimpleIni.cs
License : GNU General Public License v3.0
Project Creator : aurelitec

public string GetValue(string key, string defaultValue)
        {
            if ((this.lines != null) && (this.lines.Count > 0))
            {
                // Find the line that starts with the specified key ("key=value")
                int index = this.lines.FindIndex(line => { return line.StartsWith(key, true, null); });
                if (index >= 0)
                {
                    // If line is found, save a reference to it and remove it from the list, to ensure faster
                    // future key look-ups
                    string line = this.lines[index];
                    this.lines.RemoveAt(index);

                    // Split the line in the "name=value" format and return the "value" part
                    string[] lineParts = line.Split(VerySimpleIni.KeyValueSeparator, 2);
                    if (lineParts.Length == 2)
                    {
                        return lineParts[1].Trim();
                    }
                }
            }

            return defaultValue;
        }

19 View Source File : MultiplatformDllLoader.cs
License : GNU General Public License v3.0
Project Creator : Amebis

private static replacedembly Resolver(object sender, ResolveEventArgs args)
        {
            string replacedemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll";
            string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, Environment.Is64BitProcess ? "x64" : "x86", replacedemblyName);
            return File.Exists(archSpecificPath) ? replacedembly.LoadFile(archSpecificPath) : null;
        }

19 View Source File : SteamVR_PlayArea.cs
License : GNU General Public License v2.0
Project Creator : andrewjc

public static bool GetBounds( Size size, ref HmdQuad_t pRect )
	{
		if (size == Size.Calibrated)
		{
			var initOpenVR = (!SteamVR.active && !SteamVR.usingNativeSupport);
			if (initOpenVR)
			{
				var error = EVRInitError.None;
				OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);
			}

			var chaperone = OpenVR.Chaperone;
			bool success = (chaperone != null) && chaperone.GetPlayAreaRect(ref pRect);
			if (!success)
				Debug.LogWarning("Failed to get Calibrated Play Area bounds!  Make sure you have tracking first, and that your space is calibrated.");

			if (initOpenVR)
				OpenVR.Shutdown();

			return success;
		}
		else
		{
			try
			{
				var str = size.ToString().Substring(1);
				var arr = str.Split(new char[] {'x'}, 2);

				// convert to half size in meters (from cm)
				var x = float.Parse(arr[0]) / 200;
				var z = float.Parse(arr[1]) / 200;

				pRect.vCorners0.v0 =  x;
				pRect.vCorners0.v1 =  0;
				pRect.vCorners0.v2 =  z;

				pRect.vCorners1.v0 =  x;
				pRect.vCorners1.v1 =  0;
				pRect.vCorners1.v2 = -z;

				pRect.vCorners2.v0 = -x;
				pRect.vCorners2.v1 =  0;
				pRect.vCorners2.v2 = -z;

				pRect.vCorners3.v0 = -x;
				pRect.vCorners3.v1 =  0;
				pRect.vCorners3.v2 =  z;

				return true;
			}
			catch {}
		}

		return false;
	}

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

static bool CreatereplacedetPath( string newFolderPath )
	{
		const  int maxFoldersCount = 32;
		string currentPath;
		string[] pathFolders;

		pathFolders = newFolderPath.Split (new char[]{ '/' }, maxFoldersCount);

		if (!string.Equals ("replacedets", pathFolders [0], System.StringComparison.OrdinalIgnoreCase))
		{
			Debug.LogError( "Folder path has to be started with \" replacedets \" " );
			return false;
		}

		currentPath = "replacedets";
		for (int i = 1; i < pathFolders.Length; i++)
		{
			if (!string.IsNullOrEmpty(pathFolders[i]))
			{
				string newPath = currentPath + "/" + pathFolders[i];
				if (!replacedetDatabase.IsValidFolder(newPath))
					replacedetDatabase.CreateFolder(currentPath, pathFolders[i]);
				currentPath = newPath;
			}
		}

		Debug.Log( "Created path: " + currentPath );
		return true;
	}

19 View Source File : AuthenticationResponse.cs
License : MIT License
Project Creator : andruzzzhka

internal static AuthenticationResponse Parse (string value)
    {
      try {
        var cred = value.Split (new[] { ' ' }, 2);
        if (cred.Length != 2)
          return null;

        var schm = cred[0].ToLower ();
        return schm == "basic"
               ? new AuthenticationResponse (
                   AuthenticationSchemes.Basic, ParseBasicCredentials (cred[1]))
               : schm == "digest"
                 ? new AuthenticationResponse (
                     AuthenticationSchemes.Digest, ParseParameters (cred[1]))
                 : null;
      }
      catch {
      }

      return null;
    }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private long VersionNum(string data)
        {
            string[] separate = data.Split(new char[] { '.' }, 4);
            separate[1] = separate[1].PadLeft(4, '0');
            separate[2] = separate[2].PadLeft(4, '0');

            if (separate.Length == 4)
                separate[3] = separate[3].PadLeft(4, '0');
            else
                separate[2] = separate[2].PadRight(8, '0');

            long result;
            long.TryParse(separate[0] + separate[1] + separate[2] + (separate.Length == 4 ? separate[3] : ""), out result);

            return result;
        }

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

private void Addtolist(TwitchUser requestor, string request)
        {
            string[] parts = request.Split(new char[] { ' ', ',' }, 2);
            if (parts.Length < 2)
            {
                QueueChatMessage("Usage text... use the official help method");
                return;
            }

            try
            {

                listcollection.add(ref parts[0], ref parts[1]);
                //QueueChatMessage($"Added {parts[1]} to {parts[0]}");

            }
            catch
            {
                QueueChatMessage($"list {parts[0]} not found.");
            }
        }

19 View Source File : HttpResponse.cs
License : MIT License
Project Creator : andruzzzhka

internal static HttpResponse Parse (string[] headerParts)
    {
      var statusLine = headerParts[0].Split (new[] { ' ' }, 3);
      if (statusLine.Length != 3)
        throw new ArgumentException ("Invalid status line: " + headerParts[0]);

      var headers = new WebHeaderCollection ();
      for (int i = 1; i < headerParts.Length; i++)
        headers.InternalSet (headerParts[i], true);

      return new HttpResponse (
        statusLine[1], statusLine[2], new Version (statusLine[0].Substring (5)), headers);
    }

19 View Source File : Updater.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public static void CheckForUpdate()
        {
            string version = GetWebString(VersionUrl);

            if ( string.IsNullOrEmpty(version))
            {
                DialogResult result =
                    MessageBox.Show(
                        "An error has occurred. Please manually check the Github releases page for updates.",
                        "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                if (result == DialogResult.Yes)
                {
                    Process.Start(DownloadListUrl);
                }
            }
            else
            {
                var versionSplit = version.Split(new[] {'.'}, 3);
                int versionCode = 0;
                foreach (var s in versionSplit)
                {
                    versionCode *= 0x100;
                    versionCode += int.Parse(s);
                }

                Version vrs = replacedembly.GetExecutingreplacedembly().GetName().Version;
                int replacedemblyVersionCode = (vrs.Major * 0x100 + vrs.Minor) * 0x100 + vrs.Build;
                
                if (versionCode > replacedemblyVersionCode)
                {
                    string message =
                        "There is a new version of SparkIV available! Would you like to download the newest version?" +
                        "\n" + "\n" + "This version is:  " + vrs.Major + "." + vrs.Minor + "." + vrs.Build + "\n"
                        + "New Version is: " + version;

                    DialogResult result = MessageBox.Show(message, "New Update!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                    if (result == DialogResult.Yes)
                    {
                        var url = GetWebString(UpdateUrl);

                        if ( string.IsNullOrEmpty(url) )
                        {
                            result =
                                MessageBox.Show(
                                    "An error has occurred. Please manually check the Github releases page for updates?",
                                    "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                            if (result == DialogResult.Yes)
                            {
                                Process.Start(DownloadListUrl);
                            }
                        }
                        else
                        {
                            Process.Start( url );
                            Application.Exit();                            
                        }
                    }
                }
                else
                {
                    MessageBox.Show(String.Format("There is no update available at this time."),
                                    "No update available", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }
        }

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

private string GetBeatSaverId(string request)
        {
            request=normalize.RemoveSymbols(ref request, normalize._SymbolsNoDash);
            if (request!="360" && _digitRegex.IsMatch(request)) return request;
            if (_beatSaverRegex.IsMatch(request))
            {
                string[] requestparts = request.Split(new char[] { '-' }, 2);
                //return requestparts[0];
           
                int o;
                Int32.TryParse(requestparts[1], out o);
                     {
                        //Instance.QueueChatMessage($"key={o.ToString("x")}");
                    return o.ToString("x");
                    }
      
            }
            return "";
        }

19 View Source File : RegistryKey.cs
License : MIT License
Project Creator : ADeltaX

public RegistryKey CreateSubKey(string subkey)
        {
            if (string.IsNullOrEmpty(subkey))
            {
                return this;
            }

            string[] split = subkey.Split(new[] { '\\' }, 2);
            int cellIndex = FindSubKeyCell(split[0]);

            if (cellIndex < 0)
            {
                KeyNodeCell newKeyCell = new KeyNodeCell(split[0], _cell.Index);
                newKeyCell.SecurityIndex = _cell.SecurityIndex;
                ReferenceSecurityCell(newKeyCell.SecurityIndex);
                _hive.UpdateCell(newKeyCell, true);

                LinkSubKey(split[0], newKeyCell.Index);

                if (split.Length == 1)
                {
                    return new RegistryKey(_hive, newKeyCell);
                }
                return new RegistryKey(_hive, newKeyCell).CreateSubKey(split[1]);
            }
            KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex);
            if (split.Length == 1)
            {
                return new RegistryKey(_hive, cell);
            }
            return new RegistryKey(_hive, cell).CreateSubKey(split[1]);
        }

19 View Source File : ExcelVBAProject.cs
License : Apache License 2.0
Project Creator : Appdynamics

private void ReadModules()
        {
            foreach (var modul in Modules)
            {
                var stream = Doreplacedent.Storage.SubStorage["VBA"].DataStreams[modul.streamName];
                var byCode = VBACompression.DecompressPart(stream, (int)modul.ModuleOffset);
                string code = Encoding.GetEncoding(CodePage).GetString(byCode);
                int pos=0;
                while(pos+9<code.Length && code.Substring(pos,9)=="Attribute")
                {
                    int linePos=code.IndexOf("\r\n",pos);
                    string[] lineSplit;
                    if(linePos>0)
                    {
                        lineSplit = code.Substring(pos + 9, linePos - pos - 9).Split('=');
                    }
                    else
                    {
                        lineSplit=code.Substring(pos+9).Split(new char[]{'='},1);
                    }
                    if (lineSplit.Length > 1)
                    {
                        lineSplit[1] = lineSplit[1].Trim();
                        var attr = 
                            new ExcelVbaModuleAttribute()
                        {
                            Name = lineSplit[0].Trim(),
                            DataType = lineSplit[1].StartsWith("\"") ? eAttributeDataType.String : eAttributeDataType.NonString,
                            Value = lineSplit[1].StartsWith("\"") ? lineSplit[1].Substring(1, lineSplit[1].Length - 2) : lineSplit[1]
                        };
                        modul.Attributes._list.Add(attr);
                    }
                    pos = linePos + 2;
                }
                modul.Code=code.Substring(pos);
            }
        }

19 View Source File : INIFile.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private void ParseINIString(string iniString)
        {
            string[] lines = (iniString + "\n").Replace("\r\n", "\n").Split('\n');

            Clear();

            string section = null;

            foreach (string li in lines)
            {
                string l = li.Trim(' ', '\t'); // Trim line
                if (l.StartsWith(";")) continue; // Line is a comment

                if (l.StartsWith("[")) // found a new section
                {
                    // try to get section name, make sure it's valid
                    section = l.Trim('[', ']', ' ', '\t', ':').ToLowerInvariant();
                    string parentSection = null;

                    if (section.Contains(':')) // Sections inherits another section, name declared in the [SECTION:PARENT_SECTION] format
                    {
                        try
                        {
                            string sectionWithParent = section;
                            section = sectionWithParent.Split(':')[0].Trim();
                            parentSection = sectionWithParent.Split(':')[1].Trim();
                        }
                        catch (Exception)
                        {
                            section = l.Trim('[', ']', ' ', '\t', ':').ToLowerInvariant();
                            parentSection = null;
                        }
                    }

                    bool abstractSection = section.StartsWith("_");

                    if (string.IsNullOrEmpty(section)) { section = null; continue; }

                    if (!Sections.ContainsKey(section))
                        Sections.Add(section, new INIFileSection(abstractSection, parentSection));

                    continue;
                }

                if (l.Contains('=')) // The line contains an "equals" sign, it means we found a value
                {
                    if (section == null) continue; // we're not in a section, ignore

                    string[] v = l.Split(new char[] { '=' }, 2); // Split the line at the first "equal" sign: key = value
                    if (v.Length < 2) continue;

                    string key = v[0].Trim().Trim('"').ToLowerInvariant();
                    string value = v[1].Trim().Trim('"');
                    WriteValue(section, key, value);
                }
            }
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush

private static object GetRenderInstance(string renderInstance)
        {
            if (string.IsNullOrEmpty(renderInstance)) return null;

            string[] k = renderInstance.Split(new char[] { ',' }, 2);
            if (k.Length != 2) return null;

            string replacedemblyKey = k[1].Trim();
            string typeKey = k[0].Trim();
            string cacheKey = string.Concat(typeKey, ",", replacedemblyKey);

            //从缓存读取
            object render;
            bool flag = false;
            lock (RenderInstanceCache)
            {
                flag = RenderInstanceCache.TryGetValue(cacheKey, out render);
            }
            if (!flag || render == null)
            {
                //重新生成实例
                render = null;
                //生成实例
                replacedembly replacedembly;
                if (replacedemblyKey.IndexOf(":") != -1)
                {
                    replacedembly = replacedembly.LoadFrom(replacedemblyKey);
                }
                else
                {
                    replacedembly = replacedembly.Load(replacedemblyKey);
                }
                if (replacedembly != null)
                {
                    render = replacedembly.CreateInstance(typeKey, false);
                }
                if (render != null)
                {
                    //缓存
                    lock (RenderInstanceCache)
                    {
                        if (RenderInstanceCache.ContainsKey(cacheKey))
                        {
                            RenderInstanceCache[cacheKey] = render;
                        }
                        else
                        {
                            RenderInstanceCache.Add(cacheKey, render);
                        }
                    }
                }
            }
            return render;
        }

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

internal static bool TryGetVersionComponents(
            string packageVersion,
            out Version version,
            out float prerelease)
        {
            char[] trimChars = new char[] { ' ', '\"', ',' };

            // Note: The version is in the following format Major.Minor.Revision[-Date.Build]

            // Attempt to split the version string into version and float components
            string[] versionComponents = packageVersion.Split(new char[] { '-' }, 2);

            // Parse the version component.
            string versionString = versionComponents[0].Trim(trimChars);
            if (Version.TryParse(versionString, out version))
            {
                if (versionComponents.Length == 2)
                {
                    // Parse the float component
                    string prereleaseString = versionComponents[1].Trim(trimChars);
                    if (float.TryParse(prereleaseString, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out prerelease))
                    {
                        return true;
                    }
                }
                else
                {
                    prerelease = 0f;
                    return true;
                }
            }

            version = null;
            prerelease = float.NaN;
            return false;
        }

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

public static Task StartRead()
        {
            cancellationTokenSource = new CancellationTokenSource();
            return Task.Run(async () =>
            {
                while (!stopRequested)
                {
                    // Implement our own reader since Console.ReadLine sucks in async and breaks our CTRL+C interrupt
                    SConsole.Write(">");
                    readingInput = true;
                    int pos = 0;
                    while (true)
                    {
                        var key = SConsole.ReadKey(true);
                        if (key.Modifiers.HasFlag(ConsoleModifiers.Control) && (key.Key == ConsoleKey.C || key.Key == ConsoleKey.Pause))
                        {
                            logger.LogMessage("{verb}Stopping...");
                            Program.Exit();
                            return;
                        }
                        else if (key.Key == ConsoleKey.Backspace)
                        {
                            if (pos > 0)
                            {
                                inputBuffer.Remove(pos - 1, 1);
                                lock (consoleLock)
                                    SConsole.Write("\b \b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.Delete)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                inputBuffer.Remove(pos, 1);
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + " " + new string('\b', inputBuffer.Length - pos + 1));
                            }
                        }
                        else if (key.Key == ConsoleKey.LeftArrow)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write("\b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.RightArrow)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer[pos]);
                                pos++;
                            }
                        }
                        else if (key.Key == ConsoleKey.Home)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write(new string('\b', pos));
                                pos = 0;
                            }
                        }
                        else if (key.Key == ConsoleKey.End)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos));
                                pos = inputBuffer.Length;
                            }
                        }
                        else if (key.Key == ConsoleKey.Enter)
                        {
                            lock (consoleLock)
                                SConsole.WriteLine();
                            break;
                        }
                        else if (key.KeyChar != 0)
                        {
                            inputBuffer.Insert(pos, key.KeyChar);
                            pos++;
                            lock (consoleLock)
                            {
                                SConsole.Write(key.KeyChar);
                                if (pos < inputBuffer.Length)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + new string('\b', inputBuffer.Length - pos));
                            }
                        }
                    }
                    readingInput = false;

                    var line = inputBuffer.ToString().Trim();
                    inputBuffer.Clear();
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    var verb = line.Split(new[] { ' ' }, 2)[0];
                    var command = Commands.FirstOrDefault(c => c.Verb == verb);

                    if (command != null)
                    {
                        try
                        {
                            await command.RunAsync(line.Substring(verb.Length).Trim(), cancellationTokenSource.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            // Fine...
                        }
                        catch (Exception ex)
                        {
                            logger.LogException(ex);
                        }
                    }
                    else
                        logger.LogCommandOutput("Unknown command, use {command}help{reset} to get the list of available commands.");
                    logger.LogCommandOutput("");
                }
            });
        }

19 View Source File : IconControl.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private string GetPathData(string iconPath)
        {
            var iconNameParts = iconPath.Split(new char[] { '.' }, 2);
            var iconPackName = iconNameParts[0];
            var iconName = iconNameParts[1];

            var data = string.Empty;

            switch (iconPackName)
            {
                case nameof(PackIconEntypoKind):
                    PackIconEntypoDataFactory.DataIndex.Value?.TryGetValue((PackIconEntypoKind)Enum.Parse(typeof(PackIconEntypoKind), iconName), out data);
                    return data;
                case nameof(PackIconFeatherIconsKind):
                    PackIconFeatherIconsDataFactory.DataIndex.Value?.TryGetValue((PackIconFeatherIconsKind)Enum.Parse(typeof(PackIconFeatherIconsKind), iconName), out data);
                    return data;
                case nameof(PackIconFontAwesomeKind):
                    PackIconFontAwesomeDataFactory.DataIndex.Value?.TryGetValue((PackIconFontAwesomeKind)Enum.Parse(typeof(PackIconFontAwesomeKind), iconName), out data);
                    return data;
                case nameof(PackIconMaterialKind):
                    PackIconMaterialDataFactory.DataIndex.Value?.TryGetValue((PackIconMaterialKind)Enum.Parse(typeof(PackIconMaterialKind), iconName), out data);
                    return data;
                case nameof(PackIconOcticonsKind):
                    PackIconOcticonsDataFactory.DataIndex.Value?.TryGetValue((PackIconOcticonsKind)Enum.Parse(typeof(PackIconOcticonsKind), iconName), out data);
                    return data;
                default:
                    return null;
            }
        }

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

[STAThread]
        private static void Main(string[] Args)
        {
            var UseArgs = false;
            var TocFileLocation = "";

            if (Args.Length > 0)
            {
                TocFileLocation = Args.FirstOrDefault(File.Exists);
                if (TocFileLocation != null)
                    UseArgs = true;
                else
                    Utilities.Log("Coun't Find TOC File.", Utilities.Event.Warning);
            }

            Console.replacedle = "Onomatopaira";

            using (var FileDialog = new OpenFileDialog())
            {
                FileDialog.replacedle = "Open Yu-Gi-Oh TOC File...";
                FileDialog.Filter = "Yu-Gi-Oh! Wolf TOC File |*.toc";
                if (UseArgs == false)
                {
                    if (FileDialog.ShowDialog() != DialogResult.OK) return;
                    TocFileLocation = FileDialog.FileName;
                }

                try
                {
                    using (var reader = new StreamReader(TocFileLocation))
                    {
                        if (!File.Exists(TocFileLocation.Replace(".toc", ".dat")))
                            Utilities.Log("Can't Find DAT File.", Utilities.Event.Error, true, 1);
                        var datReader =
                            new BinaryReader(File.Open(TocFileLocation.Replace(".toc", ".dat"), FileMode.Open));
                        reader.ReadLine();

                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            if (line == null) continue;

                            line = line.TrimStart(' ');
                            line = Regex.Replace(line, @"  +", " ", RegexOptions.Compiled);
                            var Data = new FileInformation(line.Split(new char[] { ' ' }, 3));

                            Utilities.Log(
                                $"Extracting File: {new FileInfo(Data.FileName).Name} ({Data.FileSize} Bytes)",
                                Utilities.Event.Information);

                            new FileInfo("YGO_DATA/" + Data.FileName).Directory?.Create();

                            var ExtraBytes = Utilities.HexToDec(Data.FileSize);
                            if (Utilities.HexToDec(Data.FileSize) % 4 != 0)
                                while (ExtraBytes % 4 != 0)
                                    ExtraBytes = ExtraBytes + 1;

                            using (var FileWriter = new BinaryWriter(File.Open("YGO_DATA/" + Data.FileName,
                                FileMode.Create, FileAccess.Write)))
                            {
                                FileWriter.Write(datReader.ReadBytes(Utilities.HexToDec(Data.FileSize)));
                                FileWriter.Flush();
                            }

                            datReader.BaseStream.Position += ExtraBytes - Utilities.HexToDec(Data.FileSize);
                        }
                    }
                }
                catch (Exception Ex)
                {
                    Utilities.Log($"Exception Caught: {Ex.Message}", Utilities.Event.Error, true, 1);
                }
            }
        }

19 View Source File : RegistryKey.cs
License : MIT License
Project Creator : ADeltaX

public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
        {
            if (string.IsNullOrEmpty(subkey))
            {
                throw new ArgumentException("Invalid SubKey", nameof(subkey));
            }

            string[] split = subkey.Split(new[] { '\\' }, 2);

            int subkeyCellIndex = FindSubKeyCell(split[0]);
            if (subkeyCellIndex < 0)
            {
                if (throwOnMissingSubKey)
                {
                    throw new ArgumentException("No such SubKey", nameof(subkey));
                }
                return;
            }

            KeyNodeCell subkeyCell = _hive.GetCell<KeyNodeCell>(subkeyCellIndex);

            if (split.Length == 1)
            {
                if (subkeyCell.NumSubKeys != 0)
                {
                    throw new InvalidOperationException("The registry key has subkeys");
                }

                if (subkeyCell.ClreplacedNameIndex != -1)
                {
                    _hive.FreeCell(subkeyCell.ClreplacedNameIndex);
                    subkeyCell.ClreplacedNameIndex = -1;
                    subkeyCell.ClreplacedNameLength = 0;
                }

                if (subkeyCell.SecurityIndex != -1)
                {
                    DereferenceSecurityCell(subkeyCell.SecurityIndex);
                    subkeyCell.SecurityIndex = -1;
                }

                if (subkeyCell.SubKeysIndex != -1)
                {
                    FreeSubKeys(subkeyCell);
                }

                if (subkeyCell.ValueListIndex != -1)
                {
                    FreeValues(subkeyCell);
                }

                UnlinkSubKey(subkey);
                _hive.FreeCell(subkeyCellIndex);
                _hive.UpdateCell(_cell, false);
            }
            else
            {
                new RegistryKey(_hive, subkeyCell).DeleteSubKey(split[1], throwOnMissingSubKey);
            }
        }

19 View Source File : CookieMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet

private static async Task<Transaction> SendAsync(TestServer server, string uri, string cookieHeader = null, bool ajaxRequest = false)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, uri);
            if (!string.IsNullOrEmpty(cookieHeader))
            {
                request.Headers.Add("Cookie", cookieHeader);
            }
            if (ajaxRequest)
            {
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            }
            var transaction = new Transaction
            {
                Request = request,
                Response = await server.HttpClient.SendAsync(request),
            };
            if (transaction.Response.Headers.Contains("Set-Cookie"))
            {
                transaction.SetCookie = transaction.Response.Headers.GetValues("Set-Cookie").SingleOrDefault();
            }
            if (!string.IsNullOrEmpty(transaction.SetCookie))
            {
                transaction.CookieNameValue = transaction.SetCookie.Split(new[] { ';' }, 2).First();
            }
            transaction.ResponseText = await transaction.Response.Content.ReadreplacedtringAsync();

            if (transaction.Response.Content != null &&
                transaction.Response.Content.Headers.ContentType != null &&
                transaction.Response.Content.Headers.ContentType.MediaType == "text/xml")
            {
                transaction.ResponseElement = XElement.Parse(transaction.ResponseText);
            }
            return transaction;
        }

19 View Source File : SenderIDRecord.cs
License : Apache License 2.0
Project Creator : alexreinert

public static bool IsSenderIDRecord(string s, SenderIDScope scope)
		{
			if (String.IsNullOrEmpty(s))
				return false;

			string[] terms = s.Split(new[] { ' ' }, 2);

			if (terms.Length < 2)
				return false;

			int version;
			int minor;
			List<SenderIDScope> scopes;
			if (!TryParsePrefix(terms[0], out version, out minor, out scopes))
			{
				return false;
			}

			if ((version == 1) && ((scope == SenderIDScope.MFrom) || (scope == SenderIDScope.Pra)))
			{
				return true;
			}
			else
			{
				return scopes.Contains(scope);
			}
		}

19 View Source File : OAuth2TestServer.cs
License : Apache License 2.0
Project Creator : aspnet

public NameValueCollection ParseRedirectFragment()
            {
                Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
                Response.Headers.Location.Fragment.ShouldStartWith("#");
                string fragment = Response.Headers.Location.Fragment.Substring(1);
                var nvc = new NameValueCollection();
                foreach (var pair in fragment
                    .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => x.Split(new[] { '=' }, 2).Select(Uri.UnescapeDataString)))
                {
                    if (pair.Count() == 2)
                    {
                        nvc.Add(pair.First(), pair.Last());
                    }
                }
                return nvc;
            }

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

private static VmessItem ResolveSip002(string result)
        {
            Uri parsedUrl;
            try
            {
                parsedUrl = new Uri(result);
            }
            catch (UriFormatException)
            {
                return null;
            }
            VmessItem server = new VmessItem
            {
                remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped),
                address = parsedUrl.IdnHost,
                port = parsedUrl.Port,
            };

            // parse base64 UserInfo
            string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.Unescaped);
            string base64 = rawUserInfo.Replace('-', '+').Replace('_', '/');    // Web-safe base64 to normal base64
            string userInfo;
            try
            {
                userInfo = Encoding.UTF8.GetString(Convert.FromBase64String(
                base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=')));
            }
            catch (FormatException)
            {
                return null;
            }
            string[] userInfoParts = userInfo.Split(new char[] { ':' }, 2);
            if (userInfoParts.Length != 2)
            {
                return null;
            }
            server.security = userInfoParts[0];
            server.id = userInfoParts[1];

            NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUrl.Query);
            if (queryParameters["plugin"] != null)
            {
                return null;
            }

            return server;
        }

19 View Source File : Compiler.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty

public YukaScript FromSource(string scriptPath, string stringPath) {

			scriptname = Path.GetFileNameWithoutExtension(scriptPath);

			#region Import meta information
			if(File.Exists(stringPath)) {
				#region Parse CSV
				StreamReader sr;
				int offset = -1;

				bool quoted = false;
				bool justLeftQuote = false;

				List<List<string>> rows = new List<List<string>>();
				List<string> row = new List<string>();
				StringBuilder cell = new StringBuilder();

				sr = new StreamReader(new FileStream(stringPath, FileMode.Open));

				while(!sr.EndOfStream) {
					offset++;
					char ch = (char)sr.Read();
					switch(ch) {
						case '"': {
								if(quoted) {
									quoted = false;
									justLeftQuote = true;
									continue;
								}
								else if(justLeftQuote) {
									quoted = true;
									cell.Append('"');
								}
								else {
									quoted = true;
								}
								break;
							}
						case ',': {
								if(quoted) {
									cell.Append(',');
								}
								else {
									row.Add(cell.ToString());
									cell.Clear();
								}
								break;
							}
						case '\r': {
								// do nothing
								break;
							}
						case '\n': {
								if(quoted) {
									cell.Append('\n');
								}
								else {
									row.Add(cell.ToString());
									rows.Add(row);
									row = new List<string>();
									cell.Clear();
								}
								break;
							}
						default: {
								cell.Append(ch);
								break;
							}
					}
					justLeftQuote = false;
				}

				sr.Close();

				row.Add(cell.ToString());
				rows.Add(row);
				#endregion

				#region Populate string table
				//int metaColumnID = 7;
				int maxTextColumn = 6;
				int minTextColumn = 2;

				int defaultLineWidth = TextUtils.defaultLineWidth;
				int defaultCharWidth = TextUtils.defaultCharWidth;
				bool removeQuotes = true;
				bool correctPunctuation = true;
				bool replaceSpecialChars = true;
				bool wrapWords = true;

				foreach(List<string> entry in rows) {
					if(entry.Count < 3) continue;
					#region Handle row

					#region Read meta data
					int currentLineWidth = defaultLineWidth;
					int currentCharWidth = defaultCharWidth;

					string[] metaData = entry[1].Split('\n');
					string speaker = "";

					foreach(string meta in metaData) {
						string[] data = meta.Split(new[] { ':' }, 2);
						if(data.Length == 2) {
							switch(data[0].Trim().ToLower()) {
								case "lw":
								case "linewidth":
									currentLineWidth = int.Parse(data[1].Trim());
									break;
								case "dlw":
								case "defaultlinewidth":
									defaultLineWidth = int.Parse(data[1].Trim());
									currentLineWidth = defaultLineWidth;
									break;
								case "cw":
								case "charwidth":
									currentCharWidth = int.Parse(data[1].Trim());
									break;
								case "dcw":
								case "defaultcharwidth":
									defaultCharWidth = int.Parse(data[1].Trim());
									currentCharWidth = defaultCharWidth;
									break;
								case "rmq":
								case "rmquotes":
								case "removequotes":
									removeQuotes = bool.Parse(data[1].Trim());
									break;
								case "cp":
								case "correctpunctiation":
									correctPunctuation = bool.Parse(data[1].Trim());
									break;
								case "rsc":
								case "replacespecialchars":
									replaceSpecialChars = bool.Parse(data[1].Trim());
									break;
								case "ww":
								case "wordwrap":
									wrapWords = bool.Parse(data[1].Trim());
									break;
							}
						}
						else if(entry[0].Length > 0 && "LNS".Contains(entry[0][0].ToString())) {
							speaker = meta;
						}
					}
					#endregion

					#region Format string
					if(entry[0].Length > 0 && "LNS".Contains(entry[0][0].ToString())) {
						/*if(entry.Count > metaColumnID && entry[metaColumnID].Trim().Length > 0) {
							Console.WriteLine(entry[0] + ": " + entry[metaColumnID].Trim('\n'));
							// stringTable[entry[0]] = entry[metaColumnID].Trim('\n');
							// continue;
						}*/

						for(int i = maxTextColumn; i >= minTextColumn; i--) {
							if(i < entry.Count && !entry[i].Equals("") && !entry[i].Equals(".")) {
								string value = entry[i];

								if(entry[0][0] == 'L') {



									value = value.Trim('\n', '%', '#', '「', '」');
									if(value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"' && removeQuotes) {
										value = value.Substring(1, value.Length - 2);
									}


									if(replaceSpecialChars) {
										// get rid of most replacedanese double width punctuation characters
										value = TextUtils.ReplaceSpecialChars(value);
									}


									if(correctPunctuation) {
										value = TextUtils.CorrectPunctuation(value);
									}

									value = TextUtils.EncodeYukaString(value);


									/*
									var lines = TextUtils.WrapWords(value, currentLineWidth, new TextUtils.FontMetrics(currentCharWidth));
									value = string.Join("", lines).Trim();
									
									Console.WriteLine();
									Console.WriteLine($" line width: {currentLineWidth}px");
									Console.WriteLine($" char width: {currentCharWidth}px / {currentCharWidth / 2}px");
									Console.WriteLine(" speaker: " + (speaker.Length > 0 ? speaker : "none"));
									Console.WriteLine(new string('-', currentLineWidth / currentCharWidth * 2));
									Console.BackgroundColor = ConsoleColor.DarkBlue;
									Console.ForegroundColor = ConsoleColor.Magenta;
									foreach(var line in lines) {
										Console.WriteLine(line);
									}
									Console.ResetColor();
									//*/

									if(wrapWords) {
										value = string.Join(
											"@m(1000)",
											value.Split('\n').Select(
												line => string.Join(
													" ",
													line.Split(' ').Select(
														word => $"@m({word.Length + 1}){word}"
													)
												)
											)
										);
									}
								}

								//Console.WriteLine(entry[0] + ": " + value);
								stringTable[entry[0]] = new ScriptLine(currentCharWidth, speaker, value);
								break;
							}
						}
					}
					#endregion

					#endregion
				}
				#endregion
			}
			#endregion

			#region Parse script file
			BinaryReader br = new BinaryReader(new FileStream(scriptPath, FileMode.Open));
			List<ScriptElement> commands = new List<ScriptElement>();

			SkipWhitespace(br);

			ScriptElement elem;
			while((elem = NextScriptElement(br)) != null) {
				if(!(elem is DummyScriptElement)) {
					commands.Add(elem);
					if(FlagCollection.current.Has('v')) {
						Console.WriteLine(elem);
					}
				}
			}
			br.Close();
			#endregion

			return new YukaScript(commands, stringTable);
		}

19 View Source File : ConnectionString.cs
License : Apache License 2.0
Project Creator : aloneguid

private void Parse(string connectionString)
      {
         int idx = connectionString.IndexOf(PrefixSeparator);

         if(idx == -1)
         {
            Prefix = connectionString;
            return;
         }

         Prefix = connectionString.Substring(0, idx);
         connectionString = connectionString.Substring(idx + PrefixSeparator.Length);

         // prefix extracted, now get the parts of the string

         //check if this is a native connection string
         if(connectionString.StartsWith(KnownParameter.Native + "="))
         {
            _nativeConnectionString = connectionString.Substring(KnownParameter.Native.Length + 1);
            _parts[KnownParameter.Native] = _nativeConnectionString;
         }
         else
         {
            string[] parts = connectionString.Split(PartsSeparators, StringSplitOptions.RemoveEmptyEntries);
            foreach(string part in parts)
            {
               string[] kv = part.Split(PartSeparator, 2);

               string key = kv[0];
               string value = kv.Length == 1 ? string.Empty : kv[1];
               _parts[key] = value.UrlDecode();
            }
         }
      }

19 View Source File : IWhitelistValidator.cs
License : MIT License
Project Creator : AElfProject

private WhitelistSearchResult Search(Whitelist whitelist, TypeReference type, string member = null)
        {
            var typeNs = GetNameSpace(type);

            // Fail if there is no rule for the namespace
            if (!whitelist.TryGetNamespaceRule(typeNs, out var namespaceRule))
            {
                // If no exact match for namespace, check for wildcard matching
                if (whitelist.ContainsWildcardMatchedNamespaceRule(typeNs))
                    return WhitelistSearchResult.Allowed;

                return WhitelistSearchResult.DeniedNamespace;
            }

            // Fail if the type is not allowed in the namespace 
            if (!namespaceRule.Types.TryGetValue(type.Name, out var typeRule) ||
                typeRule.Permission == Permission.Denied && !typeRule.Members.Any())
            {
                return namespaceRule.Permission == Permission.Allowed
                    ? WhitelistSearchResult.Allowed
                    : WhitelistSearchResult.DeniedType;
            }

            if (typeRule.Permission == Permission.Denied && !typeRule.Members.Any())
                return WhitelistSearchResult.DeniedType;

            if (member == null)
                return WhitelistSearchResult.Allowed;

            if (!typeRule.Members.TryGetValue(member, out var memberRule))
            {
                if (!member.StartsWith("get_") && !member.StartsWith("set_"))
                    return typeRule.Permission == Permission.Allowed
                        ? WhitelistSearchResult.Allowed
                        : WhitelistSearchResult.DeniedMember;

                // Check without the prefix as well
                member = member.Split(new[] {'_'}, 2)[1];
                if (!typeRule.Members.TryGetValue(member, out memberRule))
                {
                    return typeRule.Permission == Permission.Allowed
                        ? WhitelistSearchResult.Allowed
                        : WhitelistSearchResult.DeniedMember;
                }
            }

            return memberRule.Permission == Permission.Allowed
                ? WhitelistSearchResult.Allowed
                : WhitelistSearchResult.DeniedMember;
        }

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

public static ClusterMoved ParseSimpleError(string simpleError)
                {
                    if (string.IsNullOrWhiteSpace(simpleError)) return null;
                    var ret = new ClusterMoved
                    {
                        ismoved = simpleError.StartsWith("MOVED "), //永久定向
                        isask = simpleError.StartsWith("ASK ") //临时性一次定向
                    };
                    if (ret.ismoved == false && ret.isask == false) return null;
                    var parts = simpleError.Split(new string[] { "\r\n" }, StringSplitOptions.None).FirstOrDefault().Split(new[] { ' ' }, 3);
                    if (parts.Length != 3 ||
                        ushort.TryParse(parts[1], out ret.slot) == false) return null;
                    ret.endpoint = parts[2];
                    return ret;
                }

19 View Source File : ChatUtils.cs
License : Apache License 2.0
Project Creator : AantCoder

public static void ParceCommand(string chatLine, out string command, out List<string> argsM)
        {
            var s = chatLine.Split(new char[] { ' ' }, 2);
            command = s[0].Trim().ToLower();
            var args = s.Length == 1 ? "" : s[1];
            //разбираем аргументы в кавычках '. Удвоенная кавычка указывает на её символ.
            argsM = SplitBySpace(args);
        }

19 View Source File : Version.cs
License : Apache License 2.0
Project Creator : adamralph

private static Version ParseOrDefault(string text)
        {
            var versionAndMeta = text.Split(new[] { '+' }, 2);
            var numbersAndPre = versionAndMeta[0].Split(new[] { '-' }, 2);

            return ParseOrDefault(
                numbersAndPre[0].Split('.'),
                numbersAndPre.Length > 1 ? numbersAndPre[1].Split('.') : null,
                versionAndMeta.Length > 1 ? versionAndMeta[1] : null);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private long VersionNum(string data)
        {
            string[] separate = data.Split(new char[] { '.' }, 4);
            separate[1] = separate[1].PadLeft(4, '0');
            separate[2] = separate[2].PadLeft(4, '0');
            if (separate.Length == 4) separate[3] = separate[3].PadLeft(4, '0');
            else separate[2] = separate[2].PadRight(8, '0');

            long result;
            long.TryParse(separate[0] + separate[1] + separate[2] + (separate.Length == 4 ? separate[3] : ""), out result);

            return result;
        }

19 View Source File : HttpRequest.cs
License : MIT License
Project Creator : andruzzzhka

internal static HttpRequest Parse (string[] headerParts)
    {
      var requestLine = headerParts[0].Split (new[] { ' ' }, 3);
      if (requestLine.Length != 3)
        throw new ArgumentException ("Invalid request line: " + headerParts[0]);

      var headers = new WebHeaderCollection ();
      for (int i = 1; i < headerParts.Length; i++)
        headers.InternalSet (headerParts[i], false);

      return new HttpRequest (
        requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers);
    }

See More Examples