// This behavior is case sensitive public override IEnumerable<object> FindMatchingItems(string searchText, IList items, IEnumerable<object> escapedItems, string textSearchPath, TextSearchMode textSearchMode) { var strings = searchText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (strings.Length == 0) { return base.FindMatchingItems(searchText, items, escapedItems, textSearchPath, textSearchMode); } string name = string.Empty; string capital = string.Empty; if (strings.Length > 0) { name = strings[0]; } if (strings.Length > 1) { capital = strings[1].TrimStart(' '); } IEnumerable<object> results = null; if (textSearchMode == TextSearchMode.Contains) { results = items.OfType<Country>().Where(x => x.Name.Contains(name) && x.Capital.Contains(capital)); } else { results = items.OfType<Country>().Where(x => x.Name.StartsWith(name) && x.Capital.StartsWith(capital)); } return results.Where(x => !escapedItems.Contains(x)); }
private static bool ShouldHumanize(ModelMetadata modelMetadata, IList<Attribute> propertyAttributes) { if (string.IsNullOrEmpty(modelMetadata.PropertyName)) return false; if (propertyAttributes.OfType<DisplayNameAttribute>().Any()) return false; if (propertyAttributes.OfType<DisplayAttribute>().Any()) return false; return true; }
private static bool IsTransformRequired(ModelMetadata modelMetadata, IList<Attribute> propertyAttributes) { if (string.IsNullOrEmpty(modelMetadata.PropertyName)) return false; if (propertyAttributes.OfType<DisplayNameAttribute>().Any()) return false; if (propertyAttributes.OfType<DisplayAttribute>().Any()) return false; return true; }
/// <summary> /// Copies HTTP Request Headers from parent request to all requests from multi-part child requests. /// This fixes a problem where content negotiation does not work correctly and JSON is always returned /// even when the client expects xml+atom. /// </summary> public virtual void CopyRequestHeaders(HttpRequestMessage request, IList<ODataBatchRequestItem> items) { var requests = items.OfType<OperationRequestItem>().Select(o => o.Request) .Union(items.OfType<ChangeSetRequestItem>().SelectMany(cs => cs.Requests)); foreach (var childRequest in requests) { foreach (var header in request.Headers) { childRequest.Headers.Add(header.Key, request.Headers.GetValues(header.Key)); } } }
/// <summary> /// Creates a dictionary describing argument based dependencies for the given list of functions. /// </summary> /// <param name="functions"></param> /// <returns></returns> public static IDictionary<IVariable, IEnumerable<IVariable>> GetDependentVariables(IList<IFunction> functions) { var result = new Dictionary<IVariable, IEnumerable<IVariable>>(); var variables = functions.OfType<IVariable>(); foreach (var variable in variables) { var variable1 = variable; result[variable] = functions.OfType<IVariable>() .Where(variable2 => variable2.Arguments.Contains(variable1)) .ToList(); } return result; }
protected ListPickerBox(IList items, IList selectedItems, bool singleSelection, string _title, bool minOneSelected = true, bool showSelectAllButton = false) { InitializeComponent(); this.minOneSelected = minOneSelected; if (string.IsNullOrEmpty(_title)) title.Visibility = Visibility.Collapsed; else title.Text = _title; if (selectedItems == null) selectedItems = new List<object>(); SelectAllButton.Visibility = showSelectAllButton ? Visibility.Visible : Visibility.Collapsed; list.ItemTemplate = (DataTemplate)(singleSelection ? Resources["singleTemplate"] : Resources["multipleTemplate"]); OriginalSelectedItems = selectedItems; Dispatcher.BeginInvoke(delegate { Items = items.OfType<object>(). Select(i => new ListPickerBoxItem { Item = i, IsChecked = selectedItems.Contains(i) }). ToList(); UpdateSelectedItems(); UpdateSelectAllButton(); list.ItemsSource = Items; }); }
public ClassDefinition(Token classToken, Token nameToken, Token baseClassToken, IList<Executable> members) : base(classToken) { this.NameToken = nameToken; this.BaseClassToken = baseClassToken; this.Members = members.OfType<FunctionDefinition>().ToArray(); }
public async Task<IEnumerable<IMediaFile>> StartSearchAsync(IList filesOrDirsCollection) { this.IsWorking = true; // create the cancellation token source this.CancelToken = new CancellationTokenSource(); // create the cancellation token var token = this.CancelToken.Token; this.MainTask = Task<IEnumerable<IMediaFile>>.Factory .StartNew(() => { var results = new ConcurrentQueue<IMediaFile>(); // get audio files from input collection var rawFiles = filesOrDirsCollection.OfType<string>().Where(this.IsAudioFile).OrderBy(s => s).ToList(); foreach (var rawFile in rawFiles.TakeWhile(rawDir => !token.IsCancellationRequested)) { var mf = this.GetMediaFile(rawFile); if (mf != null) { results.Enqueue(mf); } } // handle all directories from input collection var directories = new List<string>(); foreach (var source in filesOrDirsCollection.OfType<string>().Except(rawFiles).Where(IsDirectory).TakeWhile(source => !token.IsCancellationRequested)) { directories.AddRange(GetSubFolders(token, source)); } var orderedDirs = directories.Distinct().OrderBy(s => s); this.Log().Debug("search for files in {0} directories (sub directories included)", orderedDirs.Count()); foreach (var rawDir in orderedDirs.TakeWhile(rawDir => !token.IsCancellationRequested)) { this.DoFindFiles(token, rawDir, results); } return results; }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current); var mediaFiles = await this.MainTask; this.IsWorking = false; return mediaFiles; }
void BuildStickyNoteContextualMenu() { List <StickyNote> stickyNoteSelection = m_Selection?.OfType <StickyNote>().ToList(); if (stickyNoteSelection == null || !stickyNoteSelection.Any()) { return; } List <IStickyNoteModel> stickyNoteModels = stickyNoteSelection.Select(m => (IStickyNoteModel)m.GraphElementModel).ToList(); foreach (StickyNoteColorTheme value in Enum.GetValues(typeof(StickyNoteColorTheme))) { m_Evt.menu.AppendAction("Theme/" + value, menuAction => m_Store.Dispatch(new UpdateStickyNoteThemeAction(stickyNoteModels, value)), e => DropdownMenuAction.Status.Normal); } foreach (StickyNoteTextSize value in Enum.GetValues(typeof(StickyNoteTextSize))) { m_Evt.menu.AppendAction(value + " Text Size", menuAction => m_Store.Dispatch(new UpdateStickyNoteTextSizeAction(stickyNoteModels, value)), e => DropdownMenuAction.Status.Normal); } }
protected override void Render(IList<IBaseTexture> inputs) { var texture = inputs.OfType<ITexture2D>().SingleOrDefault(); if (texture == null) return; Render(texture); }
/// <summary> /// OData does not copy headers from the main request to the batch sub-request. Let's do it here... /// </summary> public virtual void CopyRequestHeadersToBatchItems(HttpRequestMessage request, IList<ODataBatchRequestItem> items) { var batchRequests = items .OfType<OperationRequestItem>().Select(o => o.Request) .Union(items.OfType<ChangeSetRequestItem>().SelectMany(cs => cs.Requests)); foreach (var batchRequest in batchRequests) { foreach (var header in request.Headers) { if (String.Equals(header.Key, DataServiceVersionHeader, StringComparison.OrdinalIgnoreCase) || String.Equals(header.Key, MaxDataServiceVersionHeader, StringComparison.OrdinalIgnoreCase)) { batchRequest.Headers.Add(header.Key, request.Headers.GetValues(header.Key)); } } } }
void BuildStickyNoteContextualMenu() { var stickyNoteSelection = m_Selection?.OfType <StickyNote>(); if (stickyNoteSelection == null || !stickyNoteSelection.Any()) { return; } var stickyNoteModels = stickyNoteSelection.Select(m => m.StickyNoteModel).ToArray(); DropdownMenuAction.Status GetThemeStatus(DropdownMenuAction a) { if (stickyNoteModels.Length == 0) { return(DropdownMenuAction.Status.Normal); } if (stickyNoteModels.Any(noteModel => noteModel.Theme != stickyNoteModels.First().Theme)) { // Values are not all the same. return(DropdownMenuAction.Status.Normal); } return(stickyNoteModels.First().Theme == (a.userData as string) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } DropdownMenuAction.Status GetSizeStatus(DropdownMenuAction a) { if (stickyNoteModels.Length == 0) { return(DropdownMenuAction.Status.Normal); } if (stickyNoteModels.Any(noteModel => noteModel.TextSize != stickyNoteModels.First().TextSize)) { // Values are not all the same. return(DropdownMenuAction.Status.Normal); } return(stickyNoteModels.First().TextSize == (a.userData as string) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } foreach (var value in Unity.Modifier.GraphElements.StickyNote.GetThemes()) { m_Evt.menu.AppendAction("Theme/" + value, menuAction => m_Store.Dispatch(new UpdateStickyNoteThemeAction(stickyNoteModels, menuAction.userData as string)), GetThemeStatus, value); } foreach (var value in Unity.Modifier.GraphElements.StickyNote.GetSizes()) { m_Evt.menu.AppendAction("Text Size/" + value, menuAction => m_Store.Dispatch(new UpdateStickyNoteTextSizeAction(stickyNoteModels, menuAction.userData as string)), GetSizeStatus, value); } }
public CompiledFilter(MIA_Management miaManagement, IFilter filter, Namespace ns, BindVarNamespace bvNamespace, string outerMIIDJoinVariable, ICollection<TableJoin> tableJoins) { _statementParts = new List<object>(); _statementBindVars = new List<BindVar>(); _requiredMIATypes = new List<MediaItemAspectMetadata>(); CompileStatementParts(miaManagement, filter, ns, bvNamespace, _requiredMIATypes, outerMIIDJoinVariable, tableJoins, _statementParts, _statementBindVars); _requiredAttributes = _statementParts.OfType<QueryAttribute>().ToList(); }
/// <summary> /// return true if every values are true else false /// if there are some invalid binding error type return true /// </summary> /// <param name="values"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(IList <object> values, Type targetType, object parameter, CultureInfo culture) { //on invalid type return true if (values.Any(x => (x is bool) == false)) { return(true); } return(values?.OfType <bool>().All(item => item)); }
protected static Device GetDevice(IList<ICallCopyEntity> callCopyEntities) { Device device = callCopyEntities.OfType<Device>().FirstOrDefault(); if (device == null) { device = new Device {Name = "Placeholder", DeviceType = "Placeholder"}; callCopyEntities.Add(device); } return device; }
public async Task<IEnumerable<IMediaFile>> StartSearchAsync(IList filesOrDirsCollection) { this.IsWorking = true; // create the cancellation token source this.cancelToken = new CancellationTokenSource(); // create the cancellation token var token = this.cancelToken.Token; this.mainTask = Task<IEnumerable<IMediaFile>>.Factory .StartNew(() => { var results = new ConcurrentQueue<IMediaFile>(); // get audio files from input collection var rawFiles = filesOrDirsCollection.OfType<string>().Where(this.IsAudioFile).OrderBy(s => s).ToList(); foreach (var rawFile in rawFiles.TakeWhile(rawDir => !token.IsCancellationRequested)) { var mf = this.GetMediaFile(rawFile); if (mf != null) { results.Enqueue(mf); } } // handle all directories from input collection var directories = new List<string>(); foreach (var source in filesOrDirsCollection.OfType<string>().Except(rawFiles).Where(IsDirectory).TakeWhile(source => !token.IsCancellationRequested)) { directories.Add(source); try { directories.AddRange(Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories).TakeWhile(dir => !token.IsCancellationRequested)); } catch (Exception e) { // System.UnauthorizedAccessException Console.WriteLine(e); } } foreach (var rawDir in directories.Distinct().OrderBy(s => s).TakeWhile(rawDir => !token.IsCancellationRequested)) { this.doFindFiles(token, rawDir, results); } return results; }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current); var mediaFiles = await this.mainTask; this.IsWorking = false; return mediaFiles; }
public SelectClauseHandler(SelectClause clause) { _references = clause.Columns.ToList(); _resolvers = _references.Select(ValueResolver.Create).ToList(); if (_resolvers.OfType<AggregateValueResolver>().Any()) { _groupingHandler = new GroupingHandler( _references.Where(ReferenceIsNotAggregateFunction).Select(r => r.GetAliasOrName()).ToArray()); } }
public IndexerNode(IList<object> arguments) { Arguments = arguments; var intArgs = Arguments.OfType<int>().ToArray(); if (intArgs.Length == arguments.Count) { _intArgs = intArgs; } }
protected WorkMode GetWorkMode(IList<ICallCopyEntity> callCopyEntities, string status) { status = status ?? string.Empty; WorkMode workMode = callCopyEntities.OfType<WorkMode>() .FirstOrDefault(x => status.Trim().Equals(x.Name)); if (workMode == null) { workMode = new WorkMode { Name = status.Trim(), Value = status.GetHashCode() }; callCopyEntities.Add(workMode); } return workMode; }
public MeasureTool() { geometries = new List<IGeometry>(); pointGeometries = geometries.OfType<GeoPoint>(); pointLayer = new VectorLayer(); pointLayer.Name = "measure"; pointLayer.DataSource = new DataTableFeatureProvider(geometries); pointLayer.Style.Symbol = TrackerSymbolHelper.GenerateSimple(Pens.DarkMagenta, Brushes.Indigo, 6, 6); pointLayer.Visible = false; pointLayer.ShowInLegend = false; }
public ByteBuffer GenerateByteCode(Parser parser, IList<Executable> lines, IList<string> spriteSheetOpsStringArgs, IList<int[]> spriteSheetOpsIntArgs) { FunctionDefinition mainFunction = lines .OfType<FunctionDefinition>() .Where<FunctionDefinition>(fd => fd.NameToken.Value == "main") .FirstOrDefault<FunctionDefinition>(); if (mainFunction == null) { throw new Exception(); // should have thrown before if there was no main function. } ByteBuffer userCode = new ByteBuffer(); this.Compile(parser, userCode, lines); ByteBuffer literalsTable = parser.LiteralLookup.BuildByteCode(); ByteBuffer tokenData = this.BuildTokenData(userCode); ByteBuffer fileContent = this.BuildFileContent(parser.GetFilesById()); ByteBuffer switchStatements = this.BuildSwitchStatementTables(parser); ByteBuffer spriteSheetStuff = this.BuildSpriteSheetStuff(spriteSheetOpsStringArgs, spriteSheetOpsIntArgs); ByteBuffer header = new Crayon.ByteBuffer(); header.Concat(literalsTable); header.Concat(tokenData); header.Concat(fileContent); header.Concat(switchStatements); header.Concat(spriteSheetStuff); header.Add(null, OpCode.FINALIZE_INITIALIZATION); ByteBuffer output = new Crayon.ByteBuffer(); output.Add(null, OpCode.USER_CODE_START, header.Size + 1, parser.VariableIds.Size); output.Concat(header); output.Concat(userCode); // artificially inject a function call to main() at the very end after all declarations are done. if (parser.MainFunctionHasArg) { output.Add(null, OpCode.DEF_LIST, 0); // TODO: op code to build a list of the command line args. For now just pass in an empty list. output.Add(null, OpCode.CALL_FUNCTION, (int)FunctionInvocationType.NORMAL_FUNCTION, 1, mainFunction.FunctionID, 0, 0); } else { output.Add(null, OpCode.CALL_FUNCTION, (int)FunctionInvocationType.NORMAL_FUNCTION, 0, mainFunction.FunctionID, 0, 0); } output.Add(null, OpCode.RETURN, 0); return output; }
protected DeviceAgent GetDeviceAgent(IList<ICallCopyEntity> callCopyEntities, string userId) { userId = userId ?? string.Empty; DeviceAgent deviceAgent = callCopyEntities.OfType<DeviceAgent>() .FirstOrDefault(x => userId.Trim().Equals(x.DeviceAgentNumber)); if (deviceAgent == null) { Device device = GetDevice(callCopyEntities); deviceAgent = new DeviceAgent {Device = device, DeviceAgentNumber = userId.Trim()}; callCopyEntities.Add(deviceAgent); } return deviceAgent; }
public void VisitChunk(IChunkVisitor visitor, OutputLocation location, IList<Chunk> body, StringBuilder output) { if (location == OutputLocation.ClassMembers) { foreach (var snippet in body.OfType<CodeStatementChunk>().SelectMany(chunk => chunk.Code)) { snippet.Value = snippet.Value.Replace("@class", "class"); } var source = new SourceWriter(new StringWriter(output)); var generator = new GeneratedCodeVisitor(source, new Dictionary<string, object>(), NullBehaviour.Strict); generator.Accept(body); } }
protected CallSplit GetCallSplit(IList<ICallCopyEntity> callCopyEntities, string huntgroupId) { huntgroupId = huntgroupId ?? string.Empty; CallSplit callSplit = callCopyEntities.OfType<CallSplit>() .FirstOrDefault(x => huntgroupId.Trim().Equals(x.Number)); if (callSplit == null) { Device device = GetDevice(callCopyEntities); callSplit = new CallSplit { Device = device, Number = huntgroupId.Trim()}; callCopyEntities.Add(callSplit); } return callSplit; }
private static bool IsLeader(IList<InstructionBase> instructions, int index) { if (index == 0) return true; var instruction = instructions[index]; if (instructions.OfType<BranchingInstruction>().Any(x => x.BranchTarget == instruction)) return true; if (index > 0 && instructions[index - 1] is BranchingInstruction) return true; return false; }
public static void AutoLayout(IList shapes, Diagram diagram) { var store = diagram.Store; List<ShapeElement> shapeElementCollection = new List<ShapeElement>(); List<ShapeElement> elements = new List<ShapeElement>(); List<ShapeElement> list3 = new List<ShapeElement>(); foreach (ShapeElement element in shapes) { var condition1 = (element is ClassShape) && ((element as ClassShape).ModelElement != null); bool condition2 = false; if (element is ClassShape) { var modelClass = (element as ClassShape).ModelElement as ModelClass; condition2 = modelClass.Baseclass != null || shapes.OfType<ClassShape>() .Any(cs => (cs.ModelElement as ModelClass).Baseclass == modelClass); } if (condition1 && condition2) { elements.Add(element); } else { if (element is InheritanceConnector) { shapeElementCollection.Add(element); continue; } list3.Add(element); } } using (Transaction transaction = store.TransactionManager.BeginTransaction("AutoLayout")) { using (new SaveLayoutFlags(elements, VGNodeFixedStates.PermeablePlace | VGNodeFixedStates.FixedPlace)) { diagram.AutoLayoutShapeElements(shapes, VGRoutingStyle.VGRouteNetwork, PlacementValueStyle.VGPlaceWE, false); } using (new SaveLayoutFlags(list3, VGNodeFixedStates.FixedPlace)) { diagram.AutoLayoutShapeElements(shapes, VGRoutingStyle.VGRouteOrgChartNS, PlacementValueStyle.VGPlaceSN, false); } using (new SaveLayoutFlags(shapes, VGNodeFixedStates.FixedPlace)) { diagram.AutoLayoutShapeElements(shapeElementCollection, VGRoutingStyle.VGRouteRightAngle, PlacementValueStyle.VGPlaceUndirected, false); } RunHandleLineRouting(diagram); transaction.Commit(); } }
protected ListPickerBox(IList items, IList selectedItems) { InitializeComponent(); OriginalSelectedItems = selectedItems; Dispatcher.BeginInvoke(delegate { Items = items.OfType<object>(). Select(i => new ListPickerBoxItem { Item = i, IsChecked = selectedItems.Contains(i) }). ToList(); UpdateSelectedItems(); list.ItemsSource = Items; }); }
/// <inheritdoc/> public async void Show(object content) { var notification = content as INotification; var notificationControl = new NotificationCard { Content = content }; if (notification != null) { notificationControl.NotificationClosed += (sender, args) => { notification.OnClose?.Invoke(); _items?.Remove(sender); }; } notificationControl.PointerPressed += (sender, args) => { if (notification != null && notification.OnClick != null) { notification.OnClick.Invoke(); } (sender as NotificationCard)?.Close(); }; _items?.Add(notificationControl); if (_items?.OfType <NotificationCard>().Count(i => !i.IsClosing) > MaxItems) { _items.OfType <NotificationCard>().First(i => !i.IsClosing).Close(); } if (notification != null && notification.Expiration == TimeSpan.Zero) { return; } await Task.Delay(notification?.Expiration ?? TimeSpan.FromSeconds(5)); notificationControl.Close(); }
public IList Write(IList content) { var newData = content.OfType<string>().ToArray(); if (newData.Length != content.Count) { throw new ArgumentException("Utf8 encoding accept only strings"); } var stringData = string.Join(Environment.NewLine, newData); var binaryData = Encoding.UTF8.GetBytes(stringData); this.saveData(binaryData); return new ArrayList() { binaryData }; }
public void SaveObjects(IEntitySession session, IList<object> items) { //Group by WebCallId, SessionId, UserName var entries = items.OfType<LogEntry>().ToList(); var groupedByWebCall = entries.GroupBy(e => e.WebCallId); foreach (var wg in groupedByWebCall) { if (wg.Key == null) { var groupedBySessionId = wg.GroupBy(e => e.UserSessionId); foreach (var sg in groupedBySessionId) { if (sg.Key == null) { var groupedByUserName = sg.GroupBy(e => e.UserName); foreach (var ug in groupedByUserName) SaveEntries(session, ug); } else SaveEntries(session, sg); }// foreach sg } //if wg.Key else SaveEntries(session, wg); }//foreach wg }
public void AddSelf(IList<INugetStep> steps) { var other = steps.OfType<InstallSolutionDependency>().Where(x => x.Dependency.Name.EqualsIgnoreCase(Dependency.Name)).SingleOrDefault(); if (other == null) { steps.Add(this); return; } if (Equals(other.Dependency, Dependency)) { return; } if (Dependency.Mode != UpdateMode.Fixed) return; if (other.Dependency.Mode == UpdateMode.Float) { steps.Remove(other); steps.Add(this); } }
/// <summary> /// Allows ledger bucket specific behaviour during reconciliation. /// </summary> public override void ApplyReconciliationBehaviour(IList<LedgerTransaction> transactions, DateTime reconciliationDate, decimal openingBalance) { var netAmount = transactions.Sum(t => t.Amount); var closingBalance = openingBalance + netAmount; var budgetTransaction = transactions.OfType<BudgetCreditLedgerTransaction>().FirstOrDefault(); if (budgetTransaction == null) { transactions.AddIfSomething(SupplementToZero(closingBalance, reconciliationDate)); return; } // Supplement if (closingBalance < budgetTransaction.Amount) { transactions.AddIfSomething(SupplementToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount)); return; } if (closingBalance < openingBalance) { transactions.AddIfSomething(SupplementToOpeningBalance(closingBalance, reconciliationDate, openingBalance)); return; } // Remove-excess if (closingBalance > openingBalance || closingBalance > budgetTransaction.Amount) { if (openingBalance > budgetTransaction.Amount) { transactions.AddIfSomething(RemoveExcessToOpeningBalance(closingBalance, reconciliationDate, openingBalance)); } else { transactions.AddIfSomething(RemoveExcessToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount)); } } }
public IActionResult GetAccountsFromPremiumAccount() { return(Ok(Accounts.OfType <PremiumAccount>().AsQueryable())); }
public void DoesntTransform_Editables_OfIncorrectTypes() { IList <IEditable> editables = builder.GetDefinitions().Single(d => d.ItemType == typeof(Items.DefinitionStartPage)).Editables; Assert.That(!editables.OfType <WithEditableNameAttribute>().Single().Title.EndsWith(" Transformed")); }
public void BuildContextualMenu() { var selectedModelsDictionary = m_Selection .OfType <IHasGraphElementModel>() .Where(x => !(x is BlackboardThisField)) // this blackboard field .Distinct(s_HasGraphElementModelComparer) .ToDictionary(x => x.GraphElementModel); IReadOnlyCollection <IGraphElementModel> selectedModelsKeys = selectedModelsDictionary.Keys.ToList(); BuildBlackboardContextualMenu(); var originatesFromBlackboard = (m_Evt.target as VisualElement)?.GetFirstOfType <Blackboard>() != null; if (!originatesFromBlackboard || m_Evt.target is IHasGraphElementModel) { BuildGraphViewContextualMenu(); if (!originatesFromBlackboard) { BuildNodeContextualMenu(selectedModelsDictionary); BuildStackContextualMenu(selectedModelsKeys); BuildEdgeContextualMenu(selectedModelsKeys); } BuildVariableNodeContextualMenu(selectedModelsKeys); if (!originatesFromBlackboard) { BuildConstantNodeContextualMenu(selectedModelsKeys); BuildStaticConstantNodeContextualMenu(selectedModelsKeys); BuildPropertyNodeContextualMenu(selectedModelsKeys); BuildSpecialContextualMenu(selectedModelsKeys); BuildStickyNoteContextualMenu(); BuildRefactorContextualMenu(selectedModelsKeys); } if (selectedModelsDictionary.Any()) { m_Evt.menu.AppendAction("Delete", menuAction => { m_Store.Dispatch(new DeleteElementsAction(selectedModelsKeys.ToArray())); }, eventBase => DropdownMenuAction.Status.Normal); } } if (originatesFromBlackboard && !(m_Evt.target is IHasGraphElementModel)) { var currentGraphModel = m_Store.GetState().CurrentGraphModel; currentGraphModel.Stencil.GetBlackboardProvider() .BuildContextualMenu(m_Evt.menu, (VisualElement)m_Evt.target, m_Store, m_Evt.mousePosition); } var renamable = originatesFromBlackboard && m_Evt.target is IRenamable ? m_Evt.target as IRenamable : (!originatesFromBlackboard && selectedModelsDictionary.Count == 1) ? selectedModelsDictionary.Single().Value as IRenamable : null; if (renamable != null) { m_Evt.menu.AppendAction("Rename", menuAction => { renamable.Rename(true); m_Evt.PreventDefault(); m_Evt.StopImmediatePropagation(); }, eventBase => DropdownMenuAction.Status.Normal); } if (m_Evt.target is IContextualMenuBuilder contextualMenuBuilder) { contextualMenuBuilder.BuildContextualMenu(m_Evt); } }
private void DoItemsAction(IList collection, Action <INotifyCollectionChanged> action) => collection?.OfType <TParent>().Select(subItems).OfType <INotifyCollectionChanged>().ForEach(action);
public MutateInResult(IList <OperationSpec> specs, ulong cas, MutationToken?token, ITypeSerializer serializer) : this(specs.OfType <MutateInSpec>().ToList(), cas, token, serializer) { }
public CustomNodeDefinition( Guid functionId, string displayName = "", IList <NodeModel> nodeModels = null) { if (functionId == Guid.Empty) { throw new ArgumentException(@"FunctionId invalid.", "functionId"); } nodeModels = nodeModels ?? new List <NodeModel>(); #region Find outputs // Find output elements for the node var outputs = nodeModels.OfType <Output>().ToList(); var topMost = new List <Tuple <int, NodeModel> >(); List <string> outNames; // if we found output nodes, add select their inputs // these will serve as the function output if (outputs.Any()) { topMost.AddRange( outputs.Where(x => x.HasInput(0)).Select(x => Tuple.Create(0, x as NodeModel))); outNames = outputs.Select(x => x.Symbol).ToList(); } else { outNames = new List <string>(); // if there are no explicitly defined output nodes // get the top most nodes and set THEM as the output IEnumerable <NodeModel> topMostNodes = nodeModels.Where(node => node.IsTopMostNode); var rtnPorts = //Grab multiple returns from each node topMostNodes.SelectMany( topNode => //If the node is a recursive instance... topNode is Function && (topNode as Function).Definition.FunctionId == functionId // infinity output ? new[] { new { portIndex = 0, node = topNode, name = "∞" } } // otherwise, grab all ports with connected outputs and package necessary info : topNode.OutPortData .Select( (port, i) => new { portIndex = i, node = topNode, name = port.NickName }) .Where(x => !topNode.HasOutput(x.portIndex))); foreach (var rtnAndIndex in rtnPorts.Select((rtn, i) => new { rtn, idx = i })) { topMost.Add(Tuple.Create(rtnAndIndex.rtn.portIndex, rtnAndIndex.rtn.node)); outNames.Add(rtnAndIndex.rtn.name ?? rtnAndIndex.idx.ToString()); } } var nameDict = new Dictionary <string, int>(); foreach (var name in outNames) { if (nameDict.ContainsKey(name)) { nameDict[name]++; } else { nameDict[name] = 0; } } nameDict = nameDict.Where(x => x.Value != 0).ToDictionary(x => x.Key, x => x.Value); outNames.Reverse(); var returnKeys = new List <string>(); foreach (var name in outNames) { int amt; if (nameDict.TryGetValue(name, out amt)) { nameDict[name] = amt - 1; returnKeys.Add(name == "" ? amt + ">" : name + amt); } else { returnKeys.Add(name); } } returnKeys.Reverse(); #endregion #region Find inputs //Find function entry point, and then compile var inputNodes = nodeModels.OfType <Symbol>().ToList(); var parameters = inputNodes.Select(x => new TypedParameter( x.GetAstIdentifierForOutputIndex(0).Value, x.Parameter.Type, x.Parameter.DefaultValue)); var displayParameters = inputNodes.Select(x => x.Parameter.Name); #endregion FunctionBody = nodeModels.Where(node => !(node is Symbol)); DisplayName = displayName; FunctionId = functionId; Parameters = parameters; ReturnKeys = returnKeys; DisplayParameters = displayParameters; OutputNodes = topMost.Select(x => x.Item2.GetAstIdentifierForOutputIndex(x.Item1)); DirectDependencies = nodeModels .OfType <Function>() .Select(node => node.Definition) .Where(def => def.FunctionId != functionId) .Distinct(); }
internal async System.Threading.Tasks.Task UpdateModules(IList<HierarchyNode> nodes) { DoPreCommandActions(); try { using (var commander = NpmController.CreateNpmCommander()) { if (nodes.Count == 1 && nodes[0] == this) { await commander.UpdatePackagesAsync(); } else { var valid = nodes.OfType<DependencyNode>().Where(CheckValidCommandTarget).ToList(); var list = valid.Where(node => node.GetPropertiesObject().IsGlobalInstall).Select(node => node.Package).ToList(); if (list.Count > 0) { await commander.UpdateGlobalPackagesAsync(list); } list = valid.Where(node => !node.GetPropertiesObject().IsGlobalInstall).Select(node => node.Package).ToList(); if (list.Count > 0) { await commander.UpdatePackagesAsync(list); } } } } catch (NpmNotFoundException nnfe) { ErrorHelper.ReportNpmNotInstalled(null, nnfe); } finally { AllowCommands(); } }
public Commands(IList <ICommand> commandCollection) { ActivateWindow = commandCollection.OfType <ActivateWindow>().Single(); CloseDocument = commandCollection.OfType <CloseDocument>().Single(); }
private void QueryToSpanQuery(Query query, ICollection <byte[]> payloads) { if (query is BooleanQuery) { BooleanClause[] queryClauses = ((BooleanQuery)query).GetClauses(); for (int i = 0; i < queryClauses.Length; i++) { if (!queryClauses[i].IsProhibited) { QueryToSpanQuery(queryClauses[i].Query, payloads); } } } else if (query is PhraseQuery) { Term[] phraseQueryTerms = ((PhraseQuery)query).GetTerms(); SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.Length]; for (int i = 0; i < phraseQueryTerms.Length; i++) { clauses[i] = new SpanTermQuery(phraseQueryTerms[i]); } int slop = ((PhraseQuery)query).Slop; bool inorder = false; if (slop == 0) { inorder = true; } SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder); sp.Boost = query.Boost; GetPayloads(payloads, sp); } else if (query is TermQuery) { SpanTermQuery stq = new SpanTermQuery(((TermQuery)query).Term); stq.Boost = query.Boost; GetPayloads(payloads, stq); } else if (query is SpanQuery) { GetPayloads(payloads, (SpanQuery)query); } else if (query is FilteredQuery) { QueryToSpanQuery(((FilteredQuery)query).Query, payloads); } else if (query is DisjunctionMaxQuery) { foreach (var q in ((DisjunctionMaxQuery)query)) { QueryToSpanQuery(q, payloads); } } else if (query is MultiPhraseQuery) { MultiPhraseQuery mpq = (MultiPhraseQuery)query; IList <Term[]> termArrays = mpq.GetTermArrays(); int[] positions = mpq.GetPositions(); if (positions.Length > 0) { int maxPosition = positions[positions.Length - 1]; for (int i = 0; i < positions.Length - 1; ++i) { if (positions[i] > maxPosition) { maxPosition = positions[i]; } } IList <Query>[] disjunctLists = new List <Query> [maxPosition + 1]; int distinctPositions = 0; for (int i = 0; i < termArrays.Count; ++i) { Term[] termArray = termArrays[i]; IList <Query> disjuncts = disjunctLists[positions[i]]; if (disjuncts == null) { disjuncts = (disjunctLists[positions[i]] = new List <Query>(termArray.Length)); ++distinctPositions; } foreach (Term term in termArray) { disjuncts.Add(new SpanTermQuery(term)); } } int positionGaps = 0; int position = 0; SpanQuery[] clauses = new SpanQuery[distinctPositions]; for (int i = 0; i < disjunctLists.Length; ++i) { IList <Query> disjuncts = disjunctLists[i]; if (disjuncts != null) { clauses[position++] = new SpanOrQuery(disjuncts.OfType <SpanQuery>().ToArray()); } else { ++positionGaps; } } int slop = mpq.Slop; bool inorder = (slop == 0); SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder); sp.Boost = query.Boost; GetPayloads(payloads, sp); } } }
public T FindRenamer <T>() { return(Renamers.OfType <T>().Single()); }
public void WhenRefreshWhitelist_AndInactivePeersInWhitelist_ThenWhitelistDoesNotContainInactivePeers() { // Arrange. Mock <IDateTimeProvider> mockDateTimeProvider = new Mock <IDateTimeProvider>(); Mock <ILogger> mockLogger = new Mock <ILogger>(); Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); ILoggerFactory loggerFactory = mockLoggerFactory.Object; mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable(); IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object; int inactiveTimePeriod = 3000; IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var activeEndpointOne = new IPEndPoint(activeIpAddressOne, 80); IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var activeEndpointTwo = new IPEndPoint(activeIpAddressTwo, 80); IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var activeEndpointThree = new IPEndPoint(activeIpAddressThree, 80); IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4"); var activeEndpointFour = new IPEndPoint(activeIpAddressFour, 80); var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >() { new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40)) }; IPAddress inactiveIpAddressOne = IPAddress.Parse("::ffff:192.168.100.1"); var inactiveEndpointOne = new IPEndPoint(inactiveIpAddressOne, 80); IPAddress inactiveIpAddressTwo = IPAddress.Parse("::ffff:192.168.100.2"); var inactiveEndpointTwo = new IPEndPoint(inactiveIpAddressTwo, 80); IPAddress inactiveIpAddressThree = IPAddress.Parse("::ffff:192.168.100.3"); var inactiveEndpointThree = new IPEndPoint(inactiveIpAddressThree, 80); var inactiveTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >() { new Tuple <IPEndPoint, DateTimeOffset> (inactiveEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-10)), new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-20)), new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-30)) }; IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet.Concat(inactiveTestDataSet).ToList()); IMasterFile spiedMasterFile = null; Mock <IDnsServer> mockDnsServer = new Mock <IDnsServer>(); mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>())) .Callback <IMasterFile>(m => { spiedMasterFile = m; }) .Verifiable(); NodeSettings nodeSettings = NodeSettings.Default(); DnsSettings dnsSettings = new Mock <DnsSettings>().Object; dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod; dnsSettings.DnsHostName = "stratis.test.com"; ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); WhitelistManager whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings); // Act. whitelistManager.RefreshWhitelist(); // Assert. spiedMasterFile.Should().NotBeNull(); Question question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A); IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question); resourceRecords.Should().NotBeNullOrEmpty(); IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList(); ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet); foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet) { ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull("the ip address is active and should be in DNS"); } foreach (Tuple <IPEndPoint, DateTimeOffset> testData in inactiveTestDataSet) { ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().BeNull("the ip address is inactive and should not be returned from DNS"); } }
public void WhenRefreshWhitelist_AndOwnIPInPeers_AndAreRunningFullNode_ThenWhitelistDoesContainOwnIP() { // Arrange. Mock <IDateTimeProvider> mockDateTimeProvider = new Mock <IDateTimeProvider>(); Mock <ILogger> mockLogger = new Mock <ILogger>(); Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); ILoggerFactory loggerFactory = mockLoggerFactory.Object; mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable(); IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object; int inactiveTimePeriod = 5000; IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var activeEndpointOne = new IPEndPoint(activeIpAddressOne, 80); IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var activeEndpointTwo = new IPEndPoint(activeIpAddressTwo, 80); IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var activeEndpointThree = new IPEndPoint(activeIpAddressThree, 80); IPAddress externalIPAdress = IPAddress.Parse("::ffff:192.168.99.99"); int externalPort = 80; var externalEndpoint = new IPEndPoint(externalIPAdress, externalPort); var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >() { new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)), new Tuple <IPEndPoint, DateTimeOffset> (externalEndpoint, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40)) }; IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet); string[] args = new string[] { $"-dnspeeractivethreshold={inactiveTimePeriod.ToString()}", $"-externalip={externalEndpoint.Address.ToString()}", $"-port={externalPort.ToString()}", }; IMasterFile spiedMasterFile = null; Mock <IDnsServer> mockDnsServer = new Mock <IDnsServer>(); mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>())) .Callback <IMasterFile>(m => { spiedMasterFile = m; }) .Verifiable(); Network network = Network.StratisTest; NodeSettings nodeSettings = new NodeSettings(network, args: args); DnsSettings dnsSettings = new Mock <DnsSettings>().Object; dnsSettings.DnsFullNode = true; dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod; dnsSettings.DnsHostName = "stratis.test.com"; ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); WhitelistManager whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings); // Act. whitelistManager.RefreshWhitelist(); // Assert. spiedMasterFile.Should().NotBeNull(); Question question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A); IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question); resourceRecords.Should().NotBeNullOrEmpty(); IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList(); ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet); foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet) { ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull(); } }
public IScheduledJob <T> FindJob <T>() where T : IJob { return(Jobs.OfType <IScheduledJob <T> >().FirstOrDefault()); }
public void WhenRefreshWhitelist_AndActivePeersAvailable_ThenWhitelistContainsActivePeers() { // Arrange. Mock <IDateTimeProvider> mockDateTimeProvider = new Mock <IDateTimeProvider>(); Mock <ILogger> mockLogger = new Mock <ILogger>(); Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); ILoggerFactory loggerFactory = mockLoggerFactory.Object; mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable(); IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object; int inactiveTimePeriod = 2000; IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var activeEndpointOne = new IPEndPoint(activeIpAddressOne, 80); IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var activeEndpointTwo = new IPEndPoint(activeIpAddressTwo, 80); IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var activeEndpointThree = new IPEndPoint(activeIpAddressThree, 80); IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4"); var activeEndpointFour = new IPEndPoint(activeIpAddressFour, 80); IPAddress activeIpAddressFive = IPAddress.Parse("2607:f8b0:4009:80e::200e"); var activeEndpointFive = new IPEndPoint(activeIpAddressFive, 80); var testDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >() { new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40)), new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFive, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(50)) }; // PeerAddressManager does not support IPv4 addresses that are not represented as embedded IPv4 addresses in an IPv6 address. IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(testDataSet); IMasterFile spiedMasterFile = null; Mock <IDnsServer> mockDnsServer = new Mock <IDnsServer>(); mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>())) .Callback <IMasterFile>(m => { spiedMasterFile = m; }) .Verifiable(); NodeSettings nodeSettings = NodeSettings.Default(); DnsSettings dnsSettings = new Mock <DnsSettings>().Object; dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod; dnsSettings.DnsHostName = "stratis.test.com"; ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); WhitelistManager whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings); // Act. whitelistManager.RefreshWhitelist(); // Assert. spiedMasterFile.Should().NotBeNull(); // Check for A records (IPv4 embedded in IPv6 and IPv4 addresses). Question question4 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A); IList <IResourceRecord> resourceRecordsIpv4 = spiedMasterFile.Get(question4); resourceRecordsIpv4.Should().NotBeNullOrEmpty(); IList <IPAddressResourceRecord> ipAddressResourceRecords4 = resourceRecordsIpv4.OfType <IPAddressResourceRecord>().ToList(); ipAddressResourceRecords4.Should().HaveCount(4); // Check for AAAA records (IPv6 addresses). Question question6 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.AAAA); IList <IResourceRecord> resourceRecordsIpv6 = spiedMasterFile.Get(question6); resourceRecordsIpv6.Should().NotBeNullOrEmpty(); IList <IPAddressResourceRecord> ipAddressResourceRecords6 = resourceRecordsIpv6.OfType <IPAddressResourceRecord>().ToList(); ipAddressResourceRecords6.Should().HaveCount(1); foreach (Tuple <IPEndPoint, DateTimeOffset> testData in testDataSet) { if (testData.Item1.Address.IsIPv4MappedToIPv6) { ipAddressResourceRecords4.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull(); } else { ipAddressResourceRecords6.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address)).Should().NotBeNull(); } } }
private static IList <GameServerInfo> CreateGameServerInfos(IList <IManageableServer> servers) { return(servers?.OfType <IGameServer>().OrderBy(s => s.Id).Select(s => new GameServerInfo(s)).ToList()); }
public void Rebuild() { _obsolete = false; ReplaceEverythingBy(_source?.OfType <object>().Select(Wrap) ?? new HierarchicalItem[0]); }
private void UpdateItemsSet(IList removedItems, IList addedItems) { IEnumerable <object> itemsToRemove = removedItems == null?Enumerable.Empty <object>() : removedItems.OfType <object>(); IEnumerable <object> itemsToAdd = addedItems == null?Enumerable.Empty <object>() : addedItems.OfType <object>(); foreach (var item in itemsToRemove) { this.SelectItem(item, false, false); } foreach (var item in itemsToAdd) { this.SelectItem(item, true, false); } this.OnSelectedItemsChanged(itemsToRemove, itemsToAdd); }
/// <summary> /// Core logic for applying the query option to the IQueryable. /// </summary> /// <param name="query">The original <see cref="IQueryable"/>.</param> /// <param name="querySettings">Query setting used for validating the query option.</param> /// <param name="orderByNodes">OrderBy information required to correctly apply the query option for default implementation.</param> /// <param name="context">The <see cref="ODataQueryContext"/> which contains the <see cref="IEdmModel"/> and some type information</param> /// <param name="skipTokenRawValue">The raw string value of the skiptoken query parameter.</param> /// <returns></returns> private static IQueryable ApplyToCore(IQueryable query, ODataQuerySettings querySettings, IList <OrderByNode> orderByNodes, ODataQueryContext context, string skipTokenRawValue) { if (query == null) { throw Error.ArgumentNull(nameof(query)); } if (context.ElementClrType == null) { throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo"); } IDictionary <string, OrderByDirection> directionMap; if (orderByNodes != null) { directionMap = orderByNodes.OfType <OrderByPropertyNode>().ToDictionary(node => node.Property.Name, node => node.Direction); } else { directionMap = new Dictionary <string, OrderByDirection>(); } IDictionary <string, object> propertyValuePairs = PopulatePropertyValuePairs(skipTokenRawValue, context); if (propertyValuePairs.Count == 0) { throw Error.InvalidOperation("Unable to get property values from the skiptoken value."); } ExpressionBinderBase binder = new FilterBinder(context.RequestContainer); bool parameterizeConstant = querySettings.EnableConstantParameterization; ParameterExpression param = Expression.Parameter(context.ElementClrType); Expression where = null; /* We will create a where lambda of the following form - * Where (Prop1>Value1) * OR (Prop1=Value1 AND Prop2>Value2) * OR (Prop1=Value1 AND Prop2=Value2 AND Prop3>Value3) * and so on... * Adding the first true to simplify implementation. */ Expression lastEquality = null; bool firstProperty = true; foreach (KeyValuePair <string, object> item in propertyValuePairs) { string key = item.Key; MemberExpression property = Expression.Property(param, key); object value = item.Value; Expression compare = null; ODataEnumValue enumValue = value as ODataEnumValue; if (enumValue != null) { value = enumValue.Value; } Expression constant = parameterizeConstant ? LinqParameterContainer.Parameterize(value.GetType(), value) : Expression.Constant(value); if (directionMap.ContainsKey(key) && directionMap[key] == OrderByDirection.Descending) { compare = binder.CreateBinaryExpression(BinaryOperatorKind.LessThan, property, constant, true); } else { compare = binder.CreateBinaryExpression(BinaryOperatorKind.GreaterThan, property, constant, true); } if (firstProperty) { lastEquality = binder.CreateBinaryExpression(BinaryOperatorKind.Equal, property, constant, true); where = compare; firstProperty = false; } else { Expression condition = Expression.AndAlso(lastEquality, compare); where = Expression.OrElse(where, condition); lastEquality = Expression.AndAlso(lastEquality, binder.CreateBinaryExpression(BinaryOperatorKind.Equal, property, constant, true)); } } Expression whereLambda = Expression.Lambda(where, param); return(ExpressionHelpers.Where(query, whereLambda, query.ElementType)); }
public override MvxBasePresentationAttribute GetPresentationAttribute(MvxViewModelRequest request) { var viewType = ViewsContainer.GetViewType(request.ViewModelType); var overrideAttribute = GetOverridePresentationAttribute(request, viewType); if (overrideAttribute != null) { return(overrideAttribute); } IList <MvxBasePresentationAttribute> attributes = viewType.GetCustomAttributes <MvxBasePresentationAttribute>(true).ToList(); if (attributes != null && attributes.Count > 0) { MvxBasePresentationAttribute attribute = null; if (attributes.Count > 1) { var fragmentAttributes = attributes.OfType <MvxFragmentPresentationAttribute>(); // check if fragment can be displayed as child fragment first foreach (var item in fragmentAttributes.Where(att => att.FragmentHostViewType != null)) { var fragment = GetFragmentByViewType(item.FragmentHostViewType); // if the fragment exists, and is on top, then use the current attribute if (fragment != null && fragment.IsVisible && fragment.View.FindViewById(item.FragmentContentId) != null) { attribute = item; break; } } // if attribute is still null, check if fragment can be displayed in current activity if (attribute == null) { var currentActivityHostViewModelType = GetCurrentActivityViewModelType(); foreach (var item in fragmentAttributes.Where(att => att.ActivityHostViewModelType != null)) { if (CurrentActivity.FindViewById(item.FragmentContentId) != null && item.ActivityHostViewModelType == currentActivityHostViewModelType) { attribute = item; break; } } } } if (attribute == null) { attribute = attributes.FirstOrDefault(); } attribute.ViewType = viewType; return(attribute); } return(CreatePresentationAttribute(request.ViewModelType, viewType)); }
public BaseViewModel GetChild <TChild>(object param) where TChild : BaseViewModel { return(_childFactories.OfType <ViewModelBaseFactory <TChild> >().FirstOrDefault().Return(x => x.Get(param), null)); }
/// <summary> /// Populates the data source. /// </summary> private static void EnsureDataSource() { if (people == null) { people = new List <Person>() { new Customer() { FirstName = "Bob", LastName = "Cat", Numbers = new Collection <string> { "111-111-1111" }, PersonID = 1, Birthday = new DateTime(1957, 4, 3), City = "London", Home = GeographyPoint.Create(32.1, 23.1) }, new Customer() { FirstName = "Jill", LastName = "Jones", Numbers = new Collection <string> { }, PersonID = 2, Birthday = new DateTime(1983, 1, 15), City = "Sydney", Home = GeographyPoint.Create(15.0, 161.8) }, new Employee() { FirstName = "Jacob", LastName = "Zip", Numbers = new Collection <string> { "333-333-3333" }, PersonID = 3, DateHired = new DateTime(2010, 12, 13), Home = GeographyPoint.Create(15.0, 161.8), Office = GeographyPoint.Create(15.0, 162) }, new Employee() { FirstName = "Elmo", LastName = "Rogers", Numbers = new Collection <string> { "444-444-4444", "555-555-5555", "666-666-6666" }, PersonID = 4, DateHired = new DateTime(2008, 3, 27), Home = GeographyPoint.Create(-15.0, -61.8), Office = GeographyPoint.Create(-15.0, -62) } }; products = new List <Product>() { new Product() { Name = "Cheetos", ProductID = 5, QuantityInStock = 100, QuantityPerUnit = "100g Bag", UnitPrice = 3.24f, Discontinued = true }, new Product() { Name = "Mushrooms", ProductID = 6, QuantityInStock = 100, QuantityPerUnit = "Pound", UnitPrice = 3.24f, Discontinued = false } }; orders = new List <Order>() { new Order() { OrderID = 7, CustomerForOrder = people.OfType <Customer>().ElementAt(1), CustomerID = people.OfType <Customer>().ElementAt(1).PersonID, LoggedInEmployee = people.OfType <Employee>().ElementAt(0), EmployeeID = people.OfType <Employee>().ElementAt(0).PersonID, OrderDate = new DateTime(2011, 5, 29, 14, 21, 12) }, new Order() { OrderID = 8, CustomerForOrder = people.OfType <Customer>().ElementAt(0), CustomerID = people.OfType <Customer>().ElementAt(0).PersonID, LoggedInEmployee = people.OfType <Employee>().ElementAt(1), EmployeeID = people.OfType <Employee>().ElementAt(1).PersonID, OrderDate = new DateTime(2011, 3, 4, 16, 3, 57) } }; orderdetails = new List <OrderDetail>() { new OrderDetail() { OrderID = orders[0].OrderID, AssociatedOrder = orders[0], ProductID = products[0].ProductID, ProductOrdered = products[0], Quantity = 50, UnitPrice = products[0].UnitPrice }, new OrderDetail() { OrderID = orders[0].OrderID, AssociatedOrder = orders[0], ProductID = products[1].ProductID, ProductOrdered = products[1], Quantity = 2, UnitPrice = products[1].UnitPrice }, new OrderDetail() { OrderID = orders[1].OrderID, AssociatedOrder = orders[1], ProductID = products[1].ProductID, ProductOrdered = products[1], Quantity = 5, UnitPrice = products[1].UnitPrice } }; } }
public IEnumerable <T> NonDocumentOperationsOf <T>() where T : IStorageOperation { return(_ancillaryOperations.OfType <T>()); }
private IList<IOptionArgument> GetOptionArgumentDefinitionsInOrder(IList<ICommandLineArgument> argumentDefinitions) { IList<IOptionArgument> retValue = argumentDefinitions .OfType<IOptionArgument>() .OrderBy(x => x.Flag) .ToList<IOptionArgument>(); return retValue; }
public StreamWriterImplControl(IList <InstanceConfiguration> instances) { Exporters = instances.OfType <ExporterConfiguration>().ToList(); InitializeComponent(); }
private static AssetBundle LoadBundleFromDependecies(IList <object> results) { return(results?.OfType <IAssetBundleResource>() .Select(AssetBundleCache.TryLoadBundle) .FirstOrDefault()); }
protected override IEnumerable <ExpressionSyntax> GetTypeOfLikeExpressions(IList <ExpressionSyntax> arrayParameters) { return(arrayParameters.OfType <GetTypeExpressionSyntax>()); }
private async Task <bool?> CalculateCartLinePrice( CartLineComponent arg, CommercePipelineExecutionContext context) { ProductArgument productArgument = ProductArgument.FromItemId(arg.ItemId); SellableItem sellableItem = null; if (productArgument.IsValid()) { sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(productArgument.ProductId, StringComparison.OrdinalIgnoreCase))); if (sellableItem == null) { string simpleName = productArgument.ProductId.SimplifyEntityName(); sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(simpleName, StringComparison.OrdinalIgnoreCase))); if (sellableItem != null) { sellableItem.ProductId = simpleName; } } } if (sellableItem == null) { CommercePipelineExecutionContext executionContext = context; CommerceContext commerceContext = context.CommerceContext; string error = context.GetPolicy <KnownResultCodes>().Error; object[] args = new object[] { arg.ItemId }; string defaultMessage = "Item '" + arg.ItemId + "' is not purchasable."; executionContext.Abort(await commerceContext.AddMessage(error, "LineIsNotPurchasable", args, defaultMessage), context); executionContext = null; return(new bool?()); } MessagesComponent messagesComponent = arg.GetComponent <MessagesComponent>(); messagesComponent.Clear(context.GetPolicy <KnownMessageCodePolicy>().Pricing); if (sellableItem.HasComponent <MessagesComponent>()) { List <MessageModel> messages = sellableItem.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing); messagesComponent.AddMessages(messages); } arg.UnitListPrice = sellableItem.ListPrice; string listPriceMessage = "CartItem.ListPrice<=SellableItem.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null); string sellPriceMessage = string.Empty; PurchaseOptionMoneyPolicy optionMoneyPolicy = new PurchaseOptionMoneyPolicy(); if (sellableItem.HasPolicy <PurchaseOptionMoneyPolicy>()) { optionMoneyPolicy.SellPrice = sellableItem.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice; sellPriceMessage = "CartItem.SellPrice<=SellableItem.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null); } PriceSnapshotComponent snapshotComponent; if (sellableItem.HasComponent <ItemVariationsComponent>()) { ItemVariationSelectedComponent lineVariant = arg.ChildComponents.OfType <ItemVariationSelectedComponent>().FirstOrDefault(); ItemVariationsComponent itemVariationsComponent = sellableItem.GetComponent <ItemVariationsComponent>(); ItemVariationComponent itemVariationComponent; if (itemVariationsComponent == null) { itemVariationComponent = null; } else { IList <Component> childComponents = itemVariationsComponent.ChildComponents; itemVariationComponent = childComponents?.OfType <ItemVariationComponent>().FirstOrDefault(v => { return(!string.IsNullOrEmpty(v.Id) ? v.Id.Equals(lineVariant?.VariationId, StringComparison.OrdinalIgnoreCase) : false); }); } if (itemVariationComponent != null) { if (itemVariationComponent.HasComponent <MessagesComponent>()) { List <MessageModel> messages = itemVariationComponent.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing); messagesComponent.AddMessages(messages); } arg.UnitListPrice = itemVariationComponent.ListPrice; listPriceMessage = "CartItem.ListPrice<=SellableItem.Variation.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null); if (itemVariationComponent.HasPolicy <PurchaseOptionMoneyPolicy>()) { optionMoneyPolicy.SellPrice = itemVariationComponent.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice; sellPriceMessage = "CartItem.SellPrice<=SellableItem.Variation.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null); } } snapshotComponent = itemVariationComponent != null?itemVariationComponent.ChildComponents.OfType <PriceSnapshotComponent>().FirstOrDefault() : null; } else { snapshotComponent = sellableItem.Components.OfType <PriceSnapshotComponent>().FirstOrDefault(); } string currentCurrency = context.CommerceContext.CurrentCurrency(); PriceTier priceTier = snapshotComponent?.Tiers.OrderByDescending(t => t.Quantity).FirstOrDefault(t => { return(t.Currency.Equals(currentCurrency, StringComparison.OrdinalIgnoreCase) ? t.Quantity <= arg.Quantity : false); }); Customer customer = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Customer), context.CommerceContext.CurrentCustomerId(), false), context) as Customer; bool isMembershipLevelPrice = false; if (customer != null && customer.HasComponent <MembershipSubscriptionComponent>()) { var membershipSubscriptionComponent = customer.GetComponent <MembershipSubscriptionComponent>(); var membershipLevel = membershipSubscriptionComponent.MemerbshipLevelName; if (snapshotComponent != null && snapshotComponent.HasComponent <MembershipTiersComponent>()) { var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>(); var membershipPriceTier = membershipTiersComponent.Tiers.FirstOrDefault(x => x.MembershipLevel == membershipLevel); if (membershipPriceTier != null) { optionMoneyPolicy.SellPrice = new Money(membershipPriceTier.Currency, membershipPriceTier.Price); isMembershipLevelPrice = true; sellPriceMessage = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: MembershipLevel={0}|Price={1}|Qty={2}", membershipSubscriptionComponent.MemerbshipLevelName, optionMoneyPolicy.SellPrice.AsCurrency(false, null), membershipPriceTier.Quantity); } } } if (!isMembershipLevelPrice && priceTier != null) { optionMoneyPolicy.SellPrice = new Money(priceTier.Currency, priceTier.Price); sellPriceMessage = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: Price={0}|Qty={1}", optionMoneyPolicy.SellPrice.AsCurrency(false, null), priceTier.Quantity); } arg.Policies.Remove(arg.Policies.OfType <PurchaseOptionMoneyPolicy>().FirstOrDefault()); if (optionMoneyPolicy.SellPrice == null) { return(false); } arg.SetPolicy(optionMoneyPolicy); if (!string.IsNullOrEmpty(sellPriceMessage)) { messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, sellPriceMessage); } if (!string.IsNullOrEmpty(listPriceMessage)) { messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, listPriceMessage); } return(true); }
public object Convert(IList <object> values, Type targetType, object parameter, CultureInfo culture) { return(values.OfType <double>().Sum()); }