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 Source : LSPDFRPlusHandler.cs
with GNU General Public License v3.0
from Albo1125

public static void Initialise()
        {
            //ini stuff

            InitializationFile ini = new InitializationFile("Plugins/LSPDFR/LSPDFR+.ini");
            ini.Create();
            try
            {
                EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton = ini.ReadEnum<ControllerButtons>("General", "BringUpTrafficStopMenuControllerButton", ControllerButtons.DPadRight);
                EnhancedTrafficStop.BringUpTrafficStopMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "BringUpTrafficStopMenuKey", "D7"));
              
                try
                {
                    stockLSPDFRIni = new InitializationFile(LSPDFRKeyIniPath);
                    string[] stockinicontents = File.ReadAllLines(LSPDFRKeyIniPath);
                    //Alternative INI reading implementation, RPH doesn't work with sectionless INIs.
                    foreach (string line in stockinicontents)
                    {
                        if (line.StartsWith("TRAFFICSTOP_INTERACT_Key="))
                        {
                            stockTrafficStopInteractKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ModifierKey"))
                        {
                            stockTrafficStopInteractModifierKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerKey"))
                        {
                            stockTrafficStopInteractControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerModifierKey"))
                        {
                            stockTrafficStopInteractModifierControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                    }
                    if ((EnhancedTrafficStop.BringUpTrafficStopMenuKey == stockTrafficStopInteractKey && stockTrafficStopInteractModifierKey == Keys.None) || (EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton == stockTrafficStopInteractControllerButton && stockTrafficStopInteractModifierControllerButton == ControllerButtons.None))
                    {
                        TrafficStopMenuPopup = new Popup("LSPDFR+: Traffic Stop Menu Conflict", "Your LSPDFR+ traffic stop menu keys (plugins/lspdfr/lspdfr+.ini) are the same as the default LSPDFR traffic stop keys (lspdfr/keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey). How would you like to solve this?",
                            new List<string>() { "Recommended: Automatically disable the default LSPDFR traffic stop menu keys (this will edit keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey to None)", "I know what I'm doing, I will change the keys in the INIs myself!" }, false, true, TrafficStopMenuCb);
                        TrafficStopMenuPopup.Display();
                    }
                }
                catch (Exception e)
                {
                    Game.LogTrivial($"Failed to determine stock LSPDFR key bind/controller button for traffic stop keys: {e}");
                }
              
                CourtSystem.OpenCourtMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuKey", "F9"));
                CourtSystem.OpenCourtMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuModifierKey", "None"));
                EnhancedTrafficStop.EnhancedTrafficStopsEnabled = ini.ReadBoolean("General", "EnhancedTrafficStopsEnabled", true);
                EnhancedPursuitAI.EnhancedPursuitAIEnabled = ini.ReadBoolean("General", "EnhancedPursuitAIEnabled", true);
                EnhancedPursuitAI.AutoPursuitBackupEnabled = ini.ReadBoolean("General", "AutoPursuitBackupEnabled", false);
                EnhancedPursuitAI.OpenPursuitTacticsMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuKey", "Q"));
                EnhancedPursuitAI.OpenPursuitTacticsMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuModifierKey", "LShiftKey"));
                EnhancedPursuitAI.DefaultAutomaticAI = ini.ReadBoolean("General", "DefaultAutomaticAI", true);

                Offence.maxpoints = ini.ReadInt32("General", "MaxPoints", 12);
                Offence.pointincstep = ini.ReadInt32("General", "PointsIncrementalStep", 1);
                Offence.maxFine = ini.ReadInt32("General", "MaxFine", 5000);

                Offence.OpenTicketMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuKey", "Q"));
                Offence.OpenTicketMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuModifierKey", "LShiftKey"));
                Offence.enablePoints = ini.ReadBoolean("General", "EnablePoints", true);

                CourtSystem.RealisticCourtDates = ini.ReadBoolean("OnlyWithoutBritishPolicingScriptInstalled", "RealisticCourtDates", true);
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
                Game.LogTrivial("Error loading LSPDFR+ INI file. Loading defaults");
                Game.DisplayNotification("~r~Error loading LSPDFR+ INI file. Loading defaults");
            }
            BetaCheck();
        }

19 Source : EmailHelpers.cs
with MIT License
from alethic

private static bool IsAtom(char c, bool allowInternational)
        {
            return c < 128 ? IsLetterOrDigit(c) || AtomCharacters.IndexOf(c) != -1 : allowInternational;
        }

19 Source : AddressUtils.cs
with MIT License
from alexanderdna

public static bool TxInSignatureContainsPublicKey(string txInSignature, PublicKey publicKey)
        {
            int indexOfDelimiter = txInSignature.IndexOf('.');
            if (indexOfDelimiter < 0) return false;

            var publicKeyString = HexUtils.HexFromByteArray(publicKey.toDer());
            if (txInSignature.Length < publicKeyString.Length) return false;

            return txInSignature.EndsWith(publicKeyString);
        }

19 Source : AddressUtils.cs
with MIT License
from alexanderdna

public static (Signature, PublicKey) SignatureAndPublicKeyFromTxInSignature(string txInSignature)
        {
            int indexOfSeparator = txInSignature.IndexOf('.');
            if (indexOfSeparator < 0)
                return (null, null);

            var bytes = HexUtils.ByteArrayFromHex(txInSignature, 0, indexOfSeparator);
            var signature = Signature.fromDer(bytes);

            bytes = HexUtils.ByteArrayFromHex(txInSignature, indexOfSeparator + 1, txInSignature.Length - indexOfSeparator - 1);
            var publicKey = PublicKey.fromDer(bytes);

            return (signature, publicKey);
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

private static string GetSelectedFileFromDesktop(IntPtr hwnd)
        {
            var processPointer = IntPtr.Zero;
            var virtualAllocPointer = IntPtr.Zero;
            try
            {
                var itemNames = new List<string>();
                var processId = (uint)0;
                NativeMethods.GetWindowThreadProcessId(hwnd, out processId);
                var itemCount = NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMCOUNT, 0, 0);
                processPointer = NativeMethods.OpenProcess(NativeConstants.PROCESS_VM_OPERATION | NativeConstants.PROCESS_VM_READ | NativeConstants.PROCESS_VM_WRITE, false, processId);
                virtualAllocPointer = NativeMethods.VirtualAllocEx(processPointer, IntPtr.Zero, 4096, NativeConstants.MEM_RESERVE | NativeConstants.MEM_COMMIT, NativeConstants.PAGE_READWRITE);

                for (int i = 0; i < itemCount; i++)
                {
                    var buffer = new byte[256];
                    var item = new LVITEM[1];
                    item[0].mask = NativeConstants.LVIF_TEXT;
                    item[0].iItem = i;
                    item[0].iSubItem = 0;
                    item[0].cchTextMax = buffer.Length;
                    item[0].pszText = (IntPtr)((int)virtualAllocPointer + Marshal.SizeOf(typeof(LVITEM)));
                    var numberOfBytesRead = (uint)0;

                    NativeMethods.WriteProcessMemory(processPointer, virtualAllocPointer, Marshal.UnsafeAddrOfPinnedArrayElement(item, 0), Marshal.SizeOf(typeof(LVITEM)), ref numberOfBytesRead);
                    NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMW, i, virtualAllocPointer.ToInt32());
                    NativeMethods.ReadProcessMemory(processPointer, (IntPtr)((int)virtualAllocPointer + Marshal.SizeOf(typeof(LVITEM))), Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0), buffer.Length, ref numberOfBytesRead);

                    var text = Encoding.Unicode.GetString(buffer, 0, (int)numberOfBytesRead);
                    text = text.Substring(0, text.IndexOf('\0'));
                    var result = NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMSTATE, i, (int)NativeConstants.LVIS_SELECTED);
                    if (result == NativeConstants.LVIS_SELECTED)
                    {
                        itemNames.Add(text);
                    }
                }

                if (itemNames.Any())
                {
                    var desktopDirectoryName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                    var commonDesktopDirectoryName = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
                    var itemName = itemNames[0];
                    var fileNames = Directory.GetFiles(desktopDirectoryName, itemName + ".*").ToList();
                    fileNames.AddRange(Directory.GetFiles(commonDesktopDirectoryName, itemName + ".*"));
                    if (fileNames.Any())
                    {
                        var fileName = fileNames[0];
                        if (Path.GetExtension(fileName).ToLower() == ".lnk")
                        {
                            WshShell shell = new WshShell();
                            IWshShortcut link = (IWshShortcut)shell.CreateShortcut(fileName);
                            return link.TargetPath;
                        }
                        return fileName;
                    }
                }
                return string.Empty;
            }
            finally
            {
                if (processPointer != IntPtr.Zero && virtualAllocPointer != IntPtr.Zero)
                {
                    NativeMethods.VirtualFreeEx(processPointer, virtualAllocPointer, 0, NativeConstants.MEM_RELEASE);
                }

                if (processPointer != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(processPointer);
                }
            }
        }

19 Source : DHLProvider.cs
with MIT License
from alexeybusygin

private void ParseRates(IEnumerable<XElement> rates)
        {
            var includedServices = _configuration.ServicesIncluded;
            var excludedServices = _configuration.ServicesExcluded;

            foreach (var rateNode in rates)
            {
                var serviceCode = rateNode.Element("GlobalProductCode")?.Value;
                if (string.IsNullOrEmpty(serviceCode) || !AvailableServices.ContainsKey(serviceCode[0]))
                {
                    AddInternalError($"Unknown DHL Global Product Code: {serviceCode}");
                    continue;
                }
                if ((includedServices.Any() && !includedServices.Contains(serviceCode[0])) ||
                    (excludedServices.Any() && excludedServices.Contains(serviceCode[0])))
                {
                    continue;
                }

                var name = rateNode.Element("ProductShortName")?.Value;
                var description = AvailableServices[serviceCode[0]];

                var totalCharges = Convert.ToDecimal(rateNode.Element("ShippingCharge")?.Value, CultureInfo.InvariantCulture);
                var currencyCode = rateNode.Element("CurrencyCode")?.Value;

                var deliveryDateValue = rateNode.XPathSelectElement("DeliveryDate")?.Value;
                var deliveryTimeValue = rateNode.XPathSelectElement("DeliveryTime")?.Value;

                if (!DateTime.TryParse(deliveryDateValue, out DateTime deliveryDate))
                    deliveryDate = DateTime.MaxValue;

                if (!string.IsNullOrEmpty(deliveryTimeValue) && deliveryTimeValue.Length >= 4)
                {
                    // Parse PTxxH or PTxxHyyM to time
                    var indexOfH = deliveryTimeValue.IndexOf('H');
                    if (indexOfH >= 3)
                    {
                        var hours = int.Parse(deliveryTimeValue.Substring(2, indexOfH - 2), CultureInfo.InvariantCulture);
                        var minutes = 0;

                        var indexOfM = deliveryTimeValue.IndexOf('M');
                        if (indexOfM > indexOfH)
                        {
                            minutes = int.Parse(deliveryTimeValue.Substring(indexOfH + 1, indexOfM - indexOfH - 1), CultureInfo.InvariantCulture);
                        }

                        deliveryDate = deliveryDate.Date + new TimeSpan(hours, minutes, 0);
                    }
                }

                AddRate(name, description, totalCharges, deliveryDate, new RateOptions()
                {
                    SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
                },
                currencyCode);
            }
        }

19 Source : LanguageElement.cs
with GNU General Public License v3.0
from alexgracianoarj

[Obsolete] //TODO: ezt a met�dust meg kell sz�ntetni
		protected static string GetNameWithoutGeneric(string name)
		{
			int index = name.IndexOf('<');
			if (index > 0)
				return name.Substring(0, index);
			else
				return name;
		}

19 Source : CustomTagsHelper.cs
with MIT License
from alexismorin

public void SetTagValue( params string[] value )
		{
			TagValue = value[ 0 ];
			switch( m_specialTag )
			{
				case TemplateSpecialTags.RenderType:
				m_renderType = TemplateHelperFunctions.StringToRenderType[ value[ 0 ] ];
				break;
				case TemplateSpecialTags.Queue:
				{
					if( value.Length == 2 )
					{
						m_renderQueue = TemplateHelperFunctions.StringToRenderQueue[ value[ 0 ] ];
						int.TryParse( value[ 1 ], out m_renderQueueOffset );
					}
					else
					{
						int indexPlus = value[ 0 ].IndexOf( '+' );
						if( indexPlus > 0 )
						{
							string[] args = value[ 0 ].Split( '+' );
							m_renderQueue = TemplateHelperFunctions.StringToRenderQueue[ args[ 0 ] ];
							int.TryParse( args[ 1 ], out m_renderQueueOffset );
						}
						else
						{
							int indexMinus = value[ 0 ].IndexOf( '-' );
							if( indexMinus > 0 )
							{
								string[] args = value[ 0 ].Split( '-' );
								m_renderQueue = TemplateHelperFunctions.StringToRenderQueue[ args[ 0 ] ];
								int.TryParse( args[ 1 ], out m_renderQueueOffset );
								m_renderQueueOffset *= -1;
							}
							else
							{
								m_renderQueue = TemplateHelperFunctions.StringToRenderQueue[ value[ 0 ] ];
								m_renderQueueOffset = 0;
							}
						}
					}
					BuildQueueTagValue();
				}
				break;

			}
		}

19 Source : Utility.cs
with MIT License
from alexrainman

public static bool MatchHostnameToPattern(string hostname, string pattern)
        {
            // check if this is a pattern
            int index = pattern.IndexOf('*');
            if (index == -1)
            {
                // not a pattern, do a direct case-insensitive comparison
                return (string.Compare(hostname, pattern, StringComparison.OrdinalIgnoreCase) == 0);
            }

            // check pattern validity
            // A "*" wildcard character MAY be used as the left-most name component in the certificate.

            // unless this is the last char (valid)
            if (index != pattern.Length - 1)
            {
                // then the next char must be a dot .'.
                if (pattern[index + 1] != '.')
                {
                    return false;
                }
            }

            // only one (A) wildcard is supported
            int i2 = pattern.IndexOf('*', index + 1);
            if (i2 != -1) return false;

            // match the end of the pattern
            string end = pattern.Substring(index + 1);
            int length = hostname.Length - end.Length;
            // no point to check a pattern that is longer than the hostname
            if (length <= 0) return false;

            if (string.Compare(hostname, length, end, 0, end.Length, StringComparison.OrdinalIgnoreCase) != 0) {
                return false;
            }

            // special case, we start with the wildcard
            if (index == 0)
            {
                // ensure we hostname non-matched part (start) doesn't contain a dot
                int i3 = hostname.IndexOf('.');
                return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
            }

            // match the start of the pattern
            string start = pattern.Substring(0, index);

            return (string.Compare(hostname, 0, start, 0, start.Length, StringComparison.OrdinalIgnoreCase) == 0);
        }

19 Source : Utility.cs
with MIT License
from alexrainman

public static void VerifyPins(string[] pins)
        {
            foreach (var pin in pins)
            {
                if (!pin.StartsWith("sha256/", StringComparison.Ordinal) && !pin.StartsWith("sha1/", StringComparison.Ordinal))
                {
                    throw new HttpRequestException(FailureMessages.InvalidPublicKey);
                }

                try
                {
                    byte[] bytes = Convert.FromBase64String(pin.Remove(0, pin.IndexOf('/') + 1));
                }
                catch (Exception ex)
                {
                    throw new HttpRequestException(FailureMessages.InvalidPublicKey, ex);
                }
            }
        }

19 Source : DnsClient.cs
with Apache License 2.0
from alexreinert

public static List<IPAddress> GetLocalConfiguredDnsServers()
		{
			List<IPAddress> res = new List<IPAddress>();

			try
			{
				foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
				{
					if ((nic.OperationalStatus == OperationalStatus.Up) && (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback))
					{
						foreach (IPAddress dns in nic.GetIPProperties().DnsAddresses)
						{
							// only use servers defined in draft-ietf-ipngwg-dns-discovery if they are in the same subnet
							// fec0::/10 is marked deprecated in RFC 3879, so nobody should use these addresses
							if (dns.AddressFamily == AddressFamily.InterNetworkV6)
							{
								IPAddress unscoped = new IPAddress(dns.GetAddressBytes());
								if (unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::1"))
								    || unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::2"))
								    || unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::3")))
								{
									if (!nic.GetIPProperties().UnicastAddresses.Any(x => x.Address.GetNetworkAddress(10).Equals(IPAddress.Parse("fec0::"))))
										continue;
								}
							}

							if (!res.Contains(dns))
								res.Add(dns);
						}
					}
				}
			}
			catch (Exception e)
			{
				Trace.TraceError("Configured nameserver couldn't be determined: " + e);
			}

			// try parsing resolv.conf since getting data by NetworkInterface is not supported on non-windows mono
			if ((res.Count == 0) && ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX)))
			{
				try
				{
					using (StreamReader reader = File.OpenText("/etc/resolv.conf"))
					{
						string line;
						while ((line = reader.ReadLine()) != null)
						{
							int commentStart = line.IndexOf('#');
							if (commentStart != -1)
							{
								line = line.Substring(0, commentStart);
							}

							string[] lineData = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
							IPAddress dns;
							if ((lineData.Length == 2) && (lineData[0] == "nameserver") && (IPAddress.TryParse(lineData[1], out dns)))
							{
								res.Add(dns);
							}
						}
					}
				}
				catch (Exception e)
				{
					Trace.TraceError("/etc/resolv.conf could not be parsed: " + e);
				}
			}

			if (res.Count == 0)
			{
				// fallback: use the public dns-resolvers of google
				res.Add(IPAddress.Parse("2001:4860:4860::8844"));
				res.Add(IPAddress.Parse("2001:4860:4860::8888"));
				res.Add(IPAddress.Parse("8.8.4.4"));
				res.Add(IPAddress.Parse("8.8.8.8"));
			}

			return res.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 1 : 0).ToList();
		}

19 Source : Zone.cs
with Apache License 2.0
from alexreinert

private static string ReadRecordLine(StreamReader reader)
		{
			string line = ReadLineWithoutComment(reader);

			int bracketPos;
			if ((bracketPos = line.IndexOf('(')) != -1)
			{
				StringBuilder sb = new StringBuilder();

				sb.Append(line.Substring(0, bracketPos));
				sb.Append(" ");
				sb.Append(line.Substring(bracketPos + 1));

				while (true)
				{
					sb.Append(" ");

					line = ReadLineWithoutComment(reader);

					if ((bracketPos = line.IndexOf(')')) == -1)
					{
						sb.Append(line);
					}
					else
					{
						sb.Append(line.Substring(0, bracketPos));
						sb.Append(" ");
						sb.Append(line.Substring(bracketPos + 1));
						line = sb.ToString();
						break;
					}
				}
			}

			return line;
		}

19 Source : JsonStringLocalizerBase.cs
with MIT License
from AlexTeixeira

private string CleanBaseName(string baseName)
        {
            if (!string.IsNullOrEmpty(baseName))
            {
                // Nested clreplacedes are seperated by + and should use the translation of their parent clreplaced.
                int plusIdx = baseName.IndexOf('+');
                return plusIdx == -1 ? baseName : baseName.Substring(0, plusIdx);
            }
            else
            {
                return string.Empty;
            }
        }

19 Source : HuobiFuturesServer.cs
with Apache License 2.0
from AlexWan

private string GetSecurityName(string data, out string channel)
        {
            int firstIndex = data.IndexOf(':');
            int secondIndex = data.IndexOf(',');

            var substring = data.Substring(firstIndex, secondIndex - firstIndex);

            var parts = substring.Split('.');

            channel = parts[2];

            var security = parts[1];

            return security;
        }

19 Source : VariableController.cs
with MIT License
from alfa-laboratory

public string GetVariableName(string key)
        {
            if (string.IsNullOrWhiteSpace(key)) return null;
            var varName = key;
            if (varName.IndexOf('.') > 0)
            {
                varName = varName.Substring(0, varName.IndexOf('.'));
            }

            if (varName.IndexOf('[') > 0)
            {
                varName = varName.Substring(0, varName.IndexOf('['));
            }

            return varName;
        }

19 Source : VariableController.cs
with MIT License
from alfa-laboratory

public object GetVariableValue(string key)
        {
            try
            {
                var name = key;
                var keyPath = string.Empty;
                var index = -1;
                string path = null;
                if (key.IndexOf('.') > 0)
                {
                    name = key.Substring(0, key.IndexOf('.'));
                    path = key.Substring(key.IndexOf('.') + 1);
                }

                if (name.IndexOf('[') > 0 && name.IndexOf(']') > name.IndexOf('['))
                {
                    if (!int.TryParse(key.Substring(name.IndexOf('[') + 1, Math.Max(0, name.IndexOf(']') - name.IndexOf('[') - 1)), out index))
                    {
                        index = -1;
                    }

                    name = key.Split('[').First();

                    keyPath = Regex.Match(key ?? string.Empty, StringPattern.BRACES, RegexOptions.None).Groups[1].Value;
                }

                var var = Variables.SingleOrDefault(_ => _.Key == name).Value;
                if (var == null)
                {
                    return null;
                }

                var varValue = var.Value;
                var varType = var.Type;

                if (varValue == null)
                {
                    return varType.GetDefault();
                }

                if (varType.HasElementType && index >= 0)
                {
                    var objArray = ((Array)varValue).Cast<object>().ToArray();
                    varValue = objArray[index];
                    varType = varType.GetElementType();
                }

                if (typeof(BsonDoreplacedent).IsreplacedignableFrom(varType))
                {
                    var json = JObject.Parse(((BsonDoreplacedent)varValue).ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.CanonicalExtendedJson }));
                    return json.SelectToken(path?.Remove(0, 2) ?? "/*") ?? varValue;
                }

                if (typeof(JObject).IsreplacedignableFrom(varType))
                {
                    var jsonObject = JObject.Parse(varValue.ToString());
                    return jsonObject.SelectToken(path?.Remove(0, 2) ?? "/*") ?? null;
                }

                if (typeof(JToken).IsreplacedignableFrom(varType))
                {
                    var jsonToken = JToken.Parse(varValue.ToString());
                    return jsonToken.SelectToken(path?.Remove(0, 2) ?? "/*") ?? null;
                }

                if (typeof(XNode).IsreplacedignableFrom(varType))
                {
                    return ((XNode)varValue).XPathSelectElement(path ?? "/*");
                }

                if (typeof(XmlNode).IsreplacedignableFrom(varType))
                {
                    return ((XmlNode)varValue).SelectSingleNode(path ?? "/*");
                }
                
                if (typeof(Dictionary<string, object>).IsreplacedignableFrom(varType))
                {
                    var objDict = ((Dictionary<string, object>)varValue);
                    return !string.IsNullOrWhiteSpace(keyPath) ? objDict[keyPath] : objDict;
                }

                if (typeof(ICollection).IsreplacedignableFrom(varType))
                {
                    var objList = ((IEnumerable)varValue).Cast<object>().ToList();
                    return index >= 0 ? objList[index] : objList;
                }
                
                try
                {
                    if (typeof(DataRow).IsreplacedignableFrom(varType))
                    {
                        if (keyPath == string.Empty)
                        {
                            return ((DataRow)varValue);
                        }
                        return int.TryParse(keyPath, out var id) ? ((DataRow)varValue).ItemArray[id]?.ToString() : ((DataRow)varValue)[keyPath].ToString();
                    }

                    if (!typeof(DataTable).IsreplacedignableFrom(varType))
                    {
                        return varValue;
                    }

                    if(!key.Contains("[") || !key.Contains("["))
                    {
                        return varValue;
                    }

                    if (!int.TryParse(key.Substring(key.IndexOf('[') + 1, key.IndexOf(']') - key.IndexOf('[') - 1), out index))
                    {
                        index = -1;
                    }

                    var row = ((DataTable)varValue).Rows[index];

                    var offset = key.IndexOf(']') + 1;

                    if (key.IndexOf('[', offset) < 0)
                    {
                        return row;
                    }

                    return int.TryParse(key.Substring(key.IndexOf('[', offset) + 1, key.IndexOf(']', offset) - key.IndexOf('[', offset) - 1), out index) ? row[index] : row[key.Substring(key.IndexOf('[', offset) + 1, key.IndexOf(']', offset) - key.IndexOf('[', offset) - 1)];
                }
                catch (IndexOutOfRangeException)
                {
                    Log.Logger().LogWarning($"Check the correctness of the key: \"{key}\"");
                    return null;
                }

            }catch (NullReferenceException)
            {
                Log.Logger().LogWarning($"Set NULL value in \"GetVariableValue\"/\"GetVariableValueText\"");
                return null;
            }
        }

19 Source : Gamesave.cs
with MIT License
from AlFasGD

public static string GetObjectString(string ls)
        {
            try
            {
                return ls.Substring(ls.IndexOf(';') + 1);
            }
            catch
            {
                return "";
            }
        }

19 Source : MeasuredDuration.cs
with MIT License
from AlFasGD

private static string DecimalPartOf(string s) => s.Substring(s.IndexOf('.') + 1);

19 Source : Yaml.cs
with Apache License 2.0
from Algoryx

public bool TryGet( out Vector3 value )
      {
        value = Vector3.zero;

        try {
          var start = Value.IndexOf( '{' );
          var end = Value.LastIndexOf( '}' );
          if ( end <= start )
            throw new FormatException();

          var strings = Value.Substring( start, end ).Split( ',' );
          var x = Convert.ToSingle( strings[ 0 ].Split( ':' )[ 1 ].Trim() );
          var y = Convert.ToSingle( strings[ 1 ].Split( ':' )[ 1 ].Trim() );
          var z = Convert.ToSingle( strings[ 2 ].Split( ':' )[ 1 ].Trim() );

          value.x = x;
          value.y = y;
          value.z = z;

          return true;
        }
        catch ( Exception ) {
          return false;
        }
      }

19 Source : Yaml.cs
with Apache License 2.0
from Algoryx

public bool TryGet( out Quaternion value )
      {
        value = Quaternion.idenreplacedy;

        try {
          var start = Value.IndexOf( '{' );
          var end = Value.LastIndexOf( '}' );
          if ( end <= start )
            throw new FormatException();

          var strings = Value.Substring( start, end ).Split( ',' );
          var x = Convert.ToSingle( strings[ 0 ].Split( ':' )[ 1 ].Trim() );
          var y = Convert.ToSingle( strings[ 1 ].Split( ':' )[ 1 ].Trim() );
          var z = Convert.ToSingle( strings[ 2 ].Split( ':' )[ 1 ].Trim() );
          var w = Convert.ToSingle( strings[ 3 ].Split( ':' )[ 1 ].Trim() );

          value.x = x;
          value.y = y;
          value.z = z;
          value.w = w;

          return true;
        }
        catch ( Exception ) {
          return false;
        }
      }

19 Source : AliyunSDKUtils.cs
with MIT License
from aliyunmq

internal static string UrlEncode(int rfcNumber, string data, bool path)
        {
            StringBuilder encoded = new StringBuilder(data.Length * 2);
            string validUrlCharacters;
            if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters))
                validUrlCharacters = ValidUrlCharacters;

            string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : ""));

            foreach (char symbol in Encoding.UTF8.GetBytes(data))
            {
                if (unreservedChars.IndexOf(symbol) != -1)
                {
                    encoded.Append(symbol);
                }
                else
                {
                    encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol));
                }
            }

            return encoded.ToString();
        }

19 Source : Base58Encoding.cs
with MIT License
from allartprotocol

public static byte[] Decode(string s)
		{
			//Contract.Requires<ArgumentNullException>(s != null);
			//Contract.Ensures(Contract.Result<byte[]>() != null);

			// Decode Base58 string to BigInteger 
			BigInteger intData = 0;
			for (int i = 0; i < s.Length; i++)
			{
				int digit = Digits.IndexOf(s[i]); //Slow
				if (digit < 0)
					throw new FormatException(string.Format("Invalid Base58 character `{0}` at position {1}", s[i], i));
				intData = intData * 58 + digit;
			}

			// Encode BigInteger to byte[]
			// Leading zero bytes get encoded as leading `1` characters
			int leadingZeroCount = s.TakeWhile(c => c == '1').Count();
			var leadingZeros = Enumerable.Repeat((byte)0, leadingZeroCount);
			var bytesWithoutLeadingZeros =
				intData.ToByteArray()
				.Reverse()// to big endian
				.SkipWhile(b => b == 0);//strip sign byte
			var result = leadingZeros.Concat(bytesWithoutLeadingZeros).ToArray();
			return result;
		}

19 Source : UrlEncoder.cs
with MIT License
from AllocZero

public static string Encode(int rfcNumber, string data, bool path)
        {
            var stringBuilder = new StringBuilder(data.Length * 2);
            
            if (!RfcEncodingSchemes.TryGetValue(rfcNumber, out var str1))
                str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
            
            string str2 = str1 + (path ? ValidPathCharacters : "");
            foreach (var b in Encoding.UTF8.GetBytes(data))
            {
                var ch = (char) b;
                if (str2.IndexOf(ch) != -1)
                    stringBuilder.Append(ch);
                else
                    // ReSharper disable once UseFormatSpecifierInInterpolation to avoid boxing
                    stringBuilder.Append($"%{((int) ch).ToString("X2", CultureInfo.InvariantCulture)}");
            }
            return stringBuilder.ToString();
        }

19 Source : WMIStart.cs
with GNU General Public License v3.0
from Alois-xx

void ExtractNameSpaceAndQuery(string prefixString, string operation)
        {
            string nameSpaceAndQuery = operation?.Substring(prefixString.Length + 3);
            int firstColon = nameSpaceAndQuery.IndexOf(':');
            if (firstColon != -1)
            {
                Query = nameSpaceAndQuery?.Substring(firstColon + 2);
                NameSpace = nameSpaceAndQuery?.Substring(0, firstColon - 1);
            }

        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private void ParseTopNQuery(string query, out int n, out int minCount)
        {
            var parts = query.Replace(" ", "").Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string condition = null;
            minCount = 0;
            if( int.TryParse(parts[0], out n) == false )
            {
                condition = parts[0];
            }
            else if( parts.Length>1)
            {
                condition = parts[1];
            }

            if( condition != null)
            {
                // cannot use > sign because the shell will interpret it was file redirection character.
                if( condition.IndexOf("N", StringComparison.OrdinalIgnoreCase) == 0  && condition.IndexOf('#') == 1 )
                {
                    int.TryParse(condition.Substring(2), out minCount);
                    DebugPrinter.Write($"Condition: {condition}, MinValue: {minCount}");
                }
                else
                {
                    Console.WriteLine($"Warning condition {condition} of query {query} could not be parsed.");
                    Console.WriteLine("A query contains ddd;N#ddd2 where ddd is the TopN limit and dddd2 will print only types which have an instance count > ddd2");
                }
            }

            DebugPrinter.Write($"N: {n}, MinCount: {minCount}");
        }

19 Source : DNSChallengeAWSValidator.cs
with GNU General Public License v3.0
from aloopkin

public bool PrepareChallengeForValidation(string dnsKeyName, string dnsKeyValue)
        {
            try
            {
                route53Client = new AmazonRoute53Client();
                HostedZone zone = null;
                if (zoneId != null)
                {
                    GetHostedZoneResponse zoneResp = route53Client.GetHostedZone(new Amazon.Route53.Model.GetHostedZoneRequest { Id = zoneId });
                    zone = zoneResp.HostedZone;
                }
                else
                {
                    ListHostedZonesResponse zones = route53Client.ListHostedZones();
                    string recordToZone = dnsKeyName;
                    while (recordToZone.IndexOf('.') > 0)
                    {
                        recordToZone = recordToZone.Substring(recordToZone.IndexOf('.') + 1);
                        zone = zones.HostedZones.Where(z => z.Name.Contains(recordToZone)).FirstOrDefault();
                        if (zone != null)
                            break;
                    }
                }
                if (zone == null)
                {
                    logger.Error("Could not find DNS zone");
                    return false;
                }

                ListResourceRecordSetsResponse txtRecordsResponse = route53Client.ListResourceRecordSets(new ListResourceRecordSetsRequest
                {
                    StartRecordName = dnsKeyName,
                    StartRecordType = "TXT",
                    MaxItems = "1",
                    HostedZoneId = zone.Id
                });
                ResourceRecordSet txtRecord = txtRecordsResponse.ResourceRecordSets.FirstOrDefault(r => (r.Name == dnsKeyName || r.Name == dnsKeyName + ".") && r.Type.Value == "TXT");

                if (txtRecord != null)
                {
                    ApplyDnsChange(zone, txtRecord, ChangeAction.DELETE);

                }

                txtRecord = new ResourceRecordSet()
                {
                    Name = dnsKeyName,
                    TTL = 5,
                    Type = RRType.TXT,
                    ResourceRecords = new List<ResourceRecord>
                {
                    new ResourceRecord { Value = "\""+dnsKeyValue+"\"" }
                }
                };

                ApplyDnsChange(zone, txtRecord, ChangeAction.UPSERT);
            }
            catch (AmazonRoute53Exception exp)
            {
                logger.Error($"Could not update AWS Route53 record: ", exp);
                return false;
            }
            return true;
        }

19 Source : ObjectExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public static string Serialize(this object obj, bool indent)
        {
            XmlSerializer ser = new XmlSerializer(obj.GetType());
            using (MemoryStream memStream = new MemoryStream())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memStream, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = indent }))
                {
                    ser.Serialize(xmlWriter, obj);
                    ArraySegment<byte> buffer;
                    if (memStream.TryGetBuffer(out buffer))
                    {
                        string xml = Encoding.UTF8.GetString(buffer.Array, 0, (int)memStream.Length);
                        xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
                        xml = xml.Substring(0, xml.LastIndexOf(Convert.ToChar(62)) + 1);
                        
                        return xml;
                    }

                    return string.Empty;
                }
            }
        }

19 Source : ShareLink.cs
with MIT License
from AmazingDM

public static Dictionary<string, string> ParseParam(string paramStr)
        {
            var paramsDict = new Dictionary<string, string>();
            var obfsParams = paramStr.Split('&');
            foreach (var p in obfsParams)
            {
                if (p.IndexOf('=') > 0)
                {
                    var index = p.IndexOf('=');
                    var key = p.Substring(0, index);
                    var val = p.Substring(index + 1);
                    paramsDict[key] = val;
                }
            }

            return paramsDict;
        }

19 Source : SolutionExplorerViewModel.cs
with MIT License
from Aminator

private static StorageItemViewModel? FindStorageItem(StorageFolderViewModel containingFolder, string path)
        {
            StorageItemViewModel? foundItem = containingFolder;

            while (foundItem != null && !foundItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase) && foundItem is StorageFolderViewModel folder)
            {
                string relativePath = StorageExtensions.GetRelativePath(foundItem.Path, path);
                int indexOfDirectorySeparatorChar = relativePath.IndexOf(Path.DirectorySeparatorChar);
                foundItem = folder.Children.FirstOrDefault(i => relativePath.replacedpan(0, indexOfDirectorySeparatorChar >= 0 ? indexOfDirectorySeparatorChar : relativePath.Length).Equals(i.Name.replacedpan(), StringComparison.OrdinalIgnoreCase));
            }

            return foundItem;
        }

19 Source : DailyTotalsByWeekProjection.cs
with MIT License
from amolenk

public override string GetViewName(string streamId, IEvent @event)
        {
            var meterId = streamId.Substring(streamId.IndexOf(':') + 1);
            var weekNumber = GetIso8601WeekOfYear(((MeterReadingsCollected)@event).Date);

            return $"DailyTotalsByWeek:{meterId}:wk{weekNumber:00}";
        }

19 Source : NumericTextBox.cs
with Apache License 2.0
from AmpScm

private bool EnteringDuplicateChar(char ch)
        {
            bool bResult = false;
            if (base.Text.IndexOf(ch) >= 0)
            {
                if (SelectionLength > 0)
                {
                    if (SelectedText.IndexOf(ch) >= 0)
                        bResult = true;
                }
                else
                    bResult = true;
            }

            return bResult;
        }

19 Source : SvnSccProvider.StatusBar.cs
with Apache License 2.0
from AmpScm

static string StripComponents(string info, int len)
        {
            bool broken = false;

            while(info.Length > len)
            {
                int n = info.IndexOf('/');

                if (n <= 0)
                    break;

                info = info.Substring(n + 1);
                broken = true;
            }

            return broken ? ".." + info : info;
        }

19 Source : SccItem.cs
with Apache License 2.0
from AmpScm

public static bool IsValidPath(string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            int lc = path.LastIndexOf(':');
            if (lc > 1)
                return false;
            else if (lc == 1 && path.IndexOf('\\') == 2)
                return true;
            else if (lc < 0 && path.StartsWith(@"\\", StringComparison.Ordinal))
                return true;

            // TODO: Add more checks. This code is called from the OpenDoreplacedentTracker, Filestatus cache and selection provider

            return false;
        }

19 Source : ProgressDialog.cs
with Apache License 2.0
from AmpScm

public void OnClientNotify(object sender, SvnNotifyEventArgs e)
        {
            //e.Detach();

            string path = e.FullPath;
            Uri uri = e.Uri;
            SvnNotifyAction action = e.Action;
            long rev = e.Revision;

            Enqueue(delegate()
            {
                ListViewItem item = null;
                string text = GetActionText(action);

                if (string.IsNullOrEmpty(text))
                    return;

                item = new ListViewItem(text);

                switch (action)
                {
                    case SvnNotifyAction.BlameRevision:
                        {
                            string file;
                            if (uri != null)
                                file = SvnTools.GetFileName(uri);
                            else
                                file = Path.GetFileName(path);

                            item.SubItems.Add(string.Format("{0} - r{1}", file, rev));
                            break;
                        }
                    default:
                        if (uri != null)
                            item.SubItems.Add(uri.ToString());
                        else if (!string.IsNullOrEmpty(path))
                        {
                            string sr = SplitRoot;
                            if (!string.IsNullOrEmpty(sr) && SvnItem.IsBelowRoot(path, sr))
                            {
                                string np = SvnItem.SubPath(path, sr, true);
                                
                                if (np.IndexOf(':') == 1)
                                    path = np; // Full path
                                else
                                    path = np.Replace(Path.DirectorySeparatorChar, '/');
                            }

                            item.SubItems.Add(path);
                        }
                        break;
                }

                if (item != null)
                    _toAdd.Add(item);
            });
        }

19 Source : ControlExample.cs
with MIT License
from amwx

protected string ResolveType(Type t)
		{
			if (t.IsGenericType)
			{
				var genType = t.GetGenericTypeDefinition().Name;
				genType = genType.Substring(0, genType.IndexOf('`'));
				var args = t.GetGenericArguments().Select(x => ResolveType(x)).ToArray();

				if (genType.Equals("Nullable", StringComparison.OrdinalIgnoreCase))
				{
					return $"{args[0]}?";
				}
				else
				{
					return $"{genType}<{string.Join(',', args)}>";
				}				
			}
			else
			{
				if (t == typeof(object))
					return "object";
				else if (t == typeof(string))
					return "string";
				else if (t == typeof(bool))
					return "bool";
				else if (t == typeof(char))
					return "char";
				else if (t == typeof(int))
					return "int";
				else if (t == typeof(float))
					return "float";
				else if (t == typeof(double))
					return "double";
				else if (t == typeof(long))
					return "long";
				else if (t == typeof(ulong))
					return "ulong";
				else if (t == typeof(uint))
					return "uint";
				else if (t == typeof(byte))
					return "byte";
				else if (t == typeof(short))
					return "short";
				else if (t == typeof(decimal))
					return "decimal";
				else if (t == typeof(void))
					return "void";

				return t.Name;
			}
		}

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

List<string> download_and_read_lines() {
      System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
      var url_format = "https://www.bgc-jena.mpg.de/wetter/mpi_roof_{0}{1}.zip";
      var csv_filepaths = new List<string>();

      // step 1: download .zip files, and extract them to .csv files
      for (int year = 2009; year < 2017; year++) {
        foreach (var c in new char[] { 'a', 'b' }) {
          var url = String.Format(url_format, year, c);
          var zip_filepath = url.Split(new char[] { '/' }).Last();
          zip_filepath = Util.fullpathForDownloadedFile("roof_data", zip_filepath);
          var csv_filepath = zip_filepath.Replace(".zip", ".csv");
          if (System.IO.File.Exists(csv_filepath)) {
            csv_filepaths.Add(csv_filepath);
            continue;
          }
          if (System.IO.File.Exists(zip_filepath) == false) {
            var success = FromStackOverflow.FileDownloader.DownloadFile(url, zip_filepath, timeoutInMilliSec: 360000);
            if (!success) {
              Console.WriteLine("Could not download " + url);
              continue;
            }
          }
          var basepath = System.IO.Path.GetDirectoryName(zip_filepath);
          System.IO.Compression.ZipFile.ExtractToDirectory(zip_filepath, basepath);
          csv_filepaths.Add(csv_filepath);
        }
      }

      // step 2: read all .csv files, skipping the first line
      var all_lines = new List<string>();
      foreach (var csv_filepath in csv_filepaths) {
        var file_lines = System.IO.File.ReadAllLines(csv_filepath);
        for (int i = 1; i < file_lines.Length; i++) {
          var comma_pos = file_lines[i].IndexOf(',');
          all_lines.Add(file_lines[i].Substring(comma_pos + 1));
        }
      }
      Console.WriteLine(all_lines.Count);
      return all_lines;
    }

19 Source : Utils.cs
with MIT License
from Analogy-LogViewer

public static string ExtractJsonObject(string mixedString)
        {
            for (var i = mixedString.IndexOf('{'); i > -1; i = mixedString.IndexOf('{', i + 1))
            {
                for (var j = mixedString.LastIndexOf('}'); j > -1; j = mixedString.LastIndexOf("}", j - 1))
                {
                    var jsonProbe = mixedString.Substring(i, j - i + 1);
                    try
                    {
                        var valid = JsonConvert.DeserializeObject(jsonProbe);
                        return jsonProbe;
                    }
                    catch
                    {
                    }
                }
            }

            return string.Empty;
        }

19 Source : Parser.cs
with MIT License
from andersnm

private static bool TryParseCurrencySymbol(string token, out string currencySymbol)
        {
            if (string.IsNullOrEmpty(token)
                || !token.StartsWith("$"))
            {
                currencySymbol = null;
                return false;
            }


            if (token.Contains("-"))
                currencySymbol = token.Substring(1, token.IndexOf('-') - 1);
            else
                currencySymbol = token.Substring(1);

            return true;
        }

19 Source : InstantPreviewManager.cs
with Apache License 2.0
from andijakl

private static IEnumerator InstallApkAndRunIfConnected(string adbPath, string localVersion)
        {
            string apkPath = null;

#if UNITY_EDITOR
            apkPath = UnityEditor.replacedetDatabase.GUIDToreplacedetPath(k_ApkGuid);
#endif // !UNITY_EDITOR

            // Early outs if set to install but the apk can't be found.
            if (!File.Exists(apkPath))
            {
                Debug.LogError(
                    string.Format("Trying to install Instant Preview apk but reference to InstantPreview.apk is " +
                                  "broken. Couldn't find an replacedet with .meta file guid={0}", k_ApkGuid));
                yield break;
            }

            Result result = new Result();

            Thread checkAdbThread = new Thread((object obj) =>
            {
                Result res = (Result)obj;
                string output;
                string errors;

                // Gets version of installed apk.
                RunAdbCommand(adbPath, "shell dumpsys package com.google.ar.core.instantpreview | grep versionName",
                              out output, out errors);
                string installedVersion = null;
                if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors))
                {
                    installedVersion = output.Substring(output.IndexOf('=') + 1);
                }

                // Early outs if no device is connected.
                if (string.Compare(errors, k_NoDevicesFoundAdbResult) == 0)
                {
                    return;
                }

                // Prints errors and exits on failure.
                if (!string.IsNullOrEmpty(errors))
                {
                    Debug.LogError(errors);
                    return;
                }

                if (installedVersion == null)
                {
                    Debug.Log(string.Format(
                        "Instant Preview: app not found on device, attempting to install it from {0}.",
                        apkPath));
                }
                else if (installedVersion != localVersion)
                {
                    Debug.Log(string.Format(
                        "Instant Preview: installed version \"{0}\" does not match local version \"{1}\", attempting upgrade.",
                        installedVersion, localVersion));
                }

                res.ShouldPromptForInstall = installedVersion != localVersion;
            });
            checkAdbThread.Start(result);

            while (!checkAdbThread.Join(0))
            {
                yield return 0;
            }

            if (result.ShouldPromptForInstall)
            {
                if (PromptToInstall())
                {
                    Thread installThread = new Thread(() =>
                    {
                        string output;
                        string errors;

                        RunAdbCommand(adbPath,
                            string.Format("uninstall com.google.ar.core.instantpreview", apkPath),
                            out output, out errors);

                        RunAdbCommand(adbPath,
                            string.Format("install \"{0}\"", apkPath),
                            out output, out errors);

                        // Prints any output from trying to install.
                        if (!string.IsNullOrEmpty(output))
                        {
                            Debug.Log(output);
                        }

                        if (!string.IsNullOrEmpty(errors))
                        {
                            if (string.Equals(errors, "Success"))
                            {
                                Debug.Log("Successfully installed Instant Preview app.");
                            }
                            else
                            {
                                Debug.LogError(errors);
                            }
                        }
                    });
                    installThread.Start();

                    while (!installThread.Join(0))
                    {
                        yield return 0;
                    }
                }
                else
                {
                    yield break;
                }
            }

            if (!NativeApi.IsConnected())
            {
                new Thread(() =>
                {
                    string output;
                    string errors;
                    RunAdbCommand(adbPath,
                        "shell am start -n com.google.ar.core.instantpreview/.InstantPreviewActivity",
                        out output, out errors);
                }).Start();
            }
        }

19 Source : Extensions.cs
with MIT License
from AndreasAmMueller

public static string GetString(this IEnumerable<ModbusObject> list, int length, int startIndex = 0, Encoding encoding = null, bool flipBytes = false)
		{
			if (list == null)
				throw new ArgumentNullException(nameof(list));

			int count = list.Count();
			if (count < length)
				throw new ArgumentException($"At least {length} registers needed", nameof(list));

			if (startIndex < 0 || count < startIndex + length)
				throw new ArgumentOutOfRangeException(nameof(startIndex));

			if (!list.All(r => r.Type == ModbusObjectType.HoldingRegister) && !list.All(r => r.Type == ModbusObjectType.InputRegister))
				throw new ArgumentException("Invalid register type");

			if (encoding == null)
				encoding = Encoding.UTF8;

			var registers = list.Skip(startIndex).Take(length).ToArray();
			byte[] blob = new byte[registers.Length * 2];

			for (int i = 0; i < registers.Length; i++)
			{
				blob[i * 2] = flipBytes ? registers[i].LoByte : registers[i].HiByte;
				blob[i * 2 + 1] = flipBytes ? registers[i].HiByte : registers[i].LoByte;
			}

			string str = encoding.GetString(blob).Trim(new[] { ' ', '\t', '\0', '\r', '\n' });
			int nullIdx = str.IndexOf('\0');

			if (nullIdx >= 0)
				return str.Substring(0, nullIdx);

			return str;
		}

19 Source : NativeMethods.cs
with GNU General Public License v3.0
from AndreiFedarets

public static StringDictionary ReadEnvironmentVariables(IntPtr environment)
        {
            StringDictionary environmentVariables = new StringDictionary();
            StringBuilder testData = new StringBuilder(string.Empty);
            unsafe
            {
                short* start = (short*)environment.ToPointer();
                bool done = false;
                short* current = start;
                while (!done)
                {
                    if ((testData.Length > 0) && (*current == 0) && (current != start))
                    {
                        String data = testData.ToString();
                        int index = data.IndexOf('=');
                        if (index == -1)
                        {
                            environmentVariables.Add(data, string.Empty);
                        }
                        else if (index == (data.Length - 1))
                        {
                            environmentVariables.Add(data.Substring(0, index), string.Empty);
                        }
                        else
                        {
                            environmentVariables.Add(data.Substring(0, index), data.Substring(index + 1));
                        }
                        testData.Length = 0;
                    }
                    if ((*current == 0) && (current != start) && (*(current - 1) == 0))
                    {
                        done = true;
                    }
                    if (*current != 0)
                    {
                        testData.Append((char)*current);
                    }
                    current++;
                }
            }
            return environmentVariables;
        }

19 Source : RegistryExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static RegistryHive GetRegistryHive(string fullName)
        {
            int index = fullName.IndexOf('\\');
            string root = index >= 0 ? fullName.Substring(0, index) : fullName;
            switch (root.ToUpperInvariant())
            {
                case LocalMachine:
                    return RegistryHive.LocalMachine;
                case CurrentUser:
                    return RegistryHive.CurrentUser;
                case ClreplacedesRoot:
                    return RegistryHive.ClreplacedesRoot;
            }
            throw new ArgumentException();
        }

19 Source : RegistryExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static string GetRegistryName(string fullName)
        {
            int index = fullName.IndexOf('\\');
            string name = index >= 0 ? fullName.Substring(fullName.IndexOf('\\') + 1) : string.Empty;
            return name;
        }

19 Source : CodeStructureParser.cs
with MIT License
from AndresTraks

private static SourceItemDefinition CreateFoldersOnPath(string path, RootFolderDefinition rootFolder)
        {
            SourceItemDefinition folder = rootFolder;

            while (path.Contains('/'))
            {
                var index = path.IndexOf('/');
                string folderName = path.Substring(0, path.IndexOf('/'));
                var existingFolder = folder.Children.FirstOrDefault(c => c.Name == folderName);
                if (existingFolder != null)
                {
                    folder = existingFolder;
                }
                else
                {
                    var newFolder = new FolderDefinition(folderName) { Parent = folder };
                    folder.Children.Add(newFolder);
                    folder = newFolder;
                }
                path = path.Substring(index + 1);
            }

            return folder;
        }

19 Source : PropertyGenerator.cs
with MIT License
from AndresTraks

private static string ToCamelCase(string name)
        {
            // one_two_three -> oneTwoThree
            while (name.Contains("_"))
            {
                int pos = name.IndexOf('_');
                name = name.Substring(0, pos) + name.Substring(pos + 1, 1).ToUpper() + name.Substring(pos + 2);
            }
            return name;
        }

19 Source : ConventionConverter.cs
with MIT License
from AndresTraks

public static string RemoveUnderscore(string value)
        {
            while (value.Contains("_"))
            {
                int pos = value.IndexOf('_');
                if (pos + 1 == value.Length)
                {
                    value = value.Substring(0, pos);
                }
                else
                {
                    value = value.Substring(0, pos) + value.Substring(pos + 1, 1).ToUpper() + value.Substring(pos + 2);
                }
            }
            return value;
        }

19 Source : AuthenticationResponse.cs
with MIT License
from andruzzzhka

internal static NameValueCollection ParseBasicCredentials (string value)
    {
      // Decode the basic-credentials (a Base64 encoded string).
      var userPreplaced = Encoding.Default.GetString (Convert.FromBase64String (value));

      // The format is [<domain>\]<username>:<preplacedword>.
      var i = userPreplaced.IndexOf (':');
      var user = userPreplaced.Substring (0, i);
      var preplaced = i < userPreplaced.Length - 1 ? userPreplaced.Substring (i + 1) : String.Empty;

      // Check if 'domain' exists.
      i = user.IndexOf ('\\');
      if (i > -1)
        user = user.Substring (i + 1);

      var res = new NameValueCollection ();
      res["username"] = user;
      res["preplacedword"] = preplaced;

      return res;
    }

19 Source : ModeSelectionFlowCoordinator.cs
with MIT License
from andruzzzhka

public void JoinGameWithSecret(string secret)
        {
            string ip = secret.Substring(0, secret.IndexOf(':'));
            int port = int.Parse(secret.Substring(secret.IndexOf(':') + 1, secret.IndexOf('?') - secret.IndexOf(':') - 1));
            uint roomId = uint.Parse(secret.Substring(secret.IndexOf('?') + 1, secret.IndexOf('#') - secret.IndexOf('?') - 1));
            string preplacedword = secret.Substring(secret.IndexOf('#') + 1);

            if (ModelSaberAPI.isCalculatingHashes)
            {
                ModelSaberAPI.hashesCalculated += () =>
                {
                    PresentFlowCoordinator(PluginUI.instance.serverHubFlowCoordinator, null, true);
                    PluginUI.instance.serverHubFlowCoordinator.JoinRoom(ip, port, roomId, !string.IsNullOrEmpty(preplacedword), preplacedword);
                };
            }
            else
            {
                PresentFlowCoordinator(PluginUI.instance.serverHubFlowCoordinator, null, true);
                PluginUI.instance.serverHubFlowCoordinator.JoinRoom(ip, port, roomId, !string.IsNullOrEmpty(preplacedword), preplacedword);
            }

        }

19 Source : CookieCollection.cs
with MIT License
from andruzzzhka

private static CookieCollection parseResponse (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var pairs = splitCookieHeaderValue (value);
      for (var i = 0; i < pairs.Length; i++) {
        var pair = pairs[i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Version = Int32.Parse (pair.GetValue ('=', true));
        }
        else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
          var buff = new StringBuilder (pair.GetValue ('='), 32);
          if (i < pairs.Length - 1)
            buff.AppendFormat (", {0}", pairs[++i].Trim ());

          DateTime expires;
          if (!DateTime.TryParseExact (
            buff.ToString (),
            new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
            CultureInfo.CreateSpecificCulture ("en-US"),
            DateTimeStyles.AdjustToUniversal | DateTimeStyles.replacedumeUniversal,
            out expires))
            expires = DateTime.Now;

          if (cookie != null && cookie.Expires == DateTime.MinValue)
            cookie.Expires = expires.ToLocalTime ();
        }
        else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
          var max = Int32.Parse (pair.GetValue ('=', true));
          var expires = DateTime.Now.AddSeconds ((double) max);
          if (cookie != null)
            cookie.Expires = expires;
        }
        else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValue ('=');

          if (cookie != null)
            cookie.Port = port;
        }
        else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Comment = urlDecode (pair.GetValue ('='), Encoding.UTF8);
        }
        else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.CommentUri = pair.GetValue ('=', true).ToUri ();
        }
        else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Discard = true;
        }
        else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Secure = true;
        }
        else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.HttpOnly = true;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }

19 Source : HttpListenerPrefix.cs
with MIT License
from andruzzzhka

private void parse (string uriPrefix)
    {
      if (uriPrefix.StartsWith ("https"))
        _secure = true;

      var len = uriPrefix.Length;
      var startHost = uriPrefix.IndexOf (':') + 3;
      var root = uriPrefix.IndexOf ('/', startHost + 1, len - startHost - 1);

      var colon = uriPrefix.LastIndexOf (':', root - 1, root - startHost - 1);
      if (uriPrefix[root - 1] != ']' && colon > startHost) {
        _host = uriPrefix.Substring (startHost, colon - startHost);
        _port = uriPrefix.Substring (colon + 1, root - colon - 1);
      }
      else {
        _host = uriPrefix.Substring (startHost, root - startHost);
        _port = _secure ? "443" : "80";
      }

      _path = uriPrefix.Substring (root);

      _prefix =
        String.Format ("http{0}://{1}:{2}{3}", _secure ? "s" : "", _host, _port, _path);
    }

See More Examples