/// <summary> /// Construct over an IDictionary instance. /// </summary> /// <param name="dictionary"></param> /// <param name="stringComparer">The string comparer to use.</param> internal CopyOnWriteHashtable(IDictionary dictionary, StringComparer stringComparer) { ErrorUtilities.VerifyThrowArgumentNull(dictionary, "dictionary"); ErrorUtilities.VerifyThrowArgumentNull(stringComparer, "stringComparer"); this.sharedLock = new object(); CopyOnWriteHashtable source = dictionary as CopyOnWriteHashtable; if (source != null) { if (source.stringComparer.GetHashCode() == stringComparer.GetHashCode()) { // If we're copying another CopyOnWriteHashtable then we can defer the clone until later. ConstructFrom(source); return; } else { // Technically, it would be legal to fall through here and let a new hashtable be constructed. // However, Engine is supposed to use consistent case comparisons everywhere and so, for us, // this means a bug in the engine code somewhere. throw new InternalErrorException("Bug: Changing the case-sensitiveness of a copied hash-table."); } } // Can't defer this because we don't control what gets written to the dictionary exogenously. writeableData = new Hashtable(dictionary, stringComparer); readonlyData = null; this.stringComparer = stringComparer; }
public static IEnumerable<Func<IEnumerable<string>, IEnumerable<Error>>> Lookup(StringComparer nameComparer) { return new List<Func<IEnumerable<string>, IEnumerable<Error>>> { HelpCommand(nameComparer) }; }
/// <summary> /// Creates a new Event Assembler code language /// </summary> /// <param name="name">Name of the language</param> /// <param name="pointerMaker">Pointer maker for this language</param> /// <param name="pointerList">Pointer list of this langauge, String is the name of the /// label to point to, List are the priorities that are pointed to.</param> /// <param name="pointerListParameters">Array of amount of pointers per POIN code for pointer list.</param> public EACodeLanguage(string name, IPointerMaker pointerMaker, Tuple<string, List<Priority>>[][] pointerList, ICodeTemplateStorer codeStorer, StringComparer stringComparer) { this.name = name; this.codeStorage = codeStorer; //codeStorage.AddCode(new RawCodeTemplate(stringComparer), Priority.low); //codeStorage.AddCode(new CodeFillerTemplate(stringComparer), Priority.low); foreach (ICodeTemplate template in codeStorer) { CodeTemplate template2 = template as CodeTemplate; if (template2 != null) { template2.PointerMaker = pointerMaker; } } reservedWords = new List<string> { offsetChanger, //Offset changing code alignOffset, //Offset aligning code currentOffset, //Referances current offset messagePrinter, //Print message to message box/something errorPrinter, //Print message to message box/something warningPrinter //Print message to message box/something }; this.assembler = new EAExpressionAssembler(codeStorage, null); this.disassembler = new EACodeLanguageDisassembler( codeStorage, pointerMaker, pointerList); }
MapValues( IEnumerable<SpecificationProperty> propertyTuples, IEnumerable<KeyValuePair<string, IEnumerable<string>>> options, Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter, StringComparer comparer) { var sequencesAndErrors = propertyTuples .Select(pt => options.SingleOrDefault( s => s.Key.MatchName(((OptionSpecification)pt.Specification).ShortName, ((OptionSpecification)pt.Specification).LongName, comparer)) .ToMaybe() .Return(sequence => converter(sequence.Value, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar()) .Return(converted => Tuple.Create( pt.WithValue(Maybe.Just(converted)), Maybe.Nothing<Error>()), Tuple.Create<SpecificationProperty, Maybe<Error>>( pt, Maybe.Just<Error>(new BadFormatConversionError(NameInfo.FromOptionSpecification((OptionSpecification)pt.Specification))))), Tuple.Create(pt, Maybe.Nothing<Error>())) ); return StatePair.Create( sequencesAndErrors.Select(se => se.Item1), sequencesAndErrors.Select(se => se.Item2).OfType<Just<Error>>().Select(se => se.Value)); }
/// <summary> /// コンストラクタ /// </summary> public SearchFileForm() { InitializeComponent(); // リストビューのソートに関する設定 listViewFileNameSorter = new ListViewItemSorter(); listViewFileNameSorter.Column = 2; listViewFileNameSorter.SortOrder = SortOrder.Ascending; IComparer<string> ignoreCaseComparer = new StringComparer(false); IComparer<string> ignoreCaseDirectoryComparer = new DirectoryComparer(false); listViewFileNameSorter.Comparers.Add(ignoreCaseComparer); listViewFileNameSorter.Comparers.Add(ignoreCaseComparer); listViewFileNameSorter.Comparers.Add(ignoreCaseDirectoryComparer); listViewFileName.ListViewItemSorter = listViewFileNameSorter; listViewFileName.SetHeaderSortArrowStyle( listViewFileNameSorter.Column, SelectHeaderSortArrows(listViewFileNameSorter.SortOrder)); // 検索ディレクトリにシステムディレクトリのルートディレクトリを設定する string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System); if (!string.IsNullOrEmpty(systemPath)) { textDirectory.Text = Path.GetPathRoot(systemPath); } }
/// <summary> /// Initializes a new instance of the <see cref="FieldDescriptor" /> class. /// </summary> /// <param name="fieldInfo">The property information.</param> /// <param name="defaultNameComparer">The default name comparer.</param> /// <exception cref="System.ArgumentNullException">fieldInfo</exception> public FieldDescriptor(FieldInfo fieldInfo, StringComparer defaultNameComparer) : base(fieldInfo, defaultNameComparer) { if (fieldInfo == null) throw new ArgumentNullException("fieldInfo"); this.fieldInfo = fieldInfo; }
/// <summary> /// Gets all the node indices with matching names. /// </summary> private IEnumerable<int> FindNodes(string name, StringComparer comparer) { // find any node that matches var position = BinarySearch(name, comparer); if (position != -1) { // back up to the first node that matches. var start = position; while (start > 0 && comparer.Compare(nodes[start - 1].Name, name) == 0) { start--; } // yield the nodes we already know that match for (int i = start; i <= position; i++) { yield return i; } // also yield any following nodes that might also match for (int i = position + 1; i < nodes.Count; i++) { var node = nodes[i]; if (comparer.Compare(node.Name, name) == 0) { yield return i; } else { break; } } } }
public static Result<IEnumerable<SpecificationProperty>, Error> MapValues( IEnumerable<SpecificationProperty> propertyTuples, IEnumerable<KeyValuePair<string, IEnumerable<string>>> options, Func<IEnumerable<string>, Type, bool, Maybe<object>> converter, StringComparer comparer) { var sequencesAndErrors = propertyTuples .Select(pt => options.FirstOrDefault( s => s.Key.MatchName(((OptionSpecification)pt.Specification).ShortName, ((OptionSpecification)pt.Specification).LongName, comparer)) .ToMaybe() .MapValueOrDefault(sequence => converter(sequence.Value, pt.Property.PropertyType, pt.Specification.TargetType != TargetType.Sequence) .MapValueOrDefault(converted => Tuple.Create( pt.WithValue(Maybe.Just(converted)), Maybe.Nothing<Error>()), Tuple.Create<SpecificationProperty, Maybe<Error>>( pt, Maybe.Just<Error>(new BadFormatConversionError(((OptionSpecification)pt.Specification).FromOptionSpecification())))), Tuple.Create(pt, Maybe.Nothing<Error>())) ); return Result.Succeed( sequencesAndErrors.Select(se => se.Item1), sequencesAndErrors.Select(se => se.Item2).OfType<Just<Error>>().Select(se => se.Value)); }
public static ParserResult<object> Choose( Func<IEnumerable<string>, IEnumerable<OptionSpecification>, StatePair<IEnumerable<Token>>> tokenizer, IEnumerable<Type> types, IEnumerable<string> arguments, StringComparer nameComparer, CultureInfo parsingCulture) { if (arguments.Empty()) { return MakeNotParsed(types, new NoVerbSelectedError()); } var firstArg = arguments.First(); Func<string, bool> preprocCompare = command => nameComparer.Equals(command, firstArg) || nameComparer.Equals(string.Concat("--", command), firstArg); var verbs = Verb.SelectFromTypes(types); if (preprocCompare("help")) { return MakeNotParsed(types, MakeHelpVerbRequestedError(verbs, arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer)); } if (preprocCompare("version")) { return MakeNotParsed(types, new VersionRequestedError()); } return MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture); }
public void SortLines(IDocument document, int startLine, int endLine, StringComparer comparer, bool removeDuplicates) { List<string> lines = new List<string>(); for (int i = startLine; i <= endLine; ++i) { IDocumentLine line = document.GetLine(i); lines.Add(document.GetText(line.Offset, line.Length)); } lines.Sort(comparer); if (removeDuplicates) { lines = lines.Distinct(comparer).ToList(); } using (document.OpenUndoGroup()) { for (int i = 0; i < lines.Count; ++i) { IDocumentLine line = document.GetLine(startLine + i); document.Replace(line.Offset, line.Length, lines[i]); } // remove removed duplicate lines for (int i = startLine + lines.Count; i <= endLine; ++i) { IDocumentLine line = document.GetLine(startLine + lines.Count); document.Remove(line.Offset, line.TotalLength); } } }
public static ParserResult<object> Choose( Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer, IEnumerable<Type> types, IEnumerable<string> arguments, StringComparer nameComparer, CultureInfo parsingCulture, IEnumerable<ErrorType> nonFatalErrors) { Func<ParserResult<object>> choose = () => { var firstArg = arguments.First(); Func<string, bool> preprocCompare = command => nameComparer.Equals(command, firstArg) || nameComparer.Equals(string.Concat("--", command), firstArg); var verbs = Verb.SelectFromTypes(types); return preprocCompare("help") ? MakeNotParsed(types, MakeHelpVerbRequestedError(verbs, arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer)) : preprocCompare("version") ? MakeNotParsed(types, new VersionRequestedError()) : MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture, nonFatalErrors); }; return arguments.Any() ? choose() : MakeNotParsed(types, new NoVerbSelectedError()); }
/// <summary> /// Gets all the node indices with matching names per the <paramref name="comparer" />. /// </summary> private IEnumerable<int> FindNodes(string name, StringComparer comparer) { // find any node that matches case-insensitively var startingPosition = BinarySearch(name); if (startingPosition != -1) { // yield if this matches by the actual given comparer if (comparer.Equals(name, _nodes[startingPosition].Name)) { yield return startingPosition; } int position = startingPosition; while (position > 0 && s_nodeSortComparer.Equals(_nodes[position - 1].Name, name)) { position--; if (comparer.Equals(_nodes[position].Name, name)) { yield return position; } } position = startingPosition; while (position + 1 < _nodes.Count && s_nodeSortComparer.Equals(_nodes[position + 1].Name, name)) { position++; if (comparer.Equals(_nodes[position].Name, name)) { yield return position; } } } }
static SisoEnvironment() { Formatting = new SisoDbFormatting(); StringConverter = new StringConverter(Formatting); StringComparer = StringComparer.InvariantCultureIgnoreCase; HashService = new Crc32HashService(); }
/// <summary> /// Creates a new instance of the NUnit Test Attribute class. /// </summary> /// <param name="name">The name of the attribute (e.g. Test) not /// the full name of the attribute (e.g. TestAttribute).</param> /// <param name="nameComparer">The string comparer to use /// when comparing attribute names.</param> public NUnitTestAttributeName(string name, StringComparer nameComparer) { this.name = name; this.nameComparer = nameComparer; qualifiedName = String.Concat(name, "Attribute"); fullyQualifiedName = String.Concat("NUnit.Framework.", name, "Attribute"); }
/// <summary> /// Basically just says "are there any variables with the name <see cref="name"/> inbetween the /// section of document defined by <see cref="rangeStart"/> and <see cref="rangeEnd"/>?" /// </summary> /// <param name="caseSensitive"></param> /// <param name="name"></param> /// <param name="rangeStart"></param> /// <param name="rangeEnd"></param> public FindReferenceVisitor(bool caseSensitive, string name, Location rangeStart, Location rangeEnd) { this.identifiers = new List<IdentifierExpression>(); this.name = name; this.rangeEnd = rangeEnd; this.rangeStart = rangeStart; this.comparer = (caseSensitive) ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase; }
public BasicReader(TextReader reader, StringComparer comparer, bool disposeReader = false) { this._reader = reader; this._buffer = new StringBuilder(); this._comparer = comparer; this._position = 0; this._disposeReader = disposeReader; }
public ITypeDefinition GetTypeDefinition(string nameSpace, string name, int typeParameterCount, StringComparer nameComparer) { foreach (ITypeDefinition type in types) { if (nameComparer.Equals(type.Name, name) && nameComparer.Equals(type.Namespace, nameSpace) && type.TypeParameterCount == typeParameterCount) return type; } return null; }
public string GetNamespace(string nameSpace, StringComparer nameComparer) { foreach (string ns in namespaces) { if (nameComparer.Equals(ns, nameSpace)) return ns; } return null; }
public ConvertVisitor(ConverterSettings settings) { this.settings = settings; this.fileName = settings.FileName; this.errors = settings.Errors; this.warnings = settings.Warnings; this.nameComparer = settings.NameComparer; }
public static bool MatchName(this string value, string shortName, string longName, StringComparer comparer) { if (value == null) throw new ArgumentNullException("value"); return value.Length == 1 ? comparer.Equals(value, shortName) : comparer.Equals(value, longName); }
public static Maybe<char> WithSeparator(string name, IEnumerable<OptionSpecification> specifications, StringComparer comparer) { return specifications.SingleOrDefault( a => name.MatchName(a.ShortName, a.LongName, comparer) && a.Separator != '\0') .ToMaybe() .Return(spec => Maybe.Just(spec.Separator), Maybe.Nothing<char>()); }
public CustomPathComparer(PathComparisonOption pathComparisonOption) { _comparison = (pathComparisonOption == PathComparisonOption.CaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); _comparer = (pathComparisonOption == PathComparisonOption.CaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); }
Lookup(StringComparer nameComparer) { return new List<Func<IEnumerable<string>, IEnumerable<Error>>> { HelpCommand(nameComparer), VersionCommand(nameComparer) }; }
public static Func<IEnumerable<string>, IEnumerable<Error>> VersionCommand(StringComparer nameComparer) { return arguments => nameComparer.Equals("--version", arguments.First()) ? new Error[] { new VersionRequestedError() } : Enumerable.Empty<Error>(); }
public static NameLookupResult Contains(string name, IEnumerable<OptionSpecification> specifications, StringComparer comparer) { var option = specifications.FirstOrDefault(a => name.MatchName(a.ShortName, a.LongName, comparer)); if (option == null) return NameLookupResult.NoOptionFound; return option.ConversionType == typeof(bool) ? NameLookupResult.BooleanOptionFound : NameLookupResult.OtherOptionFound; }
public FindReferenceVisitor(StringComparer nameComparer, string name, Location rangeStart, Location rangeEnd) { this.identifiers = new List<IdentifierExpression>(); this.name = name; this.rangeEnd = rangeEnd; this.rangeStart = rangeStart; this.comparer = nameComparer; }
/// <inheritdoc/> public ITypeDefinition GetTypeDefinition(string nameSpace, string name, int typeParameterCount, StringComparer nameComparer) { foreach (ITypeResolveContext context in children) { ITypeDefinition d = context.GetTypeDefinition(nameSpace, name, typeParameterCount, nameComparer); if (d != null) return d; } return null; }
public LanguageProcessor(bool collectDocComments, IComparer<ICodeTemplate> equalityComparer, StringComparer stringComparer) { this.collectDocComments = collectDocComments; this.templateComparer = equalityComparer; this.stringComparer = stringComparer; this.docs = new SortedDictionary<string, List<DocCode>>(new NaturalComparer()); this.languages = new Dictionary<string, ICodeTemplateStorer>(); }
/// <inheritdoc/> public string GetNamespace(string nameSpace, StringComparer nameComparer) { foreach (ITypeResolveContext context in children) { string r = context.GetNamespace(nameSpace, nameComparer); if (r != null) return r; } return null; }
public static string GetParam(this Application application, string name, StringComparer stringComparer) { stringComparer = stringComparer ?? StringComparer.CurrentCulture; return (from child in HtmlPage.Plugin.Children let nameAttribute = child.GetProperty("name") as string let valueAttribute = child.GetProperty("value") as string where stringComparer.Compare(name, nameAttribute) == 0 select valueAttribute as string).FirstOrDefault(); }
protected override IImmutableDictionary <string, TValue> Empty <TValue>(StringComparer comparer) { return(ImmutableDictionary.Create <string, TValue>(comparer)); }
/// <summary> /// Returns a StringComparer for the current language the player is using. /// </summary> /// <param name="ignoreCase">Whether or not to ignore case.</param> /// <returns>A string comparer.</returns> public static StringComparer GetCurrentLanguageComparer(bool ignoreCase = false) => StringComparer.Create(Game1.content.CurrentCulture, ignoreCase);
public static Dictionary <String, Object> CreateDisctionary(this System.Data.IDataRecord record, StringComparer comparer) { return(record.SetToDisctionary(new Dictionary <String, Object>(comparer))); }
public NamedCollection(IList items, Func <T, string> getKeyForItem, Func <object, bool> onItemMatch = null, StringComparer comparer = null) { if (getKeyForItem == null) { throw new ArgumentNullException("getKeyForItem"); } _getKeyForItem = getKeyForItem; _onItemMatch = onItemMatch; //在初始化之前必须先为委托赋值 this.Initialize(items, comparer); }
void DoUpdate(object s, EventArgs e) { StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; string RecievedLine; RecievedLine = serialPort.ReadLine(); //if (stringComparer.Equals("s\r", RecievedLine)){} //lbl_Herzfrequenz.Text = RecievedLine.Substring(0, 1); //richTextBox1.Text = "abc" + RecievedLine.Substring(0, 1); lbSent.Invoke(lbRecievedDelegate, new object[] { RecievedLine }); if (RecievedLine == "k") { RecievedLine = "kxx"; } switch (RecievedLine.Substring(0, 1)) { case "A": if (lbl_status_show.Text == "Standby") { trackBarLast.Value = Convert.ToInt32(RecievedLine.Substring(1, 3)); } break; case "s": lbl_status_show.Text = "Run"; trackBarHerzfrequenz.Value = 60; trackBarDrehzahl.Value = 60; lbl_belastungstyp_show.Text = "Block"; break; case "S": lbl_status_show.Text = "Run"; trackBarDiastole.Value = 80; trackBarSystole.Value = 100; trackBarHerzfrequenz.Value = 60; trackBarDrehzahl.Value = 60; lbl_belastungstyp_show.Text = "Block"; break; case "I": SerialWrite("SIMUP03V100\r"); break; case "W": if (lbl_status_show.Text == "Run") { trackBarLast.Value = Convert.ToInt32(RecievedLine.Substring(1, 3)); lbl_belastungstyp_show.Text = "Block"; } break; case "L": if (lbl_status_show.Text == "Run") { trackBarLast.Value = Convert.ToInt32(RecievedLine.Substring(1, 3)); lbl_belastungstyp_show.Text = "Linear"; } break; case "B": if (lbl_status_show.Text == "Run") { SerialWrite("B" + trackBarLast.Value + "\r"); } break; case "D": if (lbl_status_show.Text == "Run") { SerialWrite("D" + trackBarDrehzahl.Value + "\r"); } break; case "H": if (lbl_status_show.Text == "Run") { SerialWrite("H" + trackBarHerzfrequenz.Value + "\r"); } break; case "O": if (lbl_status_show.Text == "Run") { SerialWrite("O" + trackBarSystole.Value + "\r"); } break; case "U": if (lbl_status_show.Text == "Run") { SerialWrite("U" + trackBarDiastole.Value + "\r"); } break; case "k": int ActualSattel = Convert.ToInt16(trackBarSattel.Value); string WriteActualSattel; if (ActualSattel < 10) { WriteActualSattel = "0" + ActualSattel.ToString(); } else { WriteActualSattel = ActualSattel.ToString(); } if (RecievedLine.Substring(1, 2) == "xx") { SerialWrite("k" + WriteActualSattel + WriteActualSattel + "\r"); } else { SerialWrite("k" + WriteActualSattel + RecievedLine.Substring(1, 2) + "\r"); trackBarSattel.Value = Convert.ToInt32(RecievedLine.Substring(1, 2)); } break; case "F": InitializeTrackBars(); lbl_status_show.Text = "Standby"; lbl_belastungstyp_show.Text = "Standby"; break; case "P": if (lbl_status_show.Text == "Run") { SerialWrite("P205\r"); } break; } //richTextBox1.Text = RecievedLine; }
/// <summary> /// Initialize the new instance that performs ordinal string comparison. /// </summary> /// <param name="valueComparer">The string comparison operation that uses specific case and culture-based or ordinal comparison rules.</param> private StringArrayComparer(StringComparer valueComparer) => _valueComparer = valueComparer;
public static ProjectItem FindItem(this EnvDTE.Project project, string itemName, StringComparer comparer) { return(project.ProjectItems.FindItem(itemName, comparer)); }
public void TestSetUp() { Target = new StringComparer(); }
public static Predicate <INode> ByNodeName(string name, StringComparer comparer) { return(ByNodeName(delegate(string value) { return comparer.Compare(value, name) == 0; })); }
internal static IEqualityComparer <MetadataMember> CreateMetadataMemberNameEqualityComparer(StringComparer stringComparer) { return(new MetadataMemberNameEqualityComparer(stringComparer)); }
/// <summary> /// Checks that given <paramref name="input"/> is in a list of /// potential <paramref name="matches"/>. /// <remarks>Inspired by: <see href="http://stackoverflow.com/a/20644611/23199"/> </remarks> /// </summary> public static bool EqualsAny(this string input, StringComparer comparer, params string[] matches) => matches.Any(x => comparer.Equals(x, input));
public void ToQuantityWordsWithCustomCultureFormatting(string word, int quantity, string format, string cultureCode, string expected) { var culture = new CultureInfo(cultureCode); Assert.Equal(expected, word.ToQuantity(quantity, format, culture), StringComparer.Create(culture, false)); }
public static IDictionary <string, int> TopNWords(string document, int n, HashSet <string> stopwords, CultureInfo culture = null) { if (document == null) { throw new ArgumentNullException("document"); } culture = CultureUtils.GetCurrentCultureIfNull(culture); bool dontUseStopwords = stopwords == null; IDictionary <string, int> result = new Dictionary <string, int>(dontUseStopwords ? StringComparer.Create(culture, true) : stopwords.Comparer); string[] words = document.Split(s_WordSeparators, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < words.Length; i++) { string word = words[i]; if (dontUseStopwords || !stopwords.Contains(word)) { int count; if (result.TryGetValue(word, out count)) { result[word] = count + 1; } else { result[word] = 1; } } } return(result.OrderBy(x => x.Value).Take(n).ToDictionary(x => x.Key, x => x.Value)); }
internal MetadataMemberNameEqualityComparer(StringComparer stringComparer) { _stringComparer = stringComparer; }
public MetadataGenerator(string rootPath, StringComparer comparer = null) : base(rootPath, comparer) { }
public static string GenerateUniqueName(string baseName, ISet <string> names, StringComparer comparer) { return(GenerateUniqueName(baseName, x => !names.Contains(x, comparer))); }
public EntityBuilder PropertyNameComparer(StringComparer comparer) { PropertyComparer = comparer ?? throw new ArgumentNullException(nameof(comparer)); return(this); }
private void Initialize(string rootDirectory, List <string> ensuredDirectories) { if (ensuredDirectories == null) { ensuredDirectories = new List <string>(); } if (String.IsNullOrEmpty(rootDirectory) || rootDirectory.IndexOfAny(Path.GetInvalidPathChars()) != -1) { throw new ArgumentException("rootDirectory must be a valid file path."); } if (!Path.IsPathRooted(rootDirectory)) { rootDirectory = Path.Combine(Environment.CurrentDirectory, rootDirectory); } _rootDirectory = rootDirectory; if (!Directory.Exists(_rootDirectory)) { Directory.CreateDirectory(_rootDirectory); } StringComparer comparer = StringComparer.OrdinalIgnoreCase; List <string> sourceDirectories = ensuredDirectories; bool logsEnsured = sourceDirectories.Contains("Logs", comparer); bool dataEnsured = sourceDirectories.Contains("Data", comparer); bool cacheEnsured = sourceDirectories.Contains("Cache", comparer); if (sourceDirectories.Count == 0) { if (!logsEnsured) { sourceDirectories.Add("Logs"); } if (!dataEnsured) { sourceDirectories.Add("Data"); } if (!cacheEnsured) { sourceDirectories.Add("Cache"); } } else { if (!cacheEnsured) { sourceDirectories.Insert(0, "Cache"); } if (!dataEnsured) { sourceDirectories.Insert(0, "Data"); } if (!logsEnsured) { sourceDirectories.Insert(0, "Logs"); } } List <string> actualEnsuredDirectories = new List <string>(); foreach (string t in sourceDirectories) { string currentDir = t; if (String.IsNullOrEmpty(currentDir)) { continue; } try { currentDir = Path.IsPathRooted(currentDir) ? currentDir : Path.Combine(_rootDirectory, currentDir); } catch (Exception ex) { Dev2Logger.Log.Error(ex); currentDir = null; } if (currentDir != null) { try { if (!Directory.Exists(currentDir)) { Directory.CreateDirectory(currentDir); } } catch (Exception ex) { Dev2Logger.Log.Error(ex); currentDir = null; } if (currentDir != null) { actualEnsuredDirectories.Add(currentDir); } } } _ensuredDirectories = actualEnsuredDirectories.ToArray(); }
public Generator(string rootPath, StringComparer comparer = null) { RootPath = rootPath; Comparer = comparer ?? StringComparer.CurrentCulture; }
public static bool MatchName(this string value, string shortName, string longName, StringComparer comparer) { return(value.Length == 1 ? comparer.Equals(value, shortName) : comparer.Equals(value, longName)); }
protected abstract IImmutableDictionary <string, TValue> Empty <TValue>(StringComparer comparer);
/// <summary> /// Calculates information about types and namespaces immediately contained within a namespace. /// </summary> /// <param name="isGlobalNamespace"> /// Is current namespace a global namespace? /// </param> /// <param name="namespaceNameLength"> /// Length of the fully-qualified name of this namespace. /// </param> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name in case-sensitive manner. /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of /// this namespace. There could be multiple groups for each fully-qualified namespace name. /// /// The groups must be sorted by the keys in a manner consistent with comparer passed in as /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any, /// must be in several IGrouping at the very beginning of the sequence. /// </param> /// <param name="nameComparer"> /// Equality comparer to compare namespace names. /// </param> /// <param name="types"> /// Output parameter, never null: /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace. /// </param> /// <param name="namespaces"> /// Output parameter, never null: /// A sequence with information about namespaces immediately contained within this namespace. /// For each pair: /// Key - contains simple name of a child namespace. /// Value - contains a sequence similar to the one passed to this function, but /// calculated for the child namespace. /// </param> /// <remarks></remarks> public static void GetInfoForImmediateNamespaceMembers( bool isGlobalNamespace, int namespaceNameLength, IEnumerable <IGrouping <string, TypeDefinitionHandle> > typesByNS, StringComparer nameComparer, out IEnumerable <IGrouping <string, TypeDefinitionHandle> > types, out IEnumerable <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > > namespaces) { Debug.Assert(typesByNS != null); Debug.Assert(namespaceNameLength >= 0); Debug.Assert(!isGlobalNamespace || namespaceNameLength == 0); // A list of groups of TypeDef row ids for types immediately contained within this namespace. var nestedTypes = new List <IGrouping <string, TypeDefinitionHandle> >(); // A list accumulating information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value – contains a sequence similar to the one passed to this function, but // calculated for the child namespace. var nestedNamespaces = new List <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > >(); bool possiblyHavePairsWithDuplicateKey = false; var enumerator = typesByNS.GetEnumerator(); using (enumerator) { if (enumerator.MoveNext()) { var pair = enumerator.Current; // Simple name of the last encountered child namespace. string lastChildNamespaceName = null; // A list accumulating information about types within the last encountered child namespace. // The list is similar to the sequence passed to this function. List <IGrouping <string, TypeDefinitionHandle> > typesInLastChildNamespace = null; // if there are any types in this namespace, // they will be in the first several groups if their key length // is equal to namespaceNameLength. while (pair.Key.Length == namespaceNameLength) { nestedTypes.Add(pair); if (!enumerator.MoveNext()) { goto DoneWithSequence; } pair = enumerator.Current; } // Account for the dot following THIS namespace name. if (!isGlobalNamespace) { namespaceNameLength++; } do { pair = enumerator.Current; string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key); int cmp = nameComparer.Compare(lastChildNamespaceName, childNamespaceName); if (cmp == 0) { // We are still processing the same child namespace typesInLastChildNamespace.Add(pair); } else { // This is a new child namespace if (cmp > 0) { // The sort order is violated for child namespace names. Obfuscation is the likely reason for this. Debug.Assert((object)lastChildNamespaceName != null); possiblyHavePairsWithDuplicateKey = true; } // Preserve information about previous child namespace. if (typesInLastChildNamespace != null) { Debug.Assert(typesInLastChildNamespace.Count != 0); nestedNamespaces.Add( new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >( lastChildNamespaceName, typesInLastChildNamespace)); } typesInLastChildNamespace = new List <IGrouping <string, TypeDefinitionHandle> >(); lastChildNamespaceName = childNamespaceName; Debug.Assert((object)lastChildNamespaceName != null); typesInLastChildNamespace.Add(pair); } }while (enumerator.MoveNext()); // Preserve information about last child namespace. if (typesInLastChildNamespace != null) { Debug.Assert(typesInLastChildNamespace.Count != 0); nestedNamespaces.Add( new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >( lastChildNamespaceName, typesInLastChildNamespace)); } DoneWithSequence: /*empty statement*/ ; } } // using types = nestedTypes; // Merge pairs with the same key if (possiblyHavePairsWithDuplicateKey) { var names = new Dictionary <string, int>(nestedNamespaces.Count, nameComparer); for (int i = nestedNamespaces.Count - 1; i >= 0; i--) { names[nestedNamespaces[i].Key] = i; } if (names.Count != nestedNamespaces.Count) // nothing to merge otherwise { for (int i = 1; i < nestedNamespaces.Count; i++) { var pair = nestedNamespaces[i]; int keyIndex = names[pair.Key]; if (keyIndex != i) { Debug.Assert(keyIndex < i); var primaryPair = nestedNamespaces[keyIndex]; nestedNamespaces[keyIndex] = KeyValuePairUtil.Create(primaryPair.Key, primaryPair.Value.Concat(pair.Value)); nestedNamespaces[i] = default(KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >); } } int removed = nestedNamespaces.RemoveAll(pair => (object)pair.Key == null); Debug.Assert(removed > 0); } } namespaces = nestedNamespaces; Debug.Assert(types != null); Debug.Assert(namespaces != null); }
internal static object?ConvertToDeepIDictionary(object?input, StringComparer stringComparer) { if (input == null) { return(null); } if (input is JObject obj) { return(obj.Properties().ToDictionary(o => o.Name, obj => ConvertToDeepIDictionary(obj.Value, stringComparer), stringComparer)); } if (input is JArray ar) { return(ar.Children().Select(c => ConvertToDeepIDictionary(c, stringComparer))); } if (input is JToken tk) { switch (tk.Type) { case JTokenType.Integer: return(tk.Value <int>()); case JTokenType.Float: return(tk.Value <float>()); case JTokenType.String: return(tk.Value <string>()); case JTokenType.Boolean: return(tk.Value <bool>()); case JTokenType.Null: return(null); case JTokenType.Uri: return(tk.Value <string>()); default: throw new NotSupportedException("Cannot convert Json"); } } if (input is IReadOnlyDictionary <string, object> dict) { return(dict.ToDictionary(o => o.Key, o => ConvertToDeepIDictionary(o.Value, stringComparer), stringComparer)); } #if !NETFX if (input is ConfigurationRoot config) { return(new Dictionary <string, object?>() { { "Entities", ConvertToDeepIDictionary(config.GetSection("Entities"), stringComparer) } }); } if (input is IConfigurationSection section) { if (section.Value != null) { return(section.Value); } var children = section.GetChildren().ToArray(); if (children.Length == 0) { return(null); } // It's an array if (children[0].Key == null) { return(children.Select(c => ConvertToDeepIDictionary(c, stringComparer)).ToArray()); } // It's an object return(children.ToDictionary(o => o.Key, o => ConvertToDeepIDictionary(o, stringComparer), stringComparer)); } #endif return(input); }
protected NamedCollection(IList items, StringComparer comparer = null) { this.Initialize(items, comparer); }
/// <summary> /// Calculates information about types and namespaces immediately contained within a namespace. /// </summary> /// <param name="namespaceNameLength"> /// Length of the fully-qualified name of this namespace. /// </param> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name in case-sensitive manner. /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of /// this namespace. There could be multiple groups for each fully-qualified namespace name. /// /// The groups must be sorted by the keys in a manner consistent with comparer passed in as /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any, /// must be in several IGrouping at the very beginning of the sequence. /// </param> /// <param name="nameComparer"> /// Equality comparer to compare namespace names. /// </param> /// <param name="types"> /// Output parameter, never null: /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace. /// </param> /// <param name="namespaces"> /// Output parameter, never null: /// A sequence with information about namespaces immediately contained within this namespace. /// For each pair: /// Key - contains simple name of a child namespace. /// Value – contains a sequence similar to the one passed to this function, but /// calculated for the child namespace. /// </param> /// <remarks></remarks> public static void GetInfoForImmediateNamespaceMembers( int namespaceNameLength, IEnumerable <IGrouping <string, TypeDefinitionHandle> > typesByNS, StringComparer nameComparer, out IEnumerable <IGrouping <string, TypeDefinitionHandle> > types, out IEnumerable <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > > namespaces) { Debug.Assert(typesByNS != null); Debug.Assert(namespaceNameLength >= 0); // A list of groups of TypeDef row ids for types immediately contained within this namespace. var nestedTypes = new List <IGrouping <string, TypeDefinitionHandle> >(); // A list accumulating information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value – contains a sequence similar to the one passed to this function, but // calculated for the child namespace. var nestedNamespaces = new List <KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > > >(); var enumerator = typesByNS.GetEnumerator(); using (enumerator) { if (enumerator.MoveNext()) { var pair = enumerator.Current; // Simple name of the last encountered child namespace. string lastChildNamespaceName = null; // A list accumulating information about types within the last encountered child namespace. // The list is similar to the sequence passed to this function. List <IGrouping <string, TypeDefinitionHandle> > typesInLastChildNamespace = null; // if there are any types in this namespace, // they will be in the first several groups if their key length // is equal to namespaceNameLength. while (pair.Key.Length == namespaceNameLength) { nestedTypes.Add(pair); if (!enumerator.MoveNext()) { goto DoneWithSequence; } pair = enumerator.Current; } // Account for the dot following THIS namespace name. if (namespaceNameLength != 0) { namespaceNameLength++; } do { pair = enumerator.Current; string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key); if (nameComparer.Equals(childNamespaceName, lastChildNamespaceName)) { // We are still processing the same child namespace typesInLastChildNamespace.Add(pair); } else { // This is a new child namespace // Preserve information about previous child namespace. if (typesInLastChildNamespace != null) { Debug.Assert(typesInLastChildNamespace.Count != 0); nestedNamespaces.Add( new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >( lastChildNamespaceName, typesInLastChildNamespace)); } typesInLastChildNamespace = new List <IGrouping <string, TypeDefinitionHandle> >(); lastChildNamespaceName = childNamespaceName; typesInLastChildNamespace.Add(pair); } }while (enumerator.MoveNext()); // Preserve information about last child namespace. if (typesInLastChildNamespace != null) { Debug.Assert(typesInLastChildNamespace.Count != 0); nestedNamespaces.Add( new KeyValuePair <string, IEnumerable <IGrouping <string, TypeDefinitionHandle> > >( lastChildNamespaceName, typesInLastChildNamespace)); } DoneWithSequence: /*empty statement*/ ; } } // using types = nestedTypes; namespaces = nestedNamespaces; Debug.Assert(types != null); Debug.Assert(namespaces != null); }
/// <summary> /// Checks that given <paramref name="input"/> matches any of the potential matches. /// Inspired by: http://stackoverflow.com/a/20644611/23199 /// </summary> public static bool EqualsAny( this string input, StringComparer comparer, string match1, string match2, string match3) => comparer.Equals(input, match1) || comparer.Equals(input, match2) || comparer.Equals(input, match3);
//[NonSerialized] //List<Dictionary<FullNameAndTypeParameterCount, IUnresolvedTypeDefinition>> cachedTypeDictionariesPerNameComparer; Dictionary <FullNameAndTypeParameterCount, IUnresolvedTypeDefinition> GetTypeDictionary(StringComparer nameComparer) { Debug.Assert(IsFrozen); if (nameComparer == StringComparer.Ordinal) { return(typeDefinitions); } else { throw new NotImplementedException(); } }
/// <summary> /// Internal Constructor. /// </summary> /// <param name="additionalReferencePaths"></param> /// <param name="comparer"></param> /// <see cref="AdditionalReferencePaths"/> internal CompilationAssemblyResolverDependencyContext(IReadOnlyCollection <string> additionalReferencePaths, StringComparer comparer) { AdditionalReferencePaths = additionalReferencePaths ?? Array.Empty <string>(); comparer = comparer ?? DefaultComparer; ResolvedDirectoryPaths = new HashSet <string>(comparer); // TODO: TBD: doesn't this get recycled by the GC then? LoadContext = GetLoadContext(GetType().GetTypeInfo().Assembly); LoadContext.Resolving += OnResolvingLoadContextAssemblyReference; }
public NamedCollectionBase(StringComparer comparer) { _innerDictionary = new Dictionary <string, T>(comparer ?? StringComparer.OrdinalIgnoreCase); }
/// <summary> /// Find a value from a System.Enum by trying several possible variants /// of the string value of the enum. /// </summary> /// <param name="type">Type of enum</typeparam> /// <param name="value">Value for which to search</param> /// <param name="culture">The culture used to calculate the name variants</param> /// <returns></returns> public static object FindEnumValue(this Type type, string value, CultureInfo culture) { #if FRAMEWORK var ret = Enum.GetValues(type) .Cast <Enum>() .FirstOrDefault(v => v.ToString().GetNameVariants(culture).Contains(value, StringComparer.Create(culture, true))); if (ret == null) { int enumValueAsInt; if (Int32.TryParse(value, out enumValueAsInt) && Enum.IsDefined(type, enumValueAsInt)) { ret = (Enum)Enum.ToObject(type, enumValueAsInt); } } return(ret); #elif WindowsCE var ret = EnumHelpers.GetValues(type) .Cast <Enum>() .FirstOrDefault(v => v.ToString().GetNameVariants(culture).Contains(value, StringComparer.Create(culture, true))); if (ret == null) { try { var enumValueAsInt = Int32.Parse(value); if (Enum.IsDefined(type, enumValueAsInt)) { ret = (Enum)Enum.ToObject(type, enumValueAsInt); } } catch (FormatException) { } } return(ret); #else return(Enum.Parse(type, value, true)); #endif }