char.ToString()

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

3273 Examples 7

19 Source : CopyRecordingsService.cs
with MIT License
from AntonyCorbett

private void Copy(char driveLetter, string[] recordings, long spaceNeeded)
        {
            var di = new DriveInfo(driveLetter.ToString());
            if (spaceNeeded * 1.05 > di.AvailableFreeSpace)
            {
                throw new NoSpaceException(driveLetter);
            }

            Parallel.ForEach(
                recordings, 
                file =>
                {
                    var fileName = Path.GetFileName(file);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        var destinationFile = Path.Combine($"{driveLetter}:\\", fileName);

                        Log.Logger.Debug($"Copying {file} to {destinationFile}");
                        File.Copy(file, destinationFile, overwrite: true);
                    }
                });

            Eject(driveLetter);
        }

19 Source : WindowsNameTransform.cs
with GNU General Public License v3.0
from anydream

public static string MakeValidName(string name, char replacement)
		{
			if (name == null) {
				throw new ArgumentNullException(nameof(name));
			}

			name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString()));

			// Drop any leading slashes.
			while ((name.Length > 0) && (name[0] == Path.DirectorySeparatorChar)) {
				name = name.Remove(0, 1);
			}

			// Drop any trailing slashes.
			while ((name.Length > 0) && (name[name.Length - 1] == Path.DirectorySeparatorChar)) {
				name = name.Remove(name.Length - 1, 1);
			}

			// Convert consecutive \\ characters to \
			int index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
			while (index >= 0) {
				name = name.Remove(index, 1);
				index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
			}

			// Convert any invalid characters using the replacement one.
			index = name.IndexOfAny(InvalidEntryChars);
			if (index >= 0) {
				var builder = new StringBuilder(name);

				while (index >= 0) {
					builder[index] = replacement;

					if (index >= name.Length) {
						index = -1;
					} else {
						index = name.IndexOfAny(InvalidEntryChars, index + 1);
					}
				}
				name = builder.ToString();
			}

			// Check for names greater than MaxPath characters.
			// TODO: Were is CLR version of MaxPath defined?  Can't find it in Environment.
			if (name.Length > MaxPath) {
				throw new PathTooLongException();
			}

			return name;
		}

19 Source : WindowsNameTransform.cs
with GNU General Public License v3.0
from anydream

public string TransformDirectory(string name)
		{
			name = TransformFile(name);
			if (name.Length > 0) {
				while (name.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) {
					name = name.Remove(name.Length - 1, 1);
				}
			} else {
				throw new ZipException("Cannot have an empty directory name");
			}
			return name;
		}

19 Source : Options.cs
with MIT License
from aolszowka

private bool ParseBundledValue (string f, string n, OptionContext c)
		{
			if (f != "-")
				return false;
			for (int i = 0; i < n.Length; ++i) {
				Option p;
				string opt = f + n [i].ToString ();
				string rn = n [i].ToString ();
				if (!Contains (rn)) {
					if (i == 0)
						return false;
					throw new OptionException (string.Format (localizer (
									"Cannot bundle unregistered option '{0}'."), opt), opt);
				}
				p = this [rn];
				switch (p.OptionValueType) {
					case OptionValueType.None:
						Invoke (c, opt, n, p);
						break;
					case OptionValueType.Optional:
					case OptionValueType.Required: {
						string v     = n.Substring (i+1);
						c.Option     = p;
						c.OptionName = opt;
						ParseValue (v.Length != 0 ? v : null, c);
						return true;
					}
					default:
						throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
				}
			}
			return true;
		}

19 Source : Options.cs
with MIT License
from aolszowka

private static void AddSeparators (string name, int end, ICollection<string> seps)
		{
			int start = -1;
			for (int i = end+1; i < name.Length; ++i) {
				switch (name [i]) {
					case '{':
						if (start != -1)
							throw new ArgumentException (
									string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
									"prototype");
						start = i+1;
						break;
					case '}':
						if (start == -1)
							throw new ArgumentException (
									string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
									"prototype");
						seps.Add (name.Substring (start, i-start));
						start = -1;
						break;
					default:
						if (start == -1)
							seps.Add (name [i].ToString ());
						break;
				}
			}
			if (start != -1)
				throw new ArgumentException (
						string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
						"prototype");
		}

19 Source : Anonymizer.cs
with MIT License
from aolszowka

private static IEnumerable<string> GeneratePermutations(int slots, IEnumerable<char> possibleValues)
        {
            foreach (char value in possibleValues)
            {
                if (slots > 1)
                {
                    foreach (string otherSlotValue in GeneratePermutations(slots - 1, possibleValues))
                    {
                        yield return value + otherSlotValue;
                    }
                }
                else
                {
                    yield return value.ToString();
                }
            }
        }

19 Source : NmsStreamMessage.cs
with Apache License 2.0
from apache

public string ReadString()
        {
            CheckWriteOnlyBody();
            CheckBytesInFlight();

            string result;
            object value = facade.Peek();
            if (value == null)
                result = null;
            else if (value is string stringValue)
                result = stringValue;
            else if (value is float floatValue)
                result = floatValue.ToString(CultureInfo.InvariantCulture);
            else if (value is double doubleValue)
                result = doubleValue.ToString(CultureInfo.InvariantCulture);
            else if (value is long longValue)
                result = longValue.ToString();
            else if (value is int intValue)
                result = intValue.ToString();
            else if (value is short shortValue)
                result = shortValue.ToString();
            else if (value is byte byteValue)
                result = byteValue.ToString();
            else if (value is bool boolValue)
                result = boolValue.ToString();
            else if (value is char charValue)
                result = charValue.ToString();
            else
                throw new MessageFormatException("stream value: " + value.GetType().Name + " cannot be converted to int.");

            facade.Pop();
            return result;
        }

19 Source : NmsStreamMessageTest.cs
with Apache License 2.0
from apache

[Test, Description("Set a char, then retrieve it as all of the legal type combinations to verify it is parsed correctly")]
        public void TestWriteCharReadLegal()
        {
            NmsStreamMessage streamMessage = factory.CreateStreamMessage();

            char value = 'c';

            streamMessage.WriteChar(value);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<char>(streamMessage, true, value);
            replacedertGetStreamEntryEquals<string>(streamMessage, true, value.ToString());
        }

19 Source : MessageTest.cs
with Apache License 2.0
from apache

[Test]
        public void SendReceiveMessageProperties(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Queue);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        producer.DeliveryMode = deliveryMode;
                        IMessage request = session.CreateMessage();
                        request.Properties["a"] = a;
                        request.Properties["b"] = b;
                        request.Properties["c"] = c;
                        request.Properties["d"] = d;
                        request.Properties["e"] = e;
                        request.Properties["f"] = f;
                        request.Properties["g"] = g;
                        request.Properties["h"] = h;
                        request.Properties["i"] = i;
                        request.Properties["j"] = j;
                        request.Properties["k"] = k;
                        request.Properties["l"] = l;
                        request.Properties["m"] = m;
                        request.Properties["n"] = n;

                        try
                        {
                            request.Properties["o"] = o;
                            replacedert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                        }
                        catch
                        {
                            // Expected
                        }

                        try
                        {
                            request.Properties.SetBytes("o", o);
                            replacedert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                        }
                        catch
                        {
                            // Expected
                        }

                        producer.Send(request);

                        IMessage message = consumer.Receive(receiveTimeout);
                        replacedert.IsNotNull(message, "No message returned!");
                        replacedert.AreEqual(request.Properties.Count, message.Properties.Count,
                            "Invalid number of properties.");
                        replacedert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");
                        replacedert.AreEqual(ToHex(f), ToHex(message.Properties.GetLong("f")), "map entry: f as hex");

                        // use generic API to access entries
                        // Perform a string only comparison here since some NMS providers are type limited and
                        // may return only a string instance from the generic [] accessor.  Each provider should
                        // further test this functionality to determine that the correct type is returned if
                        // it is capable of doing so.
                        replacedert.AreEqual(a.ToString(), message.Properties["a"].ToString(), "generic map entry: a");
                        replacedert.AreEqual(b.ToString(), message.Properties["b"].ToString(), "generic map entry: b");
                        replacedert.AreEqual(c.ToString(), message.Properties["c"].ToString(), "generic map entry: c");
                        replacedert.AreEqual(d.ToString(), message.Properties["d"].ToString(), "generic map entry: d");
                        replacedert.AreEqual(e.ToString(), message.Properties["e"].ToString(), "generic map entry: e");
                        replacedert.AreEqual(f.ToString(), message.Properties["f"].ToString(), "generic map entry: f");
                        replacedert.AreEqual(g.ToString(), message.Properties["g"].ToString(), "generic map entry: g");
                        replacedert.AreEqual(h.ToString(), message.Properties["h"].ToString(), "generic map entry: h");
                        replacedert.AreEqual(i.ToString(), message.Properties["i"].ToString(), "generic map entry: i");
                        replacedert.AreEqual(j.ToString(), message.Properties["j"].ToString(), "generic map entry: j");
                        replacedert.AreEqual(k.ToString(), message.Properties["k"].ToString(), "generic map entry: k");
                        replacedert.AreEqual(l.ToString(), message.Properties["l"].ToString(), "generic map entry: l");
                        replacedert.AreEqual(m.ToString(), message.Properties["m"].ToString(), "generic map entry: m");
                        replacedert.AreEqual(n.ToString(), message.Properties["n"].ToString(), "generic map entry: n");

                        // use type safe APIs
                        replacedert.AreEqual(a, message.Properties.GetBool("a"), "map entry: a");
                        replacedert.AreEqual(b, message.Properties.GetByte("b"), "map entry: b");
                        replacedert.AreEqual(c, message.Properties.GetChar("c"), "map entry: c");
                        replacedert.AreEqual(d, message.Properties.GetShort("d"), "map entry: d");
                        replacedert.AreEqual(e, message.Properties.GetInt("e"), "map entry: e");
                        replacedert.AreEqual(f, message.Properties.GetLong("f"), "map entry: f");
                        replacedert.AreEqual(g, message.Properties.GetString("g"), "map entry: g");
                        replacedert.AreEqual(h, message.Properties.GetBool("h"), "map entry: h");
                        replacedert.AreEqual(i, message.Properties.GetByte("i"), "map entry: i");
                        replacedert.AreEqual(j, message.Properties.GetShort("j"), "map entry: j");
                        replacedert.AreEqual(k, message.Properties.GetInt("k"), "map entry: k");
                        replacedert.AreEqual(l, message.Properties.GetLong("l"), "map entry: l");
                        replacedert.AreEqual(m, message.Properties.GetFloat("m"), "map entry: m");
                        replacedert.AreEqual(n, message.Properties.GetDouble("n"), "map entry: n");
                    }
                }
            }
        }

19 Source : PatternParser.cs
with Apache License 2.0
from 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 Source : CharFunction.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 1);
            var number = ArgToInt(arguments, 0);
            ThrowExcelErrorValueExceptionIf(() => number < 1 || number > 255, eErrorType.Value);
            return CreateResult(((char) number).ToString(), DataType.String);
        }

19 Source : MultipleCharSeparatorHandler.cs
with Apache License 2.0
from Appdynamics

public override bool Handle(char c, Token tokenSeparator, TokenizerContext context, ITokenIndexProvider tokenIndexProvider)
        {
            // two operators in sequence could be "<=" or ">="
            if (IsPartOfMultipleCharSeparator(context, c))
            {
                var sOp = context.LastToken.Value + c.ToString();
                var op = _tokenSeparatorProvider.Tokens[sOp];
                context.ReplaceLastToken(op);
                context.NewToken();
                return true;
            }
            return false;
        }

19 Source : MultipleCharSeparatorHandler.cs
with Apache License 2.0
from Appdynamics

private bool IsPartOfMultipleCharSeparator(TokenizerContext context, char c)
        {
            var lastToken = context.LastToken != null ? context.LastToken.Value : string.Empty;
            return _tokenSeparatorProvider.IsOperator(lastToken)
                && _tokenSeparatorProvider.IsPossibleLastPartOfMultipleCharOperator(c.ToString())
                && !context.CurrentTokenHasValue;
        }

19 Source : TokenHandler.cs
with Apache License 2.0
from Appdynamics

private bool CharIsTokenSeparator(char c, out Token token)
        {
            var result = _tokenProvider.Tokens.ContainsKey(c.ToString());
            token = result ? token = _tokenProvider.Tokens[c.ToString()] : null;
            return result;
        }

19 Source : TokenizerContext.cs
with Apache License 2.0
from Appdynamics

public void AppendToCurrentToken(char c)
        {
            _currentToken.Append(c.ToString());
        }

19 Source : ExcelNumberFormatXml.cs
with Apache License 2.0
from Appdynamics

private void ToNetFormat(string ExcelFormat, bool forColWidth)
            {
                DataType = eFormatType.Unknown;
                int secCount = 0;
                bool isText = false;
                bool isBracket = false;
                string bracketText = "";
                bool prevBslsh = false;
                bool useMinute = false;
                bool prevUnderScore = false;
                bool ignoreNext = false;
                int fractionPos = -1;
                string specialDateFormat = "";
                bool containsAmPm = ExcelFormat.Contains("AM/PM");
                List<int> lstDec=new List<int>();
                StringBuilder sb = new StringBuilder();
                Culture = null;
                var format = "";
                var text = "";
                char clc;

                if (containsAmPm)
                {
                    ExcelFormat = Regex.Replace(ExcelFormat, "AM/PM", "");
                    DataType = eFormatType.DateTime;
                }

                for (int pos = 0; pos < ExcelFormat.Length; pos++)
                {
                    char c = ExcelFormat[pos];
                    if (c == '"')
                    {
                        isText = !isText;
                    }
                    else
                    {
                        if (ignoreNext)
                        {
                            ignoreNext = false;
                            continue;
                        }
                        else if (isText && !isBracket)
                        {
                            sb.Append(c);
                        }
                        else if (isBracket)
                        {
                            if (c == ']')
                            {
                                isBracket = false;
                                if (bracketText[0] == '$')  //Local Info
                                {
                                    string[] li = Regex.Split(bracketText, "-");
                                    if (li[0].Length > 1)
                                    {
                                        sb.Append("\"" + li[0].Substring(1, li[0].Length - 1) + "\"");     //Currency symbol
                                    }
                                    if (li.Length > 1)
                                    {
                                        if (li[1].Equals("f800", StringComparison.OrdinalIgnoreCase))
                                        {
                                            specialDateFormat = "D";
                                        }
                                        else if (li[1].Equals("f400", StringComparison.OrdinalIgnoreCase))
                                        {
                                            specialDateFormat = "T";
                                        }
                                        else
                                        {
                                            var num = int.Parse(li[1], NumberStyles.HexNumber);
                                            try
                                            {
                                                Culture = CultureInfo.GetCultureInfo(num & 0xFFFF);
                                            }
                                            catch
                                            {
                                                Culture = null;
                                            }
                                        }
                                    }
                                }
                                else if(bracketText[0]=='t')
                                {
                                    sb.Append("hh"); //TODO:This will not be correct for dates over 24H.
                                }
                                else if (bracketText[0] == 'h')
                                {
                                    specialDateFormat = "hh"; //TODO:This will not be correct for dates over 24H.
                                }
                            }
                            else
                            {
                                bracketText += c;
                            }
                        }
                        else if (prevUnderScore)
                        {
                            if (forColWidth)
                            {
                                sb.AppendFormat("\"{0}\"", c);
                            }
                            prevUnderScore = false;
                        }
                        else
                        {
                            if (c == ';') //We use first part (for positive only at this stage)
                            {
                                secCount++;
                                if (DataType == eFormatType.DateTime || secCount == 3)
                                {
                                    //Add qoutes
                                    if (DataType == eFormatType.DateTime) SetDecimal(lstDec, sb); //Remove?
                                    lstDec = new List<int>();
                                    format = sb.ToString();
                                    sb = new StringBuilder();
                                }
                                else
                                {
                                    sb.Append(c);
                                }
                            }
                            else
                            {
                                clc = c.ToString().ToLower(CultureInfo.InvariantCulture)[0];  //Lowercase character
                                //Set the datetype
                                if (DataType == eFormatType.Unknown)
                                {
                                    if (c == '0' || c == '#' || c == '.')
                                    {
                                        DataType = eFormatType.Number;
                                    }
                                    else if (clc == 'y' || clc == 'm' || clc == 'd' || clc == 'h' || clc == 'm' || clc == 's')
                                    {
                                        DataType = eFormatType.DateTime;
                                    }
                                }

                                if (prevBslsh)
                                {
                                    if (c == '.' || c == ',')
                                    {
                                        sb.Append('\\');
                                    }                                    
                                    sb.Append(c);
                                    prevBslsh = false;
                                }
                                else if (c == '[')
                                {
                                    bracketText = "";
                                    isBracket = true;
                                }
                                else if (c == '\\')
                                {
                                    prevBslsh = true;
                                }
                                else if (c == '0' ||
                                    c == '#' ||
                                    c == '.' ||
                                    c == ',' ||
                                    c == '%' ||
                                    clc == 'd' ||
                                    clc == 's')
                                {
                                    sb.Append(c);
                                    if(c=='.')
                                    {
                                        lstDec.Add(sb.Length - 1);
                                    }
                                }
                                else if (clc == 'h')
                                {
                                    if (containsAmPm)
                                    {
                                        sb.Append('h'); ;
                                    }
                                    else
                                    {
                                        sb.Append('H');
                                    }
                                    useMinute = true;
                                }
                                else if (clc == 'm')
                                {
                                    if (useMinute)
                                    {
                                        sb.Append('m');
                                    }
                                    else
                                    {
                                        sb.Append('M');
                                    }
                                }
                                else if (c == '_') //Skip next but use for alignment
                                {
                                    prevUnderScore = true;
                                }
                                else if (c == '?')
                                {
                                    sb.Append(' ');
                                }
                                else if (c == '/')
                                {
                                    if (DataType == eFormatType.Number)
                                    {
                                        fractionPos = sb.Length;
                                        int startPos = pos - 1;
                                        while (startPos >= 0 &&
                                                (ExcelFormat[startPos] == '?' ||
                                                ExcelFormat[startPos] == '#' ||
                                                ExcelFormat[startPos] == '0'))
                                        {
                                            startPos--;
                                        }

                                        if (startPos > 0)  //RemovePart
                                            sb.Remove(sb.Length-(pos-startPos-1),(pos-startPos-1)) ;

                                        int endPos = pos + 1;
                                        while (endPos < ExcelFormat.Length &&
                                                (ExcelFormat[endPos] == '?' ||
                                                ExcelFormat[endPos] == '#' ||
                                                (ExcelFormat[endPos] >= '0' && ExcelFormat[endPos]<= '9')))
                                        {
                                            endPos++;
                                        }
                                        pos = endPos;
                                        if (FractionFormat != "")
                                        {
                                            FractionFormat = ExcelFormat.Substring(startPos+1, endPos - startPos-1);
                                        }
                                        sb.Append('?'); //Will be replaced later on by the fraction
                                    }
                                    else
                                    {
                                        sb.Append('/');
                                    }
                                }
                                else if (c == '*')
                                {
                                    //repeat char--> ignore
                                    ignoreNext = true;
                                }
                                else if (c == '@')
                                {
                                    sb.Append("{0}");
                                }
                                else
                                {
                                    sb.Append(c);
                                }
                            }
                        }
                    }
                }

                //Add qoutes
                if (DataType == eFormatType.DateTime) SetDecimal(lstDec, sb); //Remove?

                // AM/PM format
                if (containsAmPm)
                {
                    format += "tt";
                }


                if (format == "")
                    format = sb.ToString();
                else
                    text = sb.ToString();
                if (specialDateFormat != "")
                {
                    format = specialDateFormat;
                }

                if (forColWidth)
                {
                    NetFormatForWidth = format;
                    NetTextFormatForWidth = text;
                }
                else
                {
                    NetFormat = format;
                    NetTextFormat = text;
                }
                if (Culture == null)
                {
                    Culture = CultureInfo.CurrentCulture;
                }
            }

19 Source : ExcelCellBase.cs
with Apache License 2.0
from Appdynamics

protected internal static string GetColumnLetter(int iColumnNumber, bool fixedCol)
        {

            if (iColumnNumber < 1)
            {
                //throw new Exception("Column number is out of range");
                return "#REF!";
            }

            string sCol = "";
            do
            {
                sCol = ((char)('A' + ((iColumnNumber - 1) % 26))).ToString() + sCol;
                iColumnNumber = (iColumnNumber - ((iColumnNumber - 1) % 26)) / 26;
            }
            while (iColumnNumber > 0);
            return fixedCol ? "$" + sCol : sCol;
        }

19 Source : BaseService.cs
with Apache License 2.0
from AppRopio

private static string DecodeEncodedNonAsciiCharacters(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            
            return Regex.Replace(
                value,
                @"\\u(?<Value>[a-zA-Z0-9]{4})",
                m =>
                {
                    if (int.TryParse(m.Groups["Value"].Value, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo, out int result))
                        return ((char)result).ToString();
                    return string.Empty;
                });
        }

19 Source : StringExtensions.cs
with MIT License
from appsonsf

private static string[] GenerateParreplacedionKeys()
        {
            var keys = new List<string>(36);
            for (int i = 48; i < 58; i++)
            {
                keys.Add(((char)i).ToString());
            }
            for (int i = 97; i < 123; i++)
            {
                keys.Add(((char)i).ToString());
            }
            return keys.ToArray();
        }

19 Source : CommHelper.cs
with MIT License
from aprilyush

public static string UpperFirst(string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            return input.First().ToString().ToUpper() + input.Substring(1);
        }

19 Source : CommHelper.cs
with MIT License
from aprilyush

public static string ToPinYin(string chrstr)
        {
            var returnstr = string.Empty;
            var nowchar = chrstr.ToCharArray();
            foreach (var t in nowchar)
            {
                var array = Encoding.Default.GetBytes(t.ToString());
                int i1 = array[0];
                int i2 = array[1];
                var chrasc = i1 * 256 + i2 - 65536;
                if (chrasc > 0 && chrasc < 160)
                {
                    returnstr += t;
                }
                else
                {
                    for (var i = (Pyvalue.Length - 1); i >= 0; i--)
                    {
                        if (Pyvalue[i] <= chrasc)
                        {
                            returnstr += Pystr[i];
                            break;
                        }
                    }
                }
            }
            return returnstr;
        }

19 Source : DirectoryUtils.cs
with MIT License
from aprilyush

public static void MoveDirectory(string srcDirectoryPath, string destDirectoryPath, bool isOverride)
        {
            //如果提供的路径中不存在末尾分隔符,则添加末尾分隔符。
            if (!srcDirectoryPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                srcDirectoryPath += Path.DirectorySeparatorChar;
            }
            if (!destDirectoryPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                destDirectoryPath += Path.DirectorySeparatorChar;
            }

            //如果目标目录不存在,则予以创建。 
            CreateDirectoryIfNotExists(destDirectoryPath);

            //从当前父目录中获取目录列表。 
            foreach (var srcDir in GetDirectoryPaths(srcDirectoryPath))
            {
                var directoryName = PathUtils.GetDirectoryName(srcDir, false);

                var destDir = destDirectoryPath + directoryName;
                //如果该目录不存在,则创建该目录。 
                CreateDirectoryIfNotExists(destDir);
                //由于我们处于递归模式下,因此还要复制子目录
                MoveDirectory(srcDir, destDir, isOverride);
            }

            //从当前父目录中获取文件。
            foreach (var srcFile in GetFilePaths(srcDirectoryPath))
            {
                var srcFileInfo = new FileInfo(srcFile);
                var destFileInfo = new FileInfo(srcFile.Replace(srcDirectoryPath, destDirectoryPath));
                //如果文件不存在,则进行复制。 
                var isExists = destFileInfo.Exists;
                if (isOverride)
                {
                    if (isExists)
                    {
                        FileUtils.DeleteFileIfExists(destFileInfo.FullName);
                    }
                    FileUtils.CopyFile(srcFileInfo.FullName, destFileInfo.FullName);
                }
                else if (!isExists)
                {
                    FileUtils.CopyFile(srcFileInfo.FullName, destFileInfo.FullName);
                }
            }
        }

19 Source : CsvFeatureSerializer.cs
with MIT License
from ar1st0crat

public async Task SerializeAsync(Stream stream, string format = "0.00000", string timeFormat = "0.000")
        {
            var comma = _delimiter.ToString();

            using (var writer = new StreamWriter(stream))
            {
                if (_names != null)
                {
                    var names = string.Join(comma, _names);
                    var header = _timeMarkers is null ? $"{names}" : $"time_pos{comma}{names}";
                    await writer.WriteLineAsync(header).ConfigureAwait(false);
                }

                if (_timeMarkers is null)
                {
                    foreach (var vector in _vectors)
                    {
                        var line = string.Join(comma, vector.Select(f => f.ToString(format, CultureInfo.InvariantCulture)));

                        await writer.WriteLineAsync(line).ConfigureAwait(false);
                    }
                }
                else
                {
                    for (var i = 0; i < _vectors.Count; i++)
                    {
                        var line = string.Format("{0}{1}{2}",
                                             _timeMarkers[i].ToString(timeFormat, CultureInfo.InvariantCulture),
                                             comma,
                                             string.Join(comma, _vectors[i].Select(f => f.ToString(format, CultureInfo.InvariantCulture))));

                        await writer.WriteLineAsync(line).ConfigureAwait(false);
                    }
                }
            }
        }

19 Source : TransferFunction.cs
with MIT License
from ar1st0crat

public void ToCsv(Stream stream, char delimiter = ',')
        {
            using (var writer = new StreamWriter(stream))
            {
                var content = string.Join(delimiter.ToString(), Numerator.Select(k => k.ToString(CultureInfo.InvariantCulture)));
                writer.WriteLine(content);

                content = string.Join(delimiter.ToString(), Denominator.Select(k => k.ToString(CultureInfo.InvariantCulture)));
                writer.WriteLine(content);
            }
        }

19 Source : StringExtensions.cs
with MIT License
from Aragas

public static string Last(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (str.Length > 0)
                {
                    var index = str.Length - 1;
                    return str[index].ToString();
                }
            }

            return string.Empty;
        }

19 Source : UIController.cs
with Apache License 2.0
from araobp

void OnTextInput(char c)
        {
            canvasGroup.alpha = 1f;
            text.text = c.ToString();
            timeTransition = 0;
        }

19 Source : SelectPathViewModel.cs
with MIT License
from arasplm

public void Navigate(IList<DirectoryItemViewModel> currenreplacedems, List<string> pathList)
		{
			var currentPath = pathList.FirstOrDefault();
			if (!string.IsNullOrEmpty(currentPath))
			{

				var currentDirectory = currenreplacedems.FirstOrDefault(di => di.Name.Replace(Path.DirectorySeparatorChar.ToString(), string.Empty) == currentPath);
				if (currentDirectory != null)
				{
					currentDirectory.Expand();
					currentDirectory.IsExpanded = true;
					currentDirectory.IsSelected = true;
					pathList.Remove(currentPath);
					Navigate(currentDirectory.Children, pathList);
				}
			}
		}

19 Source : RegexLexer.cs
with MIT License
from arbelatech

protected override IEnumerable<Token> GetTokensUnprocessed(string text)
        {
            var rules = GetStateRules();
            int pos = 0;
            var stateStack = new Stack<string>(50);
            stateStack.Push("root");
            var currentStateRules = rules[stateStack.Peek()];

            while (true)
            {
                bool found = false;
                foreach (var rule in currentStateRules)
                {
                    var m = rule.Regex.Match(text, pos);
                    if (m.Success)
                    {
                        var context = new RegexLexerContext(pos, m, stateStack, rule.TokenType);
                        Debug.replacedert(m.Index == pos, $"Regex \"{rule.Regex}\" should have matched at position {pos} but matched at {m.Index}");

                        var tokens = rule.Action.Execute(context);

                        foreach (var token in tokens)
                            yield return token;

                        pos = context.Position;
                        currentStateRules = rules[stateStack.Peek()];
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    if (pos >= text.Length)
                        break;

                    if (text[pos] == '\n')
                    {
                        stateStack.Clear();
                        stateStack.Push("root");
                        currentStateRules = rules["root"];
                        yield return new Token(pos, TokenTypes.Text, "\n");
                        pos++;
                        continue;
                    }

                    yield return new Token(pos, TokenTypes.Error, text[pos].ToString());
                    pos++;
                }
            }


        }

19 Source : RegenUtil.cs
with MIT License
from architdate

public static IEnumerable<StringInstruction>? GetEncounterFilters(IEnumerable<string> lines)
        {
            var valid = lines.Where(z => z.StartsWith(EncounterFilterPrefix.ToString()));
            if (valid.Count() == 0)
                return null;
            var cleaned = valid.Select(z => z.TrimStart(EncounterFilterPrefix));
            var filters = StringInstruction.GetFilters(cleaned).ToArray();
            BatchEditing.ScreenStrings(filters);
            return filters;
        }

19 Source : MonthlyAmrPlot.cs
with GNU General Public License v3.0
from architecture-building-systems

private void RenderMonthLabelsBuildingsRow(Graphics graphics, RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            var textHeight = GH_FontServer.MeasureString(months, BoldFont).Height;
            var x = bounds.Left;
            var columnWidth = bounds.Width / 12;
            foreach (var m in months)
            {
                var monthBounds = new RectangleF(x, bounds.Y, columnWidth, textHeight);
                graphics.DrawString(m.ToString(), BoldFont, TextBrush, monthBounds, format);
                x += columnWidth;
            }
        }

19 Source : MonthlyAmrPlot.cs
with GNU General Public License v3.0
from architecture-building-systems

private void RenderMonthLabelsSystemsRow(Graphics graphics, RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            var textHeight = GH_FontServer.MeasureString(months, BoldFont).Height;
            var x = bounds.Left;
            var columnWidth = bounds.Width / 12;
            foreach (var m in months)
            {
                var monthBounds = new RectangleF(x, bounds.Bottom - textHeight, columnWidth, textHeight);
                graphics.DrawString(m.ToString(), BoldFont, TextBrush, monthBounds, format);
                x += columnWidth;
            }
        }

19 Source : SnakeCaseNamingPolicy.cs
with MIT License
from Archomeda

public override string ConvertName(string name) =>
            string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) ? $"_{x}" : x.ToString())).ToLowerInvariant();

19 Source : GlitchingCharAnimation.cs
with MIT License
from arcusmaximus

public override void Apply(replacedLine line, replacedSection section, float t)
        {
            if (t > 0 && t < 1)
                section.Text = GetRandomChar().ToString();
        }

19 Source : HangmanGame.cs
with MIT License
from ardalis

public void Guess(char guessChar)
        {
            // TODO: Consider using Ardalis.GuardClauses
            // TODO: Consider returning Ardalis.Result
            if (char.IsWhiteSpace(guessChar)) throw new InvalidGuessException("Guess cannot be blank.");
            if (!Regex.IsMatch(guessChar.ToString(), "^[A-Z]$")) throw new InvalidGuessException("Guess must be a capital letter A through Z");
            if (IsOver) throw new InvalidGuessException("Can't make guesses after game is over.");

            if (PreviousGuesses.Any(g => g == guessChar)) throw new DuplicateGuessException();

            PreviousGuesses.Add(guessChar);

            if (_secretWord.IndexOf(guessChar) >= 0)
            {
                if (!CurrentMaskedWord.Contains(_maskChar))
                {
                    Result = GameResult.Won;
                }
                return;
            }

            if(GuessesRemaining <= 0)
            {
                Result = GameResult.Lost;
            }
        }

19 Source : LabelByChildAttributeDrawer.cs
with MIT License
from arimger

private GUIContent GetLabelByValue(SerializedProperty property, GUIContent label)
        {
            switch (property.propertyType)
            {
                case SerializedPropertyType.Generic:
                    break;
                case SerializedPropertyType.Integer:
                    label.text = property.intValue.ToString();
                    break;
                case SerializedPropertyType.Boolean:
                    label.text = property.boolValue.ToString();
                    break;
                case SerializedPropertyType.Float:
                    label.text = property.floatValue.ToString();
                    break;
                case SerializedPropertyType.String:
                    label.text = property.stringValue;
                    break;
                case SerializedPropertyType.Color:
                    label.text = property.colorValue.ToString();
                    break;
                case SerializedPropertyType.ObjectReference:
                    label.text = property.objectReferenceValue ? property.objectReferenceValue.name : "null";
                    break;
                case SerializedPropertyType.LayerMask:
                    switch (property.intValue)
                    {
                        case 0:
                            label.text = "Nothing";
                            break;
                        case ~0:
                            label.text = "Everything";
                            break;
                        default:
                            label.text = LayerMask.LayerToName((int)Mathf.Log(property.intValue, 2));
                            break;
                    }
                    break;
                case SerializedPropertyType.Enum:
                    label.text = property.enumNames[property.enumValueIndex];
                    break;
                case SerializedPropertyType.Vector2:
                    label.text = property.vector2Value.ToString();
                    break;
                case SerializedPropertyType.Vector3:
                    label.text = property.vector3Value.ToString();
                    break;
                case SerializedPropertyType.Vector4:
                    label.text = property.vector4Value.ToString();
                    break;
                case SerializedPropertyType.Rect:
                    label.text = property.rectValue.ToString();
                    break;
                case SerializedPropertyType.Character:
                    label.text = ((char)property.intValue).ToString();
                    break;
                case SerializedPropertyType.Bounds:
                    label.text = property.boundsValue.ToString();
                    break;
                case SerializedPropertyType.Quaternion:
                    label.text = property.quaternionValue.ToString();
                    break;
                default:
                    break;
            }

            return label;
        }

19 Source : Program.cs
with MIT License
from arminreiter

public static string CreateCsv(List<Meter> meters)
        {
            StringBuilder sb = new StringBuilder();

            string[] columns = new string[] {
                "MeterId", "MeterName", "MeterCategory", "MeterSubCategory",
                "Unit", "MeterTags", "MeterRegion", "MeterRates", "EffectiveDate",
                "IncludedQuanreplacedy", "MeterStatus"
            };

            sb.AppendLine(string.Join(SEP.ToString(), columns));

            meters.ForEach(x =>
            {
                string meterRates = string.Join(SEP.ToString(), x.MeterRates.Select(y => " [ " + y.Key.ToString() + " : " + y.Value.ToString() + " ]"));
                string meterTags = string.Join(SEP.ToString(), x.MeterTags);
                sb.AppendLine($"{x.MeterId}{SEP}{x.MeterName}{SEP}{x.MeterCategory}{SEP}{x.MeterSubCategory}{SEP}{x.Unit}{SEP}\"{meterTags}\"{SEP}{x.MeterRegion}{SEP}\"{meterRates}\"{SEP}{x.EffectiveDate}{SEP}{x.IncludedQuanreplacedy}{SEP}{x.MeterStatus}");
            });

            return sb.ToString();
        }

19 Source : Program.cs
with MIT License
from arminreiter

public static string CreateCsv(List<UsageValue> data)
        {
            StringBuilder sb = new StringBuilder();

            string[] columns = new string[]
            {
                "id", "name", "type",
                "properties/subscriptionId", "properties/usageStartTime", "properties/usageEndTime",
                "properties/meterName", "properties/meterCategory", "properties/unit",
                "properties/instanceData", "properties/meterId", "properties/MeterRegion",
                "properties/quanreplacedy", "properties/infoFields"
            };

            string header = string.Join(SEP.ToString(), columns);
            sb.AppendLine(header);

            data.ForEach(x =>
            {
                string[] values = new string[]
                {
                    x.Id, x.Name, x.Type,
                    x.Properties.SubscriptionId, x.Properties.UsageStartTime, x.Properties.UsageEndTime,
                    x.Properties.MeterName, x.Properties.MeterCategory,x.Properties.Unit,
                    x.Properties.InstanceDataRaw, x.Properties.MeterId, x.Properties.MeterRegion,
                    x.Properties.Quanreplacedy.ToString(), JsonConvert.SerializeObject(x.Properties.InfoFields)
                };

                sb.AppendLine(string.Join(SEP.ToString(), values));
            });

            return sb.ToString();
        }

19 Source : StringExtensions.cs
with GNU General Public License v3.0
from Artentus

public static string Capitalize(this string s, CultureInfo culture)
        {
            if (string.IsNullOrWhiteSpace(s)) return s;
            else if (s.Length == 1) return char.ToUpper(s[0], culture).ToString();
            else return char.ToUpper(s[0], culture).ToString() + s.Substring(1);
        }

19 Source : TraceLoggerPlus.cs
with GNU General Public License v3.0
from ASCOMInitiative

private string MakePrintable(string message)
        {
            string printableMessage = "";
            int charNo;

            // Present any unprintable characters in [0xHH] format
            foreach (char c in message)
            {
                charNo = (int)c;
                switch (charNo)
                {
                    case int i when i == 10 && RespectCrLf: // Handle carriage return and line feed as "printable" characters if "Respect CrLf" is enabled
                    case int j when j == 13 && RespectCrLf:
                        {
                            printableMessage += c.ToString();
                            break;
                        }

                    case int i when (i >= 0 && i <= 31) || i == 127: // Represent "non-printable" characters as hex codes
                        {
                            printableMessage += "[" + charNo.ToString("X2") + "]";
                            break;
                        }

                    default: // Handle everything else as "printable" characters 
                        {
                            printableMessage += c.ToString();
                            break;
                        }
                }
            }
            return printableMessage; // Return the formatted printable message
        }

19 Source : Lexer.cs
with GNU General Public License v2.0
from Asixa

public static Token Scan()
        {
            //remove spaces
            for (; !stream_reader.EndOfStream; ReadChar())
            {
                if (peek == ' ' || peek == '\t')
                {
                }
                else if (peek == '\r')
                {
                    ReadChar();
                    ++line;
                    ch = 0;
                }
                else break;
            }

            if (stream_reader.EndOfStream) return null;

            //remove comments
            if (peek == '/')
            {
                ReadChar();
                switch (peek)
                {
                    case '/':
                        for (;; ReadChar())
                            if (peek == '\r' || peek == '\uffff')
                                return Scan();
                    case '*':
                        for (ReadChar();; ReadChar())
                        {
                            switch (peek)
                            {
                                case '\r':
                                    line++;
                                    ch = 0;
                                    ReadChar();
                                    break;
                                case '*':
                                    ReadChar();
                                    if (peek == '/')
                                    {
                                        ReadChar();
                                        return Scan();
                                    }

                                    break;
                                case '\uffff':
                                    return Scan();
                            }
                        }
                }

                return new Token(TT.SLASH, "/");
            }

            //Operators
            switch (peek)
            {
                case '+': return ReadChar('=') ? Plusreplacedign : Plus;
                case '-': return ReadChar('=') ? Minusreplacedign : Minus;
                case '*': return ReadChar('=') ? Timereplacedign : Time;
                case '/': return ReadChar('=') ? Devidereplacedign : Devide;
                case '&': return ReadChar('&') ? And : BitAnd;
                case '|': return ReadChar('|') ? Or : BitInOr;
                case '=': return ReadChar('=') ? Equal : replacedign;
                case '!': return ReadChar('=') ? NotEqual : Not;
                case '<': return ReadChar('=') ? LessEqual : Less;
                case '>': return ReadChar('=') ? GreaterEqual : Greater;
                case '%': return ReadChar('=') ? Moldingreplacedign : Molding;
                case ':': return ReadChar(':') ?null: Colon;
                case ';':
                    ReadChar(); return Semicolon;
                case ',': ReadChar(); return Comma;
                case '(': ReadChar(); return LeftParentheses;
                case ')': ReadChar(); return RightParentheses;
                case '{': ReadChar(); return LeftBraces;
                case '}': ReadChar(); return RightBraces;
                case '[': ReadChar(); return LeftSquareBracket;
                case ']': ReadChar(); return RightSquareBracket;
                case '.': ReadChar(); return Dot;
                case '#': ReadChar(); return Preprocessor;
                case '^': ReadChar(); return BitExOr;
                case '~': ReadChar(); return Tilde;
            }

            //Digits
            if (char.IsDigit(peek))
            {
                var val = 0;
                do
                {
                    val = 10 * val + (peek - '0');
                    ReadChar();
                } while (char.IsDigit(peek));

                if (peek != '.') return new Token(TT.INTCONSTANT, val.ToString());

                float float_val = val;
                for (float d = 10;; d *= 10)
                {
                    ReadChar();
                    if (!char.IsDigit(peek)) break;
                    float_val += (peek - 48) / d;
                }

                return new Token(TT.FLOATCONSTANT, float_val.ToString(CultureInfo.InvariantCulture));
            }

            //Identifiers
            
            if (char.IsLetter(peek) || peek == '_')
            {
                var s = "";
                do
                {
                    s += peek;
                    ReadChar();
                } while (char.IsLetterOrDigit(peek)||peek=='_');

                //GLSL identifiers starts with "gl_" or contains "__" is not allowed
                if (s.Length >= 3)
                {
                    if (s.Substring(0, 3).ToLower() == "gl_") Error(4);
                    if (s.Contains("__")) Error(3);
                }
                return new Token(Keywords.ContainsKey(s) ? Keywords[s] : TT.IDENTIFIER, s);
            }

           return new Token(TT.UNEXPECTED,peek.ToString());
        }

19 Source : PhysicalFileSystem.cs
with Apache License 2.0
from aspnet

private static string GetFullRoot(string root)
        {
            var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            var fullRoot = Path.GetFullPath(Path.Combine(applicationBase, root));
            if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                // When we do matches in GetFullPath, we want to only match full directory names.
                fullRoot += Path.DirectorySeparatorChar; 
            }
            return fullRoot;
        }

19 Source : DualWriter.cs
with Apache License 2.0
from aspnet

public override void Write(char value)
        {
            InternalWrite(value.ToString());
            Writer2.Write(value);
        }

19 Source : DualWriter.cs
with Apache License 2.0
from aspnet

public override Task WriteAsync(char value)
        {
            InternalWrite(value.ToString());
            return Writer2.WriteAsync(value);
        }

19 Source : TraceTextWriter.cs
with Apache License 2.0
from aspnet

public override void Write(char value)
        {
            Write(value.ToString());
        }

19 Source : KeyPerFileConfigBuilder.cs
with MIT License
from aspnet

public override string GetValue(string key)
        {
            string filename = key;
            if (!String.IsNullOrEmpty(KeyDelimiter))
                filename = filename.Replace(KeyDelimiter, Path.DirectorySeparatorChar.ToString());

            if (!String.IsNullOrWhiteSpace(IgnorePrefix))
            {
                foreach (var pathPart in filename.Split(new char[] { Path.DirectorySeparatorChar })) {
                    if (pathPart.StartsWith(IgnorePrefix, StringComparison.OrdinalIgnoreCase))
                        return null;
                }
            }

            return ReadValueFromFile(Path.Combine(DirectoryPath, filename));
        }

19 Source : GetWidthOfTextDynamically.cs
with MIT License
from aspose-pdf

public static void Run()
        {
            //ExStart: GetWidthOfTextDynamically
            // The path to the doreplacedents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Aspose.Pdf.Text.Font font = FontRepository.FindFont("Arial");
            TextState ts = new TextState();
            ts.Font = font;
            ts.FontSize = 14;

            if (Math.Abs(font.MeasureString("A", 14) - 9.337) > 0.001)
                Console.WriteLine("Unexpected font string measure!");

            if (Math.Abs(ts.MeasureString("z") - 7.0) > 0.001)
                Console.WriteLine("Unexpected font string measure!");

            for (char c = 'A'; c <= 'z'; c++)
            {
                double fnMeasure = font.MeasureString(c.ToString(), 14);
                double tsMeasure = ts.MeasureString(c.ToString());

                if (Math.Abs(fnMeasure - tsMeasure) > 0.001)
                    Console.WriteLine("Font and state string measuring doesn't match!");
            }
            //ExEnd: GetWidthOfTextDynamically
        }

19 Source : StrToSet.cs
with MIT License
from ASStoredProcedures

private static string[] MDXSplit(string sMDX, char cDelimiter)
        {
            int iPos = 0;
            int iLastSplit = 0;
            bool bInBracket = false;
            string sDelimiter = cDelimiter.ToString();
            System.Collections.Generic.List<string> arrSplits = new System.Collections.Generic.List<string>();
            while (iPos < sMDX.Length)
            {
                if (bInBracket)
                {
                    if (sMDX.Substring(iPos, 1) == "]")
                    {
                        if (sMDX.Length > iPos + 1 && sMDX.Substring(iPos, 2) != "]]")
                        {
                            bInBracket = false;
                        }
                        else
                        {
                            iPos += 1;
                        }
                    }
                }
                else
                {
                    if (sMDX.Substring(iPos, 1) == "[")
                    {
                        bInBracket = true;
                    }
                    else if (sMDX.Substring(iPos, 1) == sDelimiter)
                    {
                        arrSplits.Add(sMDX.Substring(iLastSplit, iPos - iLastSplit));
                        iLastSplit = iPos + 1;
                    }
                }
                iPos++;
            }
            iPos = sMDX.Length;
            if (!string.IsNullOrEmpty(sMDX))
                arrSplits.Add(sMDX.Substring(iLastSplit, iPos - iLastSplit));
            return arrSplits.ToArray();
        }

19 Source : Utils.cs
with MIT License
from Assistant

public static void OpenFolder(string location)
        {
            if (!location.EndsWith(Path.DirectorySeparatorChar.ToString())) location += Path.DirectorySeparatorChar;
            if (Directory.Exists(location))
            {
                try
                {
                    Process.Start(new System.Diagnostics.ProcessStartInfo()
                    {
                        FileName = location,
                        UseShellExecute = true,
                        Verb = "open"
                    });
                    return;
                }
                catch { }
            }
            MessageBox.Show($"{string.Format((string)Application.Current.FindResource("Utils:CannotOpenFolder"), location)}.");
        }

19 Source : DefaultState.cs
with MIT License
from ASStoredProcedures

public ITokenizerState Exec(char currentChar, int position, string statement, ref StringBuilder token, List<Token> tokens)
        {
            if (char.IsWhiteSpace(currentChar))
            {
                if (token.Length > 0)
                {
                    tokens.Add(new Token(token.ToString()));
                    token = new StringBuilder();
                }
                return new WhiteSpaceState();
            }
            if (InStringState.IsStringDelimiter(currentChar))
            {
                return new InStringState();
            }
            if (InCommentState.IsCommentStart(currentChar,position>0?statement[position-1]:'\x0000'))
            {
                return new InCommentState(statement.Substring(position-1,2));
            }
            switch (currentChar)
            {
                case '(':
                case ')':
                case '[':
                case ']':
                case '=': // an equals sign that is not inside string quotes should trigger a new token
                case ',': // add commas to their own token
       
                    if (token.Length > 0)
                    {
                        tokens.Add(new Token(token.ToString()));
                        token = new StringBuilder();
                    }
                    tokens.Add(new Token(currentChar.ToString(),TokenType.Comma));
                    break;
                default:
                    //else add the current char to the string builder
                    token.Append(currentChar);
                    break;
            }
            return this; // stay in default state
        }

19 Source : KeyValue.cs
with MIT License
from Astropilot

public string ReadToken(out bool wasQuoted, out bool wasConditional)
        {
            wasQuoted = false;
            wasConditional = false;

            while (true)
            {
                EatWhiteSpace();

                if (EndOfStream)
                {
                    return null;
                }

                if (!EatCPPComment())
                {
                    break;
                }
            }

            if (EndOfStream)
            {
                return null;
            }

            char next = (char)Peek();
            if (next == '"')
            {
                wasQuoted = true;

                // "
                Read();

                var sb = new StringBuilder();
                while (!EndOfStream)
                {
                    if (Peek() == '\\')
                    {
                        Read();

                        char escapedChar = (char)Read();
                        if (s_escapedMapping.TryGetValue(escapedChar, out char replacedChar))
                        {
                            sb.Append(replacedChar);
                        }
                        else
                        {
                            sb.Append(escapedChar);
                        }

                        continue;
                    }

                    if (Peek() == '"')
                    {
                        break;
                    }

                    sb.Append((char)Read());
                }

                // "
                Read();

                return sb.ToString();
            }

            if (next == '{' || next == '}')
            {
                Read();
                return next.ToString();
            }

            bool bConditionalStart = false;
            int count = 0;
            var ret = new StringBuilder();
            while (!EndOfStream)
            {
                next = (char)Peek();

                if (next == '"' || next == '{' || next == '}')
                {
                    break;
                }

                if (next == '[')
                {
                    bConditionalStart = true;
                }

                if (next == ']' && bConditionalStart)
                {
                    wasConditional = true;
                }

                if (char.IsWhiteSpace(next))
                {
                    break;
                }

                if (count < 1023)
                {
                    ret.Append(next);
                }
                else
                {
                    throw new Exception("ReadToken overflow");
                }

                Read();
            }

            return ret.ToString();
        }

See More Examples