public MouseInputObservable(IButtonActionEvaluator actionEvaluator) { _actionEvaluator = actionEvaluator; var delegateComparer = new DelegateComparer(); _mouseButtonDictionary = new MultiValueDictionary<MouseButton, Action>(delegateComparer); }
/// <summary> /// Initializes a new instance of the <see cref="TestMethod"/> class. /// </summary> /// <param name="methodName">The method name.</param> /// <param name="displayName">The method's display name.</param> /// <param name="traits">The method's traits.</param> public TestMethod(string methodName, string displayName, MultiValueDictionary<string, string> traits) { MethodName = methodName; DisplayName = displayName; Traits = traits; RunResults = new List<TestResult>(); }
/// <summary> /// Initializes a new instance of the <see cref="MethodResult"/> class. /// </summary> /// <param name="methodName">The name of the method under test.</param> /// <param name="typeName">The type of the method under test.</param> /// <param name="displayName">The display name for the test. If null, the fully qualified /// type name is used.</param> /// <param name="traits">The traits.</param> protected MethodResult(string methodName, string typeName, string displayName, MultiValueDictionary<string, string> traits) { MethodName = methodName; TypeName = typeName; DisplayName = displayName ?? TypeName + "." + MethodName; Traits = traits ?? new MultiValueDictionary<string, string>(); }
/// <summary> /// Creates a new instance of the <see cref="FailedResult"/> class. /// </summary> /// <param name="methodName">The name of the method under test</param> /// <param name="typeName">The name of the type under test</param> /// <param name="displayName">The display name of the test</param> /// <param name="traits">The custom properties attached to the test method</param> /// <param name="exceptionType">The full type name of the exception throw</param> /// <param name="message">The exception message</param> /// <param name="stackTrace">The exception stack trace</param> public FailedResult(string methodName, string typeName, string displayName, MultiValueDictionary<string, string> traits, string exceptionType, string message, string stackTrace) : base(methodName, typeName, displayName, traits) { ExceptionType = exceptionType; Message = message; StackTrace = stackTrace; }
public void TestMultiValueDictionary() { var dict = new MultiValueDictionary<int, int>(); dict.Add(1, 1); dict.Add(1, 2); int val; Assert.IsTrue(dict.TryRemove(1, out val)); Assert.AreEqual(2, val); Assert.IsTrue(dict.TryRemove(1, out val)); Assert.AreEqual(1, val); Assert.IsFalse(dict.TryRemove(1, out val)); dict.Add(2, 1); dict.Add(2, 2); dict.Remove(2, 3); dict.Remove(2, 2); Assert.IsTrue(dict.TryRemove(2, out val)); Assert.AreEqual(1, val); }
public void MultiValueDictionary_AddRange() { var mvd = new MultiValueDictionary<int, int>(); mvd.AddRangeWithKey(5, new int[] { 42, 42 }); Assert.AreEqual(2, mvd[5].Count); }
private ProjectionGatewayConfigurationBuilder(ILocator locator) { _locator = locator; var stringEqComparer = EqualityComparerFactory.Create<string>( (x, y) => x.ToLower() == y.ToLower(), s => s.GetHashCode()); Subscriptions = new MultiValueDictionary<string, Subscription>(stringEqComparer); }
public static void ShouldAddRangeAndRetrieveViaIterator() { var expected = values2.Concat(values1); var multiDict = new MultiValueDictionary<string, string>(); multiDict.AddRange("key2", values2); multiDict.AddRange("key1", values1); CollectionAssert.AreEqual(expected, multiDict); }
public void AddSingleValue() { var dictionary = new MultiValueDictionary<string, string>(); dictionary.AddValue("Key", "Value"); Assert.Contains("Key", dictionary.Keys); Assert.Contains("Value", dictionary["Key"]); }
public void RemoveKey() { var dictionary = new MultiValueDictionary<string, string>(); dictionary.AddValue("Key", "Value"); dictionary.Remove("Key"); Assert.DoesNotContain("Key", dictionary.Keys); }
/// <summary> /// Gets the traits on a test method. /// </summary> /// <param name="method">The method to be inspected</param> /// <returns>A dictionary of the traits</returns> public static MultiValueDictionary<string, string> GetTraits(IMethodInfo method) { var traits = new MultiValueDictionary<string, string>(); foreach (IAttributeInfo attribute in method.GetCustomAttributes(typeof(TraitAttribute))) traits.AddValue(attribute.GetPropertyValue<string>("Name"), attribute.GetPropertyValue<string>("Value")); return traits; }
public void MultiValueDictionary_Add() { var mvd = new MultiValueDictionary<int, int>(); mvd.Add(5, 42); mvd.Add(5, 42); mvd.Add(42, 42); Assert.AreEqual(2, mvd.Keys.Count); Assert.AreEqual(2, mvd[5].Count); }
public static MultiValueDictionary<int, int> CreateMVD(int size) { MultiValueDictionary<int, int> mvd = new MultiValueDictionary<int, int>(); Random rand = new Random(11231992); while (mvd.Count < size) mvd.Add(rand.Next(), rand.Next()); return mvd; }
public static void ShouldNotGetValue() { var multiDict = new MultiValueDictionary<string, string>(); multiDict.Add("key", "value"); foreach(var value in values1) { multiDict.Add("key2", value); } IReadOnlyCollection<string> values; Assert.IsFalse(multiDict.TryGetValue("海亀", out values)); }
/// <summary> /// Enumerates the traits across all the loaded assemblies. /// </summary> public MultiValueDictionary<string, string> EnumerateTraits() { var results = new MultiValueDictionary<string, string>(); foreach (TestAssembly testAssembly in testAssemblies) foreach (TestClass testClass in testAssembly.EnumerateClasses()) foreach (TestMethod testMethod in testClass.EnumerateTestMethods()) testMethod.Traits.ForEach((name, value) => results.AddValue(name, value)); return results; }
private static MultiValueDictionary<string, string> GetTraitsFromAttributes(IEnumerable<IAttributeInfo> attributes, MultiValueDictionary<string, string> traits) { foreach (var attributeInfo in attributes) { var name = attributeInfo.GetPropertyValue<string>("Name"); var value = attributeInfo.GetPropertyValue<string>("Value"); if (name != null && value != null) traits.AddValue(name, value); } return traits; }
public void AddSameValueForSameKeyDoesNotDuplicateValue() { var dictionary = new MultiValueDictionary<string, string>(); dictionary.AddValue("Key", "Value1"); dictionary.AddValue("Key", "Value1"); Assert.Contains("Key", dictionary.Keys); IEnumerable<string> values = dictionary["Key"]; Assert.Single(values); Assert.Contains("Value1", values); }
public void AddTwoValuesForSameKey() { var dictionary = new MultiValueDictionary<string, string>(); dictionary.AddValue("Key", "Value1"); dictionary.AddValue("Key", "Value2"); Assert.Contains("Key", dictionary.Keys); IEnumerable<string> values = dictionary["Key"]; Assert.Contains("Value1", values); Assert.Contains("Value2", values); }
public static void ShouldClear() { var multiDict = new MultiValueDictionary<string, string>(); multiDict.AddRange("key2", values2); multiDict.AddRange("key1", values1); multiDict.Add("key3", "海亀"); multiDict.Clear(); IReadOnlyCollection<string> values; Assert.IsFalse(multiDict.TryGetValue("海亀", out values)); Assert.IsFalse(multiDict.TryGetValue("key1", out values)); Assert.IsFalse(multiDict.TryGetValue("key2", out values)); Assert.IsFalse(multiDict.TryGetValue("key3", out values)); }
public Graph_AdjacencyList_Lite(int numberOfVerticies = 0) { if (0 == numberOfVerticies) { this.Vertices = new MultiValueDictionary<int, int>(); this.Visited = new Dictionary<int, bool>(); } else { this.Vertices = new MultiValueDictionary<int, int>(numberOfVerticies); this.Visited = new Dictionary<int, bool>(numberOfVerticies); } }
public void AddRange(int size) { List<int> values = new List<int>(); for (int i = 0; i < size; i++) values.Add(i); foreach (var iteration in Benchmark.Iterations) { MultiValueDictionary<int, int> empty = new MultiValueDictionary<int, int>(); using (iteration.StartMeasurement()) for (int i = 0; i <= 20000; i++) empty.AddRange(i, values); } }
public XunitTestMethodElement GetOrCreateTestMethod(IProject project, XunitTestClassElement testClassElement, IClrTypeName typeName, string methodName, string skipReason, MultiValueDictionary<string, string> traits, bool isDynamic) { var categories = GetCategories(traits); var element = GetTestMethod(project, testClassElement, typeName, methodName); if (element != null) { element.State = UnitTestElementState.Valid; element.SetCategories(categories); return element; } return CreateTestMethod(provider, project, declaredElementProvider, testClassElement, typeName, methodName, skipReason, categories, isDynamic); }
public static void ShouldContainValue() { var multiDict = new MultiValueDictionary<int, string>(); multiDict.AddRange(100, values2); multiDict.AddRange(-5, values1); multiDict.Add(1337, "海亀"); Assert.IsTrue(multiDict.ContainsValue("dojpa2")); Assert.IsTrue(multiDict.ContainsValue("海亀")); Assert.IsTrue(multiDict.ContainsValue("test4")); Assert.IsTrue(multiDict.Contains("海亀")); Assert.IsTrue(multiDict.Contains("test1")); Assert.IsTrue(multiDict.Contains("dojpa4")); }
public Graph_AdjacencyList_Lite(int numberOfVerticies = 0) { if (0 == numberOfVerticies) { this.Vertices = new MultiValueDictionary<int, int>(); this.Visited = new Dictionary<int, bool>(); this.Edges = new MultiValueDictionary<Tuple<int, int>, double>(); } else { this.Vertices = new MultiValueDictionary<int, int>(numberOfVerticies); this.Visited = new Dictionary<int, bool>(numberOfVerticies); this.Edges = new MultiValueDictionary<Tuple<int, int>, double>(numberOfVerticies); //Best guess } }
public void Add(int size) { MultiValueDictionary<int, int> dict = CreateMVD(size); foreach (var iteration in Benchmark.Iterations) { MultiValueDictionary<int, int> copyDict = new MultiValueDictionary<int, int>(dict); using (iteration.StartMeasurement()) for (int i = 0; i <= 20000; i++) { copyDict.Add(i * 10 + 1, 0); copyDict.Add(i * 10 + 2, 0); copyDict.Add(i * 10 + 3, 0); copyDict.Add(i * 10 + 4, 0); copyDict.Add(i * 10 + 5, 0); copyDict.Add(i * 10 + 6, 0); copyDict.Add(i * 10 + 7, 0); copyDict.Add(i * 10 + 8, 0); copyDict.Add(i * 10 + 9, 0); } } }
public void CanEnumerateKeysAndValuesWithDelegate() { string result = ""; var dictionary = new MultiValueDictionary<string, string>(); dictionary.AddValue("Key1", "Value1"); dictionary.AddValue("Key2", "Value2"); dictionary.AddValue("Key2", "Value1"); dictionary.AddValue("Key3", "Value7"); dictionary.ForEach((key, value) => result += key + ": " + value + "\r\n"); Assert.Equal("Key1: Value1\r\n" + "Key2: Value2\r\n" + "Key2: Value1\r\n" + "Key3: Value7\r\n", result); }
public void Remove(int size) { MultiValueDictionary<int, int> dict = new MultiValueDictionary<int, int>(); for (int i = 0; i < size; i++) for (int j = 0; j < 100; j++) dict.Add(i, j); foreach (var iteration in Benchmark.Iterations) { MultiValueDictionary<int, int> copyDict = new MultiValueDictionary<int, int>(dict); using (iteration.StartMeasurement()) for (int i = 0; i <= size; i++) { copyDict.Remove(i); } } }
public static void ShouldAddAndTryGetValue() { var multiDict = new MultiValueDictionary<string, string>(); multiDict.Add("key", "value"); IReadOnlyCollection<string> values; Assert.IsTrue(multiDict.TryGetValue("key", out values)); Assert.AreSame("value", values.First()); foreach(var value in values1) { multiDict.Add("key2", value); } Assert.IsTrue(multiDict.TryGetValue("key2", out values)); CollectionAssert.AreEqual(values1, values); }
public void SimpleEnumerationTestWithLinqOperator() { MultiValueDictionary<int, string> container = new MultiValueDictionary<int, string> { { 1, "value1" }, { 2, "value2" }, { 2, "value3" } }; foreach(KeyValuePair<int, HashSet<string>> pair in container.OrderBy(p=>p.Key)) { switch(pair.Key) { case 1: Assert.AreEqual("value1", pair.Value.First()); break; case 2: Assert.AreEqual(2, pair.Value.Count); Assert.IsTrue(pair.Value.Contains("value2")); Assert.IsTrue(pair.Value.Contains("value3")); break; } } }
/// <summary> /// Creates a <see cref="TestAssembly"/> which is a complete object model over /// the tests inside of instance of <see cref="IExecutorWrapper"/>. /// </summary> /// <param name="executorWrapper">The executor wrapper</param> /// <returns>The fully populated object model</returns> public static TestAssembly Build(IExecutorWrapper executorWrapper) { Guard.ArgumentNotNull("executorWrapper", executorWrapper); List<TestClass> classes = new List<TestClass>(); foreach (XmlNode classNode in executorWrapper.EnumerateTests().SelectNodes("//class")) { List<TestMethod> methods = new List<TestMethod>(); string typeName = classNode.Attributes["name"].Value; foreach (XmlNode testNode in classNode.SelectNodes("method")) { string methodName = testNode.Attributes["method"].Value; string displayName = null; string skipReason = null; if (testNode.Attributes["name"] != null) displayName = testNode.Attributes["name"].Value; if (testNode.Attributes["skip"] != null) skipReason = testNode.Attributes["skip"].Value; var traits = new MultiValueDictionary<string, string>(); foreach (XmlNode traitNode in testNode.SelectNodes("traits/trait")) traits.AddValue(traitNode.Attributes["name"].Value, traitNode.Attributes["value"].Value); TestMethod testMethod = new TestMethod(methodName, displayName ?? typeName + "." + methodName, traits); methods.Add(testMethod); if (!String.IsNullOrEmpty(skipReason)) testMethod.RunResults.Add(new TestSkippedResult(testMethod.DisplayName, skipReason)); } classes.Add(new TestClass(typeName, methods)); } return new TestAssembly(executorWrapper, classes); }
public Builder() { _flags = new(); }
void DownloadsFinished(object sender, UpdateDownloader.FinishedEventArgs args) // "manuall" mode { if (mCurOperation == AgentOperation.PreparingCheck) { AppLog.Line("wsusscn2.cab downloaded"); RetCodes ret = ClearOffline(); if (ret == RetCodes.Success) { ret = SetupOffline(); } if (ret == RetCodes.Success) { ret = SearchForUpdates(); } if (ret <= 0) { OnFinished(ret); } } else { MultiValueDictionary <string, string> AllFiles = new MultiValueDictionary <string, string>(); foreach (UpdateDownloader.Task task in args.Downloads) { if (task.Failed && task.FileName != null) { continue; } AllFiles.Add(task.KB, task.Path + @"\" + task.FileName); } // TODO /*string INIPath = dlPath + @"\updates.ini"; * foreach (string KB in AllFiles.Keys) * { * string Files = ""; * foreach (string FileName in AllFiles.GetValues(KB)) * { * if (Files.Length > 0) * Files += "|"; * Files += FileName; * } * Program.IniWriteValue(KB, "Files", Files, INIPath); * }*/ AppLog.Line("Downloaded {0} out of {1} to {2}", AllFiles.GetCount(), args.Downloads.Count, dlPath); if (mCurOperation == AgentOperation.PreparingUpdates) { RetCodes ret = InstallUpdatesManually(args.Updates, AllFiles); if (ret <= 0) { OnFinished(ret); } } else { RetCodes ret = AllFiles.GetCount() == args.Downloads.Count ? RetCodes.Success : RetCodes.DownloadFailed; if (mCurOperation == AgentOperation.CancelingOperation) { ret = RetCodes.Abborted; } OnFinished(ret); } } }
///// Internal logic methods ///// private Dictionary <string, string> GetAssetNamesContainingThisTexture(MultiValueDictionary <string, string> a_rMultiDict, string a_rTextureGUID) { string[] rGUIDs = this.QueryMultiValueDict(a_rMultiDict, a_rTextureGUID); return(this.GetAssetNamesFromGUIDsAndRemoveOutdatedOnes(a_rMultiDict, rGUIDs)); }
public TestableMethodResult(string methodName, string typeName, MultiValueDictionary <string, string> traits) : base(methodName, typeName, null, traits) { }
/// <summary> /// Initialize the <see cref="NntpArticleBuilder"/> from the given <see cref="NntpArticle"/>. /// All properties are overwritten. /// </summary> /// <param name="article">The <see cref="NntpArticle"/> to initialize the <see cref="NntpArticleBuilder"/> with.</param> /// <returns>The <see cref="NntpArticleBuilder"/> so that additional calls can be chained.</returns> public NntpArticleBuilder InitializeFrom(NntpArticle article) { Guard.ThrowIfNull(article, nameof(article)); messageId = new NntpMessageId(article.MessageId.Value); groupsBuilder = new NntpGroupsBuilder().Add(article.Groups); headers = new MultiValueDictionary <string, string>(); from = null; subject = null; dateTime = null; body = null; foreach (KeyValuePair <string, ImmutableHashSet <string> > header in article.Headers) { foreach (string value in header.Value) { switch (header.Key) { case NntpHeaders.MessageId: if (!messageId.HasValue) { messageId = value; } else { log.Warn("Found more than 1 {messageId} header. Skipping it.", NntpHeaders.MessageId); } break; case NntpHeaders.From: if (from == null) { from = value; } else { log.Warn("Found more than 1 {from} header. Skipping it.", NntpHeaders.From); } break; case NntpHeaders.Subject: if (subject == null) { subject = value; } else { log.Warn("Found more than 1 {subject} header. Skipping it.", NntpHeaders.Subject); } break; case NntpHeaders.Date: if (dateTime == null) { if (DateTimeOffset.TryParseExact(value, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset headerDateTime)) { dateTime = headerDateTime; } else { log.Warn("{date} header has invalid value {value}. Skipping it.", NntpHeaders.Date, value); } } else { log.Warn("Found more than 1 {date} header. Skipping it.", NntpHeaders.Date); } break; case NntpHeaders.Newsgroups: // convert group header to list of groups, do not add as header groupsBuilder.Add(value); break; default: headers.Add(header.Key, value); break; } } } // make copy of body body = article.Body.ToList(); return(this); }
/// <summary> /// Generates a report listing the most frequently referenced opaque symbols in each module /// </summary> /// <param name="Files">The files to include in the report</param> /// <param name="ReportFileLocation">Output file for the report</param> /// <param name="Log">Writer for log output</param> public static void Generate(FileReference ReportFileLocation, DirectoryReference InputDir, HashSet <SourceFile> PreprocessedFiles, TextWriter Log) { Log.WriteLine("Writing {0}...", ReportFileLocation.FullName); // Get a count of files referencing each symbol Dictionary <Symbol, int> SymbolToRefCount = new Dictionary <Symbol, int>(); Dictionary <Symbol, int> SymbolToOpaqueRefCount = new Dictionary <Symbol, int>(); foreach (SourceFile PreprocessedFile in PreprocessedFiles) { if (PreprocessedFile.Fragments != null) { HashSet <Symbol> Symbols = new HashSet <Symbol>(); HashSet <Symbol> NonOpaqueSymbols = new HashSet <Symbol>(); foreach (SourceFragment Fragment in PreprocessedFile.Fragments) { foreach (KeyValuePair <Symbol, SymbolReferenceType> Pair in Fragment.ReferencedSymbols) { Symbols.Add(Pair.Key); if (Pair.Value != SymbolReferenceType.Opaque) { NonOpaqueSymbols.Add(Pair.Key); } } } foreach (Symbol Symbol in Symbols) { int Count; SymbolToRefCount.TryGetValue(Symbol, out Count); SymbolToRefCount[Symbol] = Count + 1; int OpaqueCount; SymbolToOpaqueRefCount.TryGetValue(Symbol, out OpaqueCount); SymbolToOpaqueRefCount[Symbol] = NonOpaqueSymbols.Contains(Symbol) ? OpaqueCount : OpaqueCount + 1; } } } // Build a map of module to symbols MultiValueDictionary <BuildModule, Symbol> ModuleToSymbols = new MultiValueDictionary <BuildModule, Symbol>(); foreach (Symbol Symbol in SymbolToRefCount.Keys) { SourceFile File = Symbol.Fragment.File; if (File.Module != null) { ModuleToSymbols.Add(File.Module, Symbol); } } // Write out a CSV report containing the list of symbols and number of files referencing them using (StreamWriter Writer = new StreamWriter(ReportFileLocation.FullName)) { Writer.WriteLine("Module,Symbol,Fwd,RefCount,OpaqueRefCount"); foreach (BuildModule Module in ModuleToSymbols.Keys) { foreach (Symbol Symbol in ModuleToSymbols[Module].OrderByDescending(x => SymbolToOpaqueRefCount[x])) { Writer.WriteLine("{0},{1},{2},{3},{4}", Module.Name, Symbol.Name, Symbol.ForwardDeclaration, SymbolToRefCount[Symbol], SymbolToOpaqueRefCount[Symbol]); } } } }
/// <summary> /// Initializes a new instance of the <see cref="CollisionUpdate"/> class. /// </summary> /// <param name="type">The <see cref="CollisionUpdateType"/> of this update.</param> /// <param name="flags">The <see cref="Flags"/> of <see cref="Position"/>s to their <see cref="DirectionFlag"/>s.</param> public CollisionUpdate(CollisionUpdateType type, MultiValueDictionary <Position, DirectionFlag> flags) { Type = type; Flags = flags; }
private void ParseManagedSemantics() { var stringTable = m_context.PathTable.StringTable; var magicNugetMarker = PathAtom.Create(stringTable, "_._"); var dllExtension = PathAtom.Create(stringTable, ".dll"); var refs = new MultiValueDictionary <NugetTargetFramework, RelativePath>(); var libs = new MultiValueDictionary <NugetTargetFramework, RelativePath>(); var assemblyToTargetFramework = new MultiValueDictionary <PathAtom, NugetTargetFramework>(); foreach (var relativePath in PackageOnDisk.Contents) { // This is a dll. Check if it is in a lib folder or ref folder. var atoms = relativePath.GetAtoms(); if (atoms.Length == 3) { var libOrRef = atoms[0]; var targetFrameworkFolder = atoms[1]; var fileName = atoms[2]; var isLib = NugetFrameworkMonikers.LibFolderName.CaseInsensitiveEquals(stringTable, libOrRef); var isRef = NugetFrameworkMonikers.RefFolderName.CaseInsensitiveEquals(stringTable, libOrRef); if (isLib || isRef) { if (!TryGetKnownTargetFramework(targetFrameworkFolder, out NugetTargetFramework targetFramework)) { // We skip unknown frameworks, packages are not necessarily well constructed. We log this // as a verbose message (i.e., this is not an error). Logger.Log.NugetUnknownFramework(m_context.LoggingContext, PackageOnDisk.Package.Id, targetFrameworkFolder.ToString(stringTable), relativePath.ToString(stringTable)); continue; } var isManagedEntry = false; var ext = fileName.GetExtension(stringTable); if (dllExtension.CaseInsensitiveEquals(stringTable, ext)) { isManagedEntry = true; if (isRef) { refs.Add(targetFramework, relativePath); } if (isLib) { libs.Add(targetFramework, relativePath); } } else if (fileName == magicNugetMarker) { isManagedEntry = true; } if (isManagedEntry) { IsManagedPackage = true; if (!TargetFrameworks.Contains(targetFramework.Moniker)) { TargetFrameworks.Add(targetFramework.Moniker); } // The magic marker is there so the framework is declared as supported, but no actual files are listed // So we don't want to add a magic marker as a real artifact that can be referenced. if (fileName != magicNugetMarker) { assemblyToTargetFramework.Add(fileName, targetFramework); } } } } } if (TargetFrameworks.Count == 0) { var history = ForceFullFrameworkQualifiersOnly ? NugetFrameworkMonikers.FullFrameworkVersionHistory : NugetFrameworkMonikers.WellknownMonikers.ToList(); // TODO: Remove this once we have a LKG with ForceFullFrameworkQualifiersOnly on spec generation if (Id.Equals("Bond.NET")) { history = NugetFrameworkMonikers.FullFrameworkVersionHistory; } foreach (var moniker in history) { TargetFrameworks.Add(moniker); } } // For the refs without lib, copy them to refs. foreach (var kv in libs) { if (!refs.ContainsKey(kv.Key)) { refs.Add(kv.Key, kv.Value.ToArray()); } } References = refs; Libraries = libs; AssemblyToTargetFramework = assemblyToTargetFramework; }
/// <nodoc /> private bool TryParseDependenciesFromNuSpec() { var dependencyNodes = m_nuSpec .Elements() .Where(el => string.Equals(el.Name.LocalName, "package", StringComparison.Ordinal)) .Elements() .Where(el => string.Equals(el.Name.LocalName, "metadata", StringComparison.Ordinal)) .Elements() .Where(el => string.Equals(el.Name.LocalName, "dependencies", StringComparison.Ordinal)) .Elements(); // Namespace independent query, nuget has about 6 different namespaces as of may 2016. var dependencies = new List <INugetPackage>(); var skipIdLookupTable = new HashSet <string>(this.DependentPackageIdsToSkip); var ignoreIdLookupTable = new HashSet <string>(this.DependentPackageIdsToIgnore); bool skipAllDependencies = skipIdLookupTable.Contains("*"); bool ignoreAllDependencies = ignoreIdLookupTable.Contains("*"); foreach (var dependency in dependencyNodes.Where(el => string.Equals(el.Name.LocalName, "dependency", StringComparison.Ordinal))) { var genericDependency = ReadDependencyElement(dependency); if (genericDependency == null && !(ignoreAllDependencies || ignoreIdLookupTable.Contains(dependency.Attribute("id")?.Value?.Trim()))) { return(false); } if (genericDependency != null && !skipAllDependencies && !skipIdLookupTable.Contains(genericDependency.GetPackageIdentity())) { dependencies.Add(genericDependency); } } var dependenciesPerFramework = new MultiValueDictionary <PathAtom, INugetPackage>(); var groups = dependencyNodes.Where(el => string.Equals(el.Name.LocalName, "group", StringComparison.Ordinal)); foreach (var group in groups) { if (group.Attribute("targetFramework") != null && NugetFrameworkMonikers.TargetFrameworkNameToMoniker.TryGetValue(group.Attribute("targetFramework").Value, out Moniker targetFramework)) { if (group.Elements().Any()) { // If there is at least one valid dependency for a known framework, then the package is defined as managed IsManagedPackage = true; // Only add the group dependency target framework if the nuget package itself also contains specific assemblies of the same version if (!TargetFrameworks.Contains(targetFramework) && (References.Keys.Any(tfm => tfm.Moniker == targetFramework) || Libraries.Keys.Any(tfm => tfm.Moniker == targetFramework))) { TargetFrameworks.Add(targetFramework); } // If the package has a pinned tfm and the groups tfm does not match, skip the groups dependency resolution if (!string.IsNullOrEmpty(this.Tfm) && NugetFrameworkMonikers.TargetFrameworkNameToMoniker.TryGetValue(this.Tfm, out Moniker pinnedTfm) && !PathAtom.Equals(pinnedTfm, targetFramework)) { continue; } foreach ( var dependency in group.Elements().Where( el => string.Equals(el.Name.LocalName, "dependency", StringComparison.Ordinal))) { var grouppedDependency = ReadDependencyElement(dependency); if (grouppedDependency == null && !(ignoreAllDependencies || ignoreIdLookupTable.Contains(dependency.Attribute("id")?.Value?.Trim()))) { return(false); } if (grouppedDependency != null && !skipAllDependencies && !skipIdLookupTable.Contains(grouppedDependency.GetPackageIdentity())) { dependenciesPerFramework.Add(targetFramework, grouppedDependency); } } } } } Dependencies = dependencies; DependenciesPerFramework = dependenciesPerFramework; IsNetStandardPackageOnly = !TargetFrameworks.Any(tfm => NugetFrameworkMonikers.FullFrameworkVersionHistory.Contains(tfm)) && !TargetFrameworks.Any(tfm => NugetFrameworkMonikers.NetCoreAppVersionHistory.Contains(tfm)); return(true); }
private void LoadState() { _components = new Dictionary <string, IComponentIntern>(); _indexes = new Dictionary <IComponentIntern, int>(); _messageHandlers = new MultiValueDictionary <Type, IComponentIntern>(); }
protected override void Initialize(SonarAnalysisContext context) { context.RegisterCompilationStartAction(analysisContext => { if (analysisContext.Compilation.IsTest()) { return; } var fieldsByNamedType = MultiValueDictionary <INamedTypeSymbol, IFieldSymbol> .Create <HashSet <IFieldSymbol> >(); var fieldsAssigned = ImmutableHashSet <IFieldSymbol> .Empty; analysisContext.RegisterSymbolAction(c => { var namedTypeSymbol = (INamedTypeSymbol)c.Symbol; if (!namedTypeSymbol.IsClass() || namedTypeSymbol.Implements(KnownType.System_IDisposable)) { return; } var disposableFields = namedTypeSymbol.GetMembers() .OfType <IFieldSymbol>() .Where(IsNonStaticNonPublicDisposableField) .ToImmutableHashSet(); fieldsByNamedType.AddRangeWithKey(namedTypeSymbol, disposableFields); }, SymbolKind.NamedType); analysisContext.RegisterSyntaxNodeAction(c => { var assignment = (AssignmentExpressionSyntax)c.Node; var expression = assignment.Right; var fieldSymbol = c.SemanticModel.GetSymbolInfo(assignment.Left).Symbol as IFieldSymbol; fieldsAssigned = AddFieldIfNeeded(fieldSymbol, expression, fieldsAssigned); }, SyntaxKind.SimpleAssignmentExpression); analysisContext.RegisterSyntaxNodeAction(c => { var field = (FieldDeclarationSyntax)c.Node; foreach (var variableDeclaratorSyntax in field.Declaration.Variables .Where(declaratorSyntax => declaratorSyntax.Initializer != null)) { var fieldSymbol = c.SemanticModel.GetDeclaredSymbol(variableDeclaratorSyntax) as IFieldSymbol; fieldsAssigned = AddFieldIfNeeded(fieldSymbol, variableDeclaratorSyntax.Initializer.Value, fieldsAssigned); } }, SyntaxKind.FieldDeclaration); analysisContext.RegisterCompilationEndAction(c => { foreach (var kv in fieldsByNamedType) { foreach (var classSyntax in kv.Key.DeclaringSyntaxReferences .Select(declaringSyntaxReference => declaringSyntaxReference.GetSyntax()) .OfType <ClassDeclarationSyntax>()) { var assignedFields = kv.Value.Intersect(fieldsAssigned).ToList(); if (!assignedFields.Any()) { continue; } var variableNames = string.Join(", ", assignedFields.Select(symbol => $"\"{symbol.Name}\"").OrderBy(s => s)); c.ReportDiagnosticIfNonGenerated( Diagnostic.Create(Rule, classSyntax.Identifier.GetLocation(), variableNames), c.Compilation); } } }); }); }
/// <summary> /// Creates a new instance of the <see cref="NntpArticleBuilder"/> class. /// </summary> public NntpArticleBuilder() { headers = new MultiValueDictionary <string, string>(() => new List <string>()); body = new List <string>(); groups = new List <string>(); }
private static bool MethodCalledFromDispose(MultiValueDictionary <INamedTypeSymbol, IMethodSymbol> disposeMethodsCalledFromDispose, IMethodSymbol dispose) { return(disposeMethodsCalledFromDispose.ContainsKey(dispose.ContainingType) && disposeMethodsCalledFromDispose[dispose.ContainingType].Contains(dispose)); }
private Dictionary <string, string> GetAssetNamesContainingTheseTextures(MultiValueDictionary <string, string> a_rMultiDict, IEnumerable <string> a_rTextureGUIDs) { string[] rGUIDs = this.MultiQueryMultiValueDict(a_rMultiDict, a_rTextureGUIDs); return(this.GetAssetNamesFromGUIDsAndRemoveOutdatedOnes(a_rMultiDict, rGUIDs)); }
public MultiValueKeyedCollection(Func <V, K> getKey, IEqualityComparer <K> comparer = null) { _dic = comparer == null ? new MultiValueDictionary <K, V>() : new MultiValueDictionary <K, V>(comparer); _getKey = getKey; }
public SymbolLookup() { symbolsByName = new MultiValueDictionary <string, Symbol>(); symbols = new SortedIntervals(this); allSymbolSets.Add(this); }
/// <inheritdoc /> public GraphPatchingStatistics PartiallyReloadGraph(HashSet <AbsolutePath> affectedSpecs) { Contract.Requires(affectedSpecs != null); var startTime = DateTime.UtcNow; var mustSkipDueToTransitivity = new VisitationTracker(m_oldPipGraph); var mustPostponeDueToServicePips = new VisitationTracker(m_oldPipGraph); var toPostpone = new SortedList <uint, Pip>(); MultiValueDictionary <int, NodeId> nodesByHeight = m_oldPipGraph.TopSort(); int numReloadedPips = 0; int numNotReloadablePips = 0; m_builder.SealDirectoryTable.StartPatching(); // go one level at a time: // - process nodes at the same height in parallel // - postpone service-related pips because they must be added in the order of creation // (because, for example, pip builder adds forward edges from service client to service finalization pips) for (int height = 0; height < nodesByHeight.Count; height++) { Parallel.ForEach( nodesByHeight[height], new ParallelOptions { MaxDegreeOfParallelism = m_maxDegreeOfParallelism }, body: (node) => { var pipId = node.ToPipId(); var pipType = m_oldPipTable.GetPipType(pipId); // skip non-reloadable pips if (!s_reloadablePipTypes.Contains(pipType)) { Interlocked.Increment(ref numNotReloadablePips); return; } var pip = HydratePip(pipId); AbsolutePath?producingSpec = GetProducerSpecFile(pip); // check if this node must be skipped due to its spec file being affected if (producingSpec == null || affectedSpecs.Contains(producingSpec.Value)) { mustSkipDueToTransitivity.MarkVisited(node); MarkAllDependentsVisited(mustSkipDueToTransitivity, node); return; } // check if this pip is a service-related pip which must be postponed if (ServicePipKindUtil.IsServiceRelatedPip(pip)) { SynchronizedAddToSortedList(toPostpone, pip); MarkAllDependentsVisited(mustPostponeDueToServicePips, node); return; } // check if this node must be postponed because it depends on a node that was already postponed if (mustPostponeDueToServicePips.WasVisited(node)) { SynchronizedAddToSortedList(toPostpone, pip); MarkAllDependentsVisited(mustPostponeDueToServicePips, node); return; } // check if this node must be skipped due to transitivity ThrowIfVisited(mustSkipDueToTransitivity, pip); // everything passed: reload this node ReloadPip(pip, ref numReloadedPips); }); } // add postponed nodes sequentially in the order of creation foreach (var pip in toPostpone.Values) { var serviceKind = ServicePipKindUtil.ServiceKind(pip); if (serviceKind != ServicePipKind.ServiceShutdown && serviceKind != ServicePipKind.ServiceFinalization) { // 'shutdown' and 'finalization' are exception because of forward edges that are added // during construction from service client pips to service shutdown/finalization pips. ThrowIfVisited(mustSkipDueToTransitivity, pip); } ReloadPip(pip, ref numReloadedPips); } m_builder.SealDirectoryTable.FinishPatching(); return(new GraphPatchingStatistics { ElapsedMilliseconds = (int)DateTime.UtcNow.Subtract(startTime).TotalMilliseconds, NumPipsReloaded = numReloadedPips, NumPipsAutomaticallyAdded = m_builder.PipCount - numReloadedPips, NumPipsNotReloadable = numNotReloadablePips, NumPipsSkipped = mustSkipDueToTransitivity.VisitedCount, AffectedSpecs = affectedSpecs, }); }
private void CreateMappingForOutputs(Process process, out MultiValueDictionary <AbsolutePath, ExpandedAbsolutePath> originalDirectories, out MultiValueDictionary <ExpandedAbsolutePath, ExpandedAbsolutePath> redirectedDirectories) { // Collect all predicted outputs (directories and files) for the given process var directories = CollectAllOutputDirectories(m_pathTable, process); // In order to keep the filter configuration to its minimum, let's remove directories that are nested within each other var dedupDirectories = AbsolutePathUtilities.CollapseDirectories(directories, m_pathTable, out var originalToCollapsedMapping); var stringTable = m_pathTable.StringTable; var reserveFoldersResolver = new ReserveFoldersResolver(new object()); originalDirectories = new MultiValueDictionary <AbsolutePath, ExpandedAbsolutePath>(originalToCollapsedMapping.Count); redirectedDirectories = new MultiValueDictionary <ExpandedAbsolutePath, ExpandedAbsolutePath>(dedupDirectories.Count, ExpandedAbsolutePathEqualityComparer.Instance); // Map from original dedup directories to unique redirected directories var uniqueRedirectedDirectories = new Dictionary <AbsolutePath, ExpandedAbsolutePath>(dedupDirectories.Count); foreach (var kvp in originalToCollapsedMapping) { AbsolutePath originalDirectory = kvp.Key; AbsolutePath originalCollapsedDirectory = kvp.Value; if (!uniqueRedirectedDirectories.TryGetValue(originalCollapsedDirectory, out var uniqueRedirectedDirectory)) { uniqueRedirectedDirectory = GetUniqueRedirectedDirectory(process, ref reserveFoldersResolver, originalCollapsedDirectory).Expand(m_pathTable); uniqueRedirectedDirectories.Add(originalCollapsedDirectory, uniqueRedirectedDirectory); redirectedDirectories.Add(uniqueRedirectedDirectory, originalCollapsedDirectory.Expand(m_pathTable)); } // Let's reconstruct the redirected directory var redirectedDirectory = originalDirectory.Relocate(m_pathTable, originalCollapsedDirectory, uniqueRedirectedDirectory.Path); originalDirectories.Add(originalDirectory, redirectedDirectory.Expand(m_pathTable)); } }
public Task BatchUpdateAsync(SCG.IReadOnlyList <PendingUpdate <K, V> > inputPendingUpdates) { return(ExecCommandAsync(async cmd => { var properties = typeof(V).GetProperties(); bool hasUpdatedColumn = false; var pendingUpdatesByUpdatedPropertyGroup = new MultiValueDictionary <string[], PendingUpdate <K, V> >( new LambdaEqualityComparer <string[]>( (a, b) => a.Length == b.Length && a.Zip(b, (aElement, bElement) => aElement == bElement).All(x => x), a => a.Aggregate(13, (h, x) => h * 17 + x.GetHashCode()) )); var pendingInserts = new SCG.List <PendingUpdate <K, V> >(); foreach (var pendingUpdate in inputPendingUpdates) { if (!pendingUpdate.Base.Exists) { pendingInserts.Add(pendingUpdate); } else { SortedSet <string> updatedProperties = new SortedSet <string>(); foreach (var p in properties) { var columnName = p.Name.ToLower(); if (columnName == "updated") { hasUpdatedColumn = true; continue; } if (object.Equals(p.GetValue(pendingUpdate.Base.Value), p.GetValue(pendingUpdate.Updated.Value))) { continue; } if (columnName == "id") { throw new InvalidStateException(); } else { updatedProperties.Add(p.Name); } } pendingUpdatesByUpdatedPropertyGroup.Add(updatedProperties.ToArray(), pendingUpdate); } } var commandTextBuilder = new StringBuilder(); /* * INSERT INTO test (id, name, updated) * SELECT * unnest(@ids), unnest(@names), unnest(@updateds) * ON CONFLICT (id) DO UPDATE * SET * name = excluded.name, updated = excluded.updated */ var batchIndex = 0; foreach (var kvp in pendingUpdatesByUpdatedPropertyGroup) { var updatedPropertyNames = kvp.Key; var updatedProperties = updatedPropertyNames.Map(n => typeof(V).GetProperty(n)); var updatedColumnNames = kvp.Key.Map(x => x.ToLower()); var pendingUpdates = kvp.Value.ToArray(); var additionalColumns = new SCG.List <string>(); var idParameter = cmd.CreateParameter(); idParameter.ParameterName = "id" + batchIndex; idParameter.Value = pendingUpdates.Map(p => p.Base.Key); cmd.Parameters.Add(idParameter); if (hasUpdatedColumn) { var updatedParameter = cmd.CreateParameter(); updatedParameter.ParameterName = "updated" + batchIndex; updatedParameter.Value = pendingUpdates.Map(p => DateTime.Now); cmd.Parameters.Add(updatedParameter); additionalColumns.Add("updated"); } for (var i = 0; i < updatedPropertyNames.Length; i++) { var updatedPropertyName = updatedPropertyNames[i]; var updatedProperty = typeof(V).GetProperty(updatedPropertyName); var array = Array.CreateInstance(updatedProperty.PropertyType, pendingUpdates.Length); for (var j = 0; j < pendingUpdates.Length; j++) { array.SetValue(updatedProperty.GetValue(pendingUpdates[j].Updated.Value), j); } var parameter = cmd.CreateParameter(); parameter.ParameterName = updatedColumnNames[i] + batchIndex; parameter.Value = array; cmd.Parameters.Add(parameter); } var query = $"UPDATE {tableName} " + "SET " + updatedColumnNames.Concat(additionalColumns).Select(n => $"{n} = temp.{n}").Join(", ") + " " + "FROM ( select " + updatedColumnNames.Concat("id").Concat(additionalColumns).Select(n => $"unnest(@{n}{batchIndex}) as {n}").Join(", ") + " ) as temp " + $"where {tableName}.id = temp.id"; commandTextBuilder.Append(query); commandTextBuilder.Append("; "); batchIndex++; } // inserts; if (pendingInserts.Any()) { var propertyNames = properties.Map(p => p.Name); var columnNames = properties.Map(p => p.Name.ToLower()); var idParameter = cmd.CreateParameter(); idParameter.ParameterName = "id_ins"; idParameter.Value = pendingInserts.Map(p => p.Base.Key); cmd.Parameters.Add(idParameter); for (var i = 0; i < properties.Length; i++) { var property = properties[i]; var array = Array.CreateInstance(property.PropertyType, pendingInserts.Count); for (var j = 0; j < pendingInserts.Count; j++) { object propertyValue; if (columnNames[i] == "updated" || columnNames[i] == "created") { propertyValue = DateTime.Now; } else { propertyValue = property.GetValue(pendingInserts[j].Updated.Value); } array.SetValue(propertyValue, j); } var parameter = cmd.CreateParameter(); parameter.ParameterName = columnNames[i] + "_ins"; parameter.Value = array; cmd.Parameters.Add(parameter); } var query = $"INSERT INTO {tableName} ({columnNames.Concat("id").Join(", ")}) " + "SELECT " + columnNames.Concat("id").Select(n => $"unnest(@{n}_ins)").Join(", ") + " " + "ON CONFLICT (id) DO UPDATE " + "SET " + columnNames.Select(n => $"{n} = excluded.{n}").Join(", "); commandTextBuilder.Append(query); commandTextBuilder.Append("; "); } cmd.CommandText = commandTextBuilder.ToString(); await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); })); }
/// <summary> /// Initializes the undirected graph /// </summary> public UndirectedGraph() { vertices = new DefaultSet(); edges = new DefaultSet(); succs = new MultiValueDictionary(); }
public IgnoredPackets() { m_ignoredPackets = new MultiValueDictionary <int, int>(); }
/// <summary> /// Initializes the graph /// </summary> public Graph() { this.annotations = new MultiValueDictionary(); }
/// <summary> /// Constructor /// </summary> public SampleArtifactsInput(string sfName, Dictionary <int, int> scale, MultiValueDictionary <int, MLArtifact> a) { SampleFileName = sfName; Scale = scale; Artifacts = a; }
/// <summary> /// Initializes the directed graph /// </summary> public DirectedGraph() { succs = new MultiValueDictionary(); preds = new MultiValueDictionary(); }
/// <summary> /// Creates a new instance of a module repository by copying the content from <param name="moduleRepository"/> /// </summary> public ModuleRepository(ModuleRepository moduleRepository) { PathTable = moduleRepository.PathTable; RootDir = moduleRepository.RootDir; m_backingDictionary = new MultiValueDictionary <ModuleDescriptor, NameContentPair>(moduleRepository.m_backingDictionary); }
public void UpdateSockets() { UInt64 curTick = MiscFunc.GetTickCount64(); UInt64 Interval = curTick - LastUpdate; LastUpdate = curTick; List <IPHelper.I_SOCKET_ROW> Sockets = new List <IPHelper.I_SOCKET_ROW>(); // enum all ockets IntPtr tcp4Table = IPHelper.GetTcpSockets(ref Sockets); IntPtr tcp6Table = IPHelper.GetTcp6Sockets(ref Sockets); IntPtr udp4Table = IPHelper.GetUdpSockets(ref Sockets); IntPtr udp6Table = IPHelper.GetUdp6Sockets(ref Sockets); MultiValueDictionary <UInt64, NetworkSocket> OldSocketList = SocketList.Clone(); for (int i = 0; i < Sockets.Count; i++) { IPHelper.I_SOCKET_ROW SocketRow = Sockets[i]; NetworkSocket Socket = FindSocket(OldSocketList, SocketRow.ProcessId, SocketRow.ProtocolType, SocketRow.LocalAddress, SocketRow.LocalPort, SocketRow.RemoteAddress, SocketRow.RemotePort, NetworkSocket.MatchMode.Strict); if (Socket != null) { //AppLog.Debug("Found Socket {0}:{1} {2}:{3}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort); OldSocketList.Remove(Socket.HashID, Socket); } else { Socket = new NetworkSocket(SocketRow.ProcessId, SocketRow.ProtocolType, SocketRow.LocalAddress, SocketRow.LocalPort, SocketRow.RemoteAddress, SocketRow.RemotePort); //AppLog.Debug("Added Socket {0}:{1} {2}:{3}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort); SocketList.Add(Socket.HashID, Socket); } // Note: sockets observed using ETW are not yet initialized as we are missing owner informations there if (Socket.ProgID == null) { Socket.CreationTime = SocketRow.CreationTime; if (Socket.RemoteAddress != null) { App.engine.DnsInspector.GetHostName(Socket.ProcessId, Socket.RemoteAddress, Socket, NetworkSocket.HostSetter); } var moduleInfo = SocketRow.Module; if (moduleInfo == null || moduleInfo.ModulePath.Equals("System", StringComparison.OrdinalIgnoreCase)) { Socket.ProgID = ProgramID.NewID(ProgramID.Types.System); } else { string fileName = moduleInfo.ModulePath; string serviceTag = moduleInfo.ModuleName; // Note: for services and system TCPIP_OWNER_MODULE_BASIC_INFO.pModuleName is the same TCPIP_OWNER_MODULE_BASIC_INFO.pModulePath // hence we don't have the actuall exe path and we will have to resolve it. if (serviceTag.Equals(fileName)) { fileName = null; // filename not valid } else { serviceTag = null; // service tag not valid } Socket.ProgID = App.engine.GetProgIDbyPID(Socket.ProcessId, serviceTag, fileName); } } // a program may have been removed than the sockets get unasigned and has to be re asigned if (Socket.Assigned == false) { Program prog = Socket.ProgID == null ? null : App.engine.ProgramList.GetProgram(Socket.ProgID, true, ProgramList.FuzzyModes.Any); prog?.AddSocket(Socket); if (prog != null) { Socket.Access = prog.LookupRuleAccess(Socket); } } Socket.Update(SocketRow, Interval); //IPHelper.ModuleInfo Info = SocketRow.Module; //AppLog.Debug("Socket {0}:{1} {2}:{3} {4}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort, (Info != null ? (Info.ModulePath + " (" + Info.ModuleName + ")") : "") + " [PID: " + Socket.ProcessId + "]"); } UInt64 CurTick = MiscFunc.GetCurTick(); foreach (NetworkSocket Socket in OldSocketList.GetAllValues()) { if (Socket.RemovedTimeStamp == 0) { Socket.RemovedTimeStamp = CurTick; } else if (Socket.RemovedTimeStamp < CurTick + 3000) // todo: customize retention time { SocketList.Remove(Socket.HashID, Socket); Program prog = Socket.ProgID == null ? null : App.engine.ProgramList.GetProgram(Socket.ProgID); prog?.RemoveSocket(Socket); } //AppLog.Debug("Removed Socket {0}:{1} {2}:{3}", CurSocket.LocalAddress, CurSocket.LocalPort, CurSocket.RemoteAddress, CurSocket.RemotePort); } // cleanup if (tcp4Table != IntPtr.Zero) { Marshal.FreeHGlobal(tcp4Table); } if (tcp6Table != IntPtr.Zero) { Marshal.FreeHGlobal(tcp6Table); } if (udp4Table != IntPtr.Zero) { Marshal.FreeHGlobal(udp4Table); } if (udp6Table != IntPtr.Zero) { Marshal.FreeHGlobal(udp6Table); } }
public static ModelBuilder BuildCustomAttributes(this ModelBuilder model, IEfCustomContext dbContext) { var entityTypes = model.Model.GetEntityTypes(); var modelChangeLock = new object(); Parallel.ForEach(entityTypes, entityType => { // matches, ctx and the tally are lazily loaded to avoid computing when no actual matching attributes // exist. MultiValueDictionary <EfIndirectProcessorBaseAttribute, EfPropertyDefinition> matches = null; EfProcessorContext ctx = null; ISet <Type> uniqueAttributeTally = null; foreach (var prop in entityType.ClrType.GetProperties()) { //TODO does this actually include types inheriting that type? var attrs = Attribute.GetCustomAttributes(prop, typeof(EfPropertyBaseAttribute)); // note to self: we don't restart the tally for every new property, that ruins the entire point, we // have AttributeUsage.AllowMultiple for that foreach (var attr in attrs) { // lazily initialize the context (so we don't do model.Entity when we don't need to) if (ctx == null) { ctx = new EfProcessorContext { Model = model, Entity = model.Entity(entityType.ClrType), EntityType = entityType, DatabaseContext = dbContext, }; } // this is better kept local var definition = new EfPropertyDefinition { Property = prop, Source = attr, }; // we need the EfPropertyBaseAttribute value, but we can't do that inside the switch block, so // we're using pattern matching here if (!(attr is EfPropertyBaseAttribute baseAttr)) { continue; } if (!baseAttr.CanHaveMultiple) { if (uniqueAttributeTally == null) { // lazily initialize the tally // if there is no tally, there is no need to check if it contains the type uniqueAttributeTally = new HashSet <Type> { baseAttr.GetType() }; } else if (!uniqueAttributeTally.Add(baseAttr.GetType())) { throw new EfAttributeException( $"The property {prop} contains multiple instances of {baseAttr.GetType()}"); } } switch (attr) { case EfPropertyProcessorBaseAttribute processor: lock (modelChangeLock) { processor.Process(ctx, definition); } break; case EfIndirectProcessorBaseAttribute indirectProcessor: if (indirectProcessor.PropertyMatches(ctx, definition)) { if (matches == null) { matches = new MultiValueDictionary <EfIndirectProcessorBaseAttribute, EfPropertyDefinition>(); } matches.Add(indirectProcessor, definition); } break; } }
/// <summary> /// Constructor /// </summary> public ParseBuildArtifactsOutput(MultiValueDictionary <string, ArtifactWithBuildMeta> arts, int tar) { ArtifactsByHash = arts; TotalArtifactsRead = tar; }
public CharSaveFilePropertiesTranspiler(SourceCodeBuilder builder, Sphere56TranspilerVisitor parentVisitor, MultiValueDictionary <string, string> invalidPropertyValues) : base(builder, parentVisitor, forbiddenProperties, invalidPropertyValues) { }
public void UpdateSockets() { UInt64 curTick = MiscFunc.GetTickCount64(); UInt64 Interval = curTick - LastUpdate; LastUpdate = curTick; List <IPHelper.I_SOCKET_ROW> Sockets = new List <IPHelper.I_SOCKET_ROW>(); // enum all ockets IntPtr tcp4Table = IPHelper.GetTcpSockets(ref Sockets); IntPtr tcp6Table = IPHelper.GetTcp6Sockets(ref Sockets); IntPtr udp4Table = IPHelper.GetUdpSockets(ref Sockets); IntPtr udp6Table = IPHelper.GetUdp6Sockets(ref Sockets); MultiValueDictionary <UInt64, NetworkSocket> OldSocketList = SocketList.Clone(); for (int i = 0; i < Sockets.Count; i++) { IPHelper.I_SOCKET_ROW SocketRow = Sockets[i]; NetworkSocket Socket = FindSocket(OldSocketList, SocketRow.ProcessId, SocketRow.ProtocolType, SocketRow.LocalAddress, SocketRow.LocalPort, SocketRow.RemoteAddress, SocketRow.RemotePort, NetworkSocket.MatchMode.Strict); if (Socket != null) { //AppLog.Debug("Found Socket {0}:{1} {2}:{3}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort); OldSocketList.Remove(Socket.HashID, Socket); } else { Socket = new NetworkSocket(SocketRow.ProcessId, SocketRow.ProtocolType, SocketRow.LocalAddress, SocketRow.LocalPort, SocketRow.RemoteAddress, SocketRow.RemotePort); //AppLog.Debug("Added Socket {0}:{1} {2}:{3}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort); SocketList.Add(Socket.HashID, Socket); } // Note: sockets observed using ETW are not yet initialized as we are missing owner informations there if (Socket.ProgID == null) { Socket.CreationTime = SocketRow.CreationTime; if (App.engine.DnsInspector != null && Socket.RemoteAddress != null) { App.engine.DnsInspector.GetHostName(Socket.ProcessId, Socket.RemoteAddress, Socket, NetworkSocket.HostSetter); } var moduleInfo = SocketRow.Module; /*if (moduleInfo != null) * Console.WriteLine("Module {0} ({1})", moduleInfo.ModuleName, moduleInfo.ModulePath);*/ if (moduleInfo == null || moduleInfo.ModulePath.Equals("System", StringComparison.OrdinalIgnoreCase)) { Socket.ProgID = ProgramID.NewID(ProgramID.Types.System); } else { string fileName = moduleInfo.ModulePath; string serviceTag = moduleInfo.ModuleName; // Note: for services and system TCPIP_OWNER_MODULE_BASIC_INFO.pModuleName is the same TCPIP_OWNER_MODULE_BASIC_INFO.pModulePath // hence we don't have the actuall exe path and we will have to resolve it. if (serviceTag.Equals(fileName)) { fileName = null; // filename not valid } else { serviceTag = null; // service tag not valid } Socket.ProgID = App.engine.GetProgIDbyPID(Socket.ProcessId, serviceTag, fileName); } } Socket.Update(SocketRow, Interval); //IPHelper.ModuleInfo Info = SocketRow.Module; //AppLog.Debug("Socket {0}:{1} {2}:{3} {4}", Socket.LocalAddress, Socket.LocalPort, Socket.RemoteAddress, Socket.RemotePort, (Info != null ? (Info.ModulePath + " (" + Info.ModuleName + ")") : "") + " [PID: " + Socket.ProcessId + "]"); } foreach (NetworkSocket Socket in OldSocketList.GetAllValues()) { bool bIsUDPPseudoCon = (Socket.ProtocolType & (UInt32)IPHelper.AF_PROT.UDP) == (UInt32)IPHelper.AF_PROT.UDP && Socket.RemotePort != 0; // Note: sockets observed using ETW are not yet initialized as we are missing owner informations there if (Socket.ProgID == null) { Socket.CreationTime = DateTime.Now; if (App.engine.DnsInspector != null && Socket.RemoteAddress != null) { App.engine.DnsInspector.GetHostName(Socket.ProcessId, Socket.RemoteAddress, Socket, NetworkSocket.HostSetter); } // Note: etw captured connections does not handle services to well :/ Socket.ProgID = App.engine.GetProgIDbyPID(Socket.ProcessId, null, null); } Socket.Update(null, Interval); if (bIsUDPPseudoCon && (DateTime.Now - Socket.LastActivity).TotalMilliseconds < 5000) // 5 sec // todo: customize udp pseudo con time { OldSocketList.Remove(Socket.HashID, Socket); if (Socket.RemovedTimeStamp != 0) { Socket.RemovedTimeStamp = 0; } } else { Socket.State = (int)IPHelper.MIB_TCP_STATE.CLOSED; } } UInt64 CurTick = MiscFunc.GetCurTick(); foreach (NetworkSocket Socket in OldSocketList.GetAllValues()) { if (Socket.RemovedTimeStamp == 0) { Socket.RemovedTimeStamp = CurTick; } else if (Socket.RemovedTimeStamp < CurTick + 3000) // todo: customize retention time { SocketList.Remove(Socket.HashID, Socket); Socket.Program?.RemoveSocket(Socket); } //AppLog.Debug("Removed Socket {0}:{1} {2}:{3}", CurSocket.LocalAddress, CurSocket.LocalPort, CurSocket.RemoteAddress, CurSocket.RemotePort); } // cleanup if (tcp4Table != IntPtr.Zero) { Marshal.FreeHGlobal(tcp4Table); } if (tcp6Table != IntPtr.Zero) { Marshal.FreeHGlobal(tcp6Table); } if (udp4Table != IntPtr.Zero) { Marshal.FreeHGlobal(udp4Table); } if (udp6Table != IntPtr.Zero) { Marshal.FreeHGlobal(udp6Table); } }