internal static void StackEquals(ContextStack <byte[]> stack1, ContextStack <byte[]> stack2) { var hash1 = stack1.Select(o => Hashes.Hash256(o)).ToArray(); var hash2 = stack2.Select(o => Hashes.Hash256(o)).ToArray(); AssertEx.CollectionEquals(hash1, hash2); }
PackageSerializationManager( ) { _serializersCacheManager = new SerializersCacheManager(this); _graphContextStack = new ContextStack(); this._rootSerializableObjectContext = null; }
public void PushContext(Context ctx) { ContextStack.Push(CurrentContext); CurrentContext = ctx; NotifyMessage("コンテキストを変更しました。"); ShowCommandsAsUsers(); }
public void ChangeContext(Context ctx) { ContextStack.Clear(); CurrentContext = ctx; NotifyMessage("コンテキストを変更しました。"); ShowCommandsAsUsers(); }
static void Main(string[] args) { //<Snippet2> // Create a ContextStack. ContextStack stack = new ContextStack(); //</Snippet2> //<Snippet3> // Push ten items on to the stack and output the value of each. for (int number = 0; number < 10; number++) { Console.WriteLine("Value pushed to stack: " + number.ToString()); stack.Push(number); } //</Snippet3> //<Snippet4> // Pop each item off the stack. object item = null; while ((item = stack.Pop()) != null) { Console.WriteLine("Value popped from stack: " + item.ToString()); } //</Snippet4> }
/// <summary> /// Creates a new child context based on the current context instance. /// Includes an optional configuration method that can be immediately /// applied to the new context. This method is used internally to create /// contexts for cloned clients and network method calls having custom /// configuration callbacks. /// </summary> private ContextStack CreateChildContext(Action <IContext>?configure) { var context = new ContextStack(_context); configure?.Invoke(context); return(context); }
protected virtual void OnSessionDisposed(EventArgs e) { _errors.Clear(); _errors = null; _serializersCache.Clear(); _serializersCache = null; _instancesByNameCache.Clear(); _instancesByNameCache = null; _instancesByValueCache.Clear(); _instancesByValueCache = null; _session = null; _contextStack = null; _resolveNameHandler = null; _serializationCompleteHandler = null; if (SessionDisposed != null) { SessionDisposed(this, e); } if (_serializationCompleteHandler != null) { _serializationCompleteHandler(this, EventArgs.Empty); } }
public void Indexer_GetWithoutItems_ReturnsNull() { var stack = new ContextStack(); Assert.Null(stack[1]); Assert.Null(stack[typeof(int)]); }
[Fact] // Item (Int32) public void Indexer1_Level_Negative() { ContextStack stack = new ContextStack(); stack.Push(new Foo()); ArgumentOutOfRangeException ex; ex = Assert.Throws <ArgumentOutOfRangeException>(() => stack[-1]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); } ex = Assert.Throws <ArgumentOutOfRangeException>(() => stack[-5]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); } }
public void Append_NoItems_Success() { var stack = new ContextStack(); stack.Append("value"); Assert.Equal("value", stack[0]); }
private bool ParseDollar(TemplateStream stream, TokenList tokens, ContextStack context, ScopeStack scope) { if (stream.Current != '$' || scope.Current == Scope.Block) { return(false); } var next = stream.Peek(); if (next == '$') { stream.Advance(2); return(true); } if (char.IsLetter(next)) { scope.Push(Scope.Statement); stream.Advance(); return(true); } if (next == '{') { scope.Push(Scope.Block); stream.Advance(); return(true); } return(false); }
public override object Execute(List <string> args) { if (args.Count != 1 || !CacheContext.TryGetTag(args[0], out var tag)) { return(false); } var oldContext = ContextStack.Context; TagInstance = tag; using (var stream = CacheContext.OpenTagCacheRead()) TagDefinition = CacheContext.Deserialize(stream, TagInstance); ContextStack.Push(EditTagContextFactory.Create(ContextStack, CacheContext, TagInstance, TagDefinition)); var groupName = CacheContext.GetString(TagInstance.Group.Name); var tagName = TagInstance?.Name ?? $"0x{TagInstance.Index:X4}"; Console.WriteLine($"Tag {tagName}.{groupName} has been opened for editing."); Console.WriteLine("New commands are now available. Enter \"help\" to view them."); Console.WriteLine("Use \"exit\" to return to {0}.", oldContext.Name); return(true); }
/// <summary>Raises the <see cref="E:System.ComponentModel.Design.Serialization.DesignerSerializationManager.SessionDisposed" /> event. </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param> protected virtual void OnSessionDisposed(EventArgs e) { try { try { this.sessionDisposedEventHandler?.Invoke(this, e); } finally { this.serializationCompleteEventHandler?.Invoke(this, EventArgs.Empty); } } finally { this.resolveNameEventHandler = null; this.serializationCompleteEventHandler = null; this.instancesByName = null; this.namesByInstance = null; this.serializers = null; this.contextStack = null; this.errorList = null; this.session = null; } }
private bool TryReuseExistingContextFrom(ContextStack stack, out T context, out IDisposable disposable) { while (true) { var current = stack.Head; if (current == null) { break; } if (Interlocked.CompareExchange(ref stack.Head, current.Next, current) != current) { continue; } context = current.Value; if (context == null) { continue; } if (!context.InUse.Raise()) { continue; } context.Renew(); disposable = new ReturnRequestContext { Parent = this, Context = context }; return(true); } context = default(T); disposable = null; return(false); }
/// <summary> /// Internal Helper function to retrieve the transaction record provided /// by the network following network consensus regarding a query or transaction. /// </summary> private async Task <Proto.TransactionRecord> GetTransactionRecordAsync(ContextStack context, TransactionID transactionRecordId) { var gateway = RequireInContext.Gateway(context); var payer = RequireInContext.Payer(context); var transfers = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit)); var transactionId = Transactions.GetOrCreateTransactionID(context); var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Transaction Record"); var query = new Query { TransactionGetRecord = new TransactionGetRecordQuery { Header = Transactions.SignQueryHeader(transactionBody, payer), TransactionID = transactionRecordId } }; var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getServerMethod, getResponseCode); var responseCode = getResponseCode(response); if (responseCode != ResponseCodeEnum.Ok) { throw new TransactionException("Unable to retrieve transaction record.", Protobuf.FromTransactionId(transactionRecordId), (ResponseCode)responseCode); } ValidateResult.PreCheck(transactionId, getResponseCode(response)); return(response.TransactionGetRecord.TransactionRecord);
/// <summary> /// Initializes a new instance of the <see cref="AttachedContext" /> /// class. /// </summary> /// <param name="contextStack">The context stack.</param> /// <param name="context">The context.</param> /// <exception cref="System.ArgumentNullException">contextStack</exception> /// <autogeneratedoc /> /// TODO Edit XML Comment Template for #ctor public AttachedContext(ContextStack <InfoContext> contextStack, InfoContext context) { _contextStack = contextStack ?? throw new ArgumentNullException(nameof(contextStack)); _infoContext = context; contextStack.Push(_infoContext); }
[Test] // Item (Int32) public void Indexer1_Level_Negative() { ContextStack stack = new ContextStack(); stack.Push(new Foo()); try { object context = stack [-1]; Assert.Fail("#A1:" + context); } catch (ArgumentOutOfRangeException ex) { Assert.AreEqual(typeof(ArgumentOutOfRangeException), ex.GetType(), "#A2"); Assert.IsNull(ex.InnerException, "#A3"); Assert.AreEqual(new ArgumentOutOfRangeException("level").Message, ex.Message, "#A4"); Assert.AreEqual("level", ex.ParamName, "#A5"); } try { object context = stack [-5]; Assert.Fail("#B1:" + context); } catch (ArgumentOutOfRangeException ex) { Assert.AreEqual(typeof(ArgumentOutOfRangeException), ex.GetType(), "#B2"); Assert.IsNull(ex.InnerException, "#B3"); Assert.AreEqual(new ArgumentOutOfRangeException("level").Message, ex.Message, "#B4"); Assert.AreEqual("level", ex.ParamName, "#B5"); } }
/// <summary> /// Attempt to go up one level in the Context stack. There must always be one Context active, so /// this method does nothing if there is only one element on the stack. /// </summary> public void PopContext() { if (ContextStack.Count > 1) { ContextStack.Pop(); } }
public static IRList analyse(List <AST_Node> program, SymbolTable globalScope) { Analyser.program = program; instructions = new IRList(); contextStack = new ContextStack(16); enclosureStack = new EnclosureStack(16); contextStack.Push(new Context(int.MaxValue, Context.Kind.STATEMENT)); // Just put something on the stack enclosureStack.Push(new Enclosure(NT.GLOBAL, null, globalScope, int.MaxValue)); program.forEach((n, i) => Console.WriteLine("{0}: {1}".fill(i, n))); Console.WriteLine(); for (cursor = 0; cursor < program.Count; incrementCursor(ref cursor)) { Action <AST_Node> action; AST_Node node = program[cursor]; if (typeDefinitionAnalysers.TryGetValue(node.nodeType, out action)) { action(node); } } isDefineFase = false; for (cursor = 0; cursor < program.Count; incrementCursor(ref cursor)) { analyseNode(program[cursor]); } return(instructions); }
internal ICollection Terminate(ICollection errors) { try { if (this.SerializationComplete != null) { this.SerializationComplete(this, EventArgs.Empty); } } catch { } if ((this._errorList != null) && (this._errorList.Count > 0)) { if ((errors != null) && (errors.Count > 0)) { this._errorList.AddRange(errors); } errors = this._errorList; } this.ResolveName = null; this.SerializationComplete = null; this._instancesByName = null; this._namesByInstance = null; this._serializers = null; this._errorList = null; this._contextStack = null; return(errors); }
private ContextStack MaybeGetCurrentContextStack() { ContextStack x = null; _contextStacksByThreadId?.TryGetValue(NativeMemory.CurrentThreadStats.InternalId, out x); return(x); }
void PushStack(SyntaxMatch curMatch, IEnumerable <SyntaxContext> nextContexts) { if (nextContexts != null) { bool first = true; foreach (var nextContext in nextContexts) { var ctx = nextContext; if (curMatch.WithPrototype != null) { ctx = new SyntaxContextWithPrototype(nextContext, curMatch.WithPrototype); } if (first) { MatchStack = MatchStack.Push(curMatch); first = false; } else { MatchStack = MatchStack.Push(null); } ContextStack = ContextStack.Push(ctx); PushScopeStack(ctx.MetaScope); PushScopeStack(ctx.MetaContentScope); } } }
public IResultWriter EndContext(Globals.ResultWriterDestination dest = Globals.ResultWriterDestination.stdOut) { if (ContextStack.Count > 0) { CurrentContext = ContextStack.Pop(); } return(this); }
void PopMetaContentScopeStack(SyntaxContext currentContext, SyntaxMatch curMatch) { if (ContextStack.Count() == 1) { return; } PopScopeStack(currentContext.MetaContentScope); }
public void DesignerSerializationManager_Context_GetWithSession_ReturnsExpected() { var manager = new SubDesignerSerializationManager(); IDisposable session = manager.CreateSession(); ContextStack context = manager.Context; Assert.Null(context.Current); Assert.Same(context, manager.Context); }
public bool TryEvaluate(ContextStack contextStack, out bool boolResult) { if (objectExpress.TryEvaluate(contextStack, out var result) && TryLossyBoolJudge(result, out boolResult)) { return(true); } boolResult = false; return(false); }
public IResultWriter EndContext(Globals.ResultWriterDestination dest = Globals.ResultWriterDestination.stdOut) { if (ContextStack.Count > 0) { CurrentContext = ContextStack.Pop(); } colNames = new List <string>(); return(this); }
public KnockoutForeachContext <TItem> Foreach <TItem>(Expression <Func <TModel, IList <TItem> > > binding) { var expression = KnockoutExpressionConverter.Convert(binding, CreateData()); var regionContext = new KnockoutForeachContext <TItem>(ViewContext, expression); regionContext.WriteStart(ViewContext.Writer); regionContext.ContextStack = ContextStack; ContextStack.Add(regionContext); return(regionContext); }
public IEnumerable <T> GetAll <T>(string name) { for (ContextStack <TContext>?ctx = this; ctx != null; ctx = ctx._parent) { if (ctx._map.TryGetValue(name, out object?asObject) && asObject is T t) { yield return(t); } } }
public void Append_Context_Null() { ContextStack stack = new ContextStack(); ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => stack.Append(null)); Assert.Equal(typeof(ArgumentNullException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("context", ex.ParamName); }
public void TestPerformance() { ContextStack<int> contextStack = new ContextStack<int>(); Stopwatch s = new Stopwatch(); s.Start(); Parallel.For(0, Loops, i => { using (contextStack.Region(i)) { Assert.AreEqual(i, contextStack.Current); } }); s.Stop(); Trace.WriteLine(s.ToString("{0} loops", Loops)); }
private void InitParsing() { this.ast = new AtTemplateAst(); this.ast.Head.References.Add(new Reference("System.dll")); this.ast.Head.References.Add(new Reference(Assembly.GetExecutingAssembly().Location)); this.currentDirective = this.ast.Body; if (this.outputStack == null) { this.outputStack = new Stack<OutputContext>(); } else { this.outputStack.Clear(); } if (this.contextStack == null) { this.contextStack = new ContextStack(); } else { this.contextStack.Clear(); } if (this.sections == null) { this.sections = new Dictionary<string, object>(); } else { this.sections.Clear(); } this.contextStack.Push(new Context(TemplateMode.Static, string.Empty)); this.lineCount = 0; this.isInGlobalBlock = false; }
public void TestAsync() { const int taskCount = 5000; // Create an asynchronous context in which to run. AsyncContext.Run( async () => { Task[] tasks = new Task[taskCount]; for (int a = 0; a < taskCount; a++) tasks[a] = TaskEx.RunEx( async () => { ContextStack<string> stack = new ContextStack<string>(); TaskCompletionSource tcs1 = new TaskCompletionSource(); TaskCompletionSource tcs2 = new TaskCompletionSource(); TaskCompletionSource tcs3 = new TaskCompletionSource(); string randomString = Guid.NewGuid().ToString(); string randomString2 = Guid.NewGuid().ToString(); using (stack.Region(randomString)) { // Check we have 'A' in the current stack. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.Last()); int threadId = Thread.CurrentThread.ManagedThreadId; // Await the task await TaskEx.Delay(500); // Check we still have 'A' in the current stack. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.Last()); // Create new thread. Task task = TaskEx.RunEx( async () => { int task2Thread = Thread.CurrentThread.ManagedThreadId; // Assess if this is a new thread if (threadId != task2Thread) Interlocked.Increment(ref _task2NewThread); // Check we have 'A' in the current stack. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.Last()); // Wait for the first signal await tcs1.Task; // Check we still have 'A' in the current stack (i.e. we're not affected by additions in first thread. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.Last()); // Add C to stack. using (stack.Region("C")) { // We should have A, C in stack now. Assert.AreEqual("C", stack.Current); Assert.AreEqual(2, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.First()); // Second signal tcs2.SetResult(); // Wait for the 3rd signal await tcs3.Task; // We should still have A, C in stack now. Assert.AreEqual("C", stack.Current); Assert.AreEqual(2, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.First()); } // Back to just having C. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.Last()); // Wait a bit before finishing. await TaskEx.Delay(100); if (task2Thread != Thread.CurrentThread.ManagedThreadId) Interlocked.Increment( ref _task2ThreadSwitch); }); // Add B to stack. using (stack.Region(randomString2)) { // We should have A, B in stack now. Assert.AreEqual(randomString2, stack.Current); Assert.AreEqual(2, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.First()); // Signal 2nd task with first signal. tcs1.SetResult(); // Wait for 2nd task to signal back with 2nd second. await tcs2.Task; // We should still have A, B in stack now. Assert.AreEqual(randomString2, stack.Current); Assert.AreEqual(2, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.First()); // Signal 2nd task with third signal tcs3.SetResult(); // Wait for task to finish. await task; // We should still have A, B in stack now. Assert.AreEqual(randomString2, stack.Current); Assert.AreEqual(2, stack.CurrentStack.Count()); Assert.AreEqual(randomString, stack.CurrentStack.First()); } // We should just have A in stack. Assert.AreEqual(randomString, stack.Current); Assert.AreEqual(1, stack.CurrentStack.Count()); if (threadId != Thread.CurrentThread.ManagedThreadId) Interlocked.Increment(ref _task1ThreadSwitch); } // The stack should be empty Assert.IsNull(stack.Current); Assert.AreEqual(0, stack.CurrentStack.Count()); }); await TaskEx.WhenAll(tasks); }); Trace.WriteLine( String.Format( "Task1 Thread Switch: {1}{0}Task2 Thread Switch: {2}{0}Task2 new thread: {3}{0}Total tasks: {4}", Environment.NewLine, _task1ThreadSwitch, _task2ThreadSwitch, _task2NewThread, taskCount)); }
public void TestThreading() { ContextStack<string> stack = new ContextStack<string>(); TestContext(stack); }
static Script PushAll(ContextStack<byte[]> values) { List<Op> result = new List<Op>(); foreach(var v in values.Reverse()) { if(v.Length == 0) { result.Add(OpcodeType.OP_0); } else { result.Add(Op.GetPushOp(v)); } } return new Script(result.ToArray()); }