本文整理汇总了C#中ConcurrentDictionary.Any方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.Any方法的具体用法?C# ConcurrentDictionary.Any怎么用?C# ConcurrentDictionary.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentDictionary
的用法示例。
在下文中一共展示了ConcurrentDictionary.Any方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadSymbols
void LoadSymbols()
{
MarketSymbols = new ConcurrentDictionary<string, string>();
resourceName = new []
{
"Windows.Controls.Resources.NYSE.csv",
"Windows.Controls.Resources.NASDAQ.csv",
"Windows.Controls.Resources.AMEX.csv"
};
var asm = Assembly.GetExecutingAssembly();
Parallel.ForEach(resourceName, (s) => ReadResourceSymbolFile(s, asm));
if (!MarketSymbols.Any())
return;
Symbols = MarketSymbols.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
for (int i = 0; i < Symbols.Count; i++)
{
var itm = Symbols.ElementAt(i);
var idx = int.Parse(itm.Value.Substring(0, 1));
// Stripping the market index char
var val = itm.Value.Substring(1);
Symbols[itm.Key] = val;
this.AppendValues(itm.Key, val, icon[idx]);
}
}
示例2: CreateProjectMapAsync
private async Task<ConcurrentDictionary<Project, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>>> CreateProjectMapAsync(
ConcurrentSet<ISymbol> symbols)
{
using (Logger.LogBlock(FeatureId.FindReference, FunctionId.FindReference_CreateProjectMapAsync, this.cancellationToken))
{
Func<Project, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> createQueue = p => new ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>();
var projectMap = new ConcurrentDictionary<Project, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>>();
#if PARALLEL
Roslyn.Utilities.TaskExtensions.RethrowIncorrectAggregateExceptions(cancellationToken, () =>
{
symbols.AsParallel().WithCancellation(cancellationToken).ForAll(s =>
{
finders.AsParallel().WithCancellation(cancellationToken).ForAll(f =>
{
var projects = f.DetermineProjectsToSearch(s, solution, cancellationToken) ?? SpecializedCollections.EmptyEnumerable<Project>();
foreach (var project in projects.Distinct())
{
projectMap.GetOrAdd(project, createQueue).Enqueue(ValueTuple.Create(s, f));
}
});
});
});
#else
var scope = this.documents != null ? this.documents.Select(d => d.Project).ToImmutableHashSet() : null;
foreach (var s in symbols)
{
foreach (var f in finders)
{
this.cancellationToken.ThrowIfCancellationRequested();
var projects = await f.DetermineProjectsToSearchAsync(s, solution, scope, cancellationToken).ConfigureAwait(false) ?? SpecializedCollections.EmptyEnumerable<Project>();
foreach (var project in projects.Distinct().WhereNotNull())
{
if (scope == null || scope.Contains(project))
{
projectMap.GetOrAdd(project, createQueue).Enqueue(ValueTuple.Create(s, f));
}
}
}
}
#endif
Contract.ThrowIfTrue(projectMap.Any(kvp => kvp.Value.Count != kvp.Value.ToSet().Count));
return projectMap;
}
}
示例3: CreateDocumentMapAsync
private async Task<ConcurrentDictionary<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>>> CreateDocumentMapAsync(
ConcurrentDictionary<Project, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> projectMap)
{
using (Logger.LogBlock(FeatureId.FindReference, FunctionId.FindReference_CreateDocumentMapAsync, this.cancellationToken))
{
Func<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> createQueue = d => new ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>();
var documentMap = new ConcurrentDictionary<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>>();
#if PARALLEL
Roslyn.Utilities.TaskExtensions.RethrowIncorrectAggregateExceptions(cancellationToken, () =>
{
projectMap.AsParallel().WithCancellation(cancellationToken).ForAll(kvp =>
{
var project = kvp.Key;
var projectQueue = kvp.Value;
projectQueue.AsParallel().WithCancellation(cancellationToken).ForAll(symbolAndFinder =>
{
var symbol = symbolAndFinder.Item1;
var finder = symbolAndFinder.Item2;
var documents = finder.DetermineDocumentsToSearch(symbol, project, cancellationToken) ?? SpecializedCollections.EmptyEnumerable<Document>();
foreach (var document in documents.Distinct().WhereNotNull())
{
if (includeDocument(document))
{
documentMap.GetOrAdd(document, createQueue).Enqueue(symbolAndFinder);
}
}
});
});
});
#else
foreach (var kvp in projectMap)
{
var project = kvp.Key;
var projectQueue = kvp.Value;
foreach (var symbolAndFinder in projectQueue)
{
this.cancellationToken.ThrowIfCancellationRequested();
var symbol = symbolAndFinder.Item1;
var finder = symbolAndFinder.Item2;
var documents = await finder.DetermineDocumentsToSearchAsync(symbol, project, this.documents, cancellationToken).ConfigureAwait(false) ?? SpecializedCollections.EmptyEnumerable<Document>();
foreach (var document in documents.Distinct().WhereNotNull())
{
if (this.documents == null || this.documents.Contains(document))
{
documentMap.GetOrAdd(document, createQueue).Enqueue(symbolAndFinder);
}
}
}
}
#endif
Contract.ThrowIfTrue(documentMap.Any(kvp => kvp.Value.Count != kvp.Value.ToSet().Count));
return documentMap;
}
}
示例4: RaiseNewPCEntries
public void RaiseNewPCEntries(ConcurrentDictionary<UInt32, ActorEntity> actorEntities)
{
if (!actorEntities.Any())
{
return;
}
// THIRD PARTY
PluginHost.Instance.RaiseNewPCEntries(actorEntities);
}
示例5: GetData
public BermudaResult GetData(string domain, string query, string mapreduce, string merge, string paging, int remdepth, string command, string cursor, string paging2)
{
var args = ParseCommand(command);
bool noCache = args.Contains("-nocache");
bool makeCursor = cursor == MakeCursorToken;
bool useCursor = !makeCursor && !string.IsNullOrWhiteSpace(cursor);
DateTime minDate = DateTime.MinValue;
DateTime maxDate = DateTime.MaxValue;
if (remdepth > 0)
{
//map
var queryHash = cursor ?? GetQueryHash(domain, query, mapreduce, merge, paging, null);
//reduce
BermudaResult cachedDatapoints;
if (!noCache && CachedData.TryGetValue(queryHash, out cachedDatapoints) && (DateTime.Now.Ticks - cachedDatapoints.CreatedOn) < CacheLifetime)
{
#if DEBUG
if (CacheTraceMessageLevel < 3) Trace.WriteLine("returned CACHED BLOBS DATAPOINTS results FOR ENTIRE BLOB SET [REMDEPTH:" + remdepth + "]");
#endif
if (useCursor)
{
var dataType = LinqRuntimeTypeBuilder.GetTypeFromTypeKey(cachedDatapoints.DataType);
return GetCursorData(paging2, cachedDatapoints, dataType);
}
else
{
return new BermudaResult { DataType = cachedDatapoints.DataType, Data = cachedDatapoints.Data, Metadata = new BermudaNodeStatistic { Notes = "Cache_Hit_1" }, CacheKey = cachedDatapoints.CacheKey };
}
}
else
{
if (useCursor) throw new Exception("Cursor " + cursor + " not found");
//var assignments = PartitionBlobs(domain, blobInterfaces, minDate, maxDate, false, true);
var reducers = HostEnvironment.Instance.GetAvailablePeerConnections();
if (!reducers.Any()) throw new Exception("Specified dataset not loaded: " + domain);
ConcurrentDictionary<PeerInfo, BermudaResult> results = new ConcurrentDictionary<PeerInfo, BermudaResult>();
Stopwatch sw = new Stopwatch();
sw.Start();
List<Task> tasks = new List<Task>();
foreach (var reducer in reducers)
{
Task t = new Task((peerObj) =>
{
var peerInfo = peerObj as PeerInfo;
var initiated = DateTime.Now;
var subqueryHash = GetQueryHash(domain, query, mapreduce, merge, paging, peerInfo.ToString());
Stopwatch sw3 = new Stopwatch();
sw3.Start();
//see if the cache contains a matching result and return it if it's not outdated
BermudaResult cachedDatapoints2;
if (!noCache && CachedData.TryGetValue(subqueryHash, out cachedDatapoints2) && (DateTime.Now.Ticks - cachedDatapoints2.CreatedOn) < CacheLifetime)
{
if (CacheTraceMessageLevel < 2) Trace.WriteLine("returned CACHED BLOB DATAPOINT results FOR BLOB SUBSET [REMDEPTH:" + remdepth + "]");
BermudaResult res = null;
if (useCursor)
{
var dataType2 = LinqRuntimeTypeBuilder.GetTypeFromTypeKey(cachedDatapoints2.DataType);
res = GetCursorData(paging2, cachedDatapoints2, dataType2);
}
else
{
res = new BermudaResult { DataType = cachedDatapoints2.DataType, Data = cachedDatapoints2.Data, Metadata = new BermudaNodeStatistic { Notes = "Cache_Hit_2" } };
}
results[peerInfo] = res;
}
else
{
try
{
Stopwatch sw2 = new Stopwatch();
sw2.Start();
BermudaResult subresult = null;
if (peerInfo.Equals(Endpoint))
{
subresult = GetData(domain, query, mapreduce, merge, paging, remdepth - 1, command, cursor, paging2);
}
else
{
using (var client = HostEnvironment.GetServiceClient(peerInfo))
{
subresult = client.GetData(domain, query, mapreduce, merge, paging, remdepth - 1, command, cursor, paging2);
}
//subresult = GetDataFromPeer(domain, query, mapreduce, merge, minDate, maxDate, remdepth - 1, command, assignment.PeerEndpoint.Endpoint);
}
sw2.Stop();
//.........这里部分代码省略.........
示例6: WhenInboundHasProblemsOutboundJustKeepsOnTrucking
public void WhenInboundHasProblemsOutboundJustKeepsOnTrucking(int numberOfMessages)
{
// arrange
var receivedMessageCount = 0;
var messageTracker = new ConcurrentDictionary<Guid, int>();
var resetEvent = new ManualResetEvent(false);
orderSystemHandlerActivator.Handle<PlaceOrderRequest>(req =>
{
if (req.What != "beer" || req.HowMuch != 12) return;
OnCommit.Do(() =>
{
messageTracker.AddOrUpdate(req.MsgId, 1, (id, count) => count + 1);
var newValue = Interlocked.Increment(ref receivedMessageCount);
if (newValue >= numberOfMessages)
{
resetEvent.Set();
}
});
});
var timeout = numberOfMessages.Seconds();
var keepMakingChaos = true;
var chaosMonkey = new Thread(() =>
{
while (keepMakingChaos)
{
Thread.Sleep(0.1.Seconds());
inbound.Stop();
Console.WriteLine("Inbound stopped - {0} messages processed...", receivedMessageCount);
Thread.Sleep(0.2.Seconds());
inbound.Start();
Thread.Sleep(2.2331.Seconds());
}
});
// act
chaosMonkey.Start();
numberOfMessages.Times(() => pricedesk.Send(CreateMessage()));
// assert
var resetEventWasSet = resetEvent.WaitOne(timeout + 5.Seconds());
keepMakingChaos = false;
chaosMonkey.Join();
// chill, be more sure to empty the queue completely
Thread.Sleep(1.Seconds());
Assert.That(resetEventWasSet, Is.True, "Request was not received in order system within timeout of {0}", timeout);
receivedMessageCount.ShouldBeGreaterThanOrEqualTo(numberOfMessages);
Console.WriteLine("Actual number of received messages: {0}", receivedMessageCount);
if (messageTracker.Any(t => t.Value > 1))
{
Console.WriteLine(@"The following IDs were received more than once:
{0}", string.Join(Environment.NewLine, messageTracker.Where(t => t.Value > 1).Select(kvp => " " + kvp.Key + ": " + kvp.Value)));
}
messageTracker.Count.ShouldBe(numberOfMessages);
}
示例7: CrawlWikiSectionPagesForData
// TODO: VehicleDetails will have to be changed to take an IVehicle as the value data type
// TODO: Pass in Enum of vehicle type to use for the processing call
public void CrawlWikiSectionPagesForData(HtmlDocument wikiHomePage, ConcurrentDictionary<string, HtmlDocument> vehicleWikiPagesContent,
ConcurrentDictionary<string, string> localFileChanges, Dictionary<string, GroundVehicle> vehicleDetails, List<string> errorsList,
Stopwatch overallStopwatch, bool createJsonFiles, bool createHtmlFiles, bool createExcelFile)
{
bool parseErrorsEncountered = _webCrawler.DoesTheDocumentContainParseErrors(wikiHomePage);
if (parseErrorsEncountered)
{
_consoleManager.HandleHtmlParseErrors(wikiHomePage);
}
else
{
// Setup initial vars
List<HtmlNode> vehicleWikiEntryLinks = new List<HtmlNode>();
webCrawlerStopwatch.Start();
// This is outside of the method because of the recursive call and we don't want the user having to press enter more than once
_consoleManager.WriteInputInstructionsAndAwaitUserInput(ConsoleColor.Yellow, ConsoleKey.Enter, "Press ENTER to begin searching for links to vehicle pages.");
Dictionary<string, int> linksFound = _webCrawler.GetLinksToVehiclePages(vehicleWikiEntryLinks, wikiHomePage);
int totalNumberOfLinksBasedOnPageText = linksFound.Where(l => l.Key.Equals("TotalNumberOfLinksBasedOnPageText")).Single().Value;
int totalNumberOfLinksFoundViaDomTraversal = linksFound.Where(l => l.Key.Equals("TotalNumberOfLinksFoundViaDomTraversal")).Single().Value;
webCrawlerStopwatch.Stop();
// Setup thread-safe collections for processing
ConcurrentDictionary<int, HtmlNode> linksToVehicleWikiPages = new ConcurrentDictionary<int, HtmlNode>();
// Populate the full list of links we need to traverse
for (int i = 0; i < vehicleWikiEntryLinks.Count(); i++)
{
HtmlNode linkNode = vehicleWikiEntryLinks[i];
linksToVehicleWikiPages.TryAdd(i, linkNode);
}
pageHtmlRetrievalStopwatch.Start();
// Crawl the pages concurrently
Task[] webCrawlerTasks = new Task[4]
{
// Going from 2 to 4 tasks halves the processing time, after 4 tasks the performance gain is negligible
Task.Factory.StartNew(() => _webCrawler.GetPageHtml(linksToVehicleWikiPages, vehicleWikiPagesContent)),
Task.Factory.StartNew(() => _webCrawler.GetPageHtml(linksToVehicleWikiPages, vehicleWikiPagesContent)),
Task.Factory.StartNew(() => _webCrawler.GetPageHtml(linksToVehicleWikiPages, vehicleWikiPagesContent)),
Task.Factory.StartNew(() => _webCrawler.GetPageHtml(linksToVehicleWikiPages, vehicleWikiPagesContent))
};
// Wait until we have crawled all of the pages
Task.WaitAll(webCrawlerTasks);
_consoleManager.WritePaddedText("Finished extracting html documents from vehicle pages.");
pageHtmlRetrievalStopwatch.Stop();
_consoleManager.WriteHorizontalSeparator();
_consoleManager.HandleCreateFileTypePrompts(createJsonFiles, createHtmlFiles, createExcelFile);
int indexPosition = 1;
processingStopwatch.Start();
// Extract information from the pages we've traversed
ProcessGroundForcesWikiHtmlFiles(vehicleWikiPagesContent, localFileChanges, vehicleDetails, vehicleWikiEntryLinks, errorsList, indexPosition, totalNumberOfLinksBasedOnPageText, createJsonFiles, createHtmlFiles, createExcelFile);
processingStopwatch.Stop();
_consoleManager.WriteLineInColourPreceededByBlankLine(ConsoleColor.Green, $"Finished processing html files for vehicle data{(createExcelFile || createHtmlFiles || createJsonFiles ? " and writing local changes." : ".")}");
if (localFileChanges.Any())
{
_logger.HandleLocalFileChanges(localFileChanges);
}
_consoleManager.WriteHorizontalSeparator();
if (errorsList.Any())
{
_logger.HandleProcessingErrors(errorsList);
}
_consoleManager.WriteHorizontalSeparator();
overallStopwatch.Stop();
_consoleManager.WriteProcessingSummary(overallStopwatch.Elapsed, totalNumberOfLinksBasedOnPageText, totalNumberOfLinksFoundViaDomTraversal, vehicleDetails.Count());
}
}
示例8: RemoveObjectsFromTenantAsync
private async Task RemoveObjectsFromTenantAsync()
{
var client = TestClients.GetSAuthc1Client();
var results = new ConcurrentDictionary<string, Exception>();
// Delete applications
var deleteApplicationTasks = this.CreatedApplicationHrefs.Select(async href =>
{
try
{
var application = await client.GetResourceAsync<IApplication>(href);
var deleteResult = await application.DeleteAsync();
results.TryAdd(href, null);
}
catch (ResourceException rex)
{
if (rex.Code == 404)
{
// Already deleted
results.TryAdd(href, null);
}
}
catch (Exception e)
{
results.TryAdd(href, e);
}
});
// Delete directories
var deleteDirectoryTasks = this.CreatedDirectoryHrefs.Select(async href =>
{
try
{
var directory = await client.GetResourceAsync<IDirectory>(href);
var deleteResult = await directory.DeleteAsync();
results.TryAdd(href, null);
}
catch (ResourceException rex)
{
if (rex.Code == 404)
{
// Already deleted
results.TryAdd(href, null);
}
}
catch (Exception e)
{
results.TryAdd(href, e);
}
});
// Delete organizations
var deleteOrganizationTasks = this.CreatedOrganizationHrefs.Select(async href =>
{
try
{
var org = await client.GetResourceAsync<IOrganization>(href);
var deleteResult = await org.DeleteAsync();
results.TryAdd(href, null);
}
catch (ResourceException rex)
{
if (rex.Code == 404)
{
// Already deleted
results.TryAdd(href, null);
}
}
catch (Exception e)
{
results.TryAdd(href, e);
}
});
await Task.WhenAll(
Task.WhenAll(deleteApplicationTasks),
Task.WhenAll(deleteDirectoryTasks),
Task.WhenAll(deleteOrganizationTasks));
// All done! Throw errors if any occurred
bool anyErrors = results.Any(kvp => kvp.Value != null);
if (anyErrors)
{
throw new ApplicationException(
"Errors occurred during test cleanup. Full log: " + Environment.NewLine
+ string.Join(Environment.NewLine, results.Select(kvp => $"{kvp.Key} : '{(kvp.Value == null ? "Good" : kvp.Value.Message)}'")));
}
}
示例9: RunDictionaryTest_Add1
private static bool RunDictionaryTest_Add1(int cLevel, int initSize, int threads, int addsPerThread)
{
TestHarness.TestLog(
"* RunDictionaryTest_Add1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})",
cLevel, initSize, threads, addsPerThread);
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
ThreadPool.QueueUserWorkItem(
(o) =>
{
for (int j = 0; j < addsPerThread; j++)
{
dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
if (dict.Any(pair => pair.Key != -pair.Value))
{
TestHarness.TestLog(" > Invalid value for some key in the dictionary.");
return false;
}
var gotKeys = dict.Select(pair => pair.Key).OrderBy(i => i).ToArray();
var expectKeys = Enumerable.Range(0, threads * addsPerThread);
if (!gotKeys.SequenceEqual(expectKeys))
{
TestHarness.TestLog(" > The set of keys in the dictionary is invalid.");
return false;
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = threads * addsPerThread;
if (dict.Count != expectedCount || dict.ToArray().Length != expectedCount || dict.ToList().Count() != expectedCount)
{
TestHarness.TestLog(" > Incorrect count of elements reported for the dictionary.");
return false;
}
return true;
}
示例10: RunDictionaryTest
private static bool RunDictionaryTest(int cLevel, int initSize, int threads, int addsPerThread, TestMethod testMethod)
{
TestHarness.TestLog("* RunDictionaryTest_{0}, Level={1}, initSize={2}, threads={3}, addsPerThread={4})",
PrintTestMethod(testMethod), cLevel, initSize, threads, addsPerThread);
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
ThreadPool.QueueUserWorkItem(
(o) =>
{
for (int j = 0; j < addsPerThread; j++)
{
//call either of the two overloads of GetOrAdd
if (j + ii % 2 == 0)
{
dict.GetOrAdd(j, -j);
}
else
{
dict.GetOrAdd(j, x => -x);
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
bool passed = true;
if (dict.Any(pair => pair.Key != -pair.Value))
{
TestHarness.TestLog(" > Invalid value for some key in the dictionary.");
passed = false;
}
var gotKeys = dict.Select(pair => pair.Key).OrderBy(i => i).ToArray();
var expectKeys = Enumerable.Range(0, addsPerThread);
if (!gotKeys.SequenceEqual(expectKeys))
{
TestHarness.TestLog(" > The set of keys in the dictionary is invalid.");
passed = false;
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = addsPerThread;
int count1 = dict.Count, count2 = dict.ToArray().Length,
count3 = dict.ToList().Count;
if (count1 != expectedCount || count2 != expectedCount || count3 != expectedCount)
{
TestHarness.TestLog(" > Incorrect count of elements reported for the dictionary. Expected {0}, Dict.Count {1}, ToArray.Length {2}, ToList.Count {3}",
expectedCount, count1, count2, count3);
passed = false;
}
return passed;
}
示例11: TaskView
public TaskView(Gtk.TreeModel model, IPreferences preferences)
{
if (preferences == null)
throw new ArgumentNullException ("preferences");
TreeView = new TreeView ();
#if GTK_2_12
// set up the timing for the tooltips
TreeView.Settings.SetLongProperty("gtk-tooltip-browse-mode-timeout", 0, "Tasque:TaskTreeView");
TreeView.Settings.SetLongProperty("gtk-tooltip-browse-timeout", 750, "Tasque:TaskTreeView");
TreeView.Settings.SetLongProperty("gtk-tooltip-timeout", 750, "Tasque:TaskTreeView");
ConnectEvents();
#endif
// TODO: Modify the behavior of the TreeView so that it doesn't show
// the highlighted row. Then, also tie in with the mouse hovering
// so that as you hover the mouse around, it will automatically
// select the row that the mouse is hovered over. By doing this,
// we should be able to not require the user to click on a task
// to select it and THEN have to click on the column item they want
// to modify.
filterTaskList = null;
modelFilter = new Gtk.TreeModelFilter (model, null);
modelFilter.VisibleFunc = FilterFunc;
modelFilter.RowInserted += OnRowInsertedHandler;
modelFilter.RowDeleted += OnRowDeletedHandler;
Refilter ();
//Model = modelFilter
TreeView.Selection.Mode = Gtk.SelectionMode.Single;
TreeView.RulesHint = false;
TreeView.HeadersVisible = false;
TreeView.HoverSelection = true;
// TODO: Figure out how to turn off selection highlight
columns = new List<ITaskColumn> ();
var nodeList = AddinManager.GetExtensionNodes (typeof(ITaskColumn)).Cast<TaskColNode> ();
var nodes = new List<TaskColNode> (nodeList);
foreach (var node in nodes)
AddColumn (node, nodes);
rowEditingDictionary = new ConcurrentDictionary<ITaskColumn, TaskRowEditingEventArgs> ();
columns.Sort ((x, y) => x.DefaultPosition.CompareTo (y.DefaultPosition));
foreach (var col in columns) {
col.Initialize (Model, this, preferences);
col.CellEditingStarted += (sender, e) => {
if (rowEditingDictionary.IsEmpty)
IsTaskBeingEdited = true;
if (!rowEditingDictionary.Any (v => v.Value.ITask == e.ITask)) {
if (RowEditingStarted != null)
RowEditingStarted (this, e);
}
rowEditingDictionary.TryAdd ((ITaskColumn)sender, e);
};
col.CellEditingFinished += (sender, e) => {
TaskRowEditingEventArgs args;
rowEditingDictionary.TryRemove ((ITaskColumn)sender, out args);
if (!rowEditingDictionary.Any (v => v.Value.ITask == e.ITask)) {
if (RowEditingFinished != null)
RowEditingFinished (this, e);
}
if (rowEditingDictionary.IsEmpty)
IsTaskBeingEdited = false;
};
TreeView.AppendColumn (col.TreeViewColumn);
}
}
示例12: Configure
internal static void Configure()
{
if(null != All) { return; }
lock(_Lock){
if(null != All) { return; }
// all
All = new ConcurrentDictionary
<string, IDataProviderSetting>();
IEnumerator all = ConfigurationManager
.ConnectionStrings
.GetEnumerator();
while(all.MoveNext()){
var settings = all.Current
as ConnectionStringSettings;
if(null == settings) { continue; }
string[] names = settings.Name.SplitAndTrim(",");
foreach (var name in names)
{
Add(new DataProviderSetting() {
Name = name.ToUpper(),
ConnectionString = settings.ConnectionString,
ProviderName = settings.ProviderName,
});
}
}
if(All.Any() && null == Default) {
Default = All.FirstOrDefault().Value;
}
}
}
示例13: TryToAddModels
public static void TryToAddModels(ConcurrentDictionary<string, TypeInfo> models, Type type, XmlCommentDocumentationProvider docProvider, ConcurrentDictionary<string, string> typesToReturn = null, int level = 0)
{
var _type = type;
if (type.IsArray)
_type = type.GetElementType();
else if (type.IsGenericType)
_type = type.GetGenericArguments().First();
string typeName = GetTypeName(_type);
if (models.Any(m => m.Key == typeName)) return;
if (IsOutputable(_type))
{
var typeInfo = new TypeInfo { id = typeName };
if (!IgnoreTypes.Contains(_type.Name.ToLower()))
{
typeInfo.description = docProvider.GetSummary(_type);
}
//Ignore properties for .net types
if (!_type.Assembly.FullName.Contains("System") && !_type.Assembly.FullName.Contains("mscorlib"))
{
var modelInfoDic = new Dictionary<string, PropInfo>();
foreach (var propertyInfo in _type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (propertyInfo.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).FirstOrDefault() != null)
continue;
var propInfo = new PropInfo();
string propName = GetPropertyName(propertyInfo);
Type propType = docProvider.GetType(propertyInfo);
SwaggerType swaggerType = GetSwaggerType(propType);
propInfo.type = swaggerType.Name;
propInfo.items = swaggerType.Items;
propInfo.required = IsRequired(propertyInfo, docProvider);
if (!modelInfoDic.Keys.Contains(propName))
modelInfoDic.Add(propName, propInfo);
if (!IgnoreTypes.Contains(propInfo.type))
{
propInfo.description = docProvider.GetSummary(propertyInfo);
if (propertyInfo.PropertyType.IsEnum)
{
modelInfoDic[propName][email protected] = propertyInfo.PropertyType.GetEnumNames();
}
//Don't go too deep
if (level < 10)
{
TryToAddModels(models, swaggerType.type, docProvider, typesToReturn, ++level);
}
}
}
typeInfo.properties = modelInfoDic;
}
if (_type.IsEnum)
{
typeInfo.values = _type.GetEnumNames();
}
models.TryAdd(typeName, typeInfo);
}
}