string.IndexOf(char, int)

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

905 Examples 7

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

private void GetFixed(string address, out bool rowFixed, out bool colFixed)
        {            
            rowFixed=colFixed=false;
            var ix=address.IndexOf('$');
            while(ix>-1)
            {
                ix++;
                if(ix < address.Length)
                {
                    if(address[ix]>='0' && address[ix]<='9')
                    {
                        rowFixed=true;
                        break;
                    }
                    else
                    {
                        colFixed=true;
                    }
                }
                ix = address.IndexOf('$', ix);
            }
        }

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

public static string TruncateLines(this string value, int maxLines, string ellipsis = "...", bool trim = false)
        {
            var count = 0;
            for (int i = value.IndexOf('\n'); i >= 0 && i < value.Length; i = value.IndexOf('\n', i + 1))
            {
                count++;
                if (count == maxLines)
                {
                    if (trim)
                        return value.Substring(0, i).TrimEnd() + ellipsis;
                    else
                        return value.Substring(0, i) + ellipsis;
                }
            }

            return value;
        }

19 View Source File : ChatService.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<Chat?> TryGet(
            string chatId, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(chatId))
                return null;
            if (chatId.StartsWith("game/")) {
                var gameId = chatId[5..];
                var game = await Games.TryGet(gameId, cancellationToken);
                if (game == null)
                    return null;
                return new Chat(chatId, ChatKind.Game) {
                    OwnerIds = ImmutableHashSet<long>.Empty.Add(game.UserId),
                    ParticipantIds = game.Players.Select(p => p.UserId).ToImmutableHashSet(),
                    IsPublic = game.IsPublic,
                };
            }
            if (chatId.StartsWith("p2p/")) {
                var dividerIndex = chatId.IndexOf('/', 4);
                if (dividerIndex < 0)
                    return null;
                if (!long.TryParse(chatId[4..dividerIndex], out var user1Id))
                    return null;
                if (!long.TryParse(chatId[(dividerIndex + 1)..], out var user2Id))
                    return null;
                if (user1Id >= user2Id)
                    return null;
                var user1 = await AppUsers.TryGet(user1Id, cancellationToken);
                if (user1 == null)
                    return null;
                var user2 = await AppUsers.TryGet(user2Id, cancellationToken);
                if (user2 == null)
                    return null;
                return new Chat(chatId, ChatKind.P2P) {
                    OwnerIds = ImmutableHashSet<long>.Empty,
                    ParticipantIds = ImmutableHashSet<long>.Empty.Add(user1Id).Add(user2Id),
                    IsPublic = false,
                };
            }
            return null;
        }

19 View Source File : OptionConverter.cs
License : Apache License 2.0
Project Creator : apache

public static string SubsreplaceduteVariables(string value, System.Collections.IDictionary props) 
		{
			StringBuilder buf = new StringBuilder();

			int i = 0;
			int j, k;
	
			while(true) 
			{
				j = value.IndexOf(DELIM_START, i);
				if (j == -1) 
				{
					if (i == 0)
					{
						return value;
					}
					else 
					{
						buf.Append(value.Substring(i, value.Length - i));
						return buf.ToString();
					}
				}
				else 
				{
					buf.Append(value.Substring(i, j - i));
					k = value.IndexOf(DELIM_STOP, j);
					if (k == -1) 
					{
						throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]");
					}
					else 
					{
						j += DELIM_START_LEN;
						string key = value.Substring(j, k - j);

						string replacement = props[key] as string;

						if (replacement != null) 
						{
							buf.Append(replacement);
						}
						i = k + DELIM_STOP_LEN;		
					}
				}
			}
		}

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

private static string GetAppLocation(string app)
        {
            if (string.IsNullOrEmpty(app))
                throw new ArgumentNullException("app");

            app = app.Trim();

            if (app.Length == 0)
                return null;

            if (app[0] == '\"')
            {
                int n = app.IndexOf('\"', 1);

                if (n > 0)
                    app = app.Substring(1, n - 1).Trim();
                else
                    app = app.Substring(1).Trim();
            }

            if (app.Contains("%"))
                app = Environment.ExpandEnvironmentVariables(app);

            return SvnTools.GetNormalizedFullPath(app);
        }

19 View Source File : ScriptAssetOpener.cs
License : MIT License
Project Creator : akof1314

public static bool Openreplacedet(string file, int line)
        {
            if (string.IsNullOrEmpty(file) || file == "None")
            {
                return false;
            }
            if (file.StartsWith("replacedets/"))
            {
                var ext = Path.GetExtension(file).ToLower();
                if (ext == ".lua" && TryOpenLuaFile(file, line))
                {
                    return true;
                }

                var obj = replacedetDatabase.LoadreplacedetAtPath<UnityEngine.Object>(file);
                if (obj)
                {
                    replacedetDatabase.Openreplacedet(obj, line);
                    return true;
                }

                return false;
            }

            char separatorChar = '\\';
            string fileFullPath;
            if (IsNotWindowsEditor())
            {
                separatorChar = '/';
                fileFullPath = Path.GetFullPath(file);
            }
            else
            {
                fileFullPath = Path.GetFullPath(file.Replace('/', separatorChar));
            }

#if UNITY_2018_1_OR_NEWER
            var packageInfos = Packages.GetAll();
            foreach (var packageInfo in packageInfos)
            {
                if (fileFullPath.StartsWith(packageInfo.resolvedPath, StringComparison.Ordinal))
                {
                    InternalEditorUtility.OpenFileAtLineExternal(fileFullPath, line);
                    return true;
                }
            }
#elif UNITY_2017_1_OR_NEWER
            // TODO
#endif

            // 别人编译的DLL,不存在文件路径,那么就以工程路径拼接组装来尝试获取本地路径
            if (!File.Exists(fileFullPath))
            {
                string directoryName = Directory.GetCurrentDirectory();
                while (true)
                {
                    if (string.IsNullOrEmpty(directoryName) || !Directory.Exists(directoryName))
                    {
                        return false;
                    }

                    int pos = fileFullPath.IndexOf(separatorChar);
                    while (pos != -1)
                    {
                        string testFullPath = Path.Combine(directoryName, fileFullPath.Substring(pos + 1));
                        if (File.Exists(testFullPath) && TryOpenVisualStudioFile(testFullPath, line))
                        {
                            return true;
                        }

                        pos = fileFullPath.IndexOf(separatorChar, pos + 1);
                    }

                    directoryName = Path.GetDirectoryName(directoryName);
                }
            }

            return TryOpenVisualStudioFile(fileFullPath, line);
        }

19 View Source File : DebugLogConsole.cs
License : MIT License
Project Creator : ArcturusZhang

private static int IndexOfChar( string command, char c, int startIndex )
		{
			int result = command.IndexOf( c, startIndex );
			if( result < 0 )
				result = command.Length;

			return result;
		}

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

public static List<string> SplitBySpace(string args)
        {
            int i = 0;
            var argsM = new List<string>();
            while (i + 1 < args.Length)
            {
                if (args[i] == '\'')
                {
                    int endK = i;
                    bool exit;
                    do //запускаем поиск след кавычки снова, если после найденной ещё одна
                    {
                        exit = true;
                        endK = args.IndexOf('\'', endK + 1);
                        if (endK >= 0 && endK + 1 < args.Length && args[endK + 1] == '\'')
                        {
                            //это двойная кавычка - пропускаем её
                            endK++;
                            exit = false;
                        }
                    }

                    while (!exit);

                    if (endK >= 0)
                    {
                        argsM.Add(args.Substring(i + 1, endK - i - 1).Replace("''", "'"));
                        i = endK + 1;
                        continue;
                    }
                }

                var ni = args.IndexOf(" ", i);
                if (ni >= 0)
                {
                    //условие недобавления для двойного пробела
                    if (ni > i) argsM.Add(args.Substring(i, ni - i));
                    i = ni + 1;
                    continue;
                }
                else
                {
                    break;
                }
            }
            if (i < args.Length)
            {
                argsM.Add(args.Substring(i));
            }

            return argsM;
        }

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

[SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "Only the host segment of a uri is provided.")]
        public static HostString FromUriComponent(string uriComponent)
        {
            if (!string.IsNullOrEmpty(uriComponent))
            {
                int index;
                if (uriComponent.IndexOf('[') >= 0)
                {
                    // IPv6 in brackets [::1], maybe with port
                }
                else if ((index = uriComponent.IndexOf(':')) >= 0
                    && index < uriComponent.Length - 1
                    && uriComponent.IndexOf(':', index + 1) >= 0)
                {
                    // IPv6 without brackets ::1 is the only type of host with 2 or more colons
                }
                else if (uriComponent.IndexOf("xn--", StringComparison.Ordinal) >= 0)
                {
                    // Contains punycode
                    if (index >= 0)
                    {
                        // Has a port
                        string port = uriComponent.Substring(index);
                        IdnMapping mapping = new IdnMapping();
                        uriComponent = mapping.GetUnicode(uriComponent, 0, index) + port;
                    }
                    else
                    {
                        IdnMapping mapping = new IdnMapping();
                        uriComponent = mapping.GetUnicode(uriComponent);
                    }
                }
            }
            return new HostString(uriComponent);
        }

19 View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit

private static string ResolveDosFilePath(string name)
        {
            if (string.IsNullOrEmpty(name)) return null;

            var volumeNumberLocation = 0;
            for (var j = 0; j < 2 && volumeNumberLocation != -1; j++)
            {
                volumeNumberLocation = name.IndexOf('\\', volumeNumberLocation + 1);
            }

            if (volumeNumberLocation == -1)
            {
                volumeNumberLocation = name.Length;
            }

            var volumeNumber = name.Substring(0, volumeNumberLocation);
            if (DeviceMap.TryGetValue(volumeNumber, out var drive))
            {
                return Regex.Replace(name, Regex.Escape(volumeNumber), drive,
                    RegexOptions.IgnoreCase);
            }

            return null;
        }

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

private static string GetRunResult(string str)
		{
			int lp = str.IndexOf('(');
			if (lp == -1)
				return null;
			++lp;
			int rp = str.IndexOf(')', lp);
			if (rp == -1)
				return null;

			return str.Substring(lp, rp - lp);
		}

19 View Source File : Utils.cs
License : MIT License
Project Creator : 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 View Source File : MemoryIterator.cs
License : Apache License 2.0
Project Creator : aequabit

public bool ReadString(long offset, SeekOrigin origin, out string lpBuffer, int len = -1, Encoding stringEncoding = null)
        {
            lpBuffer = null;
            byte[] buffer = new byte[(len > 0) ? len : 0x40];
            if (stringEncoding == null)
            {
                stringEncoding = Encoding.ASCII;
            }
            try
            {
                this._base.Seek(offset, origin);
                StringBuilder builder = new StringBuilder((len > 0) ? len : 260);
                int length = -1;
                int num2 = 0;
                int startIndex = 0;
                while ((length == -1) && ((num2 = this._base.Read(buffer, 0, buffer.Length)) > 0))
                {
                    builder.Append(stringEncoding.GetString(buffer));
                    length = builder.ToString().IndexOf('\0', startIndex);
                    startIndex += num2;
                    if ((len > 0) && (startIndex >= len))
                    {
                        break;
                    }
                }
                if (length > -1)
                {
                    lpBuffer = builder.ToString().Substring(0, length);
                }
                else if ((startIndex >= len) && (len > 0))
                {
                    lpBuffer = builder.ToString().Substring(0, len);
                }
                return (lpBuffer != null);
            }
            catch (Exception exception)
            {
                return this.SetLastError(exception);
            }
        }

19 View Source File : GuiHelper.cs
License : MIT License
Project Creator : Apostolique

private static int CountLines(string text) {
            // https://stackoverflow.com/a/40928366/1710293
            // Defaults to 1 because in a UI, you want the text to always have some height.
            if (text == null || text == string.Empty)
                return 1;
            int index = -1;
            int count = 0;
            while (-1 != (index = text.IndexOf('\n', index + 1)))
                count++;

            return count + 1;
        }

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

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

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

private static string AddToRowColumnTranslator(string Address, int row, int col, int rowIncr, int colIncr)
        {
            int fromRow, fromCol;
            if (Address == "#REF!")
            {
                return Address;
            }
            if (GetRowCol(Address, out fromRow, out fromCol, false))
            {
                if (fromRow == 0 || fromCol == 0)
                {
                    return Address;
                }
                if (rowIncr != 0 && row != 0 && fromRow >= row && Address.IndexOf('$', 1) == -1)
                {
                    if (fromRow < row - rowIncr)
                    {
                        return "#REF!";
                    }

                    fromRow = fromRow + rowIncr;
                }

                if (colIncr != 0 && col != 0 && fromCol >= col && Utils.ConvertUtil._invariantCompareInfo.IsPrefix(Address, "$") == false)
                {
                    if (fromCol < col - colIncr)
                    {
                        return "#REF!";
                    }

                    fromCol = fromCol + colIncr;
                }

                Address = GetAddress(fromRow, Address.IndexOf('$', 1) > -1, fromCol, Utils.ConvertUtil._invariantCompareInfo.IsPrefix(Address, "$"));
            }
            return Address;
        }

19 View Source File : MathRenderingExtensions.cs
License : MIT License
Project Creator : AlexGyver

private static OxySize InternalDrawMathText(
            IRenderContext rc,
            double x,
            double y,
            string s,
            OxyColor textColor,
            string fontFamily,
            double fontSize,
            double fontWeight,
            bool measureOnly)
        {
            int i = 0;

            double currentX = x;
            double maximumX = x;
            double maxHeight = 0;

            // http://en.wikipedia.org/wiki/Subscript_and_superscript
            double superscriptY = y + fontSize * SuperAlignment;
            double superscriptFontSize = fontSize * SuperSize;
            double subscriptY = y + fontSize * SubAlignment;
            double subscriptFontSize = fontSize * SubSize;

            Func<double, double, string, double, OxySize> drawText = (xb, yb, text, fSize) =>
                {
                    if (!measureOnly)
                    {
                        rc.DrawText(new ScreenPoint(xb, yb), text, textColor, fontFamily, fSize, fontWeight);
                    }

                    return rc.MeasureText(text, fontFamily, fSize, fontWeight);
                };

            while (i < s.Length)
            {
                // Superscript
                if (i + 1 < s.Length && s[i] == '^' && s[i + 1] == '{')
                {
                    int i1 = s.IndexOf('}', i);
                    if (i1 != -1)
                    {
                        string supString = s.Substring(i + 2, i1 - i - 2);
                        i = i1 + 1;
                        OxySize size = drawText(currentX, superscriptY, supString, superscriptFontSize);
                        if (currentX + size.Width > maximumX)
                        {
                            maximumX = currentX + size.Width;
                        }

                        continue;
                    }
                }

                // Subscript
                if (i + 1 < s.Length && s[i] == '_' && s[i + 1] == '{')
                {
                    int i1 = s.IndexOf('}', i);
                    if (i1 != -1)
                    {
                        string subString = s.Substring(i + 2, i1 - i - 2);
                        i = i1 + 1;
                        OxySize size = drawText(currentX, subscriptY, subString, subscriptFontSize);
                        if (currentX + size.Width > maximumX)
                        {
                            maximumX = currentX + size.Width;
                        }

                        continue;
                    }
                }

                // Regular text
                int i2 = s.IndexOfAny("^_".ToCharArray(), i);
                string regularString;
                if (i2 == -1)
                {
                    regularString = s.Substring(i);
                    i = s.Length;
                }
                else
                {
                    regularString = s.Substring(i, i2 - i);
                    i = i2;
                }

                currentX = maximumX + 2;
                OxySize size2 = drawText(currentX, y, regularString, fontSize);
                currentX += size2.Width + 2;
                maxHeight = Math.Max(maxHeight, size2.Height);
                maximumX = currentX;
            }

            return new OxySize(maximumX - x, maxHeight);
        }

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

public static string ReplaceSlashString(string src)
        {
            char[] arr = src.ToCharArray();

            int openInd = src.IndexOf('"', 0);
            int closeInd = -1;

            while (openInd >= 0)
            {
                closeInd = src.IndexOf('"', openInd + 1);

                if (closeInd >= 0)
                {
                    for (int i = openInd; i <= closeInd; i++)
                    {
                        if (arr[i] == '/')
                            arr[i] = '|';
                    }

                    openInd = src.IndexOf('"', closeInd + 1);
                }
                else
                    openInd = -1;
            }

            return new string(arr).Trim();
        }

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

public static string Splice(this string sql, params bool[] conditions)
        {
            var startIndex = 0;
            foreach (var condition in conditions)
            {
                var start = sql.IndexOf('{', startIndex);
                if (start < 0)
                    return sql;
                var end = sql.IndexOf('}', start);
                if (end < 0)
                    return sql;
                startIndex = end;

                var elseIndex = sql.IndexOf(':', start, end - start);
                if (elseIndex < 0)
                {
                    if (condition)
                    {
                        sql = sql.Remove(start, 1).Remove(end - 1, 1);
                        startIndex -= 2;
                    }
                    else
                    {
                        var count = end - start + 1;
                        sql = sql.Remove(start, count);
                        startIndex -= count;
                    }
                }
                else
                {
                    if (condition)
                    {
                        var count = end - elseIndex + 1;
                        sql = sql.Remove(start, 1).Remove(elseIndex - 1, count);
                        startIndex -= count;
                    }
                    else
                    {
                        var count = elseIndex - start + 1;
                        sql = sql.Remove(start, count).Remove(end - count, 1);
                        startIndex -= count;
                    }
                }
            }
            return sql;
        }

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

[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Only the host segment of a uri is returned.")]
        public string ToUriComponent()
        {
            int index;
            if (string.IsNullOrEmpty(_value))
            {
                return string.Empty;
            }
            else if (_value.IndexOf('[') >= 0)
            {
                // IPv6 in brackets [::1], maybe with port
                return _value;
            }
            else if ((index = _value.IndexOf(':')) >= 0
                && index < _value.Length - 1
                && _value.IndexOf(':', index + 1) >= 0)
            {
                // IPv6 without brackets ::1 is the only type of host with 2 or more colons
                return "[" + _value + "]";
            }
            else if (index >= 0)
            {
                // Has a port
                string port = _value.Substring(index);
                IdnMapping mapping = new IdnMapping();
                return mapping.GetAscii(_value, 0, index) + port;
            }
            else
            {
                IdnMapping mapping = new IdnMapping();
                return mapping.GetAscii(_value);
            }
        }

19 View Source File : VariableController.cs
License : MIT License
Project Creator : 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 View Source File : LicenseInfo.cs
License : Apache License 2.0
Project Creator : Algoryx

private static int FindDateLength( string dateStr, int endDateStartIndex )
    {
      char[] delims = new char[] { ' ', ',' };
      int lastIndex = dateStr.Length;
      foreach ( var delim in delims ) {
        var index = dateStr.IndexOf( delim, endDateStartIndex );
        if ( index >= 0 ) {
          lastIndex = index;
          break;
        }
      }
      return lastIndex - endDateStartIndex;
    }

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

public static string ReplaceSingleQuote(object exp) {
				//将 ' 转换成 "
				string exp2 = string.Concat(exp);
				int quote_pos = -1;
				while (true) {
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true) {
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						for (int p = 1; true; p++) {
							if (exp2[quote_pos - p] == '\\') r_cout++;
							else break;
						}
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
							string str1 = exp2.Substring(0, first_pos);
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 1);
							string str3 = exp2.Substring(quote_pos + 1);
							string str4 = str2.Replace("\"", "\\\"");
							quote_pos += str4.Length - str2.Length;
							exp2 = string.Concat(str1, "\"", str4, "\"", str3);
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				return exp2;
			}

19 View Source File : RepositoryUrlUtils.cs
License : Apache License 2.0
Project Creator : AmpScm

private static bool TryFindBranch(Uri uri, string path, string name, bool branch, out RepositoryLayoutInfo info)
        {
            info = null;
            string r = path;

            name = '/' + name.Trim('/') + '/';

            while (r.Length > 0 && !r.EndsWith(name, StringComparison.OrdinalIgnoreCase))
            {
                int n = r.LastIndexOf('/', r.Length - 1);

                if (n >= 0)
                {
                    int lastCharIndex = r.Length - 1;
                    // if '/' is the last character, strip and continue
                    // otherwise include '/' to give "/tags/" check a chance
                    r = r.Substring(0, (n == lastCharIndex) ? n : (n + 1));
                }
                else
                    r = "";
            }

            if (!string.IsNullOrEmpty(r))
            {
                info = new RepositoryLayoutInfo();

                string dir = (path.Length > r.Length) ? path.Substring(0, path.IndexOf('/', r.Length) + 1) : path;

                info.WorkingRoot = new Uri(uri, dir);
                info.WholeProjectRoot = new Uri(new Uri(uri, r), "../");
                info.BranchesRoot = new Uri(info.WholeProjectRoot, "branches/"); // Always set some branches suggestion?
                info.SelectedBranch = info.BranchesRoot.MakeRelativeUri(info.WorkingRoot);

                Uri itemRoot = new Uri(info.WholeProjectRoot, r.Substring(r.Length - name.Length + 1, name.Length-1)); // 'tags/' but with repos casing

                if (branch)
                    info.BranchesRoot = itemRoot;
                else
                    info.TagsRoot = itemRoot;
                return true;
            }

            return false;
        }

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

private void FromVersionString(String apiVersionString)
        {
            if (String.IsNullOrEmpty(apiVersionString))
            {
                throw new VssInvalidApiResourceVersionException(apiVersionString);
            }

            // Check for a stage/resourceVersion string
            int dashIndex = apiVersionString.IndexOf('-');
            if (dashIndex >= 0)
            {
                String stageName;

                // Check for a '.' which separate stage from resource version
                int dotIndex = apiVersionString.IndexOf('.', dashIndex);
                if (dotIndex > 0)
                {
                    stageName = apiVersionString.Substring(dashIndex + 1, dotIndex - dashIndex - 1);

                    int resourceVersion;
                    String resourceVersionString = apiVersionString.Substring(dotIndex + 1);
                    if (!int.TryParse(resourceVersionString, out resourceVersion))
                    {
                        throw new VssInvalidApiResourceVersionException(apiVersionString);
                    }
                    else
                    {
                        this.ResourceVersion = resourceVersion;
                    }
                }
                else
                {
                    stageName = apiVersionString.Substring(dashIndex + 1);
                }

                // Check for supported stage names
                if (String.Equals(stageName, c_PreviewStageName, StringComparison.OrdinalIgnoreCase))
                {
                    IsPreview = true;
                }
                else
                {
                    throw new VssInvalidApiResourceVersionException(apiVersionString);
                }

                // Api version is the string before the dash
                apiVersionString = apiVersionString.Substring(0, dashIndex);
            }

            // Trim a leading "v" for version
            apiVersionString = apiVersionString.TrimStart('v');

            double apiVersionValue;
            if (!double.TryParse(apiVersionString, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out apiVersionValue))
            {
                throw new VssInvalidApiResourceVersionException(apiVersionString);
            }

            // Store the api version
            this.ApiVersion = new Version(apiVersionValue.ToString("0.0", CultureInfo.InvariantCulture));
        }

19 View Source File : UTF8String.cs
License : GNU General Public License v3.0
Project Creator : anydream

public int IndexOf(char value, int startIndex) {
			return String.IndexOf(value, startIndex);
		}

19 View Source File : ValueConverter.cs
License : MIT License
Project Creator : AngeloCresta

public static string FormatValue(
			Chart chart,
			object obj,
            object objTag,
			double value, 
			string format, 
			ChartValueType valueType,
			ChartElementType elementType)
		{
            format = format ?? String.Empty;
            string	convertionFormat = format;
			string	result = "";

			// Make sure value index is part of the format
			if(convertionFormat != null && convertionFormat.Length > 0)
			{
				int	bracketIndex = convertionFormat.IndexOf('{', 0);
				if(bracketIndex >= 0)
				{
					while(bracketIndex >= 0)
					{
						// If format is not followed by the value index
						if(!convertionFormat.Substring(bracketIndex).StartsWith("{0:", StringComparison.Ordinal))
						{
							// Check charcter prior to the bracket
							if(bracketIndex >= 1 && convertionFormat.Substring(bracketIndex - 1, 1) == "{")
							{
								continue;
							}
							else
							{
								// Insert value index in format
								convertionFormat = convertionFormat.Insert(bracketIndex + 1, "0:");
							}
						}

						bracketIndex = convertionFormat.IndexOf('{', bracketIndex + 1);
					}
				}
				else
				{
					convertionFormat = "{0:" + convertionFormat + "}";
				}
			}

			// Date/time formating
            if (valueType == ChartValueType.DateTime || 
                valueType == ChartValueType.DateTimeOffset || 
                valueType == ChartValueType.Date)
			{
				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:d}";
                    if (valueType == ChartValueType.DateTimeOffset)
                        convertionFormat += " +0";
				}

				// Convert date to string
                result = String.Format(CultureInfo.CurrentCulture, convertionFormat, DateTime.FromOADate(value));
			}
			else if(valueType == ChartValueType.Time)
			{
				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:t}";
				}

				// Convert date to string
                result = String.Format(CultureInfo.CurrentCulture, convertionFormat, DateTime.FromOADate(value));
			}
			else
			{
				bool	failedFlag = false;

				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:G}";
				}

				try
				{
					// Numeric value formatting
                    result = String.Format(CultureInfo.CurrentCulture,convertionFormat, value);
				}
				catch(FormatException)
				{
					failedFlag = true;
				}

				// If numeric formatting failed try to format using decimal number
				if(failedFlag)
				{
					failedFlag = false;
                    try
                    {
                        // Decimal value formatting
                        result = String.Format(CultureInfo.CurrentCulture, convertionFormat, (long)value);
                    }
                    catch (ArgumentNullException)
                    {
                        failedFlag = true;
                    }
                    catch (FormatException)
                    {
                        failedFlag = true;
                    }
				}

				// Return format string as result (literal) if all formatting methods failed
				if(failedFlag)
				{
                    result = format;
				}
			}

            // For the Reporting Services chart a special number formatting
            // handler may be set and used for all formatting needs.
            if (chart != null)
            {
                // Call number formatter
                FormatNumberEventArgs eventArguments = new FormatNumberEventArgs(value, format, valueType, result, objTag, elementType);
                chart.CallOnFormatNumber(obj, eventArguments);
                result = eventArguments.LocalizedValue;
            }

			return result;
		}

19 View Source File : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio

public static string DiscoverEnvironment(Uri issuerUri)
		{
			if (null == issuerUri)
			{
				return null;
			}

			const string HostSearchString = "login.live";
			if (issuerUri.Host.Length > HostSearchString.Length &&
				issuerUri.Host.StartsWith(HostSearchString, StringComparison.OrdinalIgnoreCase))
			{
				string environment = issuerUri.Host.Substring(HostSearchString.Length);

				if ('-' == environment[0])
				{
					int separatorIndex = environment.IndexOf('.', 1);
					if (-1 != separatorIndex)
					{
						return environment.Substring(1, separatorIndex - 1);
					}
				}
			}

			//In all other cases the environment is either not applicable or it is a production system
			return null;
		}

19 View Source File : URISupport.cs
License : Apache License 2.0
Project Creator : apache

public static bool CheckParenthesis(String str)
        {
            bool result = true;

            if (str != null)
            {
                int open = 0;
                int closed = 0;

                int i = 0;
                while ((i = str.IndexOf('(', i)) >= 0)
                {
                    i++;
                    open++;
                }

                i = 0;
                while ((i = str.IndexOf(')', i)) >= 0)
                {
                    i++;
                    closed++;
                }

                result = (open == closed);
            }

            return result;
        }

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

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

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

19 View Source File : PatternParser.cs
License : Apache License 2.0
Project Creator : apache

private void ParseInternal(string pattern, string[] matches)
		{
			int offset = 0;
			while(offset < pattern.Length)
			{
				int i = pattern.IndexOf('%', offset);
				if (i < 0 || i == pattern.Length - 1)
				{
					ProcessLiteral(pattern.Substring(offset));
					offset = pattern.Length;
				}
				else
				{
					if (pattern[i+1] == '%')
					{
						// Escaped
						ProcessLiteral(pattern.Substring(offset, i - offset + 1));
						offset = i + 2;
					}
					else
					{
						ProcessLiteral(pattern.Substring(offset, i - offset));
						offset = i + 1;

						FormattingInfo formattingInfo = new FormattingInfo();

						// Process formatting options

						// Look for the align flag
						if (offset < pattern.Length)
						{
							if (pattern[offset] == '-')
							{
								// Seen align flag
								formattingInfo.LeftAlign = true;
								offset++;
							}
						}
						// Look for the minimum length
						while (offset < pattern.Length && char.IsDigit(pattern[offset]))
						{
							// Seen digit
							if (formattingInfo.Min < 0)
							{
								formattingInfo.Min = 0;
							}

							formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo);

							offset++;
						}
						// Look for the separator between min and max
						if (offset < pattern.Length)
						{
							if (pattern[offset] == '.')
							{
								// Seen separator
								offset++;
							}
						}
						// Look for the maximum length
						while (offset < pattern.Length && char.IsDigit(pattern[offset]))
						{
							// Seen digit
							if (formattingInfo.Max == int.MaxValue)
							{
								formattingInfo.Max = 0;
							}

							formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo);

							offset++;
						}

						int remainingStringLength = pattern.Length - offset;

						// Look for pattern
						for(int m=0; m<matches.Length; m++)
						{
							string key = matches[m];

							if (key.Length <= remainingStringLength)
							{
								if (string.Compare(pattern, offset, key, 0, key.Length) == 0)
								{
									// Found match
									offset = offset + matches[m].Length;

									string option = null;

									// Look for option
									if (offset < pattern.Length)
									{
										if (pattern[offset] == '{')
										{
											// Seen option start
											offset++;
											
											int optEnd = pattern.IndexOf('}', offset);
											if (optEnd < 0)
											{
												// error
											}
											else
											{
												option = pattern.Substring(offset, optEnd - offset);
												offset = optEnd + 1;
											}
										}
									}

									ProcessConverter(matches[m], option, formattingInfo);
									break;
								}
							}
						}
					}
				}
			}
		}

19 View Source File : WinAPI.cs
License : Apache License 2.0
Project Creator : aequabit

public static string ReadRemoteString(IntPtr hProcess, IntPtr lpAddress, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.ASCII;
            }
            StringBuilder builder = new StringBuilder();
            byte[] lpBuffer = new byte[0x100];
            uint lpNumberOfBytesRead = 0;
            int length = -1;
            int startIndex = 0;
            while (((length < 0) && ReadProcessMemory(hProcess, lpAddress, lpBuffer, lpBuffer.Length, out lpNumberOfBytesRead)) && (lpNumberOfBytesRead > 0))
            {
                lpAddress = lpAddress.Add((long) lpNumberOfBytesRead);
                startIndex = builder.Length;
                builder.Append(encoding.GetString(lpBuffer, 0, (int) lpNumberOfBytesRead));
                length = builder.ToString().IndexOf('\0', startIndex);
            }
            return builder.ToString().Substring(0, length);
        }

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

internal static string GetWorksheetPart(string address, string defaultWorkSheet, ref int endIx)
        {
            if(address=="") return defaultWorkSheet;
            var ix = 0;
            if (address[0] == '[')
            {
                ix = address.IndexOf(']')+1;
            }
            if (ix > 0 && ix < address.Length)
            {
                if (address[ix] == '\'')
                {
                    return GetString(address, ix, out endIx);
                }
                else
                {
                    var ixEnd = address.IndexOf('!',ix);
                    if(ixEnd>ix)
                    {
                        return address.Substring(ix, ixEnd-ix);
                    }
                    else
                    {
                        return defaultWorkSheet;
                    }
                }
            }
            else
            {
                return defaultWorkSheet;
            }
        }

19 View Source File : CICPSerializer.cs
License : MIT License
Project Creator : 0xC0000054

private static ushort GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return ushort.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

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

private string NormalizeFileName()
        {
            // here, we need to flip the backslashes to forward-slashes,
            // also, we need to trim the \\server\share syntax from any UNC path.
            // and finally, we need to remove any leading .\

            string SlashFixed = FileName.Replace("\\", "/");
            string s1 = null;
            if ((_TrimVolumeFromFullyQualifiedPaths) && (FileName.Length >= 3)
                && (FileName[1] == ':') && (SlashFixed[2] == '/'))
            {
                // trim off volume letter, colon, and slash
                s1 = SlashFixed.Substring(3);
            }
            else if ((FileName.Length >= 4)
                     && ((SlashFixed[0] == '/') && (SlashFixed[1] == '/')))
            {
                int n = SlashFixed.IndexOf('/', 2);
                if (n == -1)
                    throw new ArgumentException("The path for that entry appears to be badly formatted");
                s1 = SlashFixed.Substring(n + 1);
            }
            else if ((FileName.Length >= 3)
                     && ((SlashFixed[0] == '.') && (SlashFixed[1] == '/')))
            {
                // trim off dot and slash
                s1 = SlashFixed.Substring(2);
            }
            else
            {
                s1 = SlashFixed;
            }
            return s1;
        }

19 View Source File : AssetExtensionResolver.cs
License : MIT License
Project Creator : Albeoris

public String GetFileExtension(String replacedetAddress)
        {
            Int32 index = _catalogJson.IndexOf(replacedetAddress);
            if (index < 0)
                return String.Empty;

            Int32 lastIndex = index + replacedetAddress.Length;
            if (_catalogJson.Length <= lastIndex)
                return String.Empty;

            if (_catalogJson[lastIndex] != '.')
                return String.Empty;

            Int32 quoteIndex = _catalogJson.IndexOf('"', lastIndex + 1);
            if (quoteIndex < 0)
                return String.Empty;

            return _catalogJson.Substring(lastIndex, quoteIndex - lastIndex);
        }

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

private ExcelRange GetTableAddess(ExcelWorksheet _worksheet, string address)
        {
            int ixStart = address.IndexOf('[');
            if (ixStart == 0) //External Address
            {
                int ixEnd = address.IndexOf(']',ixStart+1);
                if (ixStart >= 0 & ixEnd >= 0)
                {
                    var external = address.Substring(ixStart + 1, ixEnd - 1);
                    //if (Worksheet.Workbook._externalReferences.Count < external)
                    //{
                    //foreach(var 
                    //}
                }
            }
            return null;
        }

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

private void readBase5()
        {
            int clreplacedID = a_Stream.ReadInt32();
            if (fileGen > 15)//5.5.0 and up
            {
                a_Stream.ReadByte();
                int type1;
                if ((type1 = a_Stream.ReadInt16()) >= 0)
                {
                    type1 = -1 - type1;
                }
                else
                {
                    type1 = clreplacedID;
                }
                clreplacedIDs.Add(new[] { type1, clreplacedID });
                clreplacedID = type1;
                /*TODO 用来替换下方的代码
                if(clreplacedID == 114)
                {
                    a_Stream.Position += 16;
                }*/
                var temp = a_Stream.ReadInt32();
                if (temp == 0)
                {
                    a_Stream.Position += 16;
                }
                a_Stream.Position -= 4;
                if (type1 < 0)
                {
                    a_Stream.Position += 16;
                }
            }
            else if (clreplacedID < 0)
            {
                a_Stream.Position += 16;
            }
            a_Stream.Position += 16;

            if (baseDefinitions)
            {
                int varCount = a_Stream.ReadInt32();
                int stringSize = a_Stream.ReadInt32();

                a_Stream.Position += varCount * 24;
                string varStrings = Encoding.UTF8.GetString(a_Stream.ReadBytes(stringSize));
                string clreplacedName = "";
                var clreplacedVar = new List<ClreplacedMember>();
                //build Clreplaced Structures
                a_Stream.Position -= varCount * 24 + stringSize;
                for (int i = 0; i < varCount; i++)
                {
                    ushort num0 = a_Stream.ReadUInt16();
                    byte level = a_Stream.ReadByte();
                    bool isArray = a_Stream.ReadBoolean();

                    ushort varTypeIndex = a_Stream.ReadUInt16();
                    ushort test = a_Stream.ReadUInt16();
                    string varTypeStr;
                    if (test == 0) //varType is an offset in the string block
                    { varTypeStr = varStrings.Substring(varTypeIndex, varStrings.IndexOf('\0', varTypeIndex) - varTypeIndex); }//substringToNull
                    else //varType is an index in an internal strig array
                    { varTypeStr = baseStrings.ContainsKey(varTypeIndex) ? baseStrings[varTypeIndex] : varTypeIndex.ToString(); }

                    ushort varNameIndex = a_Stream.ReadUInt16();
                    test = a_Stream.ReadUInt16();
                    string varNameStr;
                    if (test == 0) { varNameStr = varStrings.Substring(varNameIndex, varStrings.IndexOf('\0', varNameIndex) - varNameIndex); }
                    else { varNameStr = baseStrings.ContainsKey(varNameIndex) ? baseStrings[varNameIndex] : varNameIndex.ToString(); }

                    int size = a_Stream.ReadInt32();
                    int index = a_Stream.ReadInt32();
                    int flag = a_Stream.ReadInt32();

                    if (index == 0) { clreplacedName = varTypeStr + " " + varNameStr; }
                    else
                    {
                        clreplacedVar.Add(new ClreplacedMember()
                        {
                            Level = level - 1,
                            Type = varTypeStr,
                            Name = varNameStr,
                            Size = size,
                            Flag = flag
                        });
                    }
                }
                a_Stream.Position += stringSize;

                var aClreplaced = new ClreplacedStruct() { ID = clreplacedID, Text = clreplacedName, members = clreplacedVar };
                aClreplaced.SubItems.Add(clreplacedID.ToString());
                ClreplacedStructures[clreplacedID] = aClreplaced;
            }
        }

19 View Source File : StringUtil.cs
License : MIT License
Project Creator : arcusmaximus

public static string UnescapeC(string str)
        {
            StringBuilder result = null;
            int startOffset = 0;
            while (startOffset < str.Length)
            {
                int backslashOffset = str.IndexOf('\\', startOffset);
                if (backslashOffset < 0)
                    break;

                if (startOffset == 0)
                    result = new StringBuilder();

                result.Append(str, startOffset, backslashOffset - startOffset);
                startOffset = backslashOffset + 2;
                if (backslashOffset < str.Length - 1)
                    result.Append(MapChar(str[backslashOffset + 1], EscapeChars, ControlChars));
                else
                    result.Append('\\');
            }
            if (startOffset == 0)
                return str;

            result.Append(str, startOffset, str.Length - startOffset);
            return result.ToString();
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : 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 View Source File : LOTD_Archive.cs
License : MIT License
Project Creator : Arefu

public void Load()
        {
            //if (string.IsNullOrEmpty(InstallDirectory)) throw new Exception("Invalid directory: " + InstallDirectory);
            

            var tocPath = Path.Combine(InstallDirectory, "YGO_DATA.toc");
            var datPath = Path.Combine(InstallDirectory, "YGO_DATA.dat");

            if (!File.Exists(tocPath) || !File.Exists(datPath)) throw new Exception("Failed to find data files");

            if (Reader != null)
            {
                Reader.Close();
                Reader = null;
            }

            Root = new LOTD_Directory
            {
                Archive = this,
                IsRoot = true
            };

            var filePaths = new List<string>();

            try
            {
                long offset = 0;

                var lines = File.ReadAllLines(tocPath);
                foreach (var line in lines)
                {
                    if (line.StartsWith("UT")) continue;

                    var offsetStart = -1;
                    for (var charIndex = 0; charIndex < line.Length; charIndex++)
                        if (line[charIndex] != ' ')
                        {
                            offsetStart = charIndex;
                            break;
                        }

                    var offsetEnd = offsetStart == -1 ? -1 : line.IndexOf(' ', offsetStart);
                    var unknownStart = offsetEnd == -1 ? -1 : offsetEnd + 1;
                    var unknownEnd = unknownStart == -1 ? -1 : line.IndexOf(' ', unknownStart + 1);

                    var validLine = unknownEnd >= 0;

                    if (validLine)
                    {
                        var lengthStr = line.Substring(offsetStart, offsetEnd - offsetStart);
                        var filePathLengthStr = line.Substring(unknownStart, unknownEnd - unknownStart);
                        var filePath = line.Substring(unknownEnd + 1);

                        if (long.TryParse(lengthStr, NumberStyles.HexNumber, null, out var length) &&
                            int.TryParse(filePathLengthStr, NumberStyles.HexNumber, null, out var filePathLength) &&
                            filePathLength == filePath.Length)
                        {
                            Root.AddFile(filePath, offset, length);

                            offset += length;

                            const int align = 4;
                            if (length % align != 0) offset += align - length % align;

                            filePaths.Add(filePath);
                        }
                        else
                        {
                            validLine = false;
                        }
                    }

                    if (!validLine) throw new Exception("Failed to parse line in toc file " + line);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error when reading .toc file: " + e);
            }

            try
            {
                if (WriteAccess)
                    Reader = new BinaryReader(File.Open(datPath, FileMode.Open, FileAccess.ReadWrite));
                else
                    Reader = new BinaryReader(File.OpenRead(datPath));
            }
            catch (Exception e)
            {
                throw new Exception("Error when opening .dat file: " + e);
            }

            // Validate all file paths
            foreach (var filePath in filePaths)
            {
                var file = Root.FindFile(filePath);
                if (file == null)
                    throw new Exception("Archive loader is broken. File path not found in archive structure: '" +
                                        filePath + "'");
            }
        }

19 View Source File : SqlInjectionChecker.cs
License : MIT License
Project Creator : 0x1000000

public static void AppendStringEscape(StringBuilder builder, string original, char escape)
        {
            int start = 0;
            int index;
            do
            {
                index = original.IndexOf(escape, start);
                if (index >= 0)
                {
                    if (start < index)
                    {
                        builder.Append(original, start, index-start);
                    }
                    builder.Append(escape, 2);
                    start = index + 1;
                }
            } while (index >= 0);

            if (start < original.Length)
            {
                builder.Append(original, start, original.Length-start);
            }
        }

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

internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, bool decodePlus, bool decodeKey, object state)
        {
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);
                    if (decodePlus)
                    {
                        name = name.Replace('+', ' ');
                        value = value.Replace('+', ' ');
                    }
                    if (decodeKey)
                    {
                        name = Uri.UnescapeDataString(name);
                    }
                    value = Uri.UnescapeDataString(value);
                    callback(name, value, state);
                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
        }

19 View Source File : MessageParser.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<GameMessage> Parse(string text, CancellationToken cancellationToken = default)
        {
            List<MessageFragment> fragments = new();
            var startIndex = 0;

            void AddPlainText(int length) {
                if (length < 0)
                    startIndex -= length;
                fragments.Add(new PlainText(text.Substring(startIndex, length)));
                startIndex += length;
            }

            bool StartsWith(string start) => text.replacedpan(startIndex).StartsWith(start);

            bool TryParseDirective(string directive, out string value) {
                value = "";
                if (!StartsWith(directive))
                    return false;
                if (startIndex + directive.Length + 2 >= text.Length || text[startIndex + directive.Length] != '[') {
                    AddPlainText(directive.Length);
                    return false;
                }
                var valueStartIndex = startIndex + directive.Length + 1;
                var rightBracketIndex = text.IndexOf(']', valueStartIndex);
                if (rightBracketIndex < 0) {
                    AddPlainText(directive.Length);
                    return false;
                }
                value = text.Substring(valueStartIndex, rightBracketIndex - valueStartIndex);
                startIndex = rightBracketIndex + 1;
                return true;
            }

            while (startIndex < text.Length) {
                if (text[startIndex] != '@') {
                    var endIndex = text.IndexOf('@', startIndex);
                    if (endIndex < 0)
                        endIndex = text.Length;
                    AddPlainText(endIndex - startIndex);
                    continue;
                }
                if (StartsWith("@@")) {
                    fragments.Add(new PlainText("@"));
                    startIndex += 2;
                    continue;
                }

                var directiveStartIndex = startIndex;
                if (TryParseDirective("@user", out var userIdText)) {
                    if (!long.TryParse(userIdText, out var userId)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var user = await AppUsers.TryGet(userId, cancellationToken);
                    if (user == null) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    fragments.Add(new UserMention(user));
                    continue;
                }
                if (TryParseDirective("@score", out var scoreText)) {
                    var scoreParts = scoreText.Split(",");
                    if (scoreParts.Length != 2) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var gameId = scoreParts[0].Trim();
                    if (string.IsNullOrEmpty(gameId)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    if (!long.TryParse(scoreParts[1].Trim(), out var score)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var game = await Games.TryGet(gameId, cancellationToken);
                    if (game == null) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    fragments.Add(new GameScoreMention(game, score));
                    continue;
                }
                if (StartsWith("@")) {
                    var name = UserNameService.ParseName(text, startIndex + 1);
                    if (string.IsNullOrEmpty(name)) {
                        AddPlainText(1);
                        continue;
                    }
                    var user = await AppUsers.TryGetByName(name, cancellationToken);
                    if (user == null) {
                        AddPlainText(name.Length + 1);
                        continue;
                    }
                    fragments.Add(new UserMention(user));
                    startIndex += name.Length + 1;
                    continue;
                }
            }

            List<MessageFragment> optimizedFragments = new();
            MessageFragment? lastFragment = null;
            foreach (var fragment in fragments) {
                if (fragment is PlainText pt && lastFragment is PlainText lpt) {
                    lastFragment = new PlainText(lpt.Text + pt.Text);
                    optimizedFragments.RemoveAt(optimizedFragments.Count - 1);
                }
                else
                    lastFragment = fragment;
                optimizedFragments.Add(lastFragment);
            }

            return new GameMessage() {
                Text = text,
                Fragments = optimizedFragments.ToImmutableList()
            };
        }

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

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

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

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

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

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

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

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

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

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

public virtual void ParseAndRun(ChatCMDEnv env) {
            // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

            string raw = env.FullText;

            int index = Chat.Settings.CommandPrefix.Length + ID.Length - 1; // - 1 because next space required
            List<ChatCMDArg> args = new();
            while (
                index + 1 < raw.Length &&
                (index = raw.IndexOf(' ', index + 1)) >= 0
            ) {
                int next = index + 1 < raw.Length ? raw.IndexOf(' ', index + 1) : -2;
                if (next < 0)
                    next = raw.Length;

                int argIndex = index + 1;
                int argLength = next - index - 1;

                // + 1 because space
                args.Add(new ChatCMDArg(env).Parse(raw, argIndex, argLength));

                // Parse a split up range (with spaces) into a single range arg
                if (args.Count >= 3 &&
                    args[args.Count - 3].Type == ChatCMDArgType.Int &&
                    (args[args.Count - 2].String == "-" || args[args.Count - 2].String == "+") &&
                    args[args.Count - 1].Type == ChatCMDArgType.Int
                ) {
                    args.Add(new ChatCMDArg(env).Parse(raw, args[args.Count - 3].Index, next - args[args.Count - 3].Index));
                    args.RemoveRange(args.Count - 4, 3);
                    continue;
                }
            }

            Run(env, args);
        }

19 View Source File : ImageGridMetadata.cs
License : MIT License
Project Creator : 0xC0000054

private static uint GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return uint.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

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

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

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

19 View Source File : VSVersionProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static string ParseVersion(string version)
		{
			const string previewKeyWord = "Preview";
			int previewIndex = version.IndexOf(previewKeyWord);

			if (previewIndex < 0)
				return version;

			string baseVersion = version.Substring(0, previewIndex - 1);
			int indexOfDotInPreviewVersion = version.IndexOf('.', previewIndex);
			int previewVersionStart = previewIndex + previewKeyWord.Length + 1;
			/*
			 * The Version constructor will error if there are > 4 segments.
			 */
			string previewVersion = indexOfDotInPreviewVersion < 0
			  ? version.Substring(previewVersionStart)
			  : version.Substring(previewVersionStart, indexOfDotInPreviewVersion - previewVersionStart);

			return $"{baseVersion}.{previewVersion}";
		}

19 View Source File : ZDTextParser.cs
License : GNU General Public License v3.0
Project Creator : anotak

protected internal bool SkipWhitespace(bool skipnewline)
		{
			int offset = skipnewline ? 0 : 1;
			char c;
			
			do
			{
				if(datastream.Position == datastream.Length) return false;
				c = (char)datareader.ReadByte();

				// Check if this is comment
				if(c == '/')
				{
					if(datastream.Position == datastream.Length) return false;
					char c2 = (char)datareader.ReadByte();
					if(c2 == '/')
					{
						// Check if not a special comment with a token
						if(datastream.Position == datastream.Length) return false;
						char c3 = (char)datareader.ReadByte();
						if(c3 != '$')
						{
							// Skip entire line
							char c4 = ' ';
							while((c4 != '\n') && (datastream.Position < datastream.Length)) { c4 = (char)datareader.ReadByte(); }
							c = c4;
						}
						else
						{
							// Not a comment
							c = c3;
						}
					}
					else if(c2 == '*')
					{
						// Skip until */
						char c4, c3 = '\0';
						do
						{
							c4 = c3;
							c3 = (char)datareader.ReadByte();
						}
						while((c4 != '*') || (c3 != '/'));
						c = ' ';
					}
					else
					{
						// Not a comment, rewind from reading c2
						datastream.Seek(-1, SeekOrigin.Current);
					}
				}
			}
			while(whitespace.IndexOf(c, offset) > -1);
			
			// Go one character back so we can read this non-whitespace character again
			datastream.Seek(-1, SeekOrigin.Current);
			return true;
		}

See More Examples