string.Split(char[], System.StringSplitOptions)

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

2664 Examples 7

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

public void Add(Tuple<string, string, int> fileName)
			{
				var extensionless = Path.GetFileNameWithoutExtension(fileName.Item2);

				if (string.IsNullOrEmpty(extensionless))
				{
					throw new ArgumentException("Unable to get file name without extension.", "fileName");
				}

				Add(fileName, extensionless.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries), _rootNodes);
			}

19 View Source File : ReportModel.cs
License : MIT License
Project Creator : advancedmonitoring

public static string MakeReport(string sddl, List<string> SIDs, List<string> rights, bool isIncludeAllow, bool isIncludeDeny, bool translateSID)
        {
            var lines = sddl.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
            var prev = "";
            var sb = new StringBuilder();
            foreach (var line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    var sd = new SecurityDescriptor(line.Trim());
                    if (sd.IsOk)
                    {
                        var r = GetLineForReport(sd, SIDs, rights, isIncludeAllow, isIncludeDeny, translateSID);
                        if (!string.IsNullOrWhiteSpace(r))
                        {
                            if (!string.IsNullOrWhiteSpace(prev))
                                sb.AppendLine(prev);
                            sb.AppendLine(r);
                            sb.AppendLine();
                        }
                        prev = "";
                        continue;
                    }
                    prev = line;
                }
            }

            return sb.ToString();
        }

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 : Versions.cs
License : Apache License 2.0
Project Creator : adamralph

[Fact]
        public static async Task RepoWithHistory()
        {
            // arrange
            var historicalCommands =
@"git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0-beta.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-rc.1
git tag 1.0.0
git checkout -b foo
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1
git commit --allow-empty -m '.'
git checkout main
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-alpha.1
git commit --allow-empty -m '.'
git merge foo --no-edit
git commit --allow-empty -m '.'
git tag 1.1.0-beta.2
git tag 1.1.0-beta.10
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-rc.1
git tag 1.1.0 -a -m '.'";

            var path = MethodBase.GetCurrentMethod().GetTestDirectory();

            await EnsureEmptyRepositoryAndCommit(path);

            foreach (var command in historicalCommands.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var nameAndArgs = command.Split(" ", 2);
                _ = await ReadAsync(nameAndArgs[0], nameAndArgs[1], path);
                await Task.Delay(200);
            }

            // act
            var versionCounts = new Dictionary<string, int>();
            foreach (var sha in await GetCommitShas(path))
            {
                await Checkout(path, sha);

                var version = Versioner.GetVersion(path, default, default, default, default, default, default);
                var versionString = version.ToString();
                var tagName = $"v/{versionString}";

                _ = versionCounts.TryGetValue(versionString, out var oldVersionCount);
                var versionCount = oldVersionCount + 1;
                versionCounts[versionString] = versionCount;

                tagName = versionCount > 1 ? $"v({versionCount})/{versionString}" : tagName;

                await Tag(path, tagName, sha);
            }

            await Checkout(path, "main");

            // replacedert
            await replacedertFile.Contains("../../../versions.txt", await GetGraph(path));
        }

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

public static string Which(string command, bool require = false, ITraceWriter trace = null, string prependPath = null)
        {
            ArgUtil.NotNullOrEmpty(command, nameof(command));
            trace?.Info($"Which: '{command}'");
            if (Path.IsPathFullyQualified(command) && File.Exists(command))
            {
                trace?.Info($"Fully qualified path: '{command}'");
                return command;
            }
            string path = Environment.GetEnvironmentVariable(PathUtil.PathVariable);
            if (string.IsNullOrEmpty(path))
            {
                trace?.Info("PATH environment variable not defined.");
                path = path ?? string.Empty;
            }
            if (!string.IsNullOrEmpty(prependPath))
            {
                path = PathUtil.PrependPath(prependPath, path);
            }

            string[] pathSegments = path.Split(new Char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < pathSegments.Length; i++)
            {
                pathSegments[i] = Environment.ExpandEnvironmentVariables(pathSegments[i]);
            }

            foreach (string pathSegment in pathSegments)
            {
                if (!string.IsNullOrEmpty(pathSegment) && Directory.Exists(pathSegment))
                {
                    string[] matches = null;
#if OS_WINDOWS
                    string pathExt = Environment.GetEnvironmentVariable("PATHEXT");
                    if (string.IsNullOrEmpty(pathExt))
                    {
                        // XP's system default value for PATHEXT system variable
                        pathExt = ".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh";
                    }

                    string[] pathExtSegments = pathExt.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                    // if command already has an extension.
                    if (pathExtSegments.Any(ext => command.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
                    {
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, command);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            trace?.Info($"Location: '{matches.First()}'");
                            return matches.First();
                        }
                    }
                    else
                    {
                        string searchPattern;
                        searchPattern = StringUtil.Format($"{command}.*");
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, searchPattern);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            // add extension.
                            for (int i = 0; i < pathExtSegments.Length; i++)
                            {
                                string fullPath = Path.Combine(pathSegment, $"{command}{pathExtSegments[i]}");
                                if (matches.Any(p => p.Equals(fullPath, StringComparison.OrdinalIgnoreCase)))
                                {
                                    trace?.Info($"Location: '{fullPath}'");
                                    return fullPath;
                                }
                            }
                        }
                    }
#else
                    try
                    {
                        matches = Directory.GetFiles(pathSegment, command);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                        trace?.Verbose(ex.ToString());
                    }

                    if (matches != null && matches.Length > 0)
                    {
                        trace?.Info($"Location: '{matches.First()}'");
                        return matches.First();
                    }
#endif
                }
            }

#if OS_WINDOWS
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'Path' environment variable.");
#else
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'PATH' environment variable.");
#endif
            if (require)
            {
                throw new FileNotFoundException(
                    message: $"{command}: command not found",
                    fileName: command);
            }

            return null;
        }

19 View Source File : PropertyObserver.cs
License : MIT License
Project Creator : Accelerider

public static PropertyObserver Observers(object owner, string expression, Action onChanged)
        {
            return new PropertyObserver(
                (INotifyPropertyChanged)owner,
                new Queue<string>(expression.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)),
                onChanged);
        }

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

private static NameValueCollection ParseExpression(string expression)
		{
			var results = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
			var pairs = expression.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(arg => arg.Trim().Split('='));
			var index = 0;

			foreach (var pair in pairs)
			{
				if (pair.Length > 1)
				{
					results.Add(HttpUtility.UrlDecode(pair[0]), HttpUtility.UrlDecode(pair[1]));
				}
				else if (pair.Length == 1)
				{
					results.Add("_{0}".FormatWith(index), HttpUtility.UrlDecode(pair[0]));
				}

				++index;
			}

			return results;
		}

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

private void CheckParamSfo(ParamSfo sfo)
        {
            replacedle = sfo.Items.FirstOrDefault(i => i.Key == "replacedLE")?.StringValue?.Trim(' ', '\0');
            var replacedleParts = replacedle.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            if (replacedleParts.Length > 1)
                replacedle = string.Join(" ", replacedleParts);
            ProductCode = sfo.Items.FirstOrDefault(i => i.Key == "replacedLE_ID")?.StringValue?.Trim(' ', '\0');
            DiscVersion = sfo.Items.FirstOrDefault(i => i.Key == "VERSION")?.StringValue?.Trim();

            Log.Info($"Game replacedle: {replacedle}");
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public List<int> ToArray(string name)
        {
            var cs = GetValue(name);
            if (string.IsNullOrWhiteSpace(cs))
            {
                return null;
            }
            var css = cs.Trim('[', ']').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return css.Length > 0 ? css.Select(int.Parse).ToList() : null;
        }

19 View Source File : ExtensionMethods.cs
License : Apache License 2.0
Project Creator : A7ocin

public static int WordCount(this String str)
            {
                  return str.Split(new char[] { ' ', '.', '?' }, 
                  StringSplitOptions.RemoveEmptyEntries).Length;
            }

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

private void GetDacWithFieldTags(ITextSnapshot newSnapshot, string bqlCommand, int offset)
		{
			var matches = RegExpressions.DacWithFieldRegex.Matches(bqlCommand);

			foreach (Match dacWithFieldMatch in matches)
			{
				string[] dacParts = dacWithFieldMatch.Value.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

				if (dacParts.Length != 2)
					continue;

				GetDacTag(newSnapshot, dacWithFieldMatch, offset, dacParts);
				GetFieldTag(newSnapshot, dacWithFieldMatch, offset, dacParts);
			}	
		}

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

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
			var delimitedString = value as string;
			if (!string.IsNullOrEmpty(delimitedString)) {
				double numberValue;
				var list = new List<double>();
				var numberStrings = delimitedString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (var numberString in numberStrings) {
					if (double.TryParse(numberString, out numberValue))
						list.Add(numberValue);
				}

				return list;
			}

			return base.ConvertFrom(context, culture, value);
		}

19 View Source File : UnityPlayerBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static IEnumerable<string> SplitSceneList(string sceneList)
        {
            return from scene in sceneList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                   select scene.Trim();
        }

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

public static string MakeRelativePath(string path, string basePath)
        {
            List<string> pathElements =
                new List<string>(path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));
            List<string> basePathElements =
                new List<string>(basePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));

            if (!basePath.EndsWith("\\", StringComparison.Ordinal) && basePathElements.Count > 0)
            {
                basePathElements.RemoveAt(basePathElements.Count - 1);
            }

            // Find first part of paths that don't match
            int i = 0;
            while (i < Math.Min(pathElements.Count - 1, basePathElements.Count))
            {
                if (pathElements[i].ToUpperInvariant() != basePathElements[i].ToUpperInvariant())
                {
                    break;
                }

                ++i;
            }

            // For each remaining part of the base path, insert '..'
            StringBuilder result = new StringBuilder();
            if (i == basePathElements.Count)
            {
                result.Append(@".\");
            }
            else if (i < basePathElements.Count)
            {
                for (int j = 0; j < basePathElements.Count - i; ++j)
                {
                    result.Append(@"..\");
                }
            }

            // For each remaining part of the path, add the path element
            for (int j = i; j < pathElements.Count - 1; ++j)
            {
                result.Append(pathElements[j]);
                result.Append(@"\");
            }

            result.Append(pathElements[pathElements.Count - 1]);

            // If the target was a directory, put the terminator back
            if (path.EndsWith(@"\", StringComparison.Ordinal))
            {
                result.Append(@"\");
            }

            return result.ToString();
        }

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

private static QualifiedNameSyntax GenerateQualifiedNameSyntax(string fullName)
        {
            return GenerateQualifiedNameSyntax(fullName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries));
        }

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

private static void AppendSortExpressionToQuery(string sortExpression, Action<OrderExpression> action)
		{
			string[] parts = sortExpression.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

			for (int i = 0; i < parts.Length; ++i)
			{
				string part = parts[i].Trim();

				// attribute name and direction are separated by a space, direction is optional
				// attribute1 ascending, attribute2 descending
				string[] pairs = part.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
				OrderExpression order = new OrderExpression();
				order.AttributeName = pairs[0];
				if (pairs.Length > 1 && (pairs[1].StartsWith("desc", StringComparison.InvariantCultureIgnoreCase)))
				{
					order.OrderType = OrderType.Descending;
				}

				action(order);
			}
		}

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

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

            try
            {
                // the message needs to start with the keyword after trim leading space.
                message = message.TrimStart();
                if (!message.StartsWith(_commandKey))
                {
                    return false;
                }

                // Get the index of the separator between the command info and the data.
                int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
                if (endIndex < 0)
                {
                    return false;
                }

                // Get the command info (command and properties).
                int cmdIndex = _commandKey.Length;
                string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);

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

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

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

                command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
                return true;
            }
            catch
            {
                command = null;
                return false;
            }
        }

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

private static string ConvertDirectoryToResourceName(string directory)
		{
			// converting and individual directory
			// for all parts: prepend an '_' if the name starts with a numeric character
			// convert '-' to '_'

			var parts = directory.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

			if (parts.Any())
			{
				var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
				return string.Join(".", partsWithUnderscores.ToArray()).Replace('-', '_');
			}

			return null;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu

public static string[] SplitCommandLine(string commandLine)
        {
            var translatedArguments = new StringBuilder(commandLine);
            var escaped = false;
            for (var i = 0; i < translatedArguments.Length; i++)
            {
                if (translatedArguments[i] == '"')
                {
                    escaped = !escaped;
                }
                if (translatedArguments[i] == ' ' && !escaped)
                {
                    translatedArguments[i] = '\n';
                }
            }

            var toReturn = translatedArguments.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            for (var i = 0; i < toReturn.Length; i++)
            {
                toReturn[i] = RemoveMatchingQuotes(toReturn[i]);
            }
            return toReturn;
        }

19 View Source File : PublicizeInternals.cs
License : MIT License
Project Creator : aelij

public override bool Execute()
        {
            if (SourceReferences == null) throw new ArgumentNullException(nameof(SourceReferences));

            var replacedemblyNames = new HashSet<string>(
                (replacedemblyNames ?? string.Empty).Split(Semicolon, StringSplitOptions.RemoveEmptyEntries),
                StringComparer.OrdinalIgnoreCase);

            if (replacedemblyNames.Count == 0)
            {
                return true;
            }

            var targetPath = Path.Combine(_sourceDir, "obj", "GeneratedPublicizedreplacedemblies");
            Directory.CreateDirectory(targetPath);

            GenerateAttributes(targetPath, replacedemblyNames);

            foreach (var replacedemblyPath in SourceReferences
                .Select(a => Path.GetDirectoryName(GetFullFilePath(a.ItemSpec))))
            {
                _resolver.AddSearchDirectory(replacedemblyPath);
            }

            var targetReferences = new List<ITaskItem>();
            var removedReferences = new List<ITaskItem>();

            foreach (var replacedembly in SourceReferences)
            {
                var replacedemblyPath = GetFullFilePath(replacedembly.ItemSpec);
                var replacedemblyName = Path.GetFileNameWithoutExtension(replacedemblyPath);
                if (replacedemblyNames.Contains(replacedemblyName))
                {
                    // ReSharper disable once replacedignNullToNotNullAttribute
                    var targetreplacedemblyPath = Path.Combine(targetPath, Path.GetFileName(replacedemblyPath));

                    var targetAsemblyFileInfo = new FileInfo(targetreplacedemblyPath);
                    if (!targetAsemblyFileInfo.Exists || targetAsemblyFileInfo.Length == 0)
                    {
                        CreatePublicreplacedembly(replacedemblyPath, targetreplacedemblyPath);
                        Log.LogMessageFromText("Created publicized replacedembly at " + targetreplacedemblyPath, MessageImportance.Normal);
                    }
                    else
                    {
                        Log.LogMessageFromText("Publicized replacedembly already exists at " + targetreplacedemblyPath, MessageImportance.Low);
                    }

                    targetReferences.Add(new TaskItem(targetreplacedemblyPath));
                    removedReferences.Add(replacedembly);
                }
            }

            TargetReferences = targetReferences.ToArray();
            RemovedReferences = removedReferences.ToArray();

            return true;
        }

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

public static void ParseVersion(
            String version,
            out Int32 major,
            out Int32 minor,
            out Int32 patch,
            out String semanticVersion)
        {
            ArgumentUtility.CheckStringForNullOrEmpty(version, "version");

            String[] segments = version.Split(new char[] { '.', '-' }, StringSplitOptions.None);
            if (segments.Length < 3 || segments.Length > 4)
            {
                throw new ArgumentException("wrong number of segments");
            }

            if (!Int32.TryParse(segments[0], out major))
            {
                throw new ArgumentException("major");
            }

            if (!Int32.TryParse(segments[1], out minor))
            {
                throw new ArgumentException("minor");
            }

            if (!Int32.TryParse(segments[2], out patch))
            {
                throw new ArgumentException("patch");
            }

            semanticVersion = null;
            if (segments.Length == 4)
            {
                semanticVersion = segments[3];
            }
        }

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

public static string EnsurePathFormat(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return string.Empty;
            }

            // We always make sure that the path is rooted
            StringBuilder sb = new StringBuilder();
            String[] components = path.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (components.Length == 0)
            {
                return string.Empty;
            }

            for (int i = 0; i < components.Length; i++)
            {
                sb.AppendFormat("{0}{1}", components[i], i == components.Length - 1 ? String.Empty : "/");
            }

            return sb.ToString();
        }

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

private static RectangleF GetCropRectangle(string packedCropRect)
        {
            string[] cropCoords = packedCropRect.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (cropCoords.Length != 4)
            {
                throw new InvalidOperationException("A crop rectangle message argument must have 4 values.");
            }

            float x = float.Parse(cropCoords[0], CultureInfo.InvariantCulture);
            float y = float.Parse(cropCoords[1], CultureInfo.InvariantCulture);
            float width = float.Parse(cropCoords[2], CultureInfo.InvariantCulture);
            float height = float.Parse(cropCoords[3], CultureInfo.InvariantCulture);

            return new RectangleF(x, y, width, height);
        }

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

public static IList GetTrail(object rooreplacedem, string path) {
			// Make sure the specified path is valid
			if (string.IsNullOrEmpty(path))
				return null;

			// If the root element was not preplaceded, then we cannot build a trail
			XmlElement element = rooreplacedem as XmlElement;
			if (null == element)
				return null;

			// Break the path up based on the specified path separator
			string[] pathEntries = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
			if (null == pathEntries || 0 == pathEntries.Length)
				return null;

			// The root element need to be the first path entry, so we will do that comparison first
			string pathEntry = GetPathEntry(element);
			if (0 == string.Compare(pathEntry, pathEntries[0], StringComparison.CurrentCultureIgnoreCase)) {
				// The root element matched, so we can continue to build the trail
				List<XmlElement> trail = new List<XmlElement>(pathEntries.Length);
				trail.Add(element);

				// For the remaining entries in the path, we will search the child nodes for a match at each level. If at any
				//   point we don't find a match, then we will need to cancel the conversion.
				for (int index = 1; index < pathEntries.Length; index++) {
					// Get the first child node and loop through it's siblings until we find a match for the current path
					//   entry
					XmlNode child = element.FirstChild;
					while (null != child) {
						XmlElement childElement = child as XmlElement;
						if (null != childElement) {
							pathEntry = GetPathEntry(childElement);
							if (0 == string.Compare(pathEntry, pathEntries[index], StringComparison.CurrentCultureIgnoreCase))
								break; // Found a match
						}

						// We didn't find a match, so continue with the next sibling (if any)
						child = child.NextSibling;
					}

					// The child variable will now point to the next element in the trail, or to null which indicates at match
					//   was not found.
					element = child as XmlElement;
					if (null != element)
						trail.Add(element);
					else
						return null;
				}

				return trail;
			}

			return null;
		}

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

public static string WildcardToRegex(string pattern)
        {
            if (pattern == null) throw new ArgumentNullException(nameof(pattern));

            // Remove whitespaces
            var items = pattern.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries);
            for(var i=0; i<items.Length; i++)
            {
                items[i] = "^" + Escape(items[i].Trim()).
                 Replace("\\*", ".*").
                 Replace("\\?", ".") + "$";
            }

            return string.Join("|", items);
        }

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

public static IList GetTrail(object rooreplacedem, string path) {
			// Make sure the specified path is valid
			if (string.IsNullOrEmpty(path))
				return null;

			// If the root item was not preplaceded, then we cannot build a trail
			MyComputerData myComputerData = rooreplacedem as MyComputerData;
			if (null == myComputerData)
				return null;

			// Break the path up based on the available path separators
			string[] pathEntries = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
				StringSplitOptions.RemoveEmptyEntries);
			if (null == pathEntries || 0 == pathEntries.Length)
				return null;

			// Start to build the trail
			List<object> trail = new List<object>();
			trail.Add(myComputerData);

			if (0 != string.Compare("My Computer", pathEntries[0], StringComparison.CurrentCultureIgnoreCase)) {
				// For the remaining entries in the path, we will search the child items for a match at each level. If at any
				//   point we don't find a match, then we will need to cancel the conversion.
				//
				if (!Directory.Exists(path))
					return null;

				// The split above will remove the backslash, which we need for the comparison for drives below.
				string driveEntry = pathEntries[0] + "\\";

				// The first entry should be a drive, so we will start there
				DriveData driveData = null;
				for (int driveIndex = 0; driveIndex < myComputerData.Drives.Count; driveIndex++) {
					// Get the next DriveData and see if it's a match, if so the exit the loop
					driveData = myComputerData.Drives[driveIndex];
					if (0 == string.Compare(driveData.Info.Name, driveEntry, StringComparison.CurrentCultureIgnoreCase))
						break;

					// Set to null, because we didn't find a match and we want driveData to be null in that case
					driveData = null;
				}

				// If we found the drive, then add it to the trail and continue. Otherwise, there's a problem and we have
				//   failed to convert.
				if (null != driveData) {
					trail.Add(driveData);

					// See if there are more items, which should be all directories
					if (pathEntries.Length > 1) {

						// We need to get the first directory directly from the drive object
						DirectoryData directoryData = null;
						for (int directoryIndex = 0; directoryIndex < driveData.Directories.Count; directoryIndex++) {
							// Get the next DirectoryData and see if it's a match, if so the exit the loop
							directoryData = driveData.Directories[directoryIndex];
							if (0 == string.Compare(directoryData.Info.Name, pathEntries[1], StringComparison.CurrentCultureIgnoreCase))
								break;

							// Set to null, because we didn't find a match and we want directoryData to be null in that case
							directoryData = null;
						}

						// If we found the directory, then add it to the trail and continue. Otherwise, there's a problem and
						//   we have failed to convert.
						if (null != directoryData) {
							trail.Add(directoryData);

							// We are now looking for the remaining directories, which we can do in this loop
							for (int index = 2; index < pathEntries.Length; index++) {
								bool found = false;
								for (int directoryIndex = 0; directoryIndex < directoryData.Directories.Count; directoryIndex++) {
									// Get the next DirectoryData and see if it's a match, if so the exit the loop
									DirectoryData childDirectoryData = directoryData.Directories[directoryIndex];
									if (0 == string.Compare(childDirectoryData.Info.Name, pathEntries[index], StringComparison.CurrentCultureIgnoreCase)) {
										found = true;
										trail.Add(childDirectoryData);
										directoryData = childDirectoryData;
										break;
									}
								}

								if (!found)
									return null;
							}

							return trail;
						}
					}
					else {
						return trail;
					}
				}
			}
			else {
				return trail;
			}

			return null;
		}

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

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
			var delimitedString = value as string;
			if (!string.IsNullOrEmpty(delimitedString))
				return delimitedString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

			return base.ConvertFrom(context, culture, value);
		}

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

public static List<Process> ParseString(string input) {
            return input.Trim()
                .Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
                .Select((s, i) => Parse(i, s))
                .ToList();
        }

19 View Source File : ProcessNuPropsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (SourceFiles == null)
            {
                Log.LogMessage("No source code available");
                return true; //nothing to process
            }

            //process the source files
            var anyPackageAvailable = false;
            foreach (var sourceFile in SourceFiles)
            {
                var fileNameFull = sourceFile.GetMetadata("FullPath");
                var fileName = new FileInfo(fileNameFull).Name;

                //Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
                var sourceContent = File.ReadAllText(fileNameFull);
                var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //Extract all comments
                var stringBuilder = new StringBuilder();
                foreach (var contentLine in sourceLines)
                {
                    var sourceLine = contentLine.Trim();
                    if (sourceLine.StartsWith("///"))
                    {
                        stringBuilder.AppendLine(sourceLine.Substring(3));
                    }
                }

                //Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
                var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
                //Get NuProp comments
                var nuPropElements = xDoreplacedent.Descendants()
                    .Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();

                if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file

                //Has some NuProp -> process
                //<NuProp.Id></NuProp.Id> - package ID (mandatory)
                //<NuProp.Version></NuProp.Version>   - package version base (major.minor.patch) - optional          
                //<NuProp.Description></NuProp.Description> - package description (optional)
                //<NuProp.Tags></NuProp.Tags> - package tags (optional)
                //<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
                //<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!

                var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
                var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
                var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
                var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();

                var nuPropsIncludes = IncludesEnum.None;
                var nuPropIncludesStr = nuPropElements
                    .FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
                    .Attribute("type")?.Value;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (nuPropIncludesStr)
                {
                    case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
                    case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
                }

                var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();

                if (string.IsNullOrEmpty(nuPropId))
                {
                    Log.LogWarning($"NuProp.Id not found for {fileName}");
                    continue;
                }

                //Build the partial NuSpec file
                anyPackageAvailable = true;
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = fileNameFull + ".partnuspec";
                var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
                var outXDocStrOriginal = outXDoc.ToString();
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
                SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
                SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
                SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set

                GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
                    .Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
                        new XAttribute("include", "cs/**/*.*"),
                        new XAttribute("buildAction", "Compile")));


                //Dependencies
                var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
                if (nuPropUsings.Count > 0)
                {
                    //have some dependencies
                    foreach (var nuPropUsing in nuPropUsings)
                    {
                        // ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
                        var depId = nuPropUsing.Attribute("id").Value;
                        var depVersion = nuPropUsing.Attribute("version")?.Value;
                        var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
                        if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
                        dependencyXElement.Add(new XAttribute("version", depVersion));
                        dependenciesXElement.Add(dependencyXElement);
                    }
                }
                else
                {
                    //Clean dependencies
                    dependenciesXElement.Remove();
                }

                //<files>
                //    < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
                //    < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
                //</ files >
                var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
                files.Add(
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));

                if (nuPropsIncludes != IncludesEnum.None)
                {
                    var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
                    Log.LogMessage($"MainItemDir:{mainItemDir}");
                    IEnumerable<ITaskItem> itemsToAdd;
                    switch (nuPropsIncludes)
                    {
                        case IncludesEnum.Folder:
                            itemsToAdd = SourceFiles.Where(itm =>
                                itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        case IncludesEnum.FolderRecursive:
                            itemsToAdd = SourceFiles.Where(itm =>
                                (itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    foreach (var item in itemsToAdd)
                    {
                        var itemFileFull = item.GetMetadata("FullPath");
                        Log.LogMessage($"itemFileFull:{itemFileFull}");
                        var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
                        files.Add(
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
                    }
                }

                var outXDocStrNew = outXDoc.ToString();
                if (outXDocStrNew == outXDocStrOriginal) continue;

                //change - > save
                File.WriteAllText(outFile, outXDocStrNew);
                Log.LogMessage($"Generated/updated {outFile}");
            }

            if (!anyPackageAvailable)
            {
                Log.LogMessage("No source-only packages found");
            }
            return true;
        }

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

private async Task CreatePath(string path, byte[] data)
        {
            path = path.Trim('/');
            if (string.IsNullOrWhiteSpace(path))
                return;
            var children = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var nodePath = new StringBuilder();
            for (var i = 0; i < children.Length; i++)
            {
                nodePath.Append("/" + children[i]);
                if (await ZooKeeper.existsAsync(nodePath.ToString()) == null)
                {
                    await ZooKeeper.createAsync(nodePath.ToString(), i == children.Length - 1 ? data : null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
        }

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

public static POFlagsComment Parse(string value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            var flags = value
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(p => p.Trim())
                .ToHashSet();

            return new POFlagsComment { Flags = flags };
        }

19 View Source File : WebRequestExtensions.cs
License : MIT License
Project Creator : Accelerider

public static IEnumerable<Cookie> ToCookies(this string cookie, string domain)
	    {
		    return from item in cookie.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
			    let kv = item.Split('=')
			    let name = kv.FirstOrDefault().Trim()
			    let value = kv.Length > 1 ? kv.LastOrDefault() : string.Empty
			    select new Cookie(name, value) { Domain = domain };
	    }

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

private static IEnumerable<string> SplitOnSemicolon(string parameters)
		{
			return parameters.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim());
		}

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

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

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

public override void Render(Context context, TextWriter result)
		{
			IPortalLiquidContext portalLiquidContext;

			if (!context.TryGetPortalLiquidContext(out portalLiquidContext))
			{
				return;
			}

			var searchProvider = GetSearchProvider(context);

			// Allow empty query text, to allow return of top-ranking results based only on filter.
			string queryText = TryGetAttributeValue(context, "query", out queryText)
				? queryText
				: string.Empty;

			string filter;

			TryGetAttributeValue(context, "filter", out filter);

			string pageValue;

			int page = TryGetAttributeValue(context, "page", out pageValue)
				&& int.TryParse(pageValue, out page)
				? page
				: 1;

			string pageSizeValue;
			
			int pageSize = (TryGetAttributeValue(context, "page_size", out pageSizeValue) || TryGetAttributeValue(context, "pagesize", out pageSizeValue))
				&& int.TryParse(pageSizeValue, out pageSize)
				? pageSize
				: 10;

			string logicalNamesValue;

			var logicalNames = (TryGetAttributeValue(context, "logical_names", out logicalNamesValue) || TryGetAttributeValue(context, "logicalnames", out logicalNamesValue))
				? logicalNamesValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
				: Enumerable.Empty<string>();

			// TODO check this here for context when this is called to make sure this still works
			var contextLanguage = HttpContext.Current.GetContextLanguageInfo();

			var query = new CrmEnreplacedyQuery(queryText, page, pageSize, logicalNames, contextLanguage.ContextLanguage, contextLanguage.IsCrmMultiLanguageEnabled, filter);

			context.Stack(() =>
			{
				context[string.IsNullOrEmpty(_variableName) ? "searchindex" : _variableName] = new SearchIndexQueryDrop(portalLiquidContext, searchProvider, query);

				RenderAll(NodeList, context, result);
			});
		}

19 View Source File : HighlightTextBlock.cs
License : MIT License
Project Creator : Accelerider

private void RefreshInlines()
        {
            Inlines.Clear();

            if (string.IsNullOrEmpty(SourceText)) return;
            if (string.IsNullOrEmpty(QueriesText))
            {
                Inlines.Add(SourceText);
                return;
            }

            var sourceText = SourceText;
            var queries = QueriesText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var intervals = from query in queries.Distinct()
                            from interval in GetQueryIntervals(sourceText, query)
                            select interval;
            var mergedIntervals = MergeIntervals(intervals.ToList());
            var fragments = SplitTextByOrderedDisjointIntervals(sourceText, mergedIntervals);

            Inlines.AddRange(GenerateRunElement(fragments));
        }

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

private void InitializeParameters(out string fetchXml, out QueryByAttribute query)
		{
			// merge the select parameters
			IOrderedDictionary parameters = QueryParameters.GetValues(_context, _owner);

			fetchXml = GetNonNullOrEmpty(
				parameters[_fetchXmlParameterName] as string,
				_owner.FetchXml);

			if (!string.IsNullOrEmpty(fetchXml))
			{
				IOrderedDictionary selectParameters = SelectParameters.GetValues(_context, _owner);

				// apply select parameters replacement to the FetchXml
				foreach (DictionaryEntry entry in selectParameters)
				{
					if (entry.Key != null)
					{
						string key = entry.Key.ToString().Trim();

						if (!key.StartsWith("@"))
						{
							key = "@" + key;
						}

						string value = "{0}".FormatWith(entry.Value);

						if (Owner.EncodeParametersEnabled)
						{
							value = AntiXssEncoder.XmlEncode(value);
						}

						fetchXml = Regex.Replace(fetchXml, key, value, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
					}
				}
			}

			// process the QueryByAttribute
			query = null;

			if (_owner.QueryByAttribute != null && !string.IsNullOrEmpty(_owner.QueryByAttribute.EnreplacedyName))
			{
				IOrderedDictionary selectParameters = SelectParameters.GetValues(_context, _owner);

				query = new QueryByAttribute();
				query.EnreplacedyName = LookupParameter(selectParameters, _owner.QueryByAttribute.EnreplacedyName);
				query.Attributes.AddRange(CopyParameters(selectParameters, _owner.QueryByAttribute.Attributes));
				query.Values.AddRange(CopyParameters(selectParameters, _owner.QueryByAttribute.Values));

				if (_owner.QueryByAttribute.ColumnSet != null && _owner.QueryByAttribute.ColumnSet.Count > 0)
				{
					// specify individual columns to load
					query.ColumnSet = new ColumnSet(CopyParameters(selectParameters, _owner.QueryByAttribute.ColumnSet));
				}
				else
				{
					// default to all columns
					query.ColumnSet = new ColumnSet(true);
				}

				if (_owner.QueryByAttribute.Orders != null && _owner.QueryByAttribute.Orders.Count > 0)
				{
					for (int i = 0; i < _owner.QueryByAttribute.Orders.Count; ++i)
					{
						OrderExpression order = new OrderExpression();
						order.AttributeName = LookupParameter(selectParameters, _owner.QueryByAttribute.Orders[i].Value);

						string orderText = LookupParameter(selectParameters, _owner.QueryByAttribute.Orders[i].Text);

						if (orderText.StartsWith("desc", StringComparison.InvariantCultureIgnoreCase))
						{
							order.OrderType = OrderType.Descending;
						}

						query.Orders.Add(order);
					}
				}

				// merge the select parameters
				string enreplacedyName = parameters[_enreplacedyNameParameterName] as string;

				if (!string.IsNullOrEmpty(enreplacedyName))
				{
					query.EnreplacedyName = enreplacedyName;
				}

				// comma delimited
				string attributes = parameters[_attributesParameterName] as string;

				if (!string.IsNullOrEmpty(attributes))
				{
					query.Attributes.Clear();
					query.Attributes.AddRange(attributes.Split(','));
				}

				// comma delimited
				string values = parameters[_valuesParameterName] as string;

				if (!string.IsNullOrEmpty(values))
				{
					query.Values.Clear();
					query.Values.AddRange(values.Split(','));
				}

				// comma delimited
				string columnSet = parameters[_columnSetParameterName] as string;

				if (!string.IsNullOrEmpty(columnSet))
				{
					if (string.Compare(columnSet, _allColumnsParameterValue, StringComparison.InvariantCultureIgnoreCase) == 0)
					{
						query.ColumnSet = new ColumnSet(true);
					}
					else
					{
						string[] parts = columnSet.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

						if (parts.Length > 0)
						{
							for (int i = 0; i < parts.Length; i++)
							{
								parts[i] = parts[i].Trim();
							}

							query.ColumnSet.AddColumns(parts);
						}
						else
						{
							query.ColumnSet = new ColumnSet(true);
						}
					}
				}

				// comma delimited
				string orders = parameters[_ordersParameterName] as string;

				if (!string.IsNullOrEmpty(orders))
				{
					QueryByAttribute queryByAttribute = query;
					AppendSortExpressionToQuery(orders, order => queryByAttribute.Orders.Add(order));
					query = queryByAttribute;
				}

				// all remaining parameters are treated as key/value pairs
				Dictionary<string, object> extendedParameters = new Dictionary<string, object>();

				if (query.Attributes != null)
				{
					for (int i = 0; i < query.Attributes.Count; ++i)
					{
						extendedParameters[query.Attributes[i]] = query.Values[i];
					}
				}

				bool changed = false;

				foreach (string key in parameters.Keys)
				{
					// ignore special parameters
					if (!Array.Exists(_keywords, delegate(string value) { return string.Compare(value, key, StringComparison.InvariantCultureIgnoreCase) == 0; }))
					{
						extendedParameters[key] = parameters[key];
						changed = true;
					}
				}

				if (changed)
				{
					query.Attributes.Clear();
					query.Values.Clear();

					int i = 0;
					foreach (KeyValuePair<string, object> extendedParameter in extendedParameters)
					{
						query.Attributes[i] = extendedParameter.Key;
						query.Values[i] = extendedParameter.Value;
						++i;
					}
				}
			}
		}

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

private List<string> EnumeratePhysicalDrivesLinux()
        {
            var cdInfo = "";
            try
            {
                cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
            }
            catch (Exception e)
            {
                Log.Debug(e, e.Message);
            }
            var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
                    .Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
                    .Distinct()
                    .ToList();

        }

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

private void InitializeParameters(out string fetchXml, out QueryByAttribute query)
		{
			// merge the select parameters
			IOrderedDictionary parameters = QueryParameters.GetValues(_context, _owner);

			fetchXml = GetNonNullOrEmpty(
				parameters[_fetchXmlParameterName] as string,
				_owner.FetchXml);

			if (!string.IsNullOrEmpty(fetchXml))
			{
				IOrderedDictionary selectParameters = SelectParameters.GetValues(_context, _owner);

				// apply select parameters replacement to the FetchXml
				foreach (DictionaryEntry entry in selectParameters)
				{
					if (entry.Key != null)
					{
						string key = entry.Key.ToString().Trim();

						if (!key.StartsWith("@"))
						{
							key = "@" + key;
						}

						string value = "{0}".FormatWith(entry.Value);

						if (Owner.EncodeParametersEnabled)
						{
							value = Encoder.XmlEncode(value);
						}

						fetchXml = Regex.Replace(fetchXml, key, value, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
					}
				}
			}

			// process the QueryByAttribute
			query = null;

			if (_owner.QueryByAttribute != null && !string.IsNullOrEmpty(_owner.QueryByAttribute.EnreplacedyName))
			{
				IOrderedDictionary selectParameters = SelectParameters.GetValues(_context, _owner);

				query = new QueryByAttribute();
				query.EnreplacedyName = LookupParameter(selectParameters, _owner.QueryByAttribute.EnreplacedyName);
				query.Attributes.AddRange(CopyParameters(selectParameters, _owner.QueryByAttribute.Attributes));
				query.Values.AddRange(CopyParameters(selectParameters, _owner.QueryByAttribute.Values));

				if (_owner.QueryByAttribute.ColumnSet != null && _owner.QueryByAttribute.ColumnSet.Count > 0)
				{
					// specify individual columns to load
					query.ColumnSet = new ColumnSet(CopyParameters(selectParameters, _owner.QueryByAttribute.ColumnSet));
				}
				else
				{
					// default to all columns
					query.ColumnSet = new ColumnSet(true);
				}

				if (_owner.QueryByAttribute.Orders != null && _owner.QueryByAttribute.Orders.Count > 0)
				{
					for (int i = 0; i < _owner.QueryByAttribute.Orders.Count; ++i)
					{
						OrderExpression order = new OrderExpression();
						order.AttributeName = LookupParameter(selectParameters, _owner.QueryByAttribute.Orders[i].Value);

						string orderText = LookupParameter(selectParameters, _owner.QueryByAttribute.Orders[i].Text);

						if (orderText.StartsWith("desc", StringComparison.InvariantCultureIgnoreCase))
						{
							order.OrderType = OrderType.Descending;
						}

						query.Orders.Add(order);
					}
				}

				// merge the select parameters
				string enreplacedyName = parameters[_enreplacedyNameParameterName] as string;

				if (!string.IsNullOrEmpty(enreplacedyName))
				{
					query.EnreplacedyName = enreplacedyName;
				}

				// comma delimited
				string attributes = parameters[_attributesParameterName] as string;

				if (!string.IsNullOrEmpty(attributes))
				{
					query.Attributes.Clear();
					query.Attributes.AddRange(attributes.Split(','));
				}

				// comma delimited
				string values = parameters[_valuesParameterName] as string;

				if (!string.IsNullOrEmpty(values))
				{
					query.Values.Clear();
					query.Values.AddRange(values.Split(','));
				}

				// comma delimited
				string columnSet = parameters[_columnSetParameterName] as string;

				if (!string.IsNullOrEmpty(columnSet))
				{
					if (string.Compare(columnSet, _allColumnsParameterValue, StringComparison.InvariantCultureIgnoreCase) == 0)
					{
						query.ColumnSet = new ColumnSet(true);
					}
					else
					{
						string[] parts = columnSet.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

						if (parts.Length > 0)
						{
							for (int i = 0; i < parts.Length; i++)
							{
								parts[i] = parts[i].Trim();
							}

							query.ColumnSet.AddColumns(parts);
						}
						else
						{
							query.ColumnSet = new ColumnSet(true);
						}
					}
				}

				// comma delimited
				string orders = parameters[_ordersParameterName] as string;

				if (!string.IsNullOrEmpty(orders))
				{
					QueryByAttribute queryByAttribute = query;
					AppendSortExpressionToQuery(orders, order => queryByAttribute.Orders.Add(order));
					query = queryByAttribute;
				}

				// all remaining parameters are treated as key/value pairs
				Dictionary<string, object> extendedParameters = new Dictionary<string, object>();

				if (query.Attributes != null)
				{
					for (int i = 0; i < query.Attributes.Count; ++i)
					{
						extendedParameters[query.Attributes[i]] = query.Values[i];
					}
				}

				bool changed = false;

				foreach (string key in parameters.Keys)
				{
					// ignore special parameters
					if (!Array.Exists(_keywords, delegate(string value) { return string.Compare(value, key, StringComparison.InvariantCultureIgnoreCase) == 0; }))
					{
						extendedParameters[key] = parameters[key];
						changed = true;
					}
				}

				if (changed)
				{
					query.Attributes.Clear();
					query.Values.Clear();

					int i = 0;
					foreach (KeyValuePair<string, object> extendedParameter in extendedParameters)
					{
						query.Attributes[i] = extendedParameter.Key;
						query.Values[i] = extendedParameter.Value;
						++i;
					}
				}
			}
		}

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

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

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

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

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

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

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

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

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

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

private static void ApplyClaimsMapping(ApplicationUser user, ExternalLoginInfo loginInfo, string claimsMapping)
		{
			try
			{
				if (user != null && !string.IsNullOrWhiteSpace(claimsMapping))
				{
					foreach (var pair in claimsMapping.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
					{
						var pieces = pair.Split('=');
						var claimValue = loginInfo.ExternalIdenreplacedy.Claims.FirstOrDefault(c => c.Type == pieces[1]);

						if (pieces.Length == 2
							&& !user.Enreplacedy.Attributes.ContainsKey(pieces[0])
							&& claimValue != null)
						{
							user.Enreplacedy.SetAttributeValue(pieces[0], claimValue.Value);
							user.IsDirty = true;
						}
					}
				}
			}
			catch (Exception ex)
			{
				WebEventSource.Log.GenericErrorException(ex);
			}
		}

19 View Source File : Config.cs
License : MIT License
Project Creator : 0ffffffffh

public static Config Get()
        {
            string key, val;
            string[] optLines;

            string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            if (!File.Exists(workDir + "\\.config"))
                return conf;

            if (conf != null)
                return conf;


            conf = new Config();

            optLines = File.ReadAllLines(workDir + "\\.config");

            if (optLines == null)
                return conf;

            foreach (var item in optLines)
            {
                var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (part != null && part.Length == 2)
                {
                    key = part[0].Trim();
                    val = part[1].Trim();

                    switch (key)
                    {
                        case "memcached_port":
                            conf.MemcachedPort = TryConv<int>(val, 11211);
                            break;
                        case "memcached_path":
                            conf.MemcachedPath = val;
                            break;
                        case "sbmon_path":
                            conf.SbmonPath = val;
                            break;
                        case "log_level":
                            conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
                            break;
                        case "dbpwd":
                            conf.DbPreplacedword = val;
                            break;
                        case "test_mode":
                            conf.TestMode = TryConv<bool>(val, true);
                            break;
                        case "html_replacedet_root":
                            conf.HtmlContentRoot = val;
                            break;
                        case "cacheset_salt":
                            conf.CacheSetSalt = val;
                            break;
                        case "records_per_page":
                            conf.RecordCountPerPage = TryConv<int>(val, 40);
                            break;
                        case "basliks_per_page":
                            conf.BaslikCountPerPage = TryConv<int>(val, 15);
                            break;
                    }
                }
            }
            
            optLines = null;

            return conf;
        }

19 View Source File : UIAtlas.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public BetterList<string> GetListOfSprites(string match)
    {
        if (this.mReplacement != null)
        {
            return this.mReplacement.GetListOfSprites(match);
        }
        if (string.IsNullOrEmpty(match))
        {
            return this.GetListOfSprites();
        }
        BetterList<string> betterList = new BetterList<string>();
        int i = 0;
        int count = this.sprites.Count;
        while (i < count)
        {
            UIAtlas.Sprite sprite = this.sprites[i];
            if (sprite != null && !string.IsNullOrEmpty(sprite.name) && string.Equals(match, sprite.name, StringComparison.OrdinalIgnoreCase))
            {
                betterList.Add(sprite.name);
                return betterList;
            }
            i++;
        }
        string[] array = match.Split(new char[]
        {
            ' '
        }, StringSplitOptions.RemoveEmptyEntries);
        for (int j = 0; j < array.Length; j++)
        {
            array[j] = array[j].ToLower();
        }
        int k = 0;
        int count2 = this.sprites.Count;
        while (k < count2)
        {
            UIAtlas.Sprite sprite2 = this.sprites[k];
            if (sprite2 != null && !string.IsNullOrEmpty(sprite2.name))
            {
                string text = sprite2.name.ToLower();
                int num = 0;
                for (int l = 0; l < array.Length; l++)
                {
                    if (text.Contains(array[l]))
                    {
                        num++;
                    }
                }
                if (num == array.Length)
                {
                    betterList.Add(sprite2.name);
                }
            }
            k++;
        }
        return betterList;
    }

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

private static bool TryConvertToRegexOptions(
            String regexOptions,
            out RegexOptions result)
        {
            // Eg: "IgnoreCase, MultiLine" or "IgnoreCase"
            result = RegexOptions.ECMAScript | RegexOptions.CultureInvariant;

            if (String.IsNullOrEmpty(regexOptions))
            {
                return false;
            }

            String[] regexOptionValues = regexOptions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < regexOptionValues.Length; i++)
            {
                String option = regexOptionValues[i];

                if (String.Equals(option, WellKnownRegexOptions.IgnoreCase, StringComparison.OrdinalIgnoreCase))
                {
                    result = result | RegexOptions.IgnoreCase;
                }
                else if (String.Equals(option, WellKnownRegexOptions.Multiline, StringComparison.OrdinalIgnoreCase))
                {
                    result = result | RegexOptions.Multiline;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

19 View Source File : StatisticsHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void ParseOutput(Google.Protobuf.Collections.RepeatedField<Stat> source, out ulong up, out ulong down)
        {

            up = 0; down = 0;
            try
            {

                foreach (Stat stat in source)
                {
                    string name = stat.Name;
                    long value = stat.Value;
                    string[] nStr = name.Split(">>>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    string type = "";

                    name = name.Trim();

                    name = nStr[1];
                    type = nStr[3];

                    if (name == Global.agentTag)
                    {
                        if (type == "uplink")
                        {
                            up = (ulong)value;
                        }
                        else if (type == "downlink")
                        {
                            down = (ulong)value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Utils.SaveLog(ex.Message, ex);
            }
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private Dictionary<string,string> BuildForm(HttpListenerContext ctx)
        {
            string[] items;

            string post;

            using (StreamReader sr = new StreamReader(ctx.Request.InputStream))
            {
                post = sr.ReadToEnd();
            }

            if (string.IsNullOrEmpty(post))
                return null;

            items = post.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            var dict = new Dictionary<string, string>();

            foreach (var item in items)
            {
                string[] kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (kv.Length == 2)
                {
                    kv[1] = System.Web.HttpUtility.UrlDecode(kv[1],Encoding.GetEncoding("iso-8859-9"));


                    dict.Add(kv[0], kv[1]);
                }

            }

            return dict;
        }

19 View Source File : InternalTalk.cs
License : MIT License
Project Creator : 0ffffffffh

public Dictionary<string, string> Parse(byte[] data, int length)
        {
            Dictionary<string, string> talkInfo = new Dictionary<string, string>();

            string s = Encoding.ASCII.GetString(data,0,length);

            var items = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            Log.Verbose(s);
            foreach (var item in items)
            {
                var kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (!talkInfo.ContainsKey(kv[0].ToLower()))
                    talkInfo.Add(kv[0].ToLower(), kv[1]);

            }

            return talkInfo;
        }

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

private unsafe string ProcessOutputImage(List<string> outputLayers, OutputMode outputMode)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            string reply = string.Empty;

            List<Surface> outputImages = null;
            Exception error = null;

            try
            {
                outputImages = new List<Surface>(outputLayers.Count);

                for (int i = 0; i < outputLayers.Count; i++)
                {
                    if (!TryGetValue(outputLayers[i], "layer=", out string packedLayerArgs))
                    {
                        throw new InvalidOperationException("Expected a layer message argument.");
                    }

                    string[] layerArgs = packedLayerArgs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (layerArgs.Length != 4)
                    {
                        throw new InvalidOperationException("A layer message argument must have 4 values.");
                    }

                    string sharedMemoryName = layerArgs[0];
                    int width = int.Parse(layerArgs[1], NumberStyles.Integer, CultureInfo.InvariantCulture);
                    int height = int.Parse(layerArgs[2], NumberStyles.Integer, CultureInfo.InvariantCulture);
                    int stride = int.Parse(layerArgs[3], NumberStyles.Integer, CultureInfo.InvariantCulture);

                    Surface output = null;
                    bool disposeOutput = true;

                    try
                    {
                        output = new Surface(width, height);

                        using (MemoryMappedFile file = MemoryMappedFile.OpenExisting(sharedMemoryName))
                        {
                            using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                            {
                                byte* sourceScan0 = null;
                                RuntimeHelpers.PrepareConstrainedRegions();
                                try
                                {
                                    accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref sourceScan0);

                                    for (int y = 0; y < output.Height; y++)
                                    {
                                        byte* src = sourceScan0 + (y * stride);
                                        ColorBgra* dst = output.GetRowAddressUnchecked(y);

                                        Buffer.MemoryCopy(src, dst, stride, stride);
                                    }
                                }
                                finally
                                {
                                    if (sourceScan0 != null)
                                    {
                                        accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                                    }
                                }
                            }
                        }

                        outputImages.Add(output);
                        disposeOutput = false;
                    }
                    finally
                    {
                        if (disposeOutput)
                        {
                            output?.Dispose();
                        }
                    }
                }

                // Set the first output layer as the active layer.
                // This allows multiple G'MIC effects to be "layered" using the Apply button.
                layers[0].Dispose();
                layers[0] = new GmicLayer(outputImages[0].Clone(), true);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            OutputImageState?.Dispose();
            OutputImageState = new OutputImageState(error, outputImages);

            RaiseOutputImageChanged();

            return reply;
        }

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

private Node Resolve(string name)
        {
            var parts = name.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            var node = _root ?? throw new InvalidOperationException("The configuration has not been built");

            foreach (var part in parts)
            {
                if (!node.Children.ContainsKey(part))
                    break;

                node = node.Children[part];
            }

            return node;
        }

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

private void UpdateSearchResults() {
			var list = new List<ProducreplacedemInfo>();

			// Score all items
			var searchParts = this.SearchText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var productFamily in this.ProductData.ProductFamilies) {
				foreach (var producreplacedemInfo in productFamily.Items) {
					producreplacedemInfo.SearchScore = SampleSearchScorer.Score(producreplacedemInfo, searchParts);
					if (producreplacedemInfo.SearchScore > 0)
						list.Add(producreplacedemInfo);
				}
			}

			// Sort
			list.Sort((x, y) => y.SearchScore.CompareTo(x.SearchScore));

			// Trim to the maximum number of results
			if (list.Count > MaximumSearchResults)
				list.RemoveRange(MaximumSearchResults, list.Count - MaximumSearchResults);

			this.SearchResults = list;
		}

See More Examples