string.StartsWith(string, System.StringComparison)

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

3137 Examples 7

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

public static ImageGridMetadata TryDeserialize(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            if (!value.StartsWith("<ImageGridMetadata", StringComparison.Ordinal))
            {
                return null;
            }

            int tileColumnCount = (int)GetPropertyValue(value, TileColumnCountPropertyName);
            int tileRowCount = (int)GetPropertyValue(value, TileRowCountPropertyName);
            uint outputHeight = GetPropertyValue(value, OutputHeightPropertyName);
            uint outputWidth = GetPropertyValue(value, OutputWidthPropertyName);
            uint tileImageHeight = GetPropertyValue(value, TileImageHeightPropertyName);
            uint tileImageWidth = GetPropertyValue(value, TileImageWidthPropertyName);

            return new ImageGridMetadata(tileColumnCount, tileRowCount, outputHeight, outputWidth, tileImageHeight, tileImageWidth);
        }

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

public static CICPColorData? TryDeserialize(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }

            // "Nclx" was the old item signature.
            if (!value.StartsWith("<CICP", StringComparison.Ordinal) &&
                !value.StartsWith("<Nclx", StringComparison.Ordinal))
            {
                return null;
            }

            ushort colorPrimaries = GetPropertyValue(value, ColorPrimariesPropertyName);
            ushort transferCharacteristics = GetPropertyValue(value, TransferCharacteristicsPropertyName);
            ushort matrixCoefficients = GetPropertyValue(value, MatrixCoefficientsPropertyName);
            // We always use the full RGB/YUV color range.
            const bool fullRange = true;

            return new CICPColorData
            {
                colorPrimaries = (CICPColorPrimaries)colorPrimaries,
                transferCharacteristics = (CICPTransferCharacteristics)transferCharacteristics,
                matrixCoefficients = (CICPMatrixCoefficients)matrixCoefficients,
                fullRange = fullRange
            };
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private static bool TryGetValue(string item, string prefix, out string value)
        {
            if (item != null && item.StartsWith(prefix, StringComparison.Ordinal))
            {
                value = item.Substring(prefix.Length);

                return !string.IsNullOrWhiteSpace(value);
            }

            value = null;
            return false;
        }

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

static bool TryParseToken(string value, out uint token) {
			if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
				if (uint.TryParse(value.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out token))
					return true;
			}
			token = 0;
			return false;
		}

19 View Source File : CommandNode.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveWhereNode<T>(WhereNode node, T parameter) where T :clreplaced
        {
            var buffer = new StringBuilder();
            foreach (var item in node.Nodes)
            {
                if (parameter!=default && item is IfNode)
                {
                    var text = ResolveIfNode(item as IfNode, parameter);
                    buffer.Append($"{text} ");
                }
                else if (item is TextNode)
                {
                    var text = ResolveTextNode(item as TextNode);
                    buffer.Append($"{text} ");
                }
            }
            var sql = buffer.ToString().Trim(' ');
            if (sql.StartsWith("and", StringComparison.OrdinalIgnoreCase))
            {
                sql = sql.Remove(0, 3);
            }
            else if (sql.StartsWith("or", StringComparison.OrdinalIgnoreCase))
            {
                sql = sql.Remove(0, 2);
            }
            return sql.Length > 0 ? "WHERE " + sql : string.Empty;
        }

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool StartsWithIgnoreCase(this string s, string value)
    {
        return s.StartsWith(value, StringComparison.OrdinalIgnoreCase);
    }

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

public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
            {
                if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
                {
                    cmd.Prefix(TopOwner.Prefix);
                    switch (cmd._command)
                    {
                        case "DEL":
                        case "UNLINK":
                            return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
                        case "MSET":
                            cmd._keyIndexes.ForEach(idx => AdapterCall(cmd._command.InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
                            return default;
                        case "MGET":
                            return cmd._keyIndexes.Select((_, idx) =>
                            {
                                var rt = AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse);
                                return rt.ConvertTo<object[]>().FirstOrDefault();
                            }).ToArray().ConvertTo<TValue>();
                        case "PFCOUNT":
                            return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
                    }
                }
                return TopOwner.LogCall(cmd, () =>
                {
                    RedisResult rt = null;
                    RedisClientPool pool = null;
                    var protocolRetry = false;
                    using (var rds = GetRedisSocket(cmd))
                    {
                        pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
                        try
                        {
                            if (cmd._clusterMovedAsking)
                            {
                                cmd._clusterMovedAsking = false;
                                var askingCmd = "ASKING".SubCommand(null).FlagReadbytes(false);
                                rds.Write(askingCmd);
                                rds.Read(askingCmd);
                            }
                            rds.Write(cmd);
                            rt = rds.Read(cmd);
                        }
                        catch (ProtocolViolationException)
                        {
                            rds.ReleaseSocket();
                            cmd._protocolErrorTryCount++;
                            if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
                                protocolRetry = true;
                            else
                            {
                                if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
                                protocolRetry = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (pool?.SetUnavailable(ex) == true)
                            {
                            }
                            throw;
                        }
                    }
                    if (protocolRetry) return AdapterCall(cmd, parse);
                    if (rt.IsError && pool != null)
                    {
                        var moved = ClusterMoved.ParseSimpleError(rt.SimpleError);
                        if (moved != null && cmd._clusterMovedTryCount < 3)
                        {
                            cmd._clusterMovedTryCount++;

                            if (moved.endpoint.StartsWith("127.0.0.1"))
                                moved.endpoint = $"{DefaultRedisSocket.SplitHost(pool._policy._connectionStringBuilder.Host).Key}:{moved.endpoint.Substring(10)}";
                            else if (moved.endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
                                moved.endpoint = $"{DefaultRedisSocket.SplitHost(pool._policy._connectionStringBuilder.Host).Key}:{moved.endpoint.Substring(10)}";

                            ConnectionStringBuilder connectionString = pool._policy._connectionStringBuilder.ToString();
                            connectionString.Host = moved.endpoint;
                            RegisterClusterNode(connectionString);

                            if (moved.ismoved)
                                _slotCache.AddOrUpdate(moved.slot, connectionString.Host, (k1, v1) => connectionString.Host);

                            if (moved.isask)
                                cmd._clusterMovedAsking = true;

                            TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{(cmd.WriteTarget ?? "Not connected").PadRight(21)} > {cmd}\r\n{rt.SimpleError} ", null));
                            return AdapterCall(cmd, parse);
                        }
                    }
                    return parse(rt);
                });
            }

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

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

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

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

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

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

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

protected bool Eq(string line, out LineType type)
        {
            bool _cmp(string _a, string _b)
            {
                return _a.StartsWith(_b, StringComparison.Ordinal);
            };

            if(_cmp(line, "Microsoft Visual Studio Solution File, Format Version")) {
                type = LineType.FormatVersion;
                return true;
            }

            if(_cmp(line, "MinimumVisualStudioVersion")) {
                type = LineType.MinimumVisualStudioVersion;
                return true;
            }

            if(_cmp(line, "VisualStudioVersion")) {
                type = LineType.VisualStudioVersion;
                return true;
            }

            if(_cmp(line, "# Visual Studio")) {
                type = LineType.ProgramVersion;
                return true;
            }

            type = LineType.Unknown;
            return false;
        }

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja

public static bool IsAnonymousType(this object value)
        {
            if (value == null)
                return false;

            Type type = value.GetType();

            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
               && type.IsGenericType && type.Name.Contains("AnonymousType")
               && (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) ||
                   type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
               && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }

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

public int PlaceOrder(double price, double amount, MarketType market)
        {
            string regPrice = "", regAmount = "", method = "", mParams = "";
            switch (market)
            {
                case MarketType.BTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F4", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCBTC:
					regPrice = price.ToString("F4", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                default://"ALL" is not supported
                    throw new BTCChinaException("PlaceOrder", "N/A", "Market not supported.");
            }
            if (regPrice.StartsWith("-", StringComparison.Ordinal))
                regPrice = "null";
			if (regAmount.StartsWith("-", StringComparison.Ordinal))
            {
                regAmount = regAmount.TrimStart('-');
                method = "sellOrder2";
            }
            else
            {
                method = "buyOrder2";
            }

//          mParams = regPrice + "," + regAmount;
            mParams = "\"" + regPrice + "\",\"" + regAmount + "\"";
            //not default market
            if (market != MarketType.BTCCNY)
                mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";

            var response = DoMethod(BuildParams(method, mParams));
	        var jsonObject = JObject.Parse(response);
	        var orderId = jsonObject.Value<int>("result");

	        return orderId;
        }

19 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

protected virtual replacedembly LoadreplacedemblyByName(replacedemblyName replacedemblyName)
        {
            if (replacedemblyName.Name.StartsWith("Microsoft.Build", StringComparison.OrdinalIgnoreCase) ||
                replacedemblyName.Name.StartsWith("System.", StringComparison.OrdinalIgnoreCase))
            {
                // MSBuild and System.* make up our exchange types. So don't load them in this LoadContext.
                // We need to inherit them from the default load context.
                return null;
            }

            string replacedemblyPath = Path.Combine(this.ManagedDllDirectory, replacedemblyName.Name) + ".dll";
            if (File.Exists(replacedemblyPath))
            {
                return this.LoadreplacedemblyByPath(replacedemblyPath);
            }

            return null;
        }

19 View Source File : DateAndSizeRollingFileAppender.cs
License : MIT License
Project Creator : Abc-Arbitrage

private int FindLastRollingFileNumber(string directory)
        {
            var fileNumber = 0;
            var root = FilenameRoot + ".";
            var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
            foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
            {
                if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                {
                    var rootLength = root.Length;
                    var extensionLength = extension.Length;
                    if (filename.Length - rootLength - extensionLength > 0 && int.TryParse(filename.Substring(rootLength, filename.Length - rootLength - extensionLength), out var tempNumber))
                        fileNumber = Math.Max(fileNumber, tempNumber);
                }
            }

            return fileNumber;
        }

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

void SelecreplacedemFiltering(string query)
		{
			// if the user just typed one more character, don't filter all data but just filter what we are already displaying
			var listToFilter = (this.currentList != null && (!string.IsNullOrEmpty(this.currentText)) && (!string.IsNullOrEmpty(query)) &&
								query.StartsWith(this.currentText, StringComparison.Ordinal)) ?
				this.currentList : this.completionData;

			var matchingItems =
				from item in listToFilter
				let quality = GetMatchQuality(item.Text, query)
				where quality > 0
				select new { Item = item, Quality = quality };

			// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
			ICompletionData suggestedItem = listBox.SelectedIndex != -1 ? (ICompletionData)(listBox.Items[listBox.SelectedIndex]) : null;

			var listBoxItems = new ObservableCollection<ICompletionData>();
			int bestIndex = -1;
			int bestQuality = -1;
			double bestPriority = 0;
			int i = 0;
			foreach (var matchingItem in matchingItems) {
				double priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
				int quality = matchingItem.Quality;
				if (quality > bestQuality || (quality == bestQuality && (priority > bestPriority))) {
					bestIndex = i;
					bestPriority = priority;
					bestQuality = quality;
				}
				listBoxItems.Add(matchingItem.Item);
				i++;
			}
			this.currentList = listBoxItems;
			listBox.ItemsSource = listBoxItems;
			SelectIndexCentered(bestIndex);
		}

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

int GetMatchQuality(string itemText, string query)
		{
			if (itemText == null)
				throw new ArgumentNullException("itemText", "ICompletionData.Text returned null");

			// Qualities:
			//  	8 = full match case sensitive
			// 		7 = full match
			// 		6 = match start case sensitive
			//		5 = match start
			//		4 = match CamelCase when length of query is 1 or 2 characters
			// 		3 = match substring case sensitive
			//		2 = match substring
			//		1 = match CamelCase
			//		-1 = no match
			if (query == itemText)
				return 8;
			if (string.Equals(itemText, query, StringComparison.InvariantCultureIgnoreCase))
				return 7;

			if (itemText.StartsWith(query, StringComparison.InvariantCulture))
				return 6;
			if (itemText.StartsWith(query, StringComparison.InvariantCultureIgnoreCase))
				return 5;

			bool? camelCaseMatch = null;
			if (query.Length <= 2) {
				camelCaseMatch = CamelCaseMatch(itemText, query);
				if (camelCaseMatch == true) return 4;
			}

			// search by substring, if filtering (i.e. new behavior) turned on
			if (IsFiltering) {
				if (itemText.IndexOf(query, StringComparison.InvariantCulture) >= 0)
					return 3;
				if (itemText.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) >= 0)
					return 2;
			}

			if (!camelCaseMatch.HasValue)
				camelCaseMatch = CamelCaseMatch(itemText, query);
			if (camelCaseMatch == true)
				return 1;

			return -1;
		}

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

static HighlightingBrush ParseColor(IXmlLineInfo lineInfo, string color)
		{
			if (string.IsNullOrEmpty(color))
				return null;
			if (color.StartsWith("SystemColors.", StringComparison.Ordinal))
				return GetSystemColorBrush(lineInfo, color);
			else
				return FixedColorHighlightingBrush((Color?)ColorConverter.ConvertFromInvariantString(color));
		}

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

internal static SystemColorHighlightingBrush GetSystemColorBrush(IXmlLineInfo lineInfo, string name)
		{
			Debug.replacedert(name.StartsWith("SystemColors.", StringComparison.Ordinal));
			string shortName = name.Substring(13);
			var property = typeof(SystemColors).GetProperty(shortName + "Brush");
			if (property == null)
				throw Error(lineInfo, "Cannot find '" + name + "'.");
			return new SystemColorHighlightingBrush(property);
		}

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

protected virtual Uri GetUriFromMatch(Match match)
		{
			string targetUrl = match.Value;
			if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
				targetUrl = "http://" + targetUrl;
			if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
				return new Uri(targetUrl);

			return null;
		}

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

static HighlightingBrush ParseColor(string c)
		{
			if (c.StartsWith("#", StringComparison.Ordinal)) {
				int a = 255;
				int offset = 0;
				if (c.Length > 7) {
					offset = 2;
					a = Int32.Parse(c.Substring(1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				}

				int r = Int32.Parse(c.Substring(1 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int g = Int32.Parse(c.Substring(3 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				int b = Int32.Parse(c.Substring(5 + offset, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				return new SimpleHighlightingBrush(Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b));
			} else if (c.StartsWith("SystemColors.", StringComparison.Ordinal)) {
				return V2Loader.GetSystemColorBrush(null, c);
			} else {
				return new SimpleHighlightingBrush((Color)V2Loader.ColorConverter.ConvertFromInvariantString(c));
			}
		}

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

public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
		{
			string line = doc.Text;
			if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
			line = line.TrimStart();

			StringBuilder indent = new StringBuilder();
			if (line.Length == 0) {
				// Special treatment for empty lines:
				if (blockComment || (inString && verbatim))
					return;
				indent.Append(block.InnerIndent);
				indent.Append(Repeat(set.IndentString, block.OneLineBlock));
				if (block.Continuation)
					indent.Append(set.IndentString);
				if (doc.Text != indent.ToString())
					doc.Text = indent.ToString();
				return;
			}

			if (TrimEnd(doc))
				line = doc.Text.TrimStart();

			Block oldBlock = block;
			bool startInComment = blockComment;
			bool startInString = (inString && verbatim);

			#region Parse char by char
			lineComment = false;
			inChar = false;
			escape = false;
			if (!verbatim) inString = false;

			lastRealChar = '\n';

			char lastchar = ' ';
			char c = ' ';
			char nextchar = line[0];
			for (int i = 0; i < line.Length; i++) {
				if (lineComment) break; // cancel parsing current line

				lastchar = c;
				c = nextchar;
				if (i + 1 < line.Length)
					nextchar = line[i + 1];
				else
					nextchar = '\n';

				if (escape) {
					escape = false;
					continue;
				}

				#region Check for comment/string chars
				switch (c) {
					case '/':
						if (blockComment && lastchar == '*')
							blockComment = false;
						if (!inString && !inChar) {
							if (!blockComment && nextchar == '/')
								lineComment = true;
							if (!lineComment && nextchar == '*')
								blockComment = true;
						}
						break;
					case '#':
						if (!(inChar || blockComment || inString))
							lineComment = true;
						break;
					case '"':
						if (!(inChar || lineComment || blockComment)) {
							inString = !inString;
							if (!inString && verbatim) {
								if (nextchar == '"') {
									escape = true; // skip escaped quote
									inString = true;
								} else {
									verbatim = false;
								}
							} else if (inString && lastchar == '@') {
								verbatim = true;
							}
						}
						break;
					case '\'':
						if (!(inString || lineComment || blockComment)) {
							inChar = !inChar;
						}
						break;
					case '\\':
						if ((inString && !verbatim) || inChar)
							escape = true; // skip next character
						break;
				}
				#endregion

				if (lineComment || blockComment || inString || inChar) {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
					continue;
				}

				if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
					if (block.Bracket == '{')
						block.Continuation = true;
				}

				if (Char.IsLetterOrDigit(c)) {
					wordBuilder.Append(c);
				} else {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
				}

				#region Push/Pop the blocks
				switch (c) {
					case '{':
						block.ResetOneLineBlock();
						blocks.Push(block);
						block.StartLine = doc.LineNumber;
						if (block.LastWord == "switch") {
							block.Indent(set.IndentString + set.IndentString);
							/* oldBlock refers to the previous line, not the previous block
							 * The block we want is not available anymore because it was never pushed.
							 * } else if (oldBlock.OneLineBlock) {
							// Inside a one-line-block is another statement
							// with a full block: indent the inner full block
							// by one additional level
							block.Indent(set, set.IndentString + set.IndentString);
							block.OuterIndent += set.IndentString;
							// Indent current line if it starts with the '{' character
							if (i == 0) {
								oldBlock.InnerIndent += set.IndentString;
							}*/
						} else {
							block.Indent(set);
						}
						block.Bracket = '{';
						break;
					case '}':
						while (block.Bracket != '{') {
							if (blocks.Count == 0) break;
							block = blocks.Pop();
						}
						if (blocks.Count == 0) break;
						block = blocks.Pop();
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case '(':
					case '[':
						blocks.Push(block);
						if (block.StartLine == doc.LineNumber)
							block.InnerIndent = block.OuterIndent;
						else
							block.StartLine = doc.LineNumber;
						block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
									 (oldBlock.Continuation ? set.IndentString : "") +
									 (i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
						block.Bracket = c;
						break;
					case ')':
						if (blocks.Count == 0) break;
						if (block.Bracket == '(') {
							block = blocks.Pop();
							if (IsSingleStatementKeyword(block.LastWord))
								block.Continuation = false;
						}
						break;
					case ']':
						if (blocks.Count == 0) break;
						if (block.Bracket == '[')
							block = blocks.Pop();
						break;
					case ';':
					case ',':
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case ':':
						if (block.LastWord == "case"
							|| line.StartsWith("case ", StringComparison.Ordinal)
							|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
							block.Continuation = false;
							block.ResetOneLineBlock();
						}
						break;
				}

				if (!Char.IsWhiteSpace(c)) {
					// register this char as last char
					lastRealChar = c;
				}
				#endregion
			}
			#endregion

			if (wordBuilder.Length > 0)
				block.LastWord = wordBuilder.ToString();
			wordBuilder.Length = 0;

			if (startInString) return;
			if (startInComment && line[0] != '*') return;
			if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
				return;

			if (line[0] == '}') {
				indent.Append(oldBlock.OuterIndent);
				oldBlock.ResetOneLineBlock();
				oldBlock.Continuation = false;
			} else {
				indent.Append(oldBlock.InnerIndent);
			}

			if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
				indent.Remove(indent.Length - 1, 1);
			} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
				indent.Remove(indent.Length - 1, 1);
			}

			if (line[0] == ':') {
				oldBlock.Continuation = true;
			} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
				if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
					indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
			} else if (lastRealChar == ')') {
				if (IsSingleStatementKeyword(block.LastWord)) {
					block.OneLineBlock++;
				}
			} else if (lastRealChar == 'e' && block.LastWord == "else") {
				block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
				block.Continuation = false;
				oldBlock.OneLineBlock = block.OneLineBlock - 1;
			}

			if (doc.IsReadOnly) {
				// We can't change the current line, but we should accept the existing
				// indentation if possible (=if the current statement is not a multiline
				// statement).
				if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
					oldBlock.StartLine == block.StartLine &&
					block.StartLine < doc.LineNumber && lastRealChar != ':') {
					// use indent StringBuilder to get the indentation of the current line
					indent.Length = 0;
					line = doc.Text; // get untrimmed line
					for (int i = 0; i < line.Length; ++i) {
						if (!Char.IsWhiteSpace(line[i]))
							break;
						indent.Append(line[i]);
					}
					// /* */ multiline comments have an extra space - do not count it
					// for the block's indentation.
					if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
						indent.Length -= 1;
					}
					block.InnerIndent = indent.ToString();
				}
				return;
			}

			if (line[0] != '{') {
				if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
					indent.Append(set.IndentString);
				indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
			}

			// this is only for blockcomment lines starting with *,
			// all others keep their old indentation
			if (startInComment)
				indent.Append(' ');

			if (indent.Length != (doc.Text.Length - line.Length) ||
				!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
				Char.IsWhiteSpace(doc.Text[indent.Length])) {
				doc.Text = indent.ToString() + line;
			}
		}

19 View Source File : NumberParse.cs
License : MIT License
Project Creator : abock

static (string str, int @base, bool negate) Configure(string str)
        {
            str = str.Trim();

            var negate = false;
            if (str.Length > 0 && str[0] == '-')
            {
                negate = true;
                str = str.Substring(1);
            }

            str = strip.Replace(str, string.Empty);

            int @base = 10;

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(2);
            }
            else if (str.EndsWith("h", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(0, str.Length - 1);
            }
            else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
            {
                @base = 2;
                str = str.Substring(2);
            }

            return (str, @base, negate);
        }

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

public static string TrimStart(this string result, string trimStart)
        {
            if (result.StartsWith(trimStart, StringComparison.OrdinalIgnoreCase))
                result = result.Substring(trimStart.Length);

            return result;
        }

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

[CommandHandler("boot", AccessLevel.Sentinel, CommandHandlerFlag.None, 2,
            "Boots the character out of the game.",
            "[account | char | iid] who (, reason) \n"
            + "This command boots the specified character out of the game. You can specify who to boot by account, character name, or player instance id. 'who' is the account / character / instance id to actually boot. You can optionally include a reason for the boot.\n"
            + "Example: @boot char Character Name\n"
            + "         @boot account AccountName\n"
            + "         @boot iid 0x51234567\n"
            + "         @boot char Character Name, Reason for being booted\n")]
        public static void HandleBoot(Session session, params string[] parameters)
        {
            // usage: @boot { account,char, iid} who
            // This command boots the specified character out of the game.You can specify who to boot by account, character name, or player instance id.  'who' is the account / character / instance id to actually boot.
            // @boot - Boots the character out of the game.

            var whomToBoot = parameters[1];
            string specifiedReason = null;

            if (parameters.Length > 1)
            {
                var parametersAfterBootType = "";
                for (var i = 1; i < parameters.Length; i++)
                {
                    parametersAfterBootType += parameters[i] + " ";
                }
                parametersAfterBootType = parametersAfterBootType.Trim();
                var completeBootNamePlusCommaSeperatedReason = parametersAfterBootType.Split(",");
                whomToBoot = completeBootNamePlusCommaSeperatedReason[0].Trim();
                if (completeBootNamePlusCommaSeperatedReason.Length > 1)
                    specifiedReason = parametersAfterBootType.Replace($"{whomToBoot},", "").Trim();
            }

            string whatToBoot = null;
            Session sessionToBoot = null;
            switch (parameters[0].ToLower())
            {
                case "char":
                    whatToBoot = "character";
                    sessionToBoot = PlayerManager.GetOnlinePlayer(whomToBoot)?.Session;
                    break;
                case "account":
                    whatToBoot = "account";
                    sessionToBoot = NetworkManager.Find(whomToBoot);
                    break;
                case "iid":
                    whatToBoot = "instance id";
                    if (!whomToBoot.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
                        return;
                    }    
                    if (uint.TryParse(whomToBoot.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var iid))
                    {
                        sessionToBoot = PlayerManager.GetOnlinePlayer(iid)?.Session;
                    }
                    else
                    {
                        CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
                        return;
                    }
                    break;
                default:
                    CommandHandlerHelper.WriteOutputInfo(session, "You must specify what you are booting with char, account, or iid as the first parameter.", ChatMessageType.Broadcast);
                    return;
            }

            if (sessionToBoot == null)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Cannot boot \"{whomToBoot}\" because that {whatToBoot} is not currently online or cannot be found. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
                return;
            }

            // Boot the player
            var bootText = $"Booting {whatToBoot} {whomToBoot}.{(specifiedReason != null ? $" Reason: {specifiedReason}" : "")}";
            CommandHandlerHelper.WriteOutputInfo(session, bootText, ChatMessageType.Broadcast);
            sessionToBoot.Terminate(SessionTerminationReason.AccountBooted, new GameMessageBootAccount($"{(specifiedReason != null ? $" - {specifiedReason}" : null)}"), null, specifiedReason);
            //CommandHandlerHelper.WriteOutputInfo(session, $"...Result: Success!", ChatMessageType.Broadcast);

            PlayerManager.BroadcastToAuditChannel(session?.Player, bootText);
        }

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

public static EffectArgumentType GetEffectArgumentType(Effect effect, string operand)
        {
            if (IsNumber(operand) || Enum.TryParse(operand, out WieldRequirement wieldRequirement) || Enum.TryParse(operand, out Skill skill) || Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
            {
                if (operand.Contains('.'))
                    return EffectArgumentType.Double;
                else if (effect.Quality != null && effect.Quality.StatType == StatType.Int64)
                    return EffectArgumentType.Int64;
                else
                    return EffectArgumentType.Int;
            }
            else if (GetStatType(operand) != StatType.Undef)
            {
                return EffectArgumentType.Quality;
            }
            else if (operand.StartsWith("Random", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Random;
            else if (operand.StartsWith("Variable", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Variable;
            else
                return EffectArgumentType.Invalid;
        }

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

public static List<Hatch> GetPatternFromFile(int startIndex, string[] array)
        {
            var result = new List<Hatch>();
            for (int i = startIndex; i < array.Length - 2; i++)
            {
                if (array[i].Length > 1 && array[i].Trim().StartsWith(@"*", System.StringComparison.InvariantCulture)) {
                    var name = array[i].Substring(1).Trim();
                    i++;
                    var type = array[i].Trim();
                    var defs = new StringBuilder();
                    do
                    {
                        i++;
                        if (!array[i].StartsWith(@";", System.StringComparison.InvariantCulture)) {
                            defs.Append(array[i].Trim());
                            defs.Append(System.Environment.NewLine);
                        }
                    } while (i < (array.Length - 1) && !array[i + 1].Trim().StartsWith(@"*", System.StringComparison.InvariantCulture));
                    var hatch = new Hatch();
                    hatch.Name = name;
                    hatch.HatchPattern.Target = type.ToUpper(System.Globalization.CultureInfo.InvariantCulture).Contains("DRAFTING") ? FillPatternTarget.Drafting : FillPatternTarget.Model;
                    hatch.Definition = defs.ToString();
                    result.Add(hatch);
                }
            }
            return result;
        }

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

private string GetRemoteRefName(string refName)
        {
            if (string.IsNullOrEmpty(refName))
            {
                // If the refName is empty return the remote name for master
                refName = _remoteRefsPrefix + "master";
            }
            else if (refName.Equals("master", StringComparison.OrdinalIgnoreCase))
            {
                // If the refName is master return the remote name for master
                refName = _remoteRefsPrefix + refName;
            }
            else if (refName.StartsWith(_refsPrefix, StringComparison.OrdinalIgnoreCase))
            {
                // If the refName is refs/heads change it to the remote version of the name
                refName = _remoteRefsPrefix + refName.Substring(_refsPrefix.Length);
            }
            else if (refName.StartsWith(_pullRefsPrefix, StringComparison.OrdinalIgnoreCase))
            {
                // If the refName is refs/pull change it to the remote version of the name
                refName = refName.Replace(_pullRefsPrefix, _remotePullRefsPrefix);
            }

            return refName;
        }

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

public static string MakeRelative(string path, string folder)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            ArgUtil.NotNull(folder, nameof(folder));

            // Replace all Path.AltDirectorySeparatorChar with Path.DirectorySeparatorChar from both inputs
            path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            folder = folder.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            // Check if the dir is a prefix of the path (if not, it isn't relative at all).
            if (!path.StartsWith(folder, IOUtil.FilePathStringComparison))
            {
                return path;
            }

            // Dir is a prefix of the path, if they are the same length then the relative path is empty.
            if (path.Length == folder.Length)
            {
                return string.Empty;
            }

            // If the dir ended in a '\\' (like d:\) or '/' (like user/bin/)  then we have a relative path.
            if (folder.Length > 0 && folder[folder.Length - 1] == Path.DirectorySeparatorChar)
            {
                return path.Substring(folder.Length);
            }
            // The next character needs to be a '\\' or they aren't really relative.
            else if (path[folder.Length] == Path.DirectorySeparatorChar)
            {
                return path.Substring(folder.Length + 1);
            }
            else
            {
                return path;
            }
        }

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

private bool IsPullRequest(string sourceBranch)
        {
            return !string.IsNullOrEmpty(sourceBranch) &&
                (sourceBranch.StartsWith(_pullRefsPrefix, StringComparison.OrdinalIgnoreCase) ||
                 sourceBranch.StartsWith(_remotePullRefsPrefix, StringComparison.OrdinalIgnoreCase));
        }

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

public TaskResult Complete(TaskResult? result = null, string currentOperation = null, string resultCode = null)
        {
            if (result != null)
            {
                Result = result;
            }

            // report total delay caused by server throttling.
            if (_totalThrottlingDelayInMilliseconds > _throttlingDelayReportThreshold)
            {
                this.Warning($"The job has experienced {TimeSpan.FromMilliseconds(_totalThrottlingDelayInMilliseconds).TotalSeconds} seconds total delay caused by server throttling.");
            }

            _record.CurrentOperation = currentOperation ?? _record.CurrentOperation;
            _record.ResultCode = resultCode ?? _record.ResultCode;
            _record.FinishTime = DateTime.UtcNow;
            _record.PercentComplete = 100;
            _record.Result = _record.Result ?? TaskResult.Succeeded;
            _record.State = TimelineRecordState.Completed;

            _jobServerQueue.QueueTimelineRecordUpdate(_mainTimelineId, _record);

            // complete all detail timeline records.
            if (_detailTimelineId != Guid.Empty && _detailRecords.Count > 0)
            {
                foreach (var record in _detailRecords)
                {
                    record.Value.FinishTime = record.Value.FinishTime ?? DateTime.UtcNow;
                    record.Value.PercentComplete = record.Value.PercentComplete ?? 100;
                    record.Value.Result = record.Value.Result ?? TaskResult.Succeeded;
                    record.Value.State = TimelineRecordState.Completed;

                    _jobServerQueue.QueueTimelineRecordUpdate(_detailTimelineId, record.Value);
                }
            }

            if (Root != this)
            {
                // only dispose TokenSource for step level ExecutionContext
                _cancellationTokenSource?.Dispose();
            }

            _logger.End();

            // Skip if generated context name. Generated context names start with "__". After 3.2 the server will never send an empty context name.
            if (!string.IsNullOrEmpty(ContextName) && !ContextName.StartsWith("__", StringComparison.Ordinal))
            {
                Global.StepsContext.SetOutcome(ScopeName, ContextName, (Outcome ?? Result ?? TaskResult.Succeeded).ToActionResult());
                Global.StepsContext.SetConclusion(ScopeName, ContextName, (Result ?? TaskResult.Succeeded).ToActionResult());
            }

            return Result.Value;
        }

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

public void SetOutput(string name, string value, out string reference)
        {
            ArgUtil.NotNullOrEmpty(name, nameof(name));

            // Skip if generated context name. Generated context names start with "__". After 3.2 the server will never send an empty context name.
            if (string.IsNullOrEmpty(ContextName) || ContextName.StartsWith("__", StringComparison.Ordinal))
            {
                reference = null;
                return;
            }

            // todo: restrict multiline?

            Global.StepsContext.SetOutput(ScopeName, ContextName, name, value, out reference);
        }

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

public bool StartsWith(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return main.StartsWith(pattern, m_stringComparison);
        }

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

public async Task RunAsync()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
            ArgUtil.NotNull(Action, nameof(Action));
            var taskManager = HostContext.GetService<IActionManager>();
            var handlerFactory = HostContext.GetService<IHandlerFactory>();

            // Load the task definition and choose the handler.
            Definition definition = taskManager.LoadAction(ExecutionContext, Action);
            ArgUtil.NotNull(definition, nameof(definition));

            ActionExecutionData handlerData = definition.Data?.Execution;
            ArgUtil.NotNull(handlerData, nameof(handlerData));

            List<JobExtensionRunner> localActionContainerSetupSteps = null;
            // Handle Composite Local Actions
            // Need to download and expand the tree of referenced actions
            if (handlerData.ExecutionType == ActionExecutionType.Composite &&
                handlerData is CompositeActionExecutionData compositeHandlerData &&
                Stage == ActionRunStage.Main &&
                Action.Reference is Pipelines.RepositoryPathReference localAction &&
                string.Equals(localAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                var actionManager = HostContext.GetService<IActionManager>();
                var prepareResult = await actionManager.PrepareActionsAsync(ExecutionContext, compositeHandlerData.Steps, ExecutionContext.Id);

                // Reload definition since post may exist now (from embedded steps that were JIT downloaded)
                definition = taskManager.LoadAction(ExecutionContext, Action);
                ArgUtil.NotNull(definition, nameof(definition));
                handlerData = definition.Data?.Execution;
                ArgUtil.NotNull(handlerData, nameof(handlerData));

                // Save container setup steps so we can reference them later
                localActionContainerSetupSteps = prepareResult.ContainerSetupSteps;
            }

            if (handlerData.HasPre &&
                Action.Reference is Pipelines.RepositoryPathReference repoAction &&
                string.Equals(repoAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.Warning($"`pre` execution is not supported for local action from '{repoAction.Path}'");
            }

            // The action has post cleanup defined.
            // we need to create timeline record for them and add them to the step list that StepRunner is using
            if (handlerData.HasPost && (Stage == ActionRunStage.Pre || Stage == ActionRunStage.Main))
            {
                string postDisplayName = $"Post {this.DisplayName}";
                if (Stage == ActionRunStage.Pre &&
                    this.DisplayName.StartsWith("Pre ", StringComparison.OrdinalIgnoreCase))
                {
                    // Trim the leading `Pre ` from the display name.
                    // Otherwise, we will get `Post Pre xxx` as DisplayName for the Post step.
                    postDisplayName = $"Post {this.DisplayName.Substring("Pre ".Length)}";
                }
                var repositoryReference = Action.Reference as RepositoryPathReference;
                var pathString = string.IsNullOrEmpty(repositoryReference.Path) ? string.Empty : $"/{repositoryReference.Path}";
                var repoString = string.IsNullOrEmpty(repositoryReference.Ref) ? $"{repositoryReference.Name}{pathString}" :
                    $"{repositoryReference.Name}{pathString}@{repositoryReference.Ref}";

                ExecutionContext.Debug($"Register post job cleanup for action: {repoString}");

                var actionRunner = HostContext.CreateService<IActionRunner>();
                actionRunner.Action = Action;
                actionRunner.Stage = ActionRunStage.Post;
                actionRunner.Condition = handlerData.CleanupCondition;
                actionRunner.DisplayName = postDisplayName;

                ExecutionContext.RegisterPostJobStep(actionRunner);
            }

            IStepHost stepHost = HostContext.CreateService<IDefaultStepHost>();

            // Makes directory for event_path data
            var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
            var workflowDirectory = Path.Combine(tempDirectory, "_github_workflow");
            Directory.CreateDirectory(workflowDirectory);

            var gitHubEvent = ExecutionContext.GetGitHubContext("event");

            // adds the GitHub event path/file if the event exists
            if (gitHubEvent != null)
            {
                var workflowFile = Path.Combine(workflowDirectory, "event.json");
                Trace.Info($"Write event payload to {workflowFile}");
                File.WriteAllText(workflowFile, gitHubEvent, new UTF8Encoding(false));
                ExecutionContext.SetGitHubContext("event_path", workflowFile);
            }

            // Set GITHUB_ACTION_REPOSITORY if this Action is from a repository
            if (Action.Reference is Pipelines.RepositoryPathReference repoPathReferenceAction &&
                !string.Equals(repoPathReferenceAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.SetGitHubContext("action_repository", repoPathReferenceAction.Name);
                ExecutionContext.SetGitHubContext("action_ref", repoPathReferenceAction.Ref);
            }
            else
            {
                ExecutionContext.SetGitHubContext("action_repository", null);
                ExecutionContext.SetGitHubContext("action_ref", null);
            }

            // Setup container stephost for running inside the container.
            if (ExecutionContext.Global.Container != null)
            {
                // Make sure required container is already created.
                ArgUtil.NotNullOrEmpty(ExecutionContext.Global.Container.ContainerId, nameof(ExecutionContext.Global.Container.ContainerId));
                var containerStepHost = HostContext.CreateService<IContainerStepHost>();
                containerStepHost.Container = ExecutionContext.Global.Container;
                stepHost = containerStepHost;
            }

            // Setup File Command Manager
            var fileCommandManager = HostContext.CreateService<IFileCommandManager>();
            fileCommandManager.InitializeFiles(ExecutionContext, null);

            // Load the inputs.
            ExecutionContext.Debug("Loading inputs");
            var templateEvaluator = ExecutionContext.ToPipelineTemplateEvaluator();
            var inputs = templateEvaluator.EvaluateStepInputs(Action.Inputs, ExecutionContext.ExpressionValues, ExecutionContext.ExpressionFunctions);

            var userInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (KeyValuePair<string, string> input in inputs)
            {
                userInputs.Add(input.Key);
                string message = "";
                if (definition.Data?.Deprecated?.TryGetValue(input.Key, out message) == true)
                {
                    ExecutionContext.Warning(String.Format("Input '{0}' has been deprecated with message: {1}", input.Key, message));
                }
            }

            var validInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            if (handlerData.ExecutionType == ActionExecutionType.Container)
            {
                // container action always accept 'entryPoint' and 'args' as inputs
                // https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepswithargs
                validInputs.Add("entryPoint");
                validInputs.Add("args");
            }
            // Merge the default inputs from the definition
            if (definition.Data?.Inputs != null)
            {
                var manifestManager = HostContext.GetService<IActionManifestManager>();
                foreach (var input in definition.Data.Inputs)
                {
                    string key = input.Key.replacedertString("action input name").Value;
                    validInputs.Add(key);
                    if (!inputs.ContainsKey(key))
                    {
                        inputs[key] = manifestManager.EvaluateDefaultInput(ExecutionContext, key, input.Value);
                    }
                }
            }

            // Validate inputs only for actions with action.yml
            if (Action.Reference.Type == Pipelines.ActionSourceType.Repository)
            {
                var unexpectedInputs = new List<string>();
                foreach (var input in userInputs)
                {
                    if (!validInputs.Contains(input))
                    {
                        unexpectedInputs.Add(input);
                    }
                }

                if (unexpectedInputs.Count > 0)
                {
                    ExecutionContext.Warning($"Unexpected input(s) '{string.Join("', '", unexpectedInputs)}', valid inputs are ['{string.Join("', '", validInputs)}']");
                }
            }

            // Load the action environment.
            ExecutionContext.Debug("Loading env");
            var environment = new Dictionary<String, String>(VarUtil.EnvironmentVariableKeyComparer);

#if OS_WINDOWS
            var envContext = ExecutionContext.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = ExecutionContext.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            // Apply environment from env context, env context contains job level env and action's evn block
            foreach (var env in envContext)
            {
                environment[env.Key] = env.Value.ToString();
            }

            // Apply action's intra-action state at last
            foreach (var state in ExecutionContext.IntraActionState)
            {
                environment[$"STATE_{state.Key}"] = state.Value ?? string.Empty;
            }

            // Create the handler.
            IHandler handler = handlerFactory.Create(
                            ExecutionContext,
                            Action.Reference,
                            stepHost,
                            handlerData,
                            inputs,
                            environment,
                            ExecutionContext.Global.Variables,
                            actionDirectory: definition.Directory,
                            localActionContainerSetupSteps: localActionContainerSetupSteps);

            // Print out action details
            handler.PrintActionDetails(Stage);

            // Run the task.
            try
            {
                await handler.RunAsync(Stage);
            }
            finally
            {
                fileCommandManager.ProcessFiles(ExecutionContext, ExecutionContext.Global.Container);
            }

        }

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

private static string RemoveProtocolPrefix(string x)
            {
                if (x != null)
                {
                    if (x.StartsWith(c_tcpPrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        x = x.Substring(c_tcpPrefix.Length);
                    }
                    else if (x.StartsWith(c_npPrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        x = x.Substring(c_npPrefix.Length);
                    }
                }

                return x;
            }

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

public static Boolean IsExpression(String value)
        {
            return !String.IsNullOrEmpty(value) &&
                   value.Length > 3 &&
                   value.StartsWith("$[", StringComparison.Ordinal) &&
                   value.EndsWith("]", StringComparison.Ordinal);
        }

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

private static Boolean MatchesDirective(
            String trimmed,
            String directive,
            Int32 expectedParameters,
            out List<String> parameters,
            out Exception ex)
        {
            if (trimmed.StartsWith(directive, StringComparison.Ordinal) &&
                (trimmed.Length == directive.Length || Char.IsWhiteSpace(trimmed[directive.Length])))
            {
                parameters = new List<String>();
                var startIndex = directive.Length;
                var inString = false;
                var parens = 0;
                for (var i = startIndex; i < trimmed.Length; i++)
                {
                    var c = trimmed[i];
                    if (Char.IsWhiteSpace(c) && !inString && parens == 0)
                    {
                        if (startIndex < i)
                        {
                            parameters.Add(trimmed.Substring(startIndex, i - startIndex));
                        }

                        startIndex = i + 1;
                    }
                    else if (c == '\'')
                    {
                        inString = !inString;
                    }
                    else if (c == '(' && !inString)
                    {
                        parens++;
                    }
                    else if (c == ')' && !inString)
                    {
                        parens--;
                    }
                }

                if (startIndex < trimmed.Length)
                {
                    parameters.Add(trimmed.Substring(startIndex));
                }

                if (expectedParameters != parameters.Count)
                {
                    ex = new ArgumentException(TemplateStrings.ExpectedNParametersFollowingDirective(expectedParameters, directive, parameters.Count));
                    parameters = null;
                    return false;
                }

                ex = null;
                return true;
            }

            ex = null;
            parameters = null;
            return false;
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void BindProducts() {
			// Manually reference these type to ensure the related replacedemblies are loaded since they may not yet have been loaded by default
			var srTypes = new Type[] {
				// None: typeof(ActiproSoftware.Products.SyntaxEditor.Addons.JavaScript.SR),
				typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Python.SR),
				typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Xml.SR),
				typeof(ActiproSoftware.Products.Text.Addons.JavaScript.SR),
				typeof(ActiproSoftware.Products.Text.Addons.Python.SR),
				typeof(ActiproSoftware.Products.Text.Addons.Xml.SR),
			};

			var productResources = new List<ProductResource>();

			foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
				var name = replacedembly.GetName().Name;
				if ((name.StartsWith("ActiproSoftware.", StringComparison.OrdinalIgnoreCase)) && (name.EndsWith(".Wpf", StringComparison.OrdinalIgnoreCase))) {
					var productResource = new ProductResource(replacedembly);
					if (productResource.IsValid)
						productResources.Add(productResource);
				}
			}

			productResources.Sort((x, y) => x.Name.CompareTo(y.Name));

			productComboBox.ItemsSource = productResources;

			if (productComboBox.Items.Count > 0)
				productComboBox.SelectedIndex = 0;
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void NavigateTo(string url) {
			var activeWindow = dockSite.PrimaryDoreplacedent;
			if (activeWindow != null) {
				var browser = (WebBrowser)activeWindow.Content;
				try {
					if (
						(!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) &&
						(!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) &&
						(!url.StartsWith("about:", StringComparison.OrdinalIgnoreCase))
						)
						url = "http://" + url;

					var uri = new Uri(url, UriKind.Absolute);
					browser.Navigate(uri.AbsoluteUri);
				}
				catch {
					MessageBox.Show("Please enter an absolute URL: " + url, "Browser");
				}
			}
		}

19 View Source File : SyntaxEditorHelper.cs
License : MIT License
Project Creator : Actipro

public static void AddCommonDotNetSystemreplacedemblyReferences(IProjectreplacedembly projectreplacedembly) {
			if (projectreplacedembly is null)
				throw new ArgumentNullException(nameof(projectreplacedembly));

			// Iterate the replacedemblies in the AppDomain and load all "System" replacedemblies
			foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
				if ((replacedembly.FullName.StartsWith("System", StringComparison.OrdinalIgnoreCase)) ||
					(replacedembly.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase))) {
					projectreplacedembly.replacedemblyReferences.Add(replacedembly);
				}
			}
		}

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

public override void VisitInvocationExpression(InvocationExpressionSyntax node)
			{
				var symbolInfo = _semanticModel.GetSymbolInfo(node);
				var methodSymbol = (symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault()) as IMethodSymbol;

				// Check BQL Select / Search methods by name because
				// variations of these methods are declared in different PXSelectBase-derived clreplacedes
				var declaringType = methodSymbol?.ContainingType?.OriginalDefinition;

				if (declaringType != null && declaringType.IsBqlCommand(_pxContext) 
					&& !methodSymbol.Parameters.IsEmpty && methodSymbol.Parameters[0].Type.IsPXGraph(_pxContext) 
					&& node.ArgumentList.Arguments.Count > 0 &&
				    (methodSymbol.Name.StartsWith(SelectMethodName, StringComparison.Ordinal) ||
				     methodSymbol.Name.StartsWith(SearchMethodName, StringComparison.Ordinal)))
				{
					var graphArg = node.ArgumentList.Arguments[0].Expression;
					_graphArguments.Add(graphArg);
				}
			}

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

private bool IsDatabaseCall(IMethodSymbol candidate)
		{
			var methodSymbol = candidate.OriginalDefinition?.OverriddenMethod ?? candidate.OriginalDefinition;

			if (methodSymbol != null && _databaseQueryMethods.Contains(methodSymbol))
				return true;

			// Check BQL Select / Search methods by name because
			// variations of these methods are declared in different PXSelectBase-derived clreplacedes
			var declaringType = candidate.ContainingType?.OriginalDefinition;

			if (declaringType != null && declaringType.IsBqlCommand(_pxContext) &&
			    (candidate.Name.StartsWith(SelectMethodName, StringComparison.Ordinal) ||
			     candidate.Name.StartsWith(SearchMethodName, StringComparison.Ordinal)))
			{
				return true;
			}

			return false;
		}

19 View Source File : Parser.cs
License : MIT License
Project Creator : adamant

private static IEnumerable<string> GetUsingNamespaces(IEnumerable<string> lines)
        {
            const string start = Program.DirectiveMarker + "using";
            lines = lines.Where(l => l.StartsWith(start, StringComparison.InvariantCulture));
            // TODO error if no semicolon
            return lines.Select(l => l.Substring(start.Length).TrimEnd(';').Trim());
        }

19 View Source File : Parser.cs
License : MIT License
Project Creator : adamant

private static IEnumerable<GrammarRule> GetRules(List<string> lines)
        {
            var ruleLines = lines.Select(l => l.Trim())
                                 .Where(l => !l.StartsWith(Program.DirectiveMarker, StringComparison.InvariantCulture)
                                            && !l.StartsWith("//", StringComparison.InvariantCulture)
                                            && !string.IsNullOrWhiteSpace(l))
                                 .Select(l => l.TrimEnd(';')) // TODO error if no semicolon
                                 .ToList()!;
            foreach (var ruleLine in ruleLines)
            {
                var equalSplit = ruleLine.Split('=');
                if (equalSplit.Length > 2)
                    throw new FormatException($"Too many equal signs on line: '{ruleLine}'");
                var declaration = equalSplit[0];
                var (nonterminal, parents) = ParseDeclaration(declaration);
                var definition = equalSplit.Length == 2 ? equalSplit[1].Trim() : null;
                var properties = ParseDefinition(definition).ToList();
                if (properties.Select(p => p.Name).Distinct().Count() != properties.Count)
                    throw new FormatException($"Rule for {nonterminal} contains duplicate property definitions");

                yield return new GrammarRule(nonterminal, parents, properties);
            }
        }

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

public static Version ParseOrDefault(string text, string prefix) =>
            text == null || !text.StartsWith(prefix ?? "", StringComparison.OrdinalIgnoreCase) ? null : ParseOrDefault(text[(prefix?.Length ?? 0)..]);

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

public static string Get(string testSuiteName, string testName, object tag = null) =>
            Path.Combine(
                Path.GetTempPath(),
                testSuiteName,
                TestContext.RunId.ToString(CultureInfo.InvariantCulture),
                $"{testName}{(tag == null ? "" : (tag.GetType().Name.StartsWith("ValueTuple", StringComparison.Ordinal) ? tag : $"({tag})"))}");

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

public static (IReadOnlyList<string> Targets, Options Options, IReadOnlyList<string> UnknownOptions, bool showHelp) Parse(IReadOnlyCollection<string> args)
        {
            var helpArgs = args.Where(arg => helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));
            var nonHelpArgs = args.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));

            var targets = nonHelpArgs.Where(arg => !arg.StartsWith("-", StringComparison.Ordinal)).ToList();

            var nonTargets = nonHelpArgs.Where(arg => arg.StartsWith("-", StringComparison.Ordinal));

            var optionArgs = nonTargets.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase)).Select(arg => (arg, true));
            var result = OptionsReader.Read(optionArgs);
            var options = new Options
            {
                Clear = result.Clear,
                DryRun = result.DryRun,
                Host = result.Host,
                ListDependencies = result.ListDependencies,
                ListInputs = result.ListInputs,
                ListTargets = result.ListTargets,
                ListTree = result.ListTree,
                NoColor = result.NoColor,
                NoExtendedChars = result.NoExtendedChars,
                Parallel = result.Parallel,
                SkipDependencies = result.SkipDependencies,
                Verbose = result.Verbose,
            };

            return (targets, options, result.UnknownOptions, helpArgs.Any());
        }

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

public static string ResolvePath(string basePath, string path)
        {
            if (!path.StartsWith("\\", StringComparison.OrdinalIgnoreCase))
            {
                return ResolveRelativePath(basePath, path);
            }
            return path;
        }

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

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

            var filter = text;

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

            listViewSuggestion.ItemsSource = null;

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

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

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

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

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

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

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

                    foreach (var reg in registries)
                    {

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

                    }

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

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

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

                    listViewSuggestion.ItemsSource = str;
                }
            }
        }

19 View Source File : TestCompileAndRun.cs
License : MIT License
Project Creator : adoconnection

private static List<MetadataReference> GetMetadataReferences()
        {
            if (RuntimeInformation.FrameworkDescription.StartsWith(
                ".NET Framework",
                StringComparison.OrdinalIgnoreCase))
            {
                return new List<MetadataReference>()
                           {
                               MetadataReference.CreateFromFile(typeof(object).replacedembly.Location),
                               MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")).Location),
                               MetadataReference.CreateFromFile(replacedembly.Load(
                                   new replacedemblyName(
                                       "netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")).Location),
                               MetadataReference.CreateFromFile(typeof(System.Runtime.GCSettings).replacedembly.Location)
                           };
            }

            return new List<MetadataReference>()
                       {
                           MetadataReference.CreateFromFile(typeof(object).replacedembly.Location),
                           MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName("Microsoft.CSharp")).Location),
                           MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName("netstandard")).Location),
                           MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName("System.Runtime")).Location)
                       };
        }

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

private static IEnumerable<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>> ParseSortExpression(string sortExpression)
		{
			if (string.IsNullOrEmpty(sortExpression))
			{
				return Enumerable.Empty<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>>();
			}

			return SortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match =>
			{
				var sortNameCapture = match.Groups["name"].Value;

				Expression<Func<Enreplacedy, object>> sort;

				if (!SortExpressions.TryGetValue(sortNameCapture, out sort))
				{
					return null;
				}

				var sortDirectionCapture = match.Groups["direction"].Value;

				var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)
					? SortDirection.Ascending
					: SortDirection.Descending;

				return new Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>(sort, sortDirection);

			}).Where(sort => sort != null).ToArray();
		}

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

private static IEnumerable<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>> ParseSortExpression(string sortExpression)
		{
			if (string.IsNullOrEmpty(sortExpression))
			{
				return Enumerable.Empty<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>>();
			}

			return _sortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match =>
			{
				var sortNameCapture = match.Groups["name"].Value;

				Expression<Func<Enreplacedy, object>> sort;

				if (!SortExpressions.TryGetValue(sortNameCapture, out sort))
				{
					return null;
				}

				var sortDirectionCapture = match.Groups["direction"].Value;

				var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)
					? SortDirection.Ascending
					: SortDirection.Descending;

				return new Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>(sort, sortDirection);

			}).Where(sort => sort != null).ToArray();
		}

See More Examples