public void Dictionary_GetOrAdd_Adds_Unexisting_Key() { var dictionary = new Dictionary<int, string>(); Assert.Equal("test", dictionary.GetOrAdd(1, v => "test")); Assert.Equal("test", dictionary.GetOrAdd(1, v => "test2")); }
public static void DebugIfNeeded(List<IObject> displayList) { string behindThis = _behindThis; if (behindThis == null) return; string whyIsThis = _whyIsThis; bool renderDebug = _renderDebug; _behindThis = null; Dictionary<string, List<string>> map = new Dictionary<string, List<string>>(); const string sortWord = "Sort "; const string backwardsWord = "backwards "; foreach (var obj in displayList) { foreach (var property in obj.Properties.Ints.AllProperties()) { if (!property.Key.Contains(sortWord)) continue; if (renderDebug && property.Key.Contains(backwardsWord)) continue; if (!renderDebug && !property.Key.Contains(backwardsWord)) continue; string comparedId = property.Key.Substring(renderDebug ? property.Key.IndexOf(sortWord) + sortWord.Length : property.Key.IndexOf(backwardsWord) + backwardsWord.Length); if (property.Value > 0) map.GetOrAdd(comparedId, () => new List<string>()).Add(obj.ID); else map.GetOrAdd(obj.ID, () => new List<string>()).Add(comparedId); } } string chain = getChain(whyIsThis, behindThis, map, new HashSet<string>()); Debug.WriteLine(chain == null ? string.Format("{0} is not behind {1}", whyIsThis, behindThis) : string.Format("{0}{1}", whyIsThis, chain)); }
public void TestGetOrAdd() { var dict = new Dictionary<string, string>(); dict.GetOrAdd("x", () => "a"); dict.GetOrAdd("x", () => { throw new Exception("Should not be reached."); }); dict.Should().Equal(new Dictionary<string, string> {["x"] = "a"}); }
public void WhenGettingTwice_ThenGetsExisting() { var dictionary = new Dictionary<string, Guid>(); var value = dictionary.GetOrAdd("foo", key => Guid.NewGuid()); var value2 = dictionary.GetOrAdd("foo", key => Guid.NewGuid()); Assert.Equal(value, value2); }
public void GetOrAdd() { var dictionary = new Dictionary<int, string> { { 0, "Zero" } }; dictionary.GetOrAdd(0, "0").ShouldBe("Zero"); dictionary.GetOrAdd(1, "One").ShouldBe("One"); dictionary.GetOrAdd(2, () => "Two").ShouldBe("Two"); dictionary.GetOrAdd(3, i => i.ToString()).ShouldBe("3"); }
public void TestMiscDictionaryGetOrAdd() { string key0 = "Blinky"; var dict = new Dictionary<string, int>(); int value0 = 0; dict.GetOrAdd(key0, v => value0 = v, () => 42); Assert.Equal(0, value0); dict.GetOrAdd(key0, v => value0 = v, () => 42); Assert.Equal(42, value0); }
public void GetOrAddTest() { var stringValues = new Dictionary<string, string> { ["key1"] = "Hoge" }; Assert.AreEqual("Hoge", stringValues.GetOrAdd("key1", key => "Fuga")); Assert.AreEqual("Hoge", stringValues["key1"]); Assert.AreEqual("key2_Piyo", stringValues.GetOrAdd("key2", key => key + "_Piyo")); Assert.AreEqual("key2_Piyo", stringValues["key2"]); }
public void GetOrAdd() { var d = new Dictionary<string, StockStatus>() { {"AAPL", new StockStatus { Price = 530.12m, Position = "Sell" }}, {"GOOG", new StockStatus { Price = 123.5m, Position = "Buy" }} }; d.GetOrAdd("AAPL").Position = "Buy"; d.GetOrAdd("YHOO").Price = 1.99m; Console.Out.WriteLine(d.ToString<string, StockStatus>()); Assert.That(d["AAPL"].Position, Is.EqualTo("Buy"), "Incorrect position."); Assert.That(d.Keys, Has.Count.EqualTo(3), "Incorrect number of keys."); Assert.That(d["YHOO"].Price, Is.EqualTo(1.99m), "Incorrect price."); }
public void GetOrAdd() { // Type var @this = new Dictionary<string, string>(); // Examples string value1 = @this.GetOrAdd("Fizz", "Buzz"); // return "Buzz"; string value2 = @this.GetOrAdd("Fizz", "Buzz2"); // return "Buzz"; // The Dictionary already contains the key string value3 = @this.GetOrAdd("Fizz2", s => "Buzz"); // return "Buzz"; // Unit Test Assert.AreEqual("Buzz", value1); Assert.AreEqual("Buzz", value2); Assert.AreEqual("Buzz", value3); }
public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry> config) { var remotes = new Dictionary<string, RemoteInfo>(); foreach (var entry in config) { var keyParts = entry.Key.Split('.'); if (keyParts.Length == 3 && keyParts[0] == "tfs-remote") { var id = keyParts[1]; var key = keyParts[2]; var remote = remotes.GetOrAdd(id); remote.Id = id; if (key == "url") remote.Url = entry.Value; else if (key == "repository") remote.Repository = entry.Value; else if (key == "username") remote.Username = entry.Value; else if (key == "password") remote.Password = entry.Value; else if (key == "ignore-paths") remote.IgnoreRegex = entry.Value; else if (key == "legacy-urls") remote.Aliases = entry.Value.Split(','); else if (key == "autotag") remote.Autotag = bool.Parse(entry.Value); } } return remotes.Values; }
public int AddNewErrors(IVsEnumExternalErrors pErrors) { var projectErrors = new HashSet<DiagnosticData>(); var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>(); var errors = new ExternalError[1]; uint fetched; while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1) { var error = errors[0]; DiagnosticData diagnostic; if (error.bstrFileName != null) { diagnostic = CreateDocumentDiagnosticItem(error); if (diagnostic != null) { var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>()); diagnostics.Add(diagnostic); continue; } projectErrors.Add(CreateProjectDiagnosticItem(error)); } else { projectErrors.Add(CreateProjectDiagnosticItem(error)); } } _diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap); return VSConstants.S_OK; }
public GlobalCache(Dictionary<IAdapter, Consumer> consumers, int version) { GlobalSignalLookup = new Dictionary<Guid, List<Consumer>>(); GlobalDestinationLookup = consumers; BroadcastConsumers = new List<Consumer>(); Version = version; // Generate routes for all signals received by each consumer adapter foreach (var kvp in consumers) { var consumerAdapter = kvp.Key; var consumer = kvp.Value; if ((object)consumerAdapter.InputMeasurementKeys != null) { // Create routes for each of the consumer's input signals foreach (Guid signalID in consumerAdapter.InputMeasurementKeys.Select(key => key.SignalID)) { GlobalSignalLookup.GetOrAdd(signalID, id => new List<Consumer>()).Add(consumer); } } else { // Add this consumer to the broadcast routes to begin receiving all measurements BroadcastConsumers.Add(consumer); } } // Broadcast consumers receive all measurements, so add them to every signal route foreach (List<Consumer> consumerList in GlobalSignalLookup.Values) { consumerList.AddRange(BroadcastConsumers); } }
public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry<string>> config) { var remotes = new Dictionary<string, RemoteInfo>(); foreach (var entry in config) { var keyParts = entry.Key.Split('.'); if (keyParts.Length >= 3 && keyParts[0] == "tfs-remote") { // The branch name may contain dots ("maint-1.0.0") which must be considered since split on "." var id = string.Join(".", keyParts, 1, keyParts.Length - 2); var key = keyParts.Last(); var remote = remotes.GetOrAdd(id); remote.Id = id; if (key == "url") remote.Url = entry.Value; else if (key == "repository") remote.Repository = entry.Value; else if (key == "username") remote.Username = entry.Value; else if (key == "password") remote.Password = entry.Value; else if (key == "ignore-paths") remote.IgnoreRegex = entry.Value; else if (key == "legacy-urls") remote.Aliases = entry.Value.Split(','); else if (key == "autotag") remote.Autotag = bool.Parse(entry.Value); } } return remotes.Values; }
public void Dictionary_GetOrAdd_Gets_An_Existing_Value() { var dictionary = new Dictionary<int, string>(); dictionary.Add(1, "1"); Assert.Equal("1", dictionary.GetOrAdd(1, v => "test")); }
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs, Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs) { var map = new Dictionary<SyntaxToken, SyntaxToken>(); foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs)) { var localCopy = pair; var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken); map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia); var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken); map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia); } return map; }
public void WhenGettingNonExisting_ThenCreatesValue() { var id = Guid.NewGuid(); var dictionary = new Dictionary<string, Guid>(); var value = dictionary.GetOrAdd("foo", key => id); Assert.Equal(id, value); }
public UpgradeManager(ActorInitializer init) { upgrades = Exts.Lazy(() => { var ret = new Dictionary<string, UpgradeState>(); foreach (var up in init.Self.TraitsImplementing<IUpgradable>()) foreach (var t in up.UpgradeTypes) ret.GetOrAdd(t).Traits.Add(up); return ret; }); }
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, SyntaxToken> tokens, Dictionary<TriviaLocation, SyntaxAnnotation> annotations) { var token = default(SyntaxToken); var map = new Dictionary<SyntaxToken, SyntaxToken>(); var emptyList = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(); token = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => tokens[TriviaLocation.BeforeBeginningOfSpan]); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => tokens[TriviaLocation.AfterBeginningOfSpan]); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => tokens[TriviaLocation.BeforeEndOfSpan]); map[tokens[TriviaLocation.BeforeEndOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeEndOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => tokens[TriviaLocation.AfterEndOfSpan]); map[tokens[TriviaLocation.AfterEndOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterEndOfSpan]); return map; }
private static Dictionary<string, List<PropertyInfo>> GetPropertiesDependencies([NotNull]Type type) { var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var dependencies = new Dictionary<string, List<PropertyInfo>>(properties.Length); foreach (var property in properties) { var dependsOnAttributes = property.GetCustomAttributes<DependsOnAttribute>(); foreach (var dependsOnAttribute in dependsOnAttributes) { var propertyInfos = dependencies.GetOrAdd(dependsOnAttribute.PropertyName, () => new List<PropertyInfo>()); propertyInfos.Add(property); } } return dependencies; }
protected async Task<IDictionary<SyntaxNode, ISet<INamedTypeSymbol>>> GetAllReferencedDefinitionsAsync( Compilation compilation, IEnumerable<ISymbol> members, CancellationToken cancellationToken) { var namespaceScopeToReferencedDefinitions = new Dictionary<SyntaxNode, ISet<INamedTypeSymbol>>(); var root = await Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Func<SyntaxNode, ISet<INamedTypeSymbol>> createSet = _ => new HashSet<INamedTypeSymbol>(); var annotatedNodes = root.GetAnnotatedNodesAndTokens(SymbolAnnotation.Kind); foreach (var annotatedNode in annotatedNodes) { cancellationToken.ThrowIfCancellationRequested(); SyntaxNode namespaceScope = null; var annotations = annotatedNode.GetAnnotations(SymbolAnnotation.Kind); foreach (var annotation in annotations) { cancellationToken.ThrowIfCancellationRequested(); foreach (var namedType in SymbolAnnotation.GetSymbols(annotation, compilation).OfType<INamedTypeSymbol>()) { cancellationToken.ThrowIfCancellationRequested(); if (!IsBuiltIn(namedType)) { namespaceScope = namespaceScope ?? this.GetInnermostNamespaceScope(annotatedNode); var referencedDefinitions = namespaceScopeToReferencedDefinitions.GetOrAdd( namespaceScope, createSet); referencedDefinitions.Add(namedType); } } } } return namespaceScopeToReferencedDefinitions; }
private void PrepareForImport(Options[] options, Action<string> logger) { var folderIdsByName = new Dictionary<string, List<Tuple<string, string>>>(); AddFoldersRecusive(_session.Folders, folderIdsByName); foreach (var profile in options) { var ids = folderIdsByName.GetOrAdd(profile.OutlookFolderEntryId).FirstOrDefault(); if (ids != null) { profile.OutlookFolderEntryId = ids.Item1; profile.OutlookFolderStoreId = ids.Item2; profile.OutlookFolderAccountName = _optionTasks.GetFolderAccountNameOrNull(profile.OutlookFolderStoreId); } else { logger($"Warning: did not find Folder '{profile.OutlookFolderEntryId}'"); profile.OutlookFolderEntryId = null; profile.OutlookFolderStoreId = null; profile.OutlookFolderAccountName = null; } } }
public Tiling CreateTiling( [NotNull] TilingDefinition tilingDefinition, [NotNull] ShapeSet shapes, [NotNull] StyleManager styleManager) { if (tilingDefinition == null) throw new ArgumentNullException(nameof(tilingDefinition)); if (shapes == null) throw new ArgumentNullException(nameof(shapes)); if (styleManager == null) throw new ArgumentNullException(nameof(styleManager)); if (!Tilings.Values.Contains(tilingDefinition)) { throw new ArgumentException( Strings.Template_CreateTiling_UnknownTilingDefinition, nameof(tilingDefinition)); } HashSet<ShapeTemplate> templates = new HashSet<ShapeTemplate>(shapes.Select(s => s.Template)); if (!templates.SetEquals(ShapeTemplates.Values)) throw new ArgumentException(Strings.Template_CreateTiling_WrongShapes, nameof(shapes)); Dictionary<int, ShapeLines> shapeLines = new Dictionary<int, ShapeLines>(); List<Tile> tiles = new List<Tile>(shapes.Count); // TODO Order shapes so that the nth shape is adjacent to at least one of the previous shapes foreach (Shape shape in shapes) { Debug.Assert(shape != null, "shape != null"); string label = null; Matrix3x2 transform = default(Matrix3x2); if (tiles.Count < 1) { label = tilingDefinition.AdjacentParts .Where(l => l.Value.ShapeTemplate == shape.Template) .OrderBy(l => l.Label, StringComparer.InvariantCulture) .First().Label; transform = Matrix3x2.Identity; } else { foreach (Tile t in tiles) { foreach (EdgePartShape partShape in t.PartShapes) { Debug.Assert(partShape != null, "partShape != null"); Labeled<EdgePart> adjacent; if (!tilingDefinition.AdjacentParts.TryGetAdjacent( partShape.Part.WithLabel(t.Label), out adjacent)) continue; Debug.Assert(adjacent.Value != null, "adjacent.Value != null"); if (adjacent.Value.ShapeTemplate != shape.Template) continue; label = adjacent.Label; transform = EdgePartPosition.Create(adjacent.Value, shape) .GetTransformTo(t.GetEdgePartPosition(partShape.Part)); } if (label != null) break; } if (label == null) throw new InvalidDataException(); } EdgePartShape[] partShapes = shape.Template.EdgeParts[tilingDefinition] .Select( ep => new EdgePartShape( ep, shapes.GetEdge(ep.EdgePattern.EdgeName), shapeLines.GetOrAdd(ep.PartShapeID, _ => ShapeLines.CreateDefault()))) .ToArray(); Tile tile = new Tile(label, shape, transform, partShapes); tile.Style = styleManager.GetStyle(tile); tiles.Add(tile); } return new Tiling(this, tilingDefinition, tiles, styleManager); }
/// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="expectedSymbols">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> protected Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts(HashSet<ISymbol> expectedSymbols, IEnumerable<Tuple<DocumentId, AbstractSyntaxContext, IEnumerable<ISymbol>>> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance); foreach (var linkedContextSymbolList in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = expectedSymbols.Except(linkedContextSymbolList.Item3, LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance); foreach (var missingSymbol in symbolsMissingInLinkedContext) { missingSymbols.GetOrAdd(missingSymbol, (m) => new List<ProjectId>()).Add(linkedContextSymbolList.Item1.ProjectId); } } return missingSymbols; }
// Reads statistics from the archive and stores them in a format that can // be easily manipulated to determine which devices belong in which levels. private void ReadStatistics() { ArchiveLocator locator; DateTime startTime; DateTime endTime; Dictionary<int, Aggregate> aggregateLookup; Aggregate currentAggregate; int currentHistorianID; Dictionary<string, DeviceStats> deviceStatsLookup; DeviceStats deviceStats; SignalStats signalStats; string signalName; int index; deviceStatsLookup = new Dictionary<string, DeviceStats>(); // Create the statistics reader for reading statistics from the archive using (StatisticsReader statisticsReader = new StatisticsReader()) { // Create the archive locator to // determine the location of the archive locator = new ArchiveLocator() { ArchiveLocation = m_archiveLocation, ArchiveLocationName = "Statistics", ArchiveName = "STAT" }; endTime = m_reportDate.ToUniversalTime() + TimeSpan.FromDays(1); startTime = endTime - TimeSpan.FromDays(ReportDays); // Set up and open the statistics reader statisticsReader.StartTime = startTime; statisticsReader.EndTime = endTime; statisticsReader.ArchiveFilePath = locator.ArchiveFilePath; statisticsReader.Open(); // Create lookup tables for each aggregateLookup = new Dictionary<int, Aggregate>(); foreach (MetadataRecord record in statisticsReader.MetadataRecords) { if (IsDesiredDeviceStat(record.Synonym1)) { deviceStats = deviceStatsLookup.GetOrAdd(GetDeviceNameForStat(record.Synonym1), name => new DeviceStats() { Name = name, MeasurementsExpected = new Aggregate(ReportDays), MeasurementsReceived = new Aggregate(ReportDays), SignalStatsLookup = new Dictionary<string, SignalStats>() }); if (record.Synonym1.EndsWith("!PMU-ST5", StringComparison.Ordinal)) aggregateLookup[record.HistorianID] = deviceStats.MeasurementsExpected; else if (record.Synonym1.EndsWith("!PMU-ST4", StringComparison.Ordinal)) aggregateLookup[record.HistorianID] = deviceStats.MeasurementsReceived; } else if (IsDesiredSignalStat(record.Synonym1)) { signalName = GetSignalName(record.Synonym1); deviceStats = deviceStatsLookup.GetOrAdd(GetDeviceNameForSignal(signalName), name => new DeviceStats() { Name = name, MeasurementsExpected = new Aggregate(ReportDays), MeasurementsReceived = new Aggregate(ReportDays), SignalStatsLookup = new Dictionary<string, SignalStats>() }); signalStats = deviceStats.SignalStatsLookup.GetOrAdd(signalName, name => new SignalStats() { Name = name, MeasurementsLatched = new Aggregate(ReportDays), MeasurementsUnreasonable = new Aggregate(ReportDays) }); if (record.Synonym1.StartsWith("980!")) aggregateLookup[record.HistorianID] = signalStats.MeasurementsLatched; else if (record.Synonym1.StartsWith("900!")) aggregateLookup[record.HistorianID] = signalStats.MeasurementsUnreasonable; } } currentAggregate = null; currentHistorianID = -1; foreach (IDataPoint dataPoint in statisticsReader.Read(aggregateLookup.Keys)) { index = (dataPoint.Time.ToDateTime() - startTime).Days; if (index < 0 || index >= ReportDays) continue; if (dataPoint.HistorianID != currentHistorianID) { aggregateLookup.TryGetValue(dataPoint.HistorianID, out currentAggregate); currentHistorianID = dataPoint.HistorianID; } if ((object)currentAggregate != null) currentAggregate.Add(index, dataPoint.Value); } } // Store the statistics data to be used in the report m_deviceStatsList = deviceStatsLookup.Values.ToList(); }
private Dictionary<SyntaxToken, LeadingTrailingTriviaPair> CreateTokenLeadingTrailingTriviaMap( Dictionary<TriviaLocation, SyntaxToken> tokens) { var tuple = default(LeadingTrailingTriviaPair); var map = new Dictionary<SyntaxToken, LeadingTrailingTriviaPair>(); tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = tuple.LeadingTrivia, TrailingTrivia = _triviaList[TriviaLocation.BeforeBeginningOfSpan] }; tuple = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = _triviaList[TriviaLocation.AfterBeginningOfSpan], TrailingTrivia = tuple.TrailingTrivia }; tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.BeforeEndOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = tuple.LeadingTrivia, TrailingTrivia = _triviaList[TriviaLocation.BeforeEndOfSpan] }; tuple = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.AfterEndOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = _triviaList[TriviaLocation.AfterEndOfSpan], TrailingTrivia = tuple.TrailingTrivia }; return map; }
private static Dictionary<Project, Dictionary<Document, List<ValueTuple<ISymbol, IReferenceFinder>>>> CreateProjectMap( ConcurrentDictionary<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> map) { Contract.Requires(map.Count > 0); var projectMap = new Dictionary<Project, Dictionary<Document, List<ValueTuple<ISymbol, IReferenceFinder>>>>(); foreach (var kv in map) { var documentMap = projectMap.GetOrAdd(kv.Key.Project, s_documentMapGetter); var queue = documentMap.GetOrAdd(kv.Key, s_queueGetter); queue.AddRange(kv.Value); } ValidateProjectMap(projectMap); return projectMap; }
public void Execute() { ValidateFacets(); //We only want to run the base query once, so we capture all of the facet-ing terms then run the query // once through the collector and pull out all of the terms in one shot var allCollector = new GatherAllCollector(); var facetsByName = new Dictionary<string, Dictionary<string, FacetValue>>(); using (var currentState = Database.IndexStorage.GetCurrentStateHolder(Index)) { var currentIndexSearcher = currentState.IndexSearcher; var baseQuery = Database.IndexStorage.GetDocumentQuery(Index, IndexQuery, Database.IndexQueryTriggers); currentIndexSearcher.Search(baseQuery, allCollector); var fields = Facets.Values.Select(x => x.Name) .Concat(Ranges.Select(x => x.Key)); var fieldsToRead = new HashSet<string>(fields); IndexedTerms.ReadEntriesForFields(currentState, fieldsToRead, allCollector.Documents, (term, doc) => { var facets = Facets.Values.Where(facet => facet.Name == term.Field); foreach (var facet in facets) { switch (facet.Mode) { case FacetMode.Default: var facetValues = facetsByName.GetOrAdd(facet.DisplayName); FacetValue existing; if (facetValues.TryGetValue(term.Text, out existing) == false) { existing = new FacetValue { Range = GetRangeName(term) }; facetValues[term.Text] = existing; } ApplyFacetValueHit(existing, facet, doc, null); break; case FacetMode.Ranges: List<ParsedRange> list; if (Ranges.TryGetValue(term.Field, out list)) { for (int i = 0; i < list.Count; i++) { var parsedRange = list[i]; if (parsedRange.IsMatch(term.Text)) { var facetValue = Results.Results[term.Field].Values[i]; ApplyFacetValueHit(facetValue, facet, doc, parsedRange); } } } break; default: throw new ArgumentOutOfRangeException(); } } }); UpdateFacetResults(facetsByName); CompleteFacetCalculationsStage1(currentState); CompleteFacetCalculationsStage2(); } }
public ExcelImportResult Import(string file, int projectColumn, int taskColumn, int dateColumn, int fromColumn, int toColumn, int rateColumn, int descriptionColumn) { var excelPackage = new ExcelPackage(new FileInfo(file)); var worksheet = excelPackage.Workbook.Worksheets.First(); var clients = new Dictionary<Guid, Domain.Client>(); var projects = new Dictionary<Guid, Domain.Project>(); var result = new ExcelImportResult(); var toAdd = new List<TimeRegistration>(); for (int r = 2; r <= worksheet.Dimension.End.Row; r++) { try { Guid projectId; Guid.TryParse(worksheet.Cells[r, projectColumn].Text, out projectId); var project = projects.GetOrAdd(projectId, key => _aggregateRootRepository.GetById<Domain.Project>(key)); var client = clients.GetOrAdd(project.ClientId, key => _aggregateRootRepository.GetById<Domain.Client>(key)); if (project == null) { result.Errors.Add(r, "Project not found."); continue; } DateTime date; DateTime from; DateTime to; decimal rate; if (!DateTime.TryParseExact(worksheet.Cells[r, dateColumn].Text, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { result.Errors.Add(r, "Date does not contain a valid date."); continue; } if (!DateTime.TryParseExact(worksheet.Cells[r, fromColumn].Text, "H:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out from)) { result.Errors.Add(r, "From does not contain a valid time."); continue; } if (!DateTime.TryParseExact(worksheet.Cells[r, toColumn].Text, "H:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out to)) { result.Errors.Add(r, "To does not contain a valid time."); continue; } if (!decimal.TryParse(worksheet.Cells[r, rateColumn].Text, out rate)) { result.Errors.Add(r, "Rate does not contain a valid number."); continue; } toAdd.Add(new Domain.TimeRegistration(_idGenerator.NextGuid(), client, project, new Domain.ValueObjects.Task { Name = worksheet.Cells[r, taskColumn].Text, Rate = rate }, worksheet.Cells[r, descriptionColumn].Text, new Date(date.Year, date.Month, date.Day), new Time(from.Hour, from.Minute), new Time(to.Hour, to.Minute))); } catch (Exception ex) { result.Errors.Add(r, ex.Message); } } if (!result.Errors.Any()) { foreach (var timeRegistration in toAdd) { _aggregateRootRepository.Save(timeRegistration); result.Success++; } } return result; }
public void GetOrAdd() { var dictionary = new Dictionary<string, string>(); dictionary.GetOrAdd("fookey", "bar").Should().Be("bar"); dictionary.GetOrAdd("fookey", "foo").Should().Be("bar"); Action action = () => dictionary.GetOrAdd(null, ""); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("key"); dictionary = null; action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("source"); }
public void GetOrAddOverload() { var dictionary = new Dictionary<string, string>(); Func<string, string> adder = (key) => { key.Should().Be("fookey"); return "bar"; }; dictionary.GetOrAdd("fookey", adder).Should().Be("bar"); dictionary.GetOrAdd("fookey", adder).Should().Be("bar"); Action action = () => dictionary.GetOrAdd(null, addValueFactory: adder); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("key"); action = () => dictionary.GetOrAdd("fookey", addValueFactory: null); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("addValueFactory"); dictionary = null; action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("source"); }