string.IndexOfAny(char[])

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

515 Examples 7

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

static string ReplaceInvalidFilenameChars(string candidate) {
			var invalidChars = Path.GetInvalidFileNameChars();
			if (candidate.IndexOfAny(invalidChars) < 0)
				return candidate;
			var sb = new System.Text.StringBuilder();
			foreach (var c in candidate) {
				if (Array.IndexOf(invalidChars, c) >= 0)
					sb.Append('-');
				else
					sb.Append(c);
			}
			return sb.ToString();
		}

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

public static string Before(this string str, params char[] c)
        {
            int pos = str.IndexOfAny(c);
            if(pos == -1) {
                return null;
            }

            return str.Substring(0, pos);
        }

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

private static void DownloadAvatars(IIdenreplacedyManagementService2 idenreplacedyService, string outputAvatarsDir, IEnumerable<string> commiters)
		{
			var invalidFileChars = new []{'\\', ',', '/', '<', '>', '?', '|', ':', '*'};

			var searchCommiters1 = new string[1];
			foreach (var commiter in commiters)
			{
				if(string.IsNullOrEmpty(commiter) || commiter.IndexOfAny(invalidFileChars) >= 0)
					continue;

				var imagePath = Path.Combine(outputAvatarsDir, commiter + ".png");
				if (File.Exists(imagePath))
				{
					if ((DateTime.Now - File.GetLastWriteTime(imagePath)).TotalHours < 24)
						continue;

					// File is expired
					File.Delete(imagePath);
				}

				searchCommiters1[0] = commiter;
				var idenreplacedies = idenreplacedyService.ReadIdenreplacedies(IdenreplacedySearchFactor.DisplayName,
					searchCommiters1, MembershipQuery.Expanded, ReadIdenreplacedyOptions.ExtendedProperties);

				if (idenreplacedies == null || !idenreplacedies.Any()) 
					continue;

				foreach (var idenreplacedy in idenreplacedies[0])
				{
					object imageData;
					if (!idenreplacedy.TryGetProperty("Microsoft.TeamFoundation.Idenreplacedy.Image.Data", out imageData))
						continue;

					var imageBytes = imageData as byte[];
					if (imageBytes == null)
						continue;

					//			var imageFormat = GetImageFormat(imageBytes);
					//			Trace.WriteLine(imageFormat);
					File.WriteAllBytes(imagePath, imageBytes);
					
					break;
				}
			}
		}

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

public static string FormatChance(this double chance)
        {
            if (chance == 1)
            {
                return "100%";
            }
            if (chance == 0)
            {
                return "0%";
            }
            double r = (chance * 100);
            string p = r.ToString("F99").TrimEnd('0');
            if (!p.StartsWith("0."))
            {
                int extra = 2;
                if (p.IndexOf(".0") > -1 || p.EndsWith("."))
                {
                    extra = 0;
                }
                return p.Substring(0, p.IndexOf('.') + extra) + "%";
            }
            int i = p.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });
            if (i < 0)
            {
                return "0%";
            }
            return p.Substring(0, i + 1) + "%";
        }

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

public static DateTime ToDateTime(string dateValue)
        {
            if (string.IsNullOrEmpty(dateValue))
            {
                return new DateTime();
            }

            var date = dateValue.Trim();
            // ReSharper disable once InconsistentNaming
            const string DateDelimiters = @"-.\/_ ";
            char[] c = DateDelimiters.ToCharArray();
            int d2 = date.LastIndexOfAny(c);
            int d1 = date.IndexOfAny(c);

            try
            {
                string year = string.Empty;
                string month = string.Empty;
                string day = string.Empty;
                if (date.Length > d2 + 1)
                {
                    year = date.Substring(d2 + 1);
                }
                if (date.Length > (d1 + 1) && (d2 - d1 - 1) < date.Length - (d1 + 1))
                {
                    month = date.Substring(d1 + 1, d2 - d1 - 1);
                }
                if (date.Length > 0 && d1 <= date.Length)
                {
                    day = date.Substring(0, d1);
                }
                return new DateTime(
                    Convert.ToInt32(year, CultureInfo.InvariantCulture),
                    Convert.ToInt32(month, CultureInfo.InvariantCulture),
                    Convert.ToInt32(day, CultureInfo.InvariantCulture));
            }
            catch (ArgumentOutOfRangeException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (FormatException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (OverflowException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
        }

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

public static bool IsValidFileName(string fileName)
        {
            return  !string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
        }

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

public static string ResolvePath(String rootPath, String relativePath)
        {
            ArgUtil.NotNullOrEmpty(rootPath, nameof(rootPath));
            ArgUtil.NotNullOrEmpty(relativePath, nameof(relativePath));

            if (!Path.IsPathRooted(rootPath))
            {
                throw new ArgumentException($"{rootPath} should be a rooted path.");
            }

            if (relativePath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid path characters.");
            }
            else if (Path.GetFileName(relativePath).IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
            {
                throw new InvalidOperationException($"{relativePath} contains invalid folder name characters.");
            }
            else if (Path.IsPathRooted(relativePath))
            {
                throw new InvalidOperationException($"{relativePath} can not be a rooted path.");
            }
            else
            {
                rootPath = rootPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

                // Root the path
                relativePath = String.Concat(rootPath, Path.AltDirectorySeparatorChar, relativePath);

                // Collapse ".." directories with their parent, and skip "." directories.
                String[] split = relativePath.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
                var segments = new Stack<String>(split.Length);
                Int32 skip = 0;
                for (Int32 i = split.Length - 1; i >= 0; i--)
                {
                    String segment = split[i];
                    if (String.Equals(segment, ".", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    else if (String.Equals(segment, "..", StringComparison.Ordinal))
                    {
                        skip++;
                    }
                    else if (skip > 0)
                    {
                        skip--;
                    }
                    else
                    {
                        segments.Push(segment);
                    }
                }

                if (skip > 0)
                {
                    throw new InvalidOperationException($"The file path {relativePath} is invalid");
                }

#if OS_WINDOWS
                if (segments.Count > 1)
                {
                    return String.Join(Path.DirectorySeparatorChar, segments);
                }
                else
                {
                    return segments.Pop() + Path.DirectorySeparatorChar;
                }
#else
                return Path.DirectorySeparatorChar + String.Join(Path.DirectorySeparatorChar, segments);
#endif
            }
        }

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

public override void PrintActionDetails(ActionRunStage stage)
        {

            if (stage == ActionRunStage.Post)
            {
                throw new NotSupportedException("Script action should not have 'Post' job action.");
            }

            Inputs.TryGetValue("script", out string contents);
            contents = contents ?? string.Empty;
            if (Action.Type == Pipelines.ActionSourceType.Script)
            {
                var firstLine = contents.TrimStart(' ', '\t', '\r', '\n');
                var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
                if (firstNewLine >= 0)
                {
                    firstLine = firstLine.Substring(0, firstNewLine);
                }

                ExecutionContext.Output($"##[group]Run {firstLine}");
            }
            else
            {
                throw new InvalidOperationException($"Invalid action type {Action.Type} for {nameof(ScriptHandler)}");
            }

            var multiLines = contents.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
            foreach (var line in multiLines)
            {
                // Bright Cyan color
                ExecutionContext.Output($"\x1b[36;1m{line}\x1b[0m");
            }

            string argFormat;
            string shellCommand;
            string shellCommandPath = null;
            bool validateShellOnHost = !(StepHost is ContainerStepHost);
            string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
            string shell = null;
            if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
            {
                // TODO: figure out how defaults interact with template later
                // for now, we won't check job.defaults if we are inside a template.
                if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
                {
                    runDefaults.TryGetValue("shell", out shell);
                }
            }
            if (string.IsNullOrEmpty(shell))
            {
#if OS_WINDOWS
                shellCommand = "pwsh";
                if (validateShellOnHost)
                {
                    shellCommandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
                    if (string.IsNullOrEmpty(shellCommandPath))
                    {
                        shellCommand = "powershell";
                        Trace.Info($"Defaulting to {shellCommand}");
                        shellCommandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
                    }
                }
#else
                shellCommand = "sh";
                if (validateShellOnHost)
                {
                    shellCommandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
                }
#endif
                argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
            }
            else
            {
                var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
                shellCommand = parsed.shellCommand;
                if (validateShellOnHost)
                {
                    shellCommandPath = WhichUtil.Which(parsed.shellCommand, true, Trace, prependPath);
                }

                argFormat = $"{parsed.shellArgs}".TrimStart();
                if (string.IsNullOrEmpty(argFormat))
                {
                    argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
                }
            }

            if (!string.IsNullOrEmpty(shellCommandPath))
            {
                ExecutionContext.Output($"shell: {shellCommandPath} {argFormat}");
            }
            else
            {
                ExecutionContext.Output($"shell: {shellCommand} {argFormat}");
            }

            if (this.Environment?.Count > 0)
            {
                ExecutionContext.Output("env:");
                foreach (var env in this.Environment)
                {
                    ExecutionContext.Output($"  {env.Key}: {env.Value}");
                }
            }

            ExecutionContext.Output("##[endgroup]");
        }

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

protected String TrimDisplayString(String displayString)
        {
            var firstLine = displayString.TrimStart(' ', '\t', '\r', '\n');
            var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
            if (firstNewLine >= 0)
            {
                firstLine = firstLine.Substring(0, firstNewLine);
            }
            return firstLine;
        }

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

private static string FormatStepName(string prefix, string stepName)
        {
            if (string.IsNullOrEmpty(stepName))
            {
                return string.Empty;
            }

            var result = stepName.TrimStart(' ', '\t', '\r', '\n');
            var firstNewLine = result.IndexOfAny(new[] { '\r', '\n' });
            if (firstNewLine >= 0)
            {
                result = result.Substring(0, firstNewLine);
            }
            return $"{prefix}{result}";
        }

19 View Source File : FileLoggerProcessor.cs
License : MIT License
Project Creator : adams85

private async ValueTask WriteEntryAsync(LogFileInfo logFile, FileLogEntry entry, CancellationToken cancellationToken)
        {
            const int checkFileState = 0;
            const int tryOpenFileState = 1;
            const int retryOpenFileState = 2;
            const int writeState = 3;
            const int idleState = 4;

            int state = checkFileState;
            IFileInfo fileInfo = null;
            for (; ; )
                switch (state)
                {
                    case checkFileState:
                        try
                        {
                            if (UpdateFilePath(logFile, entry, cancellationToken) && logFile.IsOpen)
                                logFile.Close();

                            if (!logFile.IsOpen)
                            {
                                // GetFileInfo behavior regarding invalid filenames is inconsistent across .NET runtimes (and operating systems?)
                                // e.g. PhysicalFileProvider returns NotFoundFileInfo in .NET 5 but throws an exception in previous versions on Windows
                                fileInfo = logFile.FileAppender.FileProvider.GetFileInfo(Path.Combine(logFile.BasePath, logFile.CurrentPath));
                                state = tryOpenFileState;
                            }
                            else
                                state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            // discarding entry when file path is invalid
                            if (logFile.CurrentPath.IndexOfAny(s_invalidPathChars.Value) >= 0)
                                return;

                            state = idleState;
                        }
                        break;
                    case tryOpenFileState:
                        try
                        {
                            logFile.Open(fileInfo);

                            state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            state = retryOpenFileState;
                        }
                        break;
                    case retryOpenFileState:
                        try
                        {
                            await logFile.FileAppender.EnsureDirAsync(fileInfo, cancellationToken).ConfigureAwait(false);
                            logFile.Open(fileInfo);

                            state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            // discarding entry when file path is invalid
                            if (logFile.CurrentPath.IndexOfAny(s_invalidPathChars.Value) >= 0)
                                return;

                            state = idleState;
                        }
                        break;
                    case writeState:
                        try
                        {
                            try
                            {
                                if (logFile.ShouldEnsurePreamble)
                                    await logFile.EnsurePreambleAsync(cancellationToken).ConfigureAwait(false);

                                await logFile.WriteBytesAsync(logFile.Encoding.GetBytes(entry.Text), cancellationToken).ConfigureAwait(false);

                                if (logFile.AccessMode == LogFileAccessMode.KeepOpenAndAutoFlush)
                                    logFile.Flush();
                            }
                            finally
                            {
                                if (logFile.AccessMode == LogFileAccessMode.OpenTemporarily)
                                    logFile.Close();
                            }

                            return;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            state = idleState;
                        }
                        break;
                    case idleState:
                        // discarding failed entry on forced complete
                        if (Context.WriteRetryDelay > TimeSpan.Zero)
                            await Task.Delay(Context.WriteRetryDelay, cancellationToken).ConfigureAwait(false);
                        else
                            cancellationToken.ThrowIfCancellationRequested();

                        state = checkFileState;
                        break;
                }

            void ReportFailure(LogFileInfo logFile, FileLogEntry entry, Exception exception)
            {
                Context.ReportDiagnosticEvent(new FileLoggerDiagnosticEvent.LogEntryWriteFailed(this, logFile, entry, exception));
            }
        }

19 View Source File : ValidFolderName.cs
License : MIT License
Project Creator : AiursoftWeb

public override bool IsValid(object value)
        {
            if (value is string val)
            {
                return
                    val.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
                    !string.IsNullOrWhiteSpace(val);
            }
            return false;
        }

19 View Source File : JPath.cs
License : MIT License
Project Creator : akaskela

private object ParseValue()
        {
            char currentChar = _expression[_currentIndex];
            if (currentChar == '\'')
            {
                return ReadQuotedString();
            }
            else if (char.IsDigit(currentChar) || currentChar == '-')
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(currentChar);

                _currentIndex++;
                while (_currentIndex < _expression.Length)
                {
                    currentChar = _expression[_currentIndex];
                    if (currentChar == ' ' || currentChar == ')')
                    {
                        string numberText = sb.ToString();

                        if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
                        {
                            double d;
                            if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
                            {
                                return d;
                            }
                            else
                            {
                                throw new JsonException("Could not read query value.");
                            }
                        }
                        else
                        {
                            long l;
                            if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
                            {
                                return l;
                            }
                            else
                            {
                                throw new JsonException("Could not read query value.");
                            }
                        }
                    }
                    else
                    {
                        sb.Append(currentChar);
                        _currentIndex++;
                    }
                }
            }
            else if (currentChar == 't')
            {
                if (Match("true"))
                {
                    return true;
                }
            }
            else if (currentChar == 'f')
            {
                if (Match("false"))
                {
                    return false;
                }
            }
            else if (currentChar == 'n')
            {
                if (Match("null"))
                {
                    return null;
                }
            }

            throw new JsonException("Could not read query value.");
        }

19 View Source File : JsonPosition.cs
License : MIT License
Project Creator : akaskela

internal void WriteTo(StringBuilder sb)
        {
            switch (Type)
            {
                case JsonContainerType.Object:
                    string propertyName = PropertyName;
                    if (propertyName.IndexOfAny(SpecialCharacters) != -1)
                    {
                        sb.Append(@"['");
                        sb.Append(propertyName);
                        sb.Append(@"']");
                    }
                    else
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append('.');
                        }

                        sb.Append(propertyName);
                    }
                    break;
                case JsonContainerType.Array:
                case JsonContainerType.Constructor:
                    sb.Append('[');
                    sb.Append(Position);
                    sb.Append(']');
                    break;
            }
        }

19 View Source File : FormatExpressionBuilder.cs
License : MIT License
Project Creator : alethic

static bool ValidateIdnHostname(string value)
        {
            return IdnHostnameRegex.IsMatch(value) && value.IndexOfAny(DisallowedIdnChars) == -1 && TryGetIdnAsciiString(value, out var idn) && idn.Split('.').All(i => i.Length <= 63);
        }

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

private static string urlDecode (string s, Encoding encoding)
    {
      if (s == null)
        return null;

      if (s.IndexOfAny (new[] { '%', '+' }) == -1)
        return s;

      try {
        return HttpUtility.UrlDecode (s, encoding);
      }
      catch {
        return null;
      }
    }

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

public void AddService<TBehavior> (
      string path, Action<TBehavior> initializer
    )
      where TBehavior : WebSocketBehavior, new ()
    {
      if (path == null)
        throw new ArgumentNullException ("path");

      if (path.Length == 0)
        throw new ArgumentException ("An empty string.", "path");

      if (path[0] != '/')
        throw new ArgumentException ("Not an absolute path.", "path");

      if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
        var msg = "It includes either or both query and fragment components.";
        throw new ArgumentException (msg, "path");
      }

      path = path.TrimSlashFromEnd ();

      lock (_sync) {
        WebSocketServiceHost host;
        if (_hosts.TryGetValue (path, out host))
          throw new ArgumentException ("Already in use.", "path");

        host = new WebSocketServiceHost<TBehavior> (
                 path, () => new TBehavior (), initializer, _log
               );

        if (!_clean)
          host.KeepClean = false;

        if (_waitTime != host.WaitTime)
          host.WaitTime = _waitTime;

        if (_state == ServerState.Start)
          host.Start ();

        _hosts.Add (path, host);
      }
    }

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

public bool TryGetServiceHost (string path, out WebSocketServiceHost host)
    {
      if (path == null)
        throw new ArgumentNullException ("path");

      if (path.Length == 0)
        throw new ArgumentException ("An empty string.", "path");

      if (path[0] != '/')
        throw new ArgumentException ("Not an absolute path.", "path");

      if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
        var msg = "It includes either or both query and fragment components.";
        throw new ArgumentException (msg, "path");
      }

      return InternalTryGetServiceHost (path, out host);
    }

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

[Obsolete ("This method will be removed. Use added one instead.")]
    public void AddWebSocketService<TBehavior> (
      string path, Func<TBehavior> creator
    )
      where TBehavior : WebSocketBehavior
    {
      if (path == null)
        throw new ArgumentNullException ("path");

      if (creator == null)
        throw new ArgumentNullException ("creator");

      if (path.Length == 0)
        throw new ArgumentException ("An empty string.", "path");

      if (path[0] != '/')
        throw new ArgumentException ("Not an absolute path.", "path");

      if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
        var msg = "It includes either or both query and fragment components.";
        throw new ArgumentException (msg, "path");
      }

      _services.Add<TBehavior> (path, creator);
    }

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

public bool RemoveService (string path)
    {
      if (path == null)
        throw new ArgumentNullException ("path");

      if (path.Length == 0)
        throw new ArgumentException ("An empty string.", "path");

      if (path[0] != '/')
        throw new ArgumentException ("Not an absolute path.", "path");

      if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
        var msg = "It includes either or both query and fragment components.";
        throw new ArgumentException (msg, "path");
      }

      path = path.TrimSlashFromEnd ();

      WebSocketServiceHost host;
      lock (_sync) {
        if (!_hosts.TryGetValue (path, out host))
          return false;

        _hosts.Remove (path);
      }

      if (host.State == ServerState.Start)
        host.Stop (1001, String.Empty);

      return true;
    }

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

private static string urlDecode (string s, Encoding encoding)
    {
      return s.IndexOfAny (new[] { '%', '+' }) > -1
             ? HttpUtility.UrlDecode (s, encoding)
             : s;
    }

19 View Source File : BaseEngine.cs
License : MIT License
Project Creator : angelsix

protected void ProcessInlineTag(FileProcessingData data, FileOutputData output, string inlineData, Match match)
        {
            // No error to start with
            data.Error = string.Empty;

            // Profile name
            string profileName = null;

            // If the name starts with : then left half is the profile name
            if (inlineData[0] == ':')
            {
                // Set profile path
                // Find first index of a space or newline
                profileName = inlineData.Substring(1, inlineData.IndexOfAny(new[] { ' ', '\r', '\n' }) - 1);

                // Set inline data (+2 to exclude the space after the profile name and the starting :
                inlineData = inlineData.Substring(profileName.Length + 2);
            }

            // NOTE: A blank profile should be included for everything
            //       A ! means only include if no specific profile name is given
            //       Anything else is the a profile name so should only include if matched

            // If the profile is blank, always include it
            if (string.IsNullOrEmpty(profileName) ||
                // Or if we specify ! only include it if the specified profile is  blank
                (profileName == "!" && string.IsNullOrEmpty(output.ProfileName)) ||
                // Or if the profile name matches include it
                output.ProfileName.EqualsIgnoreCase(profileName))
            {
                // Replace the tag with the contents
                ReplaceTag(output, match, inlineData, removeNewline: false);
            }
            // Remove include tag and finish
            else
            {
                ReplaceTag(output, match, string.Empty);
            }
        }

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

private bool ValidateKeyword(string keyword, string file, int errorline)
		{
			bool validateresult;
			
			// Check if key is an empty string
			if(keyword == "")
			{
				// ERROR: Missing key name in statement
				if(errorline > -1) RaiseError(file, errorline, ERROR_replacedIGNINVALID);
				validateresult = false;
			}
			else
			{
				// Check if there are spaces in the key
				if(keyword.IndexOfAny(" ".ToCharArray()) > -1)
				{
					// ERROR: Spaces not allowed in key names
					if(errorline > -1) RaiseError(file, errorline, ERROR_replacedIGNINVALID);
					validateresult = false;
				}
				else
				{
					// Key OK
					validateresult = true;
				}
			}
			
			// Return result
			return validateresult;
		}

19 View Source File : WindowsNameTransform.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : ZipNameTransform.cs
License : GNU General Public License v3.0
Project Creator : anydream

public static bool IsValidName(string name)
		{
			bool result =
				(name != null) &&
				(name.IndexOfAny(InvalidEntryChars) < 0) &&
				(name.IndexOf('/') != 0)
				;
			return result;
		}

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

static string MakeValidName(string name, char replacement)
		{
			int 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();
			}

			if (name.Length > 0xffff) {
				throw new PathTooLongException();
			}

			return name;
		}

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

public static bool IsValidName(string name, bool relaxed)
		{
			bool result = (name != null);

			if (result) {
				if (relaxed) {
					result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0;
				} else {
					result =
						(name.IndexOfAny(InvalidEntryChars) < 0) &&
						(name.IndexOf('/') != 0);
				}
			}

			return result;
		}

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

static bool NameIsValid(string name)
		{
			return !string.IsNullOrEmpty(name) &&
				(name.IndexOfAny(Path.GetInvalidPathChars()) < 0);
		}

19 View Source File : Options.cs
License : MIT License
Project Creator : aolszowka

private OptionValueType ParsePrototype ()
		{
			char type = '\0';
			List<string> seps = new List<string> ();
			for (int i = 0; i < names.Length; ++i) {
				string name = names [i];
				if (name.Length == 0)
					throw new ArgumentException ("Empty option names are not supported.", "prototype");

				int end = name.IndexOfAny (NameTerminator);
				if (end == -1)
					continue;
				names [i] = name.Substring (0, end);
				if (type == '\0' || type == name [end])
					type = name [end];
				else 
					throw new ArgumentException (
							string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
							"prototype");
				AddSeparators (name, end, seps);
			}

			if (type == '\0')
				return OptionValueType.None;

			if (count <= 1 && seps.Count != 0)
				throw new ArgumentException (
						string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
						"prototype");
			if (count > 1) {
				if (seps.Count == 0)
					this.separators = new string[]{":", "="};
				else if (seps.Count == 1 && seps [0].Length == 0)
					this.separators = null;
				else
					this.separators = seps.ToArray ();
			}

			return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
		}

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

protected internal void SetAddress(string address)
        {
            address = address.Trim();
            if (Utils.ConvertUtil._invariantCompareInfo.IsPrefix(address, "'") || Utils.ConvertUtil._invariantCompareInfo.IsPrefix(address, "["))
            {
                //int pos = address.IndexOf("'", 1);
                //while (pos < address.Length && address[pos + 1] == '\'')
                //{
                //    pos = address.IndexOf("'", pos + 2);
                //}
                //var wbws = address.Substring(1, pos - 1).Replace("''", "'");
                SetWbWs(address);
                //_address = address.Substring(pos + 2);
            }
            else
            {
                _address = address;
            }

            _addresses = null;
            if (_address.IndexOfAny(new char[] {',','!', '['}) > -1)
            {
                //Advanced address. Including Sheet or multi or table.
                ExtractAddress(_address);
            }
            else
            {
                //Simple address
                GetRowColFromAddress(_address, out _fromRow, out _fromCol, out _toRow, out  _toCol, out _fromRowFixed, out _fromColFixed,  out _toRowFixed, out _toColFixed);
                _start = null;
                _end = null;
            }
            _address = address;
            Validate();
        }

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

public string GetRelativePathOnDisk(string path, string rootDir, bool isFile)
        {
            if (isFile && !File.Exists(path) || !isFile && !Directory.Exists(path)) return null;

            path = Path.GetFullPath(path);
            rootDir = Path.GetFullPath(rootDir);

            var dir = isFile ? Path.GetDirectoryName(path) : path;
            if (!IsSameOrSubDirectory(rootDir, dir))
                throw new Exception("Path Needs To Be A Sub-Directory Of RootDir! PLEASE CHECK CODE!");

            var pathUri = new Uri(path);
            var referenceUri = new Uri(rootDir);
            var relativePath = referenceUri.MakeRelativeUri(pathUri).ToString();
            var firstPathIndex = relativePath.IndexOfAny(new[] {Path.PathSeparator, Path.AltDirectorySeparatorChar});
            if (firstPathIndex >= 0) relativePath = relativePath.Substring(firstPathIndex + 1);

            return relativePath;
        }

19 View Source File : UserSecretsConfigBuilder.cs
License : MIT License
Project Creator : aspnet

private string GetSecretsFileFromId(string secretsId)
        {
            // The common VS scenario will leave this Id attribute empty, or as a place-holding token. In that case,
            // go look up the user secrets id from the magic file.
            if (String.IsNullOrWhiteSpace(secretsId) || secretsId.Equals("${UserSecretsId}", StringComparison.InvariantCultureIgnoreCase))
            {
                // The magic file should be deployed in our codebase
                string codebase = System.Reflection.replacedembly.GetExecutingreplacedembly().CodeBase;
                string localpath = new Uri(codebase).LocalPath;
                string magicId = File.ReadAllText(localpath + ".UserSecretsId.txt");

                if (!String.IsNullOrWhiteSpace(magicId))
                {
                    secretsId = magicId.Trim();
                }
            }

            // Make sure the identifier is legal for file paths.
            int badCharIndex = secretsId.IndexOfAny(Path.GetInvalidFileNameChars());
            if (badCharIndex != -1)
            {
                throw new InvalidOperationException($"Invalid character '{secretsId[badCharIndex]}' in '{userSecretsIdTag}'.");
            }

            // Try Windows-style first
            string root = Environment.GetEnvironmentVariable("APPDATA");
            if (!String.IsNullOrWhiteSpace(root))
                return Path.Combine(root, "Microsoft", "UserSecrets", secretsId, "secrets.xml");

            // Then try unix-style
            root = Environment.GetEnvironmentVariable("HOME");
            if (!String.IsNullOrWhiteSpace(root))
                return Path.Combine(root, ".microsoft", "usersecrets", secretsId, "secrets.xml");

            return null;
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : atifaziz

internal static bool TryParseParameter (string parameter, out string processor, out string directive, out string name, out string value)
        {
            processor = directive = name = value = "";

            int start = 0;
            int end = parameter.IndexOfAny (new [] { '=', '!' });
            if (end < 0)
                return false;

            //simple format n=v
            if (parameter [end] == '=') {
                name = parameter.Substring (start, end);
                value = parameter.Substring (end + 1);
                return !string.IsNullOrEmpty (name);
            }

            //official format, p!d!n!v
            processor = parameter.Substring (start, end);

            start = end + 1;
            end = parameter.IndexOf ('!', start);
            if (end < 0) {
                //unlike official version, we allow you to omit processor/directive
                name = processor;
                value = parameter.Substring (start);
                processor = "";
                return !string.IsNullOrEmpty (name);
            }

            directive = parameter.Substring (start, end - start);


            start = end + 1;
            end = parameter.IndexOf ('!', start);
            if (end < 0) {
                //we also allow you just omit the processor
                name = directive;
                directive = processor;
                value = parameter.Substring (start);
                processor = "";
                return !string.IsNullOrEmpty (name);
            }

            name = parameter.Substring (start, end - start);
            value = parameter.Substring (end + 1);

            return !string.IsNullOrEmpty (name);
        }

19 View Source File : NDesk.Options.cs
License : Apache License 2.0
Project Creator : atifaziz

private OptionValueType ParsePrototype ()
		{
			char type = '\0';
			List<string> seps = new List<string> ();
			for (int i = 0; i < names.Length; ++i) {
				string name = names [i];
				if (name.Length == 0)
					throw new ArgumentException ("Empty option names are not supported.", "prototype");

				int end = name.IndexOfAny (NameTerminator);
				if (end == -1)
					continue;
				names [i] = name.Substring (0, end);
				if (type == '\0' || type == name [end])
					type = name [end];
				else
					throw new ArgumentException (
							string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
							"prototype");
				AddSeparators (name, end, seps);
			}

			if (type == '\0')
				return OptionValueType.None;

			if (count <= 1 && seps.Count != 0)
				throw new ArgumentException (
						string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
						"prototype");
			if (count > 1) {
				if (seps.Count == 0)
					this.separators = new string[]{":", "="};
				else if (seps.Count == 1 && seps [0].Length == 0)
					this.separators = null;
				else
					this.separators = seps.ToArray ();
			}

			return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
		}

19 View Source File : Options.cs
License : MIT License
Project Creator : atifaziz

private OptionValueType ParsePrototype ()
        {
            char type = '\0';
            List<string> seps = new List<string> ();
            for (int i = 0; i < names.Length; ++i) {
                string name = names [i];
                if (name.Length == 0)
                    throw new ArgumentException ("Empty option names are not supported.", "prototype");

                int end = name.IndexOfAny (NameTerminator);
                if (end == -1)
                    continue;
                names [i] = name.Substring (0, end);
                if (type == '\0' || type == name [end])
                    type = name [end];
                else
                    throw new ArgumentException (
                            string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
                            "prototype");
                AddSeparators (name, end, seps);
            }

            if (type == '\0')
                return OptionValueType.None;

            if (count <= 1 && seps.Count != 0)
                throw new ArgumentException (
                        string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
                        "prototype");
            if (count > 1) {
                if (seps.Count == 0)
                    this.separators = new string[]{":", "="};
                else if (seps.Count == 1 && seps [0].Length == 0)
                    this.separators = null;
                else
                    this.separators = seps.ToArray ();
            }

            return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
        }

19 View Source File : WalletNameViewModel.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public override void Next()
        {
            if (string.IsNullOrEmpty(WalletName)) {
                Warning = Resources.CwvEmptyWalletName;
                return;
            }

            if (WalletName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1 ||
                WalletName.IndexOf('.') != -1) {
                Warning = Resources.CwvInvalidWalletName;
                return;
            }

            var pathToWallet = $"{WalletInfo.CurrentWalletDirectory}/{WalletName}/{WalletInfo.DefaultWalletFileName}";

            try
            {
                var _ = Path.GetFullPath(pathToWallet);
            }
            catch (Exception)
            {
                Warning = Resources.CwvInvalidWalletName;
                return;
            }

            if (File.Exists(pathToWallet)) {
                Warning = Resources.CwvWalletAlreadyExists;
                return;
            }

            StepData.PathToWallet = pathToWallet;

            RaiseOnNext(StepData);
        }

19 View Source File : ApplEnv.cs
License : GNU General Public License v3.0
Project Creator : audiamus

private static string getCompanyFileName () {
      string company = replacedemblyCompany;
      if (string.IsNullOrEmpty (company))
        company = "misc";
      if (company.IndexOfAny (INVALID_CHARS) >= 0)
        foreach (char c in INVALID_CHARS)
          company.Replace (c, ' ');
      company = company.Replace (' ', '_');
      return company;
    }

19 View Source File : CognitoPasswordValidator.cs
License : Apache License 2.0
Project Creator : aws

public async Task<IdenreplacedyResult> ValidateAsync(UserManager<CognitoUser> manager, CognitoUser user, string preplacedword)
        {
            // Retrieve the preplacedword policy set by the user's user pool
            var preplacedwordPolicy = await user.UserPool.GetPreplacedwordPolicyTypeAsync().ConfigureAwait(false);

            var errorDescriber = new IdenreplacedyErrorDescriber();
            var errors = new List<IdenreplacedyError>();

            if (preplacedword.Length < preplacedwordPolicy.MinimumLength)
            {
                errors.Add(errorDescriber.PreplacedwordTooShort(preplacedwordPolicy.MinimumLength));
            }

            if (!preplacedword.Any(char.IsLower) && preplacedwordPolicy.RequireLowercase)
            {
                errors.Add(errorDescriber.PreplacedwordRequiresLower());
            }

            if (!preplacedword.Any(char.IsUpper) && preplacedwordPolicy.RequireUppercase)
            {
                errors.Add(errorDescriber.PreplacedwordRequiresUpper());
            }

            if (!preplacedword.Any(char.IsNumber) && preplacedwordPolicy.RequireNumbers)
            {
                errors.Add(errorDescriber.PreplacedwordRequiresDigit());
            }

            var preplacedwordContainsASymbol = preplacedword.IndexOfAny(CognitoSymbols) >= 0;
            if (!preplacedwordContainsASymbol && preplacedwordPolicy.RequireSymbols)
            {
                errors.Add(errorDescriber.PreplacedwordRequiresNonAlphanumeric());
            }

            if (errors.Count > 0)
            {
                return IdenreplacedyResult.Failed(errors.ToArray());
            }
            else
            {
                return IdenreplacedyResult.Success;
            }
        }

19 View Source File : FastZip.cs
License : MIT License
Project Creator : ay2015

static bool NameIsValid(string name)
		{
			return (name != null) &&
				(name.Length > 0) &&
				(name.IndexOfAny(Path.GetInvalidPathChars()) < 0);
		}

19 View Source File : ZipNameTransform.cs
License : MIT License
Project Creator : ay2015

static string MakeValidName(string name, char replacement)
		{
			int index = name.IndexOfAny(InvalidEntryChars);
			if (index >= 0) {
				StringBuilder 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();
			}

			if (name.Length > 0xffff) {
				throw new PathTooLongException();
			}

			return name;
		}

19 View Source File : WindowsNameTransform.cs
License : MIT License
Project Creator : ay2015

public static string MakeValidName(string name, char replacement)
		{
			if ( name == null ) {
				throw new ArgumentNullException("name");
			}
			
			name = WindowsPathUtils.DropPathRoot(name.Replace("/", @"\"));

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

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

			// Convert consecutive \\ characters to \
			int index = name.IndexOf(@"\\");
			while (index >= 0) {
				name = name.Remove(index, 1);
				index = name.IndexOf(@"\\");
			}

			// Convert any invalid characters using the replacement one.
			index = name.IndexOfAny(InvalidEntryChars);
			if (index >= 0) {
				StringBuilder 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 View Source File : ZipNameTransform.cs
License : MIT License
Project Creator : ay2015

public static bool IsValidName(string name, bool relaxed)
		{
			bool result = (name != null);

			if ( result ) {
				if ( relaxed ) {
					result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0;
				}
				else {
					result = 
						(name.IndexOfAny(InvalidEntryChars) < 0) &&
						(name.IndexOf('/') != 0);
				}
			}

			return result;
		}

19 View Source File : ZipNameTransform.cs
License : MIT License
Project Creator : ay2015

public static bool IsValidName(string name)
		{
			bool result = 
				(name != null) &&
				(name.IndexOfAny(InvalidEntryChars) < 0) &&
				(name.IndexOf('/') != 0)
				;
			return result;
		}

19 View Source File : JsonDocumentPath.cs
License : MIT License
Project Creator : azambrano

private bool TryParseValue(out object? value)
        {
            char currentChar = _expression[_currentIndex];
            if (currentChar == '\'')
            {
                value = ReadQuotedString();
                return true;
            }
            else if (char.IsDigit(currentChar) || currentChar == '-')
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(currentChar);

                _currentIndex++;
                while (_currentIndex < _expression.Length)
                {
                    currentChar = _expression[_currentIndex];
                    if (currentChar == ' ' || currentChar == ')')
                    {
                        string numberText = sb.ToString();

                        if (numberText.IndexOfAny(FloatCharacters) != -1)
                        {
                            bool result = double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var d);
                            value = d;
                            return result;
                        }
                        else
                        {
                            bool result = long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var l);
                            value = l;
                            return result;
                        }
                    }
                    else
                    {
                        sb.Append(currentChar);
                        _currentIndex++;
                    }
                }
            }
            else if (currentChar == 't')
            {
                if (Match("true"))
                {
                    value = true;
                    return true;
                }
            }
            else if (currentChar == 'f')
            {
                if (Match("false"))
                {
                    value = false;
                    return true;
                }
            }
            else if (currentChar == 'n')
            {
                if (Match("null"))
                {
                    value = null;
                    return true;
                }
            }
            else if (currentChar == '/')
            {
                value = ReadRegexString();
                return true;
            }

            value = null;
            return false;
        }

19 View Source File : CSVFileSink.cs
License : MIT License
Project Creator : azist

private static string escape(string str)
    {
      if (str==null) return string.Empty;

      bool needsQuotes = str.IndexOfAny(new char[] { ' ', ',', '\n', '\r', '"' }) >= 0;

      str = str.Replace("\n", @"\n");
      str = str.Replace("\r", @"\r");
      str = str.Replace("\"", "\"\"");

      return needsQuotes ? "\"" + str + "\"" : str;
    }

19 View Source File : CSVWriter.cs
License : MIT License
Project Creator : azist

private static string escape(string str, char del)
      {
        bool needsQuotes = str.IndexOfAny(new char[] {'\n', '\r', '"', del}) >= 0;

        str = str.Replace("\"", "\"\"");

        return needsQuotes ? "\"" + str + "\"" : str;
      }

19 View Source File : ProgramBody.cs
License : MIT License
Project Creator : azist

public static void Main(string[] args)
    {
      const string deffmt = "yyyyMMddHHmmss";

      if ((args.Length > 0) && (args[0] == "/?"))
      {
        ConsoleColor cForeground = Console.ForegroundColor;
        ConsoleColor cBackground = Console.BackgroundColor;

        Console.ForegroundColor = ConsoleColor.White;
        Console.BackgroundColor = ConsoleColor.Black;
        Console.WriteLine();
        Console.WriteLine("Date/Time Utility");
        Console.WriteLine("Returns system data time in a specified format");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("Copyright (c) 2020 Azist Group");
        Console.WriteLine("Version 3.0 / Azos as of Oct 2018");
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Magenta;
        Console.WriteLine(" Usage:");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("    getdatetime [format] ([[{+/-},{part spec},{num}]/[{=,{part spec},{num}]]) ");
        Console.WriteLine(" ");
        Console.WriteLine("    [format] - standard .net date/time formatting pattern");
        Console.WriteLine("     \"" + deffmt + "\" will be used if no [format] param supplied");
        Console.WriteLine(" ");
        Console.WriteLine("    (modifier) - optional, allows to alter date time, may be repeated, evaluated from left to right");

        Console.WriteLine(" ");
        Console.WriteLine("    Shift Modifier:");
        Console.WriteLine("     [{+/-},{part spec},{num}] - allows to shift date time");
        Console.WriteLine("       {+/-}  add/subtract ");
        Console.WriteLine("       {part spec}  date/time part to change ");
        Console.WriteLine("       {num}  value of change (integer) ");
        Console.WriteLine(" ");

        Console.WriteLine("    Set Modifier:");
        Console.WriteLine("     [{=},{part spec},{num}] - allows to set date time part to a specific value");
        Console.WriteLine("       {=}  set ");
        Console.WriteLine("       {part spec}  date/time part to change ");
        Console.WriteLine("       {num}  new value (integer)");
        Console.WriteLine(" ");

        Console.WriteLine("    part spec:");
        Console.WriteLine("       {m/d/y/h/i/s} ");
        Console.WriteLine("           m  - month ");
        Console.WriteLine("           d  - day ");
        Console.WriteLine("           y  - year ");
        Console.WriteLine("           h  - hour ");
        Console.WriteLine("           i  - minute ");
        Console.WriteLine("           s  - second ");
        Console.WriteLine(" ");
        Console.WriteLine(" ");
        Console.ForegroundColor = ConsoleColor.Magenta;
        Console.WriteLine(" Example:");
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine(" ");
        Console.WriteLine("  getdatetime yyyyMMddHHmmss  -,d,15");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("   returns date and time 15 days ago from current system date time stamp");
        Console.WriteLine(" ");

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("  getdatetime yyyyMMddHHmmss  -,d,15 =,h,1 =,i,0 =,s,0");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("   returns date 15 days ago from current system date, time is set to 1:00 AM ");

        Console.ForegroundColor = cForeground;
        Console.BackgroundColor = cBackground;

        return;
      }//help


      string fmt = deffmt;
      DateTime dt = DateTime.Now;


      try
      {

        for (int i = 0; i < args.Length; i++)
        {
          string arg = args[i].Trim();
          if (arg.Length == 0) continue;// safeguard
          if (args[i].IndexOfAny(new char[] { '+', '-', '=' }) >= 0)
          {
            string[] cmd = args[i].Split(',');
            if (cmd.Length < 3) continue;//safeguard

            int val = int.Parse(cmd[2]);
            string part = cmd[1].Trim().ToLower();

            if (part.Length == 0) continue;//safeguard


            if (cmd[0] == "=") //set
            {
              switch (part)
              {
                case "m": dt = new DateTime(dt.Year, val, dt.Day, dt.Hour, dt.Minute, dt.Second); break;
                case "d": dt = new DateTime(dt.Year, dt.Month, val, dt.Hour, dt.Minute, dt.Second); break;
                case "y": dt = new DateTime(val, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); break;
                case "h": dt = new DateTime(dt.Year, dt.Month, dt.Day, val, dt.Minute, dt.Second); break;
                case "i": dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, val, dt.Second); break;
                case "s": dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, val); break;
                default: throw new Exception("Invalid date time part spec");
              }//switch
            }//set

            if ((cmd[0] == "+") || (cmd[0] == "-")) //set
            {
              if (cmd[0] == "-") val *= -1;
              switch (part)
              {
                case "m": dt = dt.AddMonths(val); break;
                case "d": dt = dt.AddDays(val); break;
                case "y": dt = dt.AddYears(val); break;
                case "h": dt = dt.AddHours(val); break;
                case "i": dt = dt.AddMinutes(val); break;
                case "s": dt = dt.AddSeconds(val); break;
                default: throw new Exception("Invalid date time part spec");
              }//switch
            }//set


          }
          else fmt = args[i];
        }//for

      }//try
      catch (Exception err)
      {
        Console.WriteLine("Error: " + err.Message);
        System.Environment.ExitCode = -1;
        return;
      }//catch



      Console.WriteLine(dt.ToString(fmt));
      System.Environment.ExitCode = 0;
    }

19 View Source File : Replay.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team

private static bool isValid(string fileName)
        {
            return !string.IsNullOrEmpty(fileName) &&
                   fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
        }

19 View Source File : PipeStreamExtens.cs
License : Apache License 2.0
Project Creator : beetlex-io

public static string SubLeftWith(this string span, char[] chars, out string item)
        {
            item = default;
            int index = span.IndexOfAny(chars);
            if (index > 0)
            {
                item = span.Substring(0, index);
                return span.Substring(index + chars.Length);
            }
            return span;
        }

19 View Source File : ProcessingParameters.cs
License : MIT License
Project Creator : bibigone

public bool TrySetMkvPath(string value, [NotNullWhen(returnValue: false)] out string? message)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                message = "Path to MKV file cannot be empty";
                return false;
            }

            value = value.Trim();

            if (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
            {
                message = "Path to MKV file contains some invalid symbols";
                return false;
            }

            if (!File.Exists(value))
            {
                message = "MKV file does not exist.";
                return false;
            }

            var extension = Path.GetExtension(value);
            if (!MKV_FILE_EXTENSION.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
            {
                message = "Path to MKV video is expected";
                return false;
            }

            MkvPath = value;
            message = null;
            return true;
        }

See More Examples