private static string ConvertCalculatedCharactersToBaseString(IList<char> characters, int baseValue) { var convertedString = new StringBuilder(); foreach (var character in characters.Reverse()) convertedString.Append(character); return convertedString.ToString().PadLeft(Paddings[baseValue], '0'); }
protected override ActionExecutedContext InvokeActionMethodWithFilters(System.Reflection.MethodInfo methodInfo, IDictionary<string, object> parameters, IList<IActionFilter> filters) { if (methodInfo == null) { throw new ArgumentNullException("methodInfo"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (filters == null) { throw new ArgumentNullException("filters"); } ActionExecutingContext preContext = new ActionExecutingContext(ControllerContext, parameters); Func<ActionExecutedContext> continuation = () => new ActionExecutedContext(ControllerContext, false /* canceled */, null /* exception */) { Result = InvokeActionMethod(methodInfo, parameters) }; // need to reverse the filter list because the continuations are built up backward Func<ActionExecutedContext> thunk = filters.Reverse().Aggregate(continuation, (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next)); return thunk(); }
protected override ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, System.Exception exception) { var context = new ExceptionContext(controllerContext, exception); foreach (var filter in filters.Reverse()) { filter.OnException(context); } SetExceptionResult(controllerContext, context); return context; }
private void GenerateResults(List<int>[] prevs, string s, int i, IList<string> temp, IList<IList<string>> results) { if (i < 0) { results.Add(temp.Reverse().ToList()); } else { foreach (var prev in prevs[i]) { temp.Add(s.Substring(prev + 1, i - prev)); GenerateResults(prevs, s, prev, temp, results); temp.RemoveAt(temp.Count - 1); } } }
private string ApplyRules(IList<Rule> rules, string word) { var result = word; foreach (var rule in rules.Reverse()) if ((result = rule.Apply(word)) != null) return result; return result; }
private void SaveDisposeInterceptors(IList<IRequestHandlerInterceptor> interceptors) { foreach (var interceptor in interceptors.Reverse()) { try { IoC.Container.Release(interceptor); interceptor.Dispose(); } catch (Exception exc) { _logger.Error("error disposing " + interceptor, exc); } } }
public void ReverseTest_Int(IList <int> source) { var expected = source.Reverse().ToArray(); var actual = source.ReverseF().ToArrayF(); Assert.Equal(expected, actual); }
private static void ReplaceLineWithNewWords(IList <TWord> iWordList, TChar[] finalTCharString) { var words = iWordList.Reverse().ToArray(); TWord[] finalTWords = new TWord[iWordList.Count]; finalTWords[0] = new TWord(); finalTWords[0].AddStyle(words[0].Style); finalTWords[0].Confidance = words[0].Confidance; for (int i = 0, j = 0; i < finalTCharString.Length; i++) { if (finalTCharString[i].CharData == ' ') { iWordList[j] = finalTWords[j]; j++; finalTWords[j] = new TWord(); finalTWords[j].AddStyle(words[j].Style); finalTWords[j].Confidance = words[j].Confidance; } else { finalTWords[j].AddChar(finalTCharString[i]); } } iWordList[iWordList.Count - 1] = finalTWords[iWordList.Count - 1]; }
/// <inheritdoc /> protected override void InternalCompute() { UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge> dfs = null; try { dfs = new UndirectedDepthFirstSearchAlgorithm <TVertex, TEdge>( this, VisitedGraph, new Dictionary <TVertex, GraphColor>(VisitedGraph.VertexCount)); dfs.BackEdge += BackEdge; dfs.FinishVertex += OnVertexFinished; dfs.Compute(); } finally { if (dfs != null) { dfs.BackEdge -= BackEdge; dfs.FinishVertex -= OnVertexFinished; SortedVertices = _sortedVertices.Reverse().ToArray(); } } }
public RequestDelegate Build() { RequestDelegate app = context => { Console.WriteLine("默认中间件"); return(Task.CompletedTask); }; // 上面的代码是一个默认的中间件 // 重要的是下面几句,这里对Func<RequestDelegate, RequestDelegate>集合进行反转, // 逐一执行添加中间件的委托,最后返回第一个中间件委托 // 这里的作用就是把list里独立的中间件委托给串起来,然后返回反转后的最后一个中间件(实际上的第一个) // 管道才真正的建立起来,每一个中间件都首尾相连 // 兜底中间件传给2号中间件的委托,包含有链子的中间件就被创建出来,把2号中间件返回出来 foreach (var component in _components.Reverse()) { app = component(app); } //上面的一步仅仅是得到第一个中间件返回的一个委托,这个委托等待Kestrel监听请求把HttpContext的请求包传给这个委托,这个 //委托触发了会接连触发一系列的每个中间件,在下面模式请求来了开始执行的这个动作; //HttpContext context = null; //app(context); return(app); }
/// <summary> /// Dispose the scope and container /// </summary> public void Dispose() { // When startup was called, but shutdown not, do this now if (_isStartedUp && !_isShutDown) { // Auto shutdown using (new NoSynchronizationContextScope()) { try { ShutdownAsync().Wait(); } catch (AggregateException ex) { throw ex.GetBaseException(); } } } if (_disposables.Count > 0) { var reversedDisposables = _disposables.Reverse().Where(disposable => disposable != null).ToList(); _disposables.Clear(); foreach (var disposable in reversedDisposables) { disposable?.Dispose(); } } Scope?.Dispose(); Container?.Dispose(); Resolver.Dispose(); }
internal void Lance(int nombreDeQuillesTombees) { SetResultatLancer(nombreDeQuillesTombees); Quilles -= nombreDeQuillesTombees; ++framesFois2; if (ResultatLancer == Lancer.Strike) { ++framesFois2; } if (framesFois2 % 2 == 0) { Quilles = 10; } Score += nombreDeQuillesTombees; if (lancers.Count >= 2 && lancers[lancers.Count - 2] == Lancer.Spare) { Score += nombreDeQuillesTombees; } Score += nombreDeQuillesTombees * lancers.Reverse().Skip(1).Take(2).Count(x => x == Lancer.Strike); if (Frame >= 10 && posDernierLancer == 0) { posDernierLancer = lancers.Count - 1; } if (Frame >= 10 && EstCePasLesLancersSupplementaires()) { PartieFinie = true; } }
public IList <ToDoTask> Sort(IList <ToDoTask> tasks, SEARCH_SORT_TYPE type = SEARCH_SORT_TYPE.ID, SORT_ORDER order = SORT_ORDER.ASCENDING) { switch (type) { case SEARCH_SORT_TYPE.NAME: tasks = tasks.OrderBy(m => m.Title).ToList(); break; case SEARCH_SORT_TYPE.SCOPE: tasks = tasks.OrderBy(m => m.Scope).ToList(); break; case SEARCH_SORT_TYPE.STATUS: tasks = tasks.OrderBy(m => m.Status).ToList(); break; default: tasks = tasks.OrderBy(m => m.Id).ToList(); break; } if (order.Equals(SORT_ORDER.DESCENDING)) { tasks = tasks.Reverse().ToList(); } return(tasks); }
public string this[string key] { get { foreach (var provider in _providers.Reverse()) { string value; if (provider.TryGet(key, out value)) { return(value); } } return(null); } set { if (!_providers.Any()) { throw new InvalidOperationException(Resources.Error_NoSources); } foreach (var provider in _providers) { provider.Set(key, value); } } }
public async Task <HttpResponseMessage> PostAllAsync(int playlistId, [FromBody] IList <PlaylistItemDto> model, CancellationToken cancellationToken) { if (model == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } var playlist = await _services.Media.FindByIdAsync(playlistId, cancellationToken); if (playlist == null) { return(Request.CreateFaultResponse(HttpStatusCode.NotFound, "Playlist was not found.")); } if (ProjectIdentity == null || ProjectIdentity.Id != playlist.ContactId) { return(Request.CreateFaultResponse(HttpStatusCode.Forbidden, "Playlist has already been taken.")); } var store = _services.Media; foreach (var playlistItem in model.Reverse()) { await store.AddItemAsync(new MediaPlaylistItem { PlaylistId = playlistId, Name = playlistItem.Name, MediaType = playlistItem.MediaType, MediaId = playlistItem.MediaId, Duration = playlistItem.Duration, PublishDate = playlistItem.PublishDate }, cancellationToken); } await _services.SaveAsync(cancellationToken); return(Request.CreateResponse(HttpStatusCode.Created)); }
//sort public IList <User> Sort(IList <User> users, SEARCH_SORT_TYPE type = SEARCH_SORT_TYPE.ID, SORT_ORDER order = SORT_ORDER.ASCENDING) { switch (type) { case SEARCH_SORT_TYPE.NAME: users = users.OrderBy(m => m.Name).ToList(); break; case SEARCH_SORT_TYPE.ROLE: users = users.OrderBy(m => m.Role).ToList(); break; case SEARCH_SORT_TYPE.STATUS: users = users.OrderBy(m => m.Status).ToList(); break; default: users = users.OrderBy(m => m.Id).ToList(); break; } if (order.Equals(SORT_ORDER.DESCENDING)) { users = users.Reverse().ToList(); } return(users); }
public void Undo() { foreach (var command in _commands.Reverse()) { command.Undo(); } }
public static IList <T> Reverse <T>(this IList <T> array) { if (array is null) { return(null); } if (array is List <T> list) { list.Reverse(); } else { T[] items = array.Reverse().ToArray(); array.Clear(); foreach (T item in items) { array.Add(item); } } return(array); }
public ResquestDelegate Build() { //ResquestDelegate rd = x => x.ResponseAsync("您还未添加任何中间件!!!"); ResquestDelegate rd; if (_endMethod == null) { rd = x => { Console.WriteLine("没有结束中间件!!!!!!"); throw new Exception(); }; } else { rd = _endMethod; } foreach (var middleware in _components.Reverse()) { rd = middleware(rd); } return(rd); }
/// <summary> /// Decrypt a string using all specified CryptoTools. /// </summary> /// <param name="cryptoTools"></param> /// <param name="message"></param> /// <param name="password"></param> /// <returns></returns> public static string RunSelectedDecryption(IList <iCryptoTool> cryptoTools, string message, string password) { string result = message; //Reverse The list cryptoTools = cryptoTools.Reverse().ToList(); try { if (cryptoTools.Count > 0) { foreach (var tool in cryptoTools) { result = tool.DecryptRun(result, password); } } } catch (Exception e) { Console.WriteLine( "Decryption Failed" + Environment.NewLine + Environment.NewLine + "Please check your password and selected encryption types." ); throw e; } return(result); }
/// <summary> /// Returns all possible orderings of the values in the source list /// </summary> public static IEnumerable <IEnumerable <T> > Permutations <T>(this IList <T> source) { if (source.Count == 2) { yield return(source); yield return(source.Reverse()); } else if (source.Count == 1) { yield return(source); } else { var enumerator = source.GetEnumerator(); int pinned = 0; while (enumerator.MoveNext()) { foreach (var permutation in source.ExceptIndex(pinned).Permutations(source.Count - 1)) { yield return(enumerator.Current.PrependTo(permutation)); } pinned++; } } }
public void Rollback() { foreach (var operation in _operations.Reverse()) { operation.Rollback(); } }
public RequestDelegate Build() { RequestDelegate app = context => { // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened. // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware. var endpoint = context.GetEndpoint(); var endpointRequestDelegate = endpoint?.RequestDelegate; if (endpointRequestDelegate != null) { var message = $"The request reached the end of the pipeline without executing the endpoint: '{endpoint!.DisplayName}'. " + $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " + $"routing."; throw new InvalidOperationException(message); } context.Response.StatusCode = StatusCodes.Status404NotFound; return(Task.CompletedTask); }; foreach (var component in _components.Reverse()) { app = component(app); } return(app); }
private async void QueryPosts(object sender, Microsoft.Phone.Notification.NotificationEventArgs e) { Dispatcher.BeginInvoke(() => { pbLoading.Visibility = Visibility.Visible; }); PostViewModel latestPost = App.Hub.Posts.OrderByDescending(p => p.At).FirstOrDefault(); IList <Post> newPosts = Enumerable.Empty <Post>().ToList(); try { newPosts = latestPost != null ? await App.Hub.Source.NewPosts(latestPost.At) : await App.Hub.Source.Posts(); } catch (Exception ex) { } Dispatcher.BeginInvoke(() => { foreach (var post in newPosts.Reverse()) { App.Hub.Posts.Insert(0, new PostViewModel(post)); } pbLoading.Visibility = Visibility.Collapsed; }); }
public static void RefreshRecentScenes() { if (Classes.Prefrences.SceneHistoryStorage.Collection.List.Count > 0) { Instance.MenuBar.NoRecentScenesItem.Visibility = Visibility.Collapsed; Instance.StartScreen.NoRecentsLabel1.Visibility = Visibility.Collapsed; CleanUpRecentScenesList(); foreach (var RecentItem in Classes.Prefrences.SceneHistoryStorage.Collection.List) { RecentSceneItems.Add(new Tuple <MenuItem, ListBoxItem>(CreateRecentScenesMenuLink(RecentItem.EntryName), CreateRecentScenesItem(RecentItem.EntryName, true))); } foreach (var menuItem in RecentSceneItems.Reverse()) { Instance.MenuBar.RecentScenes.Items.Insert(0, menuItem.Item1); Instance.StartScreen.RecentScenesList.Items.Insert(0, menuItem.Item2); } } else { Instance.MenuBar.NoRecentScenesItem.Visibility = Visibility.Visible; Instance.StartScreen.NoRecentsLabel1.Visibility = Visibility.Visible; } }
internal static void LoadModBuffs(Player player, IList <TagCompound> list) { //buffs list is guaranteed to be compacted int buffCount = Player.maxBuffs; while (buffCount > 0 && player.buffType[buffCount - 1] == 0) { buffCount--; } //iterate the list in reverse, insert each buff at its index and push the buffs after it up a slot foreach (var tag in list.Reverse()) { var mod = ModLoader.GetMod(tag.GetString("mod")); int type = mod?.BuffType(tag.GetString("name")) ?? 0; if (type == 0) { continue; } int index = Math.Min(tag.GetByte("index"), buffCount); Array.Copy(player.buffType, index, player.buffType, index + 1, Player.maxBuffs - index - 1); Array.Copy(player.buffTime, index, player.buffTime, index + 1, Player.maxBuffs - index - 1); player.buffType[index] = type; player.buffTime[index] = tag.GetInt("time"); } }
public void DumpSolution() { foreach (IMove move in answer.Reverse()) { Console.WriteLine(move); } }
private void tvOutputViewer_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { string outputPath = null; // if the double clicked node has no children, aka.. the value if (e.Node.Nodes.Count != 0) { return; } IList <TreeNode> ancestorList = TreeHelpers.GetAncestors(e.Node, x => x.Parent).ToList(); foreach (TreeNode row in ancestorList.Reverse()) { if (string.IsNullOrEmpty(row.Text)) { break; } outputPath += "." + row.Text; } var path = outputPath?.Replace(".body", "").Replace(".PathFinder_JSON_Object", ""); if (path.All(char.IsWhiteSpace)) { return; } rtbSelectedPaths.AppendText(path.TrimStart('.') + "\r\n"); }
/// <summary> /// Gets or sets the value corresponding to a configuration key. /// </summary> /// <param name="key">The configuration key.</param> /// <returns>The configuration value.</returns> public string this[string key] { get { foreach (var provider in _providers.Reverse()) { if (provider.TryGet(key, out string value)) { return(value); } } return(null); } set { if (_providers.Count == 0) { throw new InvalidOperationException(); } foreach (var provider in _providers) { provider.Set(key, value); } } }
protected virtual ActionExecutedContext InvokeActionMethodWithFilters( ControllerContext controllerContext, IList <IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters ) { ActionExecutingContext preContext = new ActionExecutingContext( controllerContext, actionDescriptor, parameters ); Func <ActionExecutedContext> continuation = () => new ActionExecutedContext( controllerContext, actionDescriptor, false /* canceled */ , null /* exception */ ) { Result = InvokeActionMethod(controllerContext, actionDescriptor, parameters) }; // need to reverse the filter list because the continuations are built up backward Func <ActionExecutedContext> thunk = filters .Reverse() .Aggregate( continuation, (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next) ); return(thunk()); }
public static ConnectionStringSettings ConnectionStrings(string key) { ConnectionStringSettings value = null; foreach (var reader in ConnectionStringReaders.Reverse()) { var readerMethod = MethodNameFormatter.GetFormattedName(reader); Logger($"{nameof(ExtensibleSourceConfigurationManager)} attempting to read named connection string: [{key}] using reader: [{readerMethod}]"); value = reader(key); if (null == value) { Logger($"Named connection string: [{key}] not found using reader: [{readerMethod}]"); continue; } Logger($"Named connection string: [{key}] value: [{value}] found using reader: [{readerMethod}'"); break; } if (null == value) { ThrowOnValueNotFound(key); } return(value); }
private int RunLimit(IList <Range> ranges) { int result = end; //ListIterator<Range> it = ranges.listIterator(ranges.size()); //while (it.hasPrevious()) //{ // Range range = it.previous(); foreach (var range in ranges.Reverse()) { if (range.end <= begin) { break; } if (offset >= range.start && offset < range.end) { return(InRange(range) ? range.end : result); } else if (offset >= range.end) { break; } result = range.start; } return(result); }
public void UndoActions() { foreach (var productCommand in _commands.Reverse()) { productCommand.UndoAction(); } }
public void MoveChannels(IList <ChannelInfo> channels, bool up) { if (channels.Count == 0) { return; } if (up && channels[0].GetPosition(this.SubListIndex) <= this.ChannelList.FirstProgramNumber) { return; } int delta = (up ? -1 : +1); foreach (var channel in (up ? channels : channels.Reverse())) { int newProgramNr = channel.GetPosition(this.SubListIndex) + delta; ChannelInfo channelAtNewPos = this.ChannelList.Channels.FirstOrDefault(ch => ch.GetPosition(this.SubListIndex) == newProgramNr); if (channelAtNewPos != null) { channelAtNewPos.ChangePosition(this.SubListIndex, -delta); } channel.ChangePosition(this.SubListIndex, delta); } this.DataRoot.NeedsSaving = true; }
protected override void Dispose(bool disposing) { if (!disposing) { base.Dispose(false); return; } if (_projectFileGenerators != null) { var projectFileGenerators = _projectFileGenerators; _projectFileGenerators = null; UnregisterProjectFileGenerators(projectFileGenerators); } foreach (var disposable in _disposables.Reverse()) { disposable.Dispose(); } _disposables.Clear(); IServiceContainer container = this; container.RemoveService(typeof(TLanguageService)); // Base still needs shell to save settings base.Dispose(true); }
public void Redo() { foreach (var undoItem in subItems.Reverse()) { undoItem.Redo(); } }
/// <summary> /// Initializes a new instance of the <see cref="CompilationEngine"/> class. /// </summary> /// <param name="classtokensList">The classtokens list.</param> public CompilationEngine(IList<Pair<string, string>> classTokensList) { // reverse tokens before push onto stack (so we Pop them in the correct order!) classTokensList = classTokensList.Reverse().ToList(); this.classTokens = new Stack<Pair<string, string>>(); foreach (Pair<string, string> token in classTokensList) { this.classTokens.Push(token); } }
protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) { ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters); Func<ActionExecutedContext> continuation = () => new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */) { Result = InvokeActionMethod(controllerContext, actionDescriptor, parameters) }; // need to reverse the filter list because the continuations are built up backward Func<ActionExecutedContext> thunk = filters.Reverse().Aggregate(continuation, (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next)); return thunk(); }
public static IQueryable<UserModel> ApplySorting(this IQueryable<UserModel> data, IList<GroupDescriptor> groupDescriptors, IList<SortDescriptor> sortDescriptors) { if (groupDescriptors.Any()) { foreach (var groupDescriptor in groupDescriptors.Reverse()) { data = AddSortExpression(data, groupDescriptor.SortDirection, groupDescriptor.Member); } } if (sortDescriptors.Any()) { foreach (SortDescriptor sortDescriptor in sortDescriptors) { data = AddSortExpression(data, sortDescriptor.SortDirection, sortDescriptor.Member); } } return data; }
IEnumerator HistoryToTail(IList<IList<Posture>> history) { yield return new WaitForFixedUpdate(); gameObject .AfterSelf() .Zip(history.Reverse(), (tail, buf) => new { tail, buf }) .Select(t => Observable.FromCoroutine(() => BufferToTail(t.tail.transform, t.buf))) .WhenAll() .Subscribe( onNext: _ => { }, onCompleted: () => { currentTailCoroutine = StartCoroutine(HistoryToTail(postureHistory)); }) .AddTo(GameMaster.Current) ; Debug.Log("yield return end"); }
internal static void LoadModBuffs(Player player, IList<TagCompound> list) { //buffs list is guaranteed to be compacted int buffCount = Player.maxBuffs; while (buffCount > 0 && player.buffType[buffCount - 1] == 0) buffCount--; //iterate the list in reverse, insert each buff at its index and push the buffs after it up a slot foreach (var tag in list.Reverse()) { var mod = ModLoader.GetMod(tag.GetString("mod")); int type = mod?.BuffType(tag.GetString("name")) ?? 0; if (type == 0) continue; int index = Math.Min(tag.GetByte("index"), buffCount); Array.Copy(player.buffType, index, player.buffType, index+1, Player.maxBuffs-index-1); Array.Copy(player.buffTime, index, player.buffTime, index+1, Player.maxBuffs-index-1); player.buffType[index] = type; player.buffTime[index] = tag.GetInt("time"); } }
internal ImportCompletionAnalysis(IList<ClassificationSpan> tokens, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options) : base(span, textBuffer, options) { Debug.Assert(tokens[0].Span.GetText() == "import"); int beforeLastComma = tokens .Reverse() .SkipWhile(tok => !tok.ClassificationType.IsOfType(JPredefinedClassificationTypeNames.Comma)) .Count(); if (tokens.Count >= 2 && beforeLastComma < tokens.Count) { int spanEnd = Span.GetEndPoint(textBuffer.CurrentSnapshot).Position; var nameParts = new List<string>(); bool removeLastPart = false, lastWasError = false; foreach(var tok in tokens.Skip(beforeLastComma > 0 ? beforeLastComma : 1)) { if (tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier)) { nameParts.Add(tok.Span.GetText()); // Only remove the last part if the trigger point is // not right at the end of it. removeLastPart = (tok.Span.End.Position != spanEnd); } else if (tok.ClassificationType.IsOfType(JPredefinedClassificationTypeNames.Dot)) { removeLastPart = false; } else { lastWasError = true; break; } } if (!lastWasError) { if (removeLastPart && nameParts.Count > 0) { nameParts.RemoveAt(nameParts.Count - 1); } _namespace = nameParts.ToArray(); } } }
/// <summary> /// Called by the <see cref="BlockChain"/> when the best chain (representing total work done) has changed. In this case, /// we need to go through our transactions and find out if any have become invalid. It's possible for our balance /// to go down in this case: money we thought we had can suddenly vanish if the rest of the network agrees it /// should be so. /// </summary> /// <remarks> /// The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last. /// </remarks> /// <exception cref="VerificationException"/> internal void Reorganize(IList<StoredBlock> oldBlocks, IList<StoredBlock> newBlocks) { lock (this) { // This runs on any peer thread with the block chain synchronized. // // The reorganize functionality of the wallet is tested in ChainSplitTests. // // For each transaction we track which blocks they appeared in. Once a re-org takes place we have to find all // transactions in the old branch, all transactions in the new branch and find the difference of those sets. // // receive() has been called on the block that is triggering the re-org before this is called. _log.Info(" Old part of chain (top to bottom):"); foreach (var b in oldBlocks) _log.InfoFormat(" {0}", b.Header.HashAsString); _log.InfoFormat(" New part of chain (top to bottom):"); foreach (var b in newBlocks) _log.InfoFormat(" {0}", b.Header.HashAsString); // Transactions that appear in the old chain segment. IDictionary<Sha256Hash, Transaction> oldChainTransactions = new Dictionary<Sha256Hash, Transaction>(); // Transactions that appear in the old chain segment and NOT the new chain segment. IDictionary<Sha256Hash, Transaction> onlyOldChainTransactions = new Dictionary<Sha256Hash, Transaction>(); // Transactions that appear in the new chain segment. IDictionary<Sha256Hash, Transaction> newChainTransactions = new Dictionary<Sha256Hash, Transaction>(); // Transactions that don't appear in either the new or the old section, ie, the shared trunk. IDictionary<Sha256Hash, Transaction> commonChainTransactions = new Dictionary<Sha256Hash, Transaction>(); IDictionary<Sha256Hash, Transaction> all = new Dictionary<Sha256Hash, Transaction>(); foreach (var pair in Unspent.Concat(Spent).Concat(_inactive)) { all[pair.Key] = pair.Value; } foreach (var tx in all.Values) { var appearsIn = tx.AppearsIn; Debug.Assert(appearsIn != null); // If the set of blocks this transaction appears in is disjoint with one of the chain segments it means // the transaction was never incorporated by a miner into that side of the chain. var inOldSection = appearsIn.Any(oldBlocks.Contains) || oldBlocks.Any(appearsIn.Contains); var inNewSection = appearsIn.Any(newBlocks.Contains) || newBlocks.Any(appearsIn.Contains); var inCommonSection = !inNewSection && !inOldSection; if (inCommonSection) { Debug.Assert(!commonChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in common chain segment"); commonChainTransactions[tx.Hash] = tx; } else { if (inOldSection) { Debug.Assert(!oldChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in old chain segment"); oldChainTransactions[tx.Hash] = tx; if (!inNewSection) { Debug.Assert(!onlyOldChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in only-old map"); onlyOldChainTransactions[tx.Hash] = tx; } } if (inNewSection) { Debug.Assert(!newChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in new chain segment"); newChainTransactions[tx.Hash] = tx; } } } // If there is no difference it means we have nothing we need to do and the user does not care. var affectedUs = oldChainTransactions.Count != newChainTransactions.Count || !oldChainTransactions.All( item => { Transaction rightValue; return newChainTransactions.TryGetValue(item.Key, out rightValue) && Equals(item.Value, rightValue); }); _log.Info(affectedUs ? "Re-org affected our transactions" : "Re-org had no effect on our transactions"); if (!affectedUs) return; // For simplicity we will reprocess every transaction to ensure it's in the right bucket and has the right // connections. Attempting to update each one with minimal work is possible but complex and was leading to // edge cases that were hard to fix. As re-orgs are rare the amount of work this implies should be manageable // unless the user has an enormous wallet. As an optimization fully spent transactions buried deeper than // 1000 blocks could be put into yet another bucket which we never touch and assume re-orgs cannot affect. foreach (var tx in onlyOldChainTransactions.Values) _log.InfoFormat(" Only Old: {0}", tx.HashAsString); foreach (var tx in oldChainTransactions.Values) _log.InfoFormat(" Old: {0}", tx.HashAsString); foreach (var tx in newChainTransactions.Values) _log.InfoFormat(" New: {0}", tx.HashAsString); // Break all the existing connections. foreach (var tx in all.Values) tx.DisconnectInputs(); foreach (var tx in Pending.Values) tx.DisconnectInputs(); // Reconnect the transactions in the common part of the chain. foreach (var tx in commonChainTransactions.Values) { var badInput = tx.ConnectForReorganize(all); Debug.Assert(badInput == null, "Failed to connect " + tx.HashAsString + ", " + badInput); } // Recalculate the unspent/spent buckets for the transactions the re-org did not affect. Unspent.Clear(); Spent.Clear(); _inactive.Clear(); foreach (var tx in commonChainTransactions.Values) { var unspentOutputs = 0; foreach (var output in tx.Outputs) { if (output.IsAvailableForSpending) unspentOutputs++; } if (unspentOutputs > 0) { _log.InfoFormat(" TX {0}: ->unspent", tx.HashAsString); Unspent[tx.Hash] = tx; } else { _log.InfoFormat(" TX {0}: ->spent", tx.HashAsString); Spent[tx.Hash] = tx; } } // Now replay the act of receiving the blocks that were previously in a side chain. This will: // - Move any transactions that were pending and are now accepted into the right bucket. // - Connect the newly active transactions. foreach (var b in newBlocks.Reverse()) // Need bottom-to-top but we get top-to-bottom. { _log.InfoFormat("Replaying block {0}", b.Header.HashAsString); ICollection<Transaction> txns = new HashSet<Transaction>(); foreach (var tx in newChainTransactions.Values) { if (tx.AppearsIn.Contains(b)) { txns.Add(tx); _log.InfoFormat(" containing tx {0}", tx.HashAsString); } } foreach (var t in txns) { Receive(t, b, BlockChain.NewBlockType.BestChain, true); } } // Find the transactions that didn't make it into the new chain yet. For each input, try to connect it to the // transactions that are in {spent,unspent,pending}. Check the status of each input. For inactive // transactions that only send us money, we put them into the inactive pool where they sit around waiting for // another re-org or re-inclusion into the main chain. For inactive transactions where we spent money we must // put them back into the pending pool if we can reconnect them, so we don't create a double spend whilst the // network heals itself. IDictionary<Sha256Hash, Transaction> pool = new Dictionary<Sha256Hash, Transaction>(); foreach (var pair in Unspent.Concat(Spent).Concat(Pending)) { pool[pair.Key] = pair.Value; } IDictionary<Sha256Hash, Transaction> toReprocess = new Dictionary<Sha256Hash, Transaction>(); foreach (var pair in onlyOldChainTransactions.Concat(Pending)) { toReprocess[pair.Key] = pair.Value; } _log.Info("Reprocessing:"); // Note, we must reprocess dead transactions first. The reason is that if there is a double spend across // chains from our own coins we get a complicated situation: // // 1) We switch to a new chain (B) that contains a double spend overriding a pending transaction. It goes dead. // 2) We switch BACK to the first chain (A). The dead transaction must go pending again. // 3) We resurrect the transactions that were in chain (B) and assume the miners will start work on putting them // in to the chain, but it's not possible because it's a double spend. So now that transaction must become // dead instead of pending. // // This only occurs when we are double spending our own coins. foreach (var tx in _dead.Values.ToList()) { ReprocessTxAfterReorg(pool, tx); } foreach (var tx in toReprocess.Values) { ReprocessTxAfterReorg(pool, tx); } _log.InfoFormat("post-reorg balance is {0}", Utils.BitcoinValueToFriendlyString(GetBalance())); // Inform event listeners that a re-org took place. if (Reorganized != null) { // Synchronize on the event listener as well. This allows a single listener to handle events from // multiple wallets without needing to worry about being thread safe. lock (Reorganized) { Reorganized(this, EventArgs.Empty); } } } }
private int CommonNodesLengthFromEnd(IList<SyntaxNode> nodes1, IList<SyntaxNode> nodes2) { nodes1 = nodes1.Reverse().ToList(); nodes2 = nodes2.Reverse().ToList(); return CommonNodesLengthFromStart(nodes1, nodes2); }
private IEnumerable<Exception> RunInvokedInterceptorsSafely(RequestProcessingContext requestProcessingState, IList<IRequestHandlerInterceptor> invokedInterceptors) { var exceptionsFromInterceptor = new List<Exception>(); foreach (var interceptor in invokedInterceptors.Reverse()) { try { interceptor.AfterHandlingRequest(requestProcessingState); } catch (Exception exc) { exceptionsFromInterceptor.Add(exc); } } return exceptionsFromInterceptor; }
protected virtual ResultExecutedContext InvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult) { ResultExecutingContext preContext = new ResultExecutingContext(controllerContext, actionResult); Func<ResultExecutedContext> continuation = delegate { InvokeActionResult(controllerContext, actionResult); return new ResultExecutedContext(controllerContext, actionResult, false /* canceled */, null /* exception */); }; // need to reverse the filter list because the continuations are built up backward Func<ResultExecutedContext> thunk = filters.Reverse().Aggregate(continuation, (next, filter) => () => InvokeActionResultFilter(filter, preContext, next)); return thunk(); }
private void WriteReferences(XmlDocument xmlDoc, IList<Reference> references) { var proj = xmlDoc.GetElementsByTagName("Project").Item(0) as XmlNode; XmlNode refItemGroup = null; var refNodes = xmlDoc.GetElementsByTagName("Reference"); var removeNodes = new List<XmlNode>(); foreach (var refNode in refNodes) { var node = refNode as XmlNode; refItemGroup = node.ParentNode; var hintNode = node.GetChildNamed("HintPath"); if (hintNode != null) { removeNodes.Add(node); //and whitespace node so we don't add loads of //empty lines if (node.PreviousSibling.NodeType == XmlNodeType.Whitespace) { removeNodes.Add(node.PreviousSibling); } } } foreach (var node in removeNodes) { if (node.ParentNode != null) { node.ParentNode.RemoveChild(node); } } var appendReferences = references.Reverse(); foreach (var reference in appendReferences) { AddReferenceTo(refItemGroup, reference); } //TODO:if we have any embedded resources, then update the resources section WriteXml(xmlDoc); }
public void MoveChannels(IList<ChannelInfo> channels, bool up) { if (channels.Count == 0) return; if (up && channels[0].GetPosition(this.SubListIndex) <= this.ChannelList.FirstProgramNumber) return; int delta = (up ? -1 : +1); foreach (var channel in (up ? channels : channels.Reverse())) { int newProgramNr = channel.GetPosition(this.SubListIndex) + delta; ChannelInfo channelAtNewPos = this.ChannelList.Channels.FirstOrDefault(ch => ch.GetPosition(this.SubListIndex) == newProgramNr); if (channelAtNewPos != null) channelAtNewPos.ChangePosition(this.SubListIndex, -delta); channel.ChangePosition(this.SubListIndex, delta); } this.DataRoot.NeedsSaving = true; }
private void PackagesServiceRunFinished(IList<Package> packages) { if (this.InvokeRequired) { Invoke(new PackageSServiceHandler(PackagesServiceRunFinished), new object[] { packages }); } else { EnableUserInteraction(); ClearStatus(); var distinct = packages; if (packageTabControl.SelectedTab == tabInstalled) distinct = packages.Reverse().Distinct().Reverse().ToList(); lblStatus.Text = string.Format(strings.num_installed_packages, distinct.Count()); this.Activate(); PackageGrid.DataSource = distinct; } }
private string GetCombatLog(IList<CombatLogEntry> logEntries) { if (_combatSteps.Current == CombatStep.PlayerDead) { return null; } return string.Join( Environment.NewLine + Environment.NewLine, logEntries.Reverse().Select(x => x.Text)); }
public void MoveTowards(Transform target) { path = GetPathTo(target); var colors = new[] { Color.magenta, Color.yellow }; for (int i = 1; i < path.Count; i++) { Debug.DrawLine(path[i - 1], path[i], colors[i%colors.Length]); } Vector2 targetPosition = transform.position; Vector2 position = transform.position; foreach (var nodePosition in path.Reverse()) { var distance = nodePosition - position; var direction = distance.normalized; var hit = Physics2D.Raycast(position, direction, distance.magnitude, wallMask); if (!hit) { targetPosition = nodePosition; break; } } Debug.DrawLine(position, targetPosition, Color.cyan); var currentAngle = transform.eulerAngles.z; var targetDistance = targetPosition - position; var targetAngle = FastMath.Atan2(-targetDistance.x, targetDistance.y) * Mathf.Rad2Deg; System.Func<float, float, float> mod = (a, n) => a - Mathf.Floor(a/n) * n; var da = Mathf.Abs(mod((targetAngle - currentAngle + 180), 360) - 180); //Debug.LogFormat("{0}, {1}, {2}", targetAngle, currentAngle, da); var targetRotation = Quaternion.Euler(0, 0, targetAngle); transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, turnRate * 5 * Time.deltaTime); var frontOffset = transform.TransformPoint(Vector3.up * repelFocus); var rightOffset = transform.TransformPoint(repelOffset); var leftOffset = transform.TransformPoint(new Vector3(-repelOffset.x, repelOffset.y)); Debug.DrawLine(rightOffset, rightOffset + (frontOffset - rightOffset).normalized * repelCastDistance); if (Physics2D.Raycast(rightOffset, frontOffset - rightOffset, repelCastDistance, wallMask)) { repel = Mathf.Max(repel - repelIncrement, -maxRepel); } Debug.DrawLine(leftOffset, leftOffset + (frontOffset - leftOffset).normalized * repelCastDistance); if (Physics2D.Raycast(leftOffset, frontOffset - leftOffset, repelCastDistance, wallMask)) { repel = Mathf.Min(repel + repelIncrement, maxRepel); } repel = repel * (1 - rapelDecay); // Mathf.Abs(repel) < .01f ? 0 : repel * .8f; if (da > 90) { reverseTime = .25f; } var reverse = false; if (reverseTime > 0) { reverse = true; reverseTime -= Time.deltaTime; return; } //var reverse = da > 60; //if (reverse) // return; var moveDirection = new Vector3(repel, (1 - Mathf.Abs(repel)) * (reverse ? -1 : 1)); // "forward" Debug.DrawLine(transform.position, transform.position + transform.up); Debug.DrawLine(transform.position, transform.position + transform.TransformDirection(moveDirection).normalized, Color.yellow); if (GetComponent<Animator>()) { GetComponent<Animator>().SetFloat("Slide", repel); } transform.Translate(moveDirection * moveSpeed * .1f * Time.deltaTime, Space.Self); }
void InsertWithCursorOnLayer(EditorScript currentScript, InsertionCursorLayer layer, TaskCompletionSource<Script> tcs, IList<AstNode> nodes, IDocument target) { layer.Exited += delegate(object s, InsertionCursorEventArgs args) { if (args.Success) { if (args.InsertionPoint.LineAfter == NewLineInsertion.None && args.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count > 1) { args.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse ()) { int indentLevel = currentScript.GetIndentLevelAt(target.GetOffset(args.InsertionPoint.Location)); var output = currentScript.OutputNode(indentLevel, node); var offset = target.GetOffset(args.InsertionPoint.Location); var delta = args.InsertionPoint.Insert(target, output.Text); output.RegisterTrackedSegments(currentScript, delta + offset); } tcs.SetResult(currentScript); } layer.Dispose(); DisposeOnClose(); }; }
protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) { Func<ActionExecutedContext> endContinuation = null; BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) { ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters); IAsyncResult innerAsyncResult = null; Func<Func<ActionExecutedContext>> beginContinuation = () => { innerAsyncResult = BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters, asyncCallback, asyncState); return () => new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */) { Result = EndInvokeActionMethod(innerAsyncResult) }; }; // need to reverse the filter list because the continuations are built up backward Func<Func<ActionExecutedContext>> thunk = filters.Reverse().Aggregate(beginContinuation, (next, filter) => () => InvokeActionMethodFilterAsynchronously(filter, preContext, next)); endContinuation = thunk(); if (innerAsyncResult != null) { // we're just waiting for the inner result to complete return innerAsyncResult; } else { // something was short-circuited and the action was not called, so this was a synchronous operation SimpleAsyncResult newAsyncResult = new SimpleAsyncResult(asyncState); newAsyncResult.MarkCompleted(true /* completedSynchronously */, asyncCallback); return newAsyncResult; } }; EndInvokeDelegate<ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult) { return endContinuation(); }; return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodWithFiltersTag); }
/// <summary> /// Creates a new instance of a complex lens using a definition of /// elements. /// </summary> /// <remarks> /// The first and last surfaces have to be spherical. TODO: this is /// needed only for simpler sampling. In general planar surfaces or /// stops could be sampled too. /// </remarks> /// <param name="surfaceDefs">List of definitions of spherical or /// planar element surfaces or stops. Ordered from front to back. /// Must not be empty or null. /// </param> /// <param name="mediumRefractiveIndex">Index of refraction of medium /// outside the lens. It is assumed there is one medium on the scene /// side, senzor side and inside the lens.</param> /// <returns>The created complex lens instance.</returns> public static ComplexLens Create( IList<SphericalElementSurfaceDefinition> surfaceDefs, double mediumRefractiveIndex, double scale) { var surfaces = new List<ElementSurface>(); var surfaceDefsReverse = surfaceDefs.Reverse().ToList(); // scale the lens if needed if (Math.Abs(scale - 1.0) > epsilon) { surfaceDefsReverse = surfaceDefsReverse.Select(surface => surface.Scale(scale)).ToList(); } // thickness of the whole lens (from front to back apex) // (without the distance to the senzor - backmost surface def.) double lensThickness = surfaceDefsReverse.Skip(1).Sum(def => def.Thickness); double elementBasePlaneShiftZ = lensThickness; double lastCapHeight = 0; double capHeight = 0; // definition list is ordered from front to back, working list // must be ordered from back to front, so a conversion has to be // performed int defIndex = 0; foreach (var definition in surfaceDefsReverse) { if (defIndex > 0) { elementBasePlaneShiftZ -= definition.Thickness; } ElementSurface surface = new ElementSurface(); surface.ApertureRadius = 0.5 * definition.ApertureDiameter; if (defIndex + 1 < surfaceDefsReverse.Count) { surface.NextRefractiveIndex = surfaceDefsReverse[defIndex + 1].NextRefractiveIndex; } else { surface.NextRefractiveIndex = mediumRefractiveIndex; } if (definition.CurvatureRadius.HasValue) { // spherical surface double radius = definition.CurvatureRadius.Value; // convexity reverses when converting from front-to-back // back-to-front ordering surface.Convex = radius < 0; Sphere sphere = new Sphere() { Radius = Math.Abs(radius) }; sphere.Center = Math.Sign(radius) * sphere.GetCapCenter(surface.ApertureRadius, Vector3d.UnitZ); capHeight = Math.Sign(radius) * sphere.GetCapHeight(sphere.Radius, surface.ApertureRadius); elementBasePlaneShiftZ -= lastCapHeight - capHeight; sphere.Center += new Vector3d(0, 0, elementBasePlaneShiftZ); surface.Surface = sphere; surface.SurfaceNormalField = sphere; } else { // planar surface // both media are the same -> circular stop // else -> planar element surface surface.NextRefractiveIndex = definition.NextRefractiveIndex; surface.Convex = true; capHeight = 0; elementBasePlaneShiftZ -= lastCapHeight - capHeight; Circle circle = new Circle() { Radius = 0.5 * definition.ApertureDiameter, Z = elementBasePlaneShiftZ, }; surface.Surface = circle; surface.SurfaceNormalField = circle; } lastCapHeight = capHeight; surfaces.Add(surface); defIndex++; } //DEBUG //foreach (var surface in surfaces) //{ // Console.WriteLine("{0}, {1}, {2}", surface.ApertureRadius, // surface.Convex, surface.NextRefractiveIndex); //} ComplexLens lens = new ComplexLens(surfaces) { MediumRefractiveIndex = mediumRefractiveIndex }; return lens; }
void InsertWithCursorOnLayer(EditorScript currentScript, InsertionCursorLayer layer, TaskCompletionSource<Script> tcs, IList<AstNode> nodes, IDocument target) { var doc = target as TextDocument; var op = new UndoOperation(layer, tcs); if (doc != null) { doc.UndoStack.Push(op); } layer.Exited += delegate(object s, InsertionCursorEventArgs args) { doc.UndoStack.StartContinuedUndoGroup(); try { if (args.Success) { if (args.InsertionPoint.LineAfter == NewLineInsertion.None && args.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count > 1) { args.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse ()) { int indentLevel = currentScript.GetIndentLevelAt(target.GetOffset(args.InsertionPoint.Location)); var output = currentScript.OutputNode(indentLevel, node); var offset = target.GetOffset(args.InsertionPoint.Location); var delta = args.InsertionPoint.Insert(target, output.Text); output.RegisterTrackedSegments(currentScript, delta + offset); } tcs.SetResult(currentScript); } layer.Dispose(); DisposeOnClose(); } finally { doc.UndoStack.EndUndoGroup(); } op.Reset(); }; }
void InsertWithCursorOnLayer(EditorScript currentScript, InsertionCursorLayer layer, TaskCompletionSource<Script> tcs, IList<AstNode> nodes, IDocument target) { var doc = target as TextDocument; var op = new UndoOperation(layer, tcs); if (doc != null) { doc.UndoStack.Push(op); } layer.ScrollToInsertionPoint(); layer.Exited += delegate(object s, InsertionCursorEventArgs args) { doc.UndoStack.StartContinuedUndoGroup(); try { if (args.Success) { if (args.InsertionPoint.LineAfter == NewLineInsertion.None && args.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count > 1) { args.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } var insertionPoint = args.InsertionPoint; if (nodes.All(n => n is EnumMemberDeclaration)) { insertionPoint.LineAfter = NewLineInsertion.Eol; insertionPoint.LineBefore = NewLineInsertion.None; } int offset = currentScript.GetCurrentOffset(insertionPoint.Location); int indentLevel = currentScript.GetIndentLevelAt(Math.Max(0, offset - 1)); foreach (var node in nodes.Reverse()) { var output = currentScript.OutputNode(indentLevel, node); var text = output.Text; if (node is EnumMemberDeclaration) { if (insertionPoint != layer.InsertionPoints.Last()) { text += ","; } else { var parentEnum = currentScript.context.RootNode.GetNodeAt(insertionPoint.Location, n => (n is TypeDeclaration) && ((TypeDeclaration)n).ClassType == ClassType.Enum) as TypeDeclaration; if (parentEnum != null) { var lastMember = parentEnum.Members.LastOrDefault(); if (lastMember != null) { var segment = currentScript.GetSegment(lastMember); currentScript.InsertText(segment.EndOffset, ","); } } } } int delta = insertionPoint.Insert(target, text); output.RegisterTrackedSegments(currentScript, delta + offset); } currentScript.FormatText(nodes); tcs.SetResult(currentScript); } layer.Dispose(); DisposeOnClose(); } finally { doc.UndoStack.EndUndoGroup(); } op.Reset(); }; }
protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) { ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters); // what makes this different from the synchronous version of this method is that we have to // aggregate both the begin + end delegates together. overall, though, it's the same logic. var continuation = new { Begin = (BeginInvokeCallback)((innerCallback, innerState) => BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters, innerCallback, innerState)), End = (AsyncCallback<ActionExecutedContext>)(ar => new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */) { Result = EndInvokeActionMethod(ar) }) }; // need to reverse the filter list because the continuations are built up backward var invocation = filters.Reverse().Aggregate(continuation, (next, filter) => new { Begin = (BeginInvokeCallback)((innerCallback, innerState) => BeginInvokeActionMethodFilter(filter, preContext, next.Begin, next.End, innerCallback, innerState)), End = (AsyncCallback<ActionExecutedContext>)EndInvokeActionMethodFilter }); return AsyncResultWrapper.Wrap(callback, state, invocation.Begin, invocation.End, _invokeActionMethodWithFiltersTag); }
public override Task<Script> InsertWithCursor (string operation, InsertPosition defaultPosition, IList<AstNode> nodes) { var tcs = new TaskCompletionSource<Script> (); var editor = context.TextEditor; DocumentLocation loc = context.TextEditor.Caret.Location; var declaringType = context.ParsedDocument.GetInnermostTypeDefinition (loc); var mode = new InsertionCursorEditMode ( editor.Parent, MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints (context.TextEditor, context.ParsedDocument, declaringType)); if (mode.InsertionPoints.Count == 0) { MessageService.ShowError ( GettextCatalog.GetString ("No valid insertion point can be found in type '{0}'.", declaringType.Name) ); return tcs.Task; } var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow (); helpWindow.TitleText = operation; mode.HelpWindow = helpWindow; switch (defaultPosition) { case InsertPosition.Start: mode.CurIndex = 0; break; case InsertPosition.End: mode.CurIndex = mode.InsertionPoints.Count - 1; break; case InsertPosition.Before: for (int i = 0; i < mode.InsertionPoints.Count; i++) { if (mode.InsertionPoints [i].Location < loc) mode.CurIndex = i; } break; case InsertPosition.After: for (int i = 0; i < mode.InsertionPoints.Count; i++) { if (mode.InsertionPoints [i].Location > loc) { mode.CurIndex = i; break; } } break; } operationsRunning++; mode.StartMode (); mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) { if (iCArgs.Success) { if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None && iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count () > 1) { iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse ()) { var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); var offset = context.TextEditor.LocationToOffset (iCArgs.InsertionPoint.Location); var delta = iCArgs.InsertionPoint.Insert (editor, output.Text); output.RegisterTrackedSegments (this, delta + offset); } tcs.SetResult (this); } else { Rollback (); } DisposeOnClose (); }; return tcs.Task; }
protected virtual ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception) { ExceptionContext context = new ExceptionContext(controllerContext, exception); foreach (IExceptionFilter filter in filters.Reverse()) { filter.OnException(context); } return context; }
private void DisposeInterceptorsSafely(IList<IRequestHandlerInterceptor> interceptors) { if (interceptors == null) { return; } foreach (var interceptor in interceptors.Reverse()) { try { IoC.Container.Release(interceptor); interceptor.Dispose(); } catch (Exception exc) { logger.Error("error disposing " + interceptor, exc); } } }