Пример #1
0
        /// <summary>
        /// Specifies that the value of a cell should be mapped to a fixed value if it cannot be parsed. This
        /// is useful for mapping columns where equivilent data was entered differently.
        /// </summary>
        /// <typeparam name="TPropertyMap">The type of the property map.</typeparam>
        /// <typeparam name="T">The type of the property or field that the property map represents.</typeparam>
        /// <param name="propertyMap">The property map to use.</param>
        /// <param name="mappingDictionary">A dictionary that maps a fixed string value to a fixed value of T.</param>
        /// <param name="comparer">The comparer uses to map fixed string values. This allows for case-insensitive mappings, for example.</param>
        /// <returns>The property map on which this method was invoked.</returns>
        public static TPropertyMap WithMapping <TPropertyMap, T>(this TPropertyMap propertyMap, IDictionary <string, T> mappingDictionary, IEqualityComparer <string> comparer = null) where TPropertyMap : ISinglePropertyMap <T>
        {
            var item = new DictionaryMapper <T>(mappingDictionary, comparer);

            propertyMap.AddCellValueMapper(item);
            return(propertyMap);
        }
Пример #2
0
 /// <summary>
 /// Initializes the helper.
 /// </summary>
 /// <param name="graphControl">The control that displays the graph.</param>
 /// <param name="component">The component the is dragged.</param>
 /// <param name="components">Defines components that should not be separated by the layout algorithm.</param>
 public ClearAreaLayoutHelper(GraphControl graphControl, IGraph component, DictionaryMapper <INode, object> components)
 {
     this.graphControl = graphControl;
     this.oldLocation  = GetCenter(component);
     this.Component    = component;
     this.components   = components;
 }
Пример #3
0
        public void Can_Map_Key_Property()
        {
            // Act
            string column = new DictionaryMapper(MockSqlContext(), CreateMaps()).Map("Key");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsDictionary].[id]"));
        }
Пример #4
0
        public void Can_Map_ItemKey_Property()
        {
            // Act
            string column = new DictionaryMapper().Map(new SqlCeSyntaxProvider(), "ItemKey");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsDictionary].[key]"));
        }
        public void Can_Map_ItemKey_Property()
        {
            // Act
            string column = new DictionaryMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("ItemKey");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsDictionary].[key]"));
        }
Пример #6
0
        protected DictionaryMapper Property <TKey, TValue>(
            Expression <Func <TEntity, IDictionary <TKey, TValue> > > predicate)
        {
            var mapper = new DictionaryMapper(predicate.ExtractNameAndType());

            _mappers.Add(mapper);
            return(mapper);
        }
Пример #7
0
    public void Can_Map_Id_Property()
    {
        // Act
        var column = new DictionaryMapper(TestHelper.GetMockSqlContext(), TestHelper.CreateMaps()).Map("Id");

        // Assert
        Assert.That(column, Is.EqualTo("[cmsDictionary].[pk]"));
    }
Пример #8
0
 void Awake()
 {
     _sceneMapping = new DictionaryMapper <string, string>(k => k);
     foreach (StringPair stringPair in sceneMapping)
     {
         _sceneMapping[stringPair.First] = stringPair.Second;
     }
 }
Пример #9
0
        public void Can_Map_ItemKey_Property()
        {
            // Arrange
            SqlSyntaxContext.SqlSyntaxProvider = SqlCeSyntax.Provider;

            // Act
            string column = new DictionaryMapper().Map("ItemKey");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsDictionary].[key]"));
        }
        private static void AddNodeHalos(LayoutGraphAdapter adapter, IGraph graph, bool layoutOnlySelection)
        {
            var nodeHalos = new DictionaryMapper <INode, NodeHalo>();

            foreach (var node in graph.Nodes)
            {
                var top    = 0.0;
                var left   = 0.0;
                var bottom = 0.0;
                var right  = 0.0;

                // for each port with an EventPortStyle extend the node halo to cover the ports render size
                foreach (var port in node.Ports)
                {
                    var eventPortStyle = port.Style as EventPortStyle;
                    if (eventPortStyle != null)
                    {
                        var renderSize = eventPortStyle.RenderSize;
                        var location   = port.GetLocation();
                        top    = Math.Max(top, node.Layout.Y - location.Y - renderSize.Height / 2);
                        left   = Math.Max(left, node.Layout.X - location.X - renderSize.Width / 2);
                        bottom = Math.Max(bottom, location.Y + renderSize.Height / 2 - node.Layout.GetMaxY());
                        right  = Math.Max(right, location.X + renderSize.Width / 2 - node.Layout.GetMaxX());
                    }
                }

                // for each node without incoming or outgoing edges reserve space for laid out exterior labels
                if (graph.InDegree(node) == 0 || graph.OutDegree(node) == 0)
                {
                    foreach (var label in node.Labels)
                    {
                        if (IsNodeLabelAffected(label, adapter, layoutOnlySelection))
                        {
                            var labelBounds = label.GetLayout().GetBounds();
                            if (graph.InDegree(node) == 0)
                            {
                                left = Math.Max(left, labelBounds.Width);
                                top  = Math.Max(top, labelBounds.Height);
                            }
                            if (graph.OutDegree(node) == 0)
                            {
                                right  = Math.Max(right, labelBounds.Width);
                                bottom = Math.Max(bottom, labelBounds.Height);
                            }
                        }
                    }
                }

                nodeHalos[node] = NodeHalo.Create(top, left, bottom, right);
            }
            adapter.AddDataProvider(NodeHalo.NodeHaloDpKey, nodeHalos);
        }
Пример #11
0
        public static InputInfo CreateInputClassInfo(XPDictionary outputDictionary, string inputPutClass, params ColumnInfo[] columnInfos)
        {
            var table = CreateDbTable(inputPutClass, columnInfos);

            var dataSet          = new DataSet();
            var inputUnitOfWork  = new UnitOfWork(new SimpleDataLayer(new DataSetDataStore(dataSet, AutoCreateOption.DatabaseAndSchema)));
            var dictionaryMapper = new DictionaryMapper(new[] { table });

            dictionaryMapper.Map(outputDictionary, inputUnitOfWork.Dictionary);
            var classInfo = inputUnitOfWork.Dictionary.QueryClassInfo(null, inputPutClass);

            return(new InputInfo(classInfo, inputUnitOfWork, dataSet));
        }
Пример #12
0
        public void Ctor_Dictionary_ReturnsExpected()
        {
            var mapping = new Dictionary <string, object> {
                { "key", "value" }
            };
            var comparer = StringComparer.CurrentCulture;
            var item     = new DictionaryMapper <object>(mapping, comparer);

            Dictionary <string, object> itemMapping = Assert.IsType <Dictionary <string, object> >(item.MappingDictionary);

            Assert.Equal(mapping, itemMapping);
            Assert.Same(comparer, itemMapping.Comparer);
        }
        private async void OnLoaded(object sender, EventArgs e)
        {
            InitializeInteraction();

            configOptionsValid = true;
            SetUiDisabled(false);

            incrementalNodesMapper = new DictionaryMapper <INode, bool> {
                DefaultValue = false
            };

            var samples = new[] {
                new Sample("Sample: Minimum Spanning Tree", "MinimumSpanningTree"),
                new Sample("Sample: Connected Components", "Connectivity"),
                new Sample("Sample: Biconnected Components", "Connectivity"),
                new Sample("Sample: Strongly Connected Components", "Connectivity"),
                new Sample("Sample: Reachability", "Connectivity"),
                new Sample("Sample: Shortest Paths", "Paths"),
                new Sample("Sample: All Paths", "Paths"),
                new Sample("Sample: All Chains", "Paths"),
                new Sample("Sample: Single Source", "Paths"),
                new Sample("Sample: Cycles", "Cycles"),
                new Sample("Sample: Degree Centrality", "Centrality"),
                new Sample("Sample: Weight Centrality", "Centrality"),
                new Sample("Sample: Graph Centrality", "Centrality"),
                new Sample("Sample: Node Edge Betweenness Centrality", "Centrality"),
                new Sample("Sample: Closeness Centrality", "Centrality"),
                new Sample("Sample: Independent Sets", "MinimumSpanningTree")
            };

            sampleComboBox.ComboBox.DataSource = samples;
            sampleComboBox.SelectedIndex       = 0;

            directionComboBox.ComboBox.Enabled = false;
            directionComboBox.SelectedIndex    = 0;

            uniformEdgeWeightsComboBox.ComboBox.Enabled = false;
            uniformEdgeWeightsComboBox.SelectedIndex    = 0;

            RegisterCommands();

            InitializeGraph();

            UpdateGraphInformation();

            preventLayout = true;
            InitializeAlgorithms();
            mIsInitializing = false;

            await RunLayout(false, true, true);
        }
Пример #14
0
        public void GetProperty_ValidStringValue_ReturnsSuccess(string stringValue, PropertyMapperResultType expectedType, object expectedValue)
        {
            var mapping = new Dictionary <string, object> {
                { "key", "value" }, { "KEY2", 10 }
            };
            var comparer = StringComparer.OrdinalIgnoreCase;
            var item     = new DictionaryMapper <object>(mapping, comparer);

            object value = null;
            PropertyMapperResultType result = item.GetProperty(new ReadCellValueResult(-1, stringValue), ref value);

            Assert.Equal(expectedType, result);
            Assert.Equal(expectedValue, value);
        }
Пример #15
0
        /// <summary>
        /// Creates and configures the graph that is used for the placer configuration preview.
        /// </summary>
        private void SetupPreview()
        {
            IGraph graph = previewControl.Graph;
            DictionaryMapper <INode, bool> assistantMap =
                graph.MapperRegistry.CreateMapper <INode, bool>(AssistantNodePlacer.AssistantNodeDpKey);

            graph.NodeDefaults.Size  = new SizeD(40, 30);
            graph.NodeDefaults.Style = new ShinyPlateNodeStyle
            {
                Brush      = Brushes.LightGray,
                Insets     = new InsetsD(5),
                DrawShadow = false,
                Pen        = Pens.Black
            };
            var rootStyle = new ShinyPlateNodeStyle
            {
                Brush      = Brushes.Red,
                Insets     = new InsetsD(5),
                Pen        = Pens.Black,
                DrawShadow = false
            };
            var assistantStyle = new ShinyPlateNodeStyle
            {
                Brush  = Brushes.LightGray,
                Insets = new InsetsD(5),
                Pen    = new Pen(Brushes.Black, 1)
                {
                    DashStyle = DashStyles.Dash
                },
                DrawShadow = false
            };
            INode root = graph.CreateNode();

            graph.SetStyle(root, rootStyle);
            INode n1 = graph.CreateNode();

            graph.SetStyle(n1, assistantStyle);
            assistantMap[n1] = true;
            INode n2 = graph.CreateNode();
            INode n3 = graph.CreateNode();
            INode n4 = graph.CreateNode();
            INode n5 = graph.CreateNode(new RectD(0, 0, 60, 30));

            graph.CreateEdge(root, n1);
            graph.CreateEdge(root, n2);
            graph.CreateEdge(root, n3);
            graph.CreateEdge(root, n4);
            graph.CreateEdge(root, n5);
            previewLayout = new TreeLayout();
        }
Пример #16
0
        public ObservableCollection <RefTypeModel> GetRefTypeModels()
        {
            var request = PrepareRequest(new RefTypeRequest());

            request.LoadOptions = new[] { "RefTypes" };

            var response = RefTypeClient.GetRefTypes(request);

            if (response.Acknowledge != AcknowledgeType.Success)
            {
                throw new ApplicationException(response.Message);
            }

            return(DictionaryMapper.FromDataTransferObjects(response.RefTypes));
        }
Пример #17
0
        public IActionResult Get([FromRoute] long id)
        {
            IResult <Dictionary> result = _queryBus.Send <DictionaryGetByIdQuery, Dictionary>(new DictionaryGetByIdQuery(id));

            if (!result.IsValid())
            {
                var Error = (InvalidResult <Dictionary>)result;
                return(BadRequest(Error.Errors));
            }

            var        Success    = (SuccessResult <Dictionary>)result;
            Dictionary dictionary = Success.Data;

            return(Ok(DictionaryMapper.MapToReadModel(dictionary)));
        }
Пример #18
0
        public IActionResult GetMany([FromQuery] int amount = 20, [FromQuery] int pages = 1)
        {
            IResult <List <Dictionary> > result = _queryBus.Send <DictionaryGetManyQuery, List <Dictionary> >(new DictionaryGetManyQuery(amount, pages));

            if (!result.IsValid())
            {
                var Error = (InvalidResult <List <Dictionary> >)result;
                return(BadRequest(Error.Errors));
            }

            var Success = (SuccessResult <List <Dictionary> >)result;
            List <Dictionary> dictionaries = Success.Data;

            return(Ok(dictionaries.Select(x => DictionaryMapper.MapToReadModel(x))));
        }
Пример #19
0
        ///<summary>
        /// Random graph generator in case multiple edges are allowed.
        ///</summary>
        private void GenerateMultipleGraph(IGraph G)
        {
            int n = NodeCount;
            int m = EdgeCount;
            IMapper <IPortOwner, int> index = new DictionaryMapper <IPortOwner, int>();

            int[]   deg = new int[n];
            INode[] V   = new INode[n];
            for (int i = 0; i < n; i++)
            {
                V[i]        = G.CreateNode();
                index[V[i]] = i;
            }

            for (int i = 0; i < m; i++)
            {
                deg[random.Next(n)]++;
            }

            for (int i = 0; i < n; i++)
            {
                INode v = V[i];
                int   d = deg[i];
                while (d > 0)
                {
                    int j = random.Next(n);
                    if (j == i && (!AllowCycles || !AllowSelfLoops))
                    {
                        continue;
                    }
                    G.CreateEdge(v, V[j]);
                    d--;
                }
            }

            if (!AllowCycles)
            {
                foreach (IEdge edge in G.Edges)
                {
                    IPort sourcePort = edge.SourcePort;
                    IPort targetPort = edge.TargetPort;
                    if (index[sourcePort.Owner] > index[targetPort.Owner])
                    {
                        G.SetEdgePorts(edge, targetPort, sourcePort);
                    }
                }
            }
        }
Пример #20
0
        ///<summary>
        /// Random graph generator for sparse graphs.
        ///</summary>
        private void GenerateSparseGraph(IGraph G)
        {
            G.Clear();
            IMapper <IPortOwner, int> index = new DictionaryMapper <IPortOwner, int>();

            int n = NodeCount;

            int m = Math.Min(GetMaxEdges(), EdgeCount);

            INode[] V = new INode[n];

            for (int i = 0; i < n; i++)
            {
                V[i]        = G.CreateNode();
                index[V[i]] = i;
            }

            RandomSupport.Permutate(random, V);

            int count = m;

            while (count > 0)
            {
                int   vi = random.Next(n);
                INode v  = V[vi];
                INode w  = V[random.Next(n)];

                if (G.GetEdge(v, w) != null || (v == w && (!AllowSelfLoops || !AllowCycles)))
                {
                    continue;
                }
                G.CreateEdge(v, w);
                count--;
            }

            if (!AllowCycles)
            {
                foreach (IEdge edge in G.Edges)
                {
                    IPort sourcePort = edge.SourcePort;
                    IPort targetPort = edge.TargetPort;
                    if (index[sourcePort.Owner] > index[targetPort.Owner])
                    {
                        G.SetEdgePorts(edge, targetPort, sourcePort);
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Wires up the UI components.
        /// </summary>
        public ComponentDragAndDropForm()
        {
            InitializeComponent();

            // load description
            description.LoadFile(new MemoryStream(Properties.Resources.description), RichTextBoxStreamType.RichText);

            // set commands to buttons and menu items
            undoButton.SetCommand(Commands.Undo, graphControl);
            redoButton.SetCommand(Commands.Redo, graphControl);
            zoomInButton.SetCommand(Commands.IncreaseZoom, graphControl);
            zoomOutButton.SetCommand(Commands.DecreaseZoom, graphControl);
            zoomFitButton.SetCommand(Commands.FitContent, graphControl);

            graphComponents = new DictionaryMapper <INode, object>();
        }
Пример #22
0
        public void ShouldMapTypeByDictionary()
        {
            var source = new Dictionary <string, int>();

            source.Add("Prop", 1);
            source.Add("Prop2", 1);
            source.Add("Prop3", 1);
            var mapper = new DictionaryMapper <int, ClassW4Properties>();

            var dest = mapper.Map(source);

            Assert.IsNotNull(dest);
            Assert.AreEqual(source["Prop"], dest.Prop);
            Assert.AreEqual(source["Prop2"], dest.Prop2);
            Assert.AreEqual(source["Prop3"], dest.Prop3);
        }
Пример #23
0
        private void ReadSampleGraph()
        {
            string fileName = string.Format("Resources" + Path.DirectorySeparatorChar + "{0}.graphml", graphChooserBox.SelectedItem.ToString());
            DictionaryMapper <IGraph, string> descriptionMapper = new DictionaryMapper <IGraph, string>();

            graphControl.Graph.Clear();
            var ioHandler = new GraphMLIOHandler();

            ioHandler.AddRegistryInputMapper <INode, string>("Description");
            ioHandler.AddRegistryInputMapper <INode, string>("ToolTip");
            ioHandler.AddRegistryInputMapper <INode, string>("Url");
            ioHandler.AddInputMapper <IGraph, string>("GraphDescription", descriptionMapper);
            ioHandler.Read(graphControl.Graph, fileName);
            graphDescriptionTextBlock.Text = descriptionMapper[graphControl.Graph.GetFoldingView().Manager.MasterGraph] ?? string.Empty;
            graphControl.FitGraphBounds(new InsetsD(10));
        }
Пример #24
0
        public void WithMapping_ValidReader_Success()
        {
            var dictionaryMapping = new Dictionary <string, DateTime> {
                { "key", DateTime.MinValue }
            };
            StringComparer comparer = StringComparer.CurrentCultureIgnoreCase;

            SingleExcelPropertyMap <DateTime> propertyMap = Map(t => t.DateValue);

            Assert.Same(propertyMap, propertyMap.WithMapping(dictionaryMapping, comparer));

            DictionaryMapper <DateTime> item = propertyMap.CellValueMappers.OfType <DictionaryMapper <DateTime> >().Single();

            Assert.NotSame(dictionaryMapping, item.MappingDictionary);
            Assert.Equal(dictionaryMapping, item.MappingDictionary);

            Assert.Same(comparer, Assert.IsType <Dictionary <string, DateTime> >(item.MappingDictionary).Comparer);
        }
Пример #25
0
        /// <summary>
        /// Initializes the graph instance, setting default styles
        /// and creating a small sample graph.
        /// </summary>
        protected virtual void InitializeGraph()
        {
            // create the manager for the folding operations
            FoldingManager foldingManager = new FoldingManager();

            // create a view
            foldingView = foldingManager.CreateFoldingView();

            // and set it to the GraphControl
            graphControl.Graph = foldingView.Graph;

            // decorate the behavior of nodes
            NodeDecorator nodeDecorator = graphControl.Graph.GetDecorator().NodeDecorator;

            // adjust the insets so that labels are considered
            nodeDecorator.InsetsProviderDecorator.SetImplementationWrapper(
                delegate(INode node, INodeInsetsProvider insetsProvider) {
                if (insetsProvider != null)
                {
                    InsetsD insets = insetsProvider.GetInsets(node);
                    return(new LabelInsetsProvider(insets));
                }
                else
                {
                    return(new LabelInsetsProvider());
                }
            });

            //Constrain group nodes to at least the size of their labels
            nodeDecorator.SizeConstraintProviderDecorator.SetImplementationWrapper(
                (node, oldImpl) => new LabelSizeConstraintProvider(oldImpl));

            fixedGroupNodeLayout = graphControl.Graph.MapperRegistry.CreateMapper <INode, RectD?>("NodeLayouts");
            ReadSampleGraph();
            incrementalNodes.UnionWith(graphControl.Graph.Nodes);
        }
 /// <summary>
 /// Wires up the UI components.
 /// </summary>
 public ComponentDragAndDropDemo()
 {
     InitializeComponent();
     components = new DictionaryMapper <INode, object>();
 }
Пример #27
0
        private void LoadDefaults(string uri)
        {
            Style accordionStyle = (Style)Application.Current.Resources["AccordionItemStyle"];
            IMapper <string, HeaderedContentControl> accordionItems = new DictionaryMapper <string, HeaderedContentControl>();
            {
                var graph = new DefaultGraph();
                try {
                    new GraphMLIOHandler().Read(graph, uri);
                } catch (Exception) {
                    return;
                }
                List <StyleChooser> nodeChoosers = new List <StyleChooser>();
                foreach (var node in graph.Nodes)
                {
                    string tag = (string)(node.Tag ?? "Other");

                    if ("Dummy" == tag)
                    {
                        continue;
                    }

                    HeaderedContentControl accordionItem = accordionItems[tag];
                    if (null == accordionItem)
                    {
                        accordionItem = new Expander()
                        {
                            Style = accordionStyle
                        };
                        accordionItem.Header = tag;
                        accordionItems[tag]  = accordionItem;
                        StyleChooserAccordion.Items.Add(accordionItem);
                        var styleChooser = new StyleChooser();
                        styleChooser.ItemType          = typeof(INodeStyle);
                        styleChooser.ItemsSource       = new ObservableCollection <INode>();
                        styleChooser.SelectionChanged += delegate(object sender, SelectionChangedEventArgs args) {
                            if (args.AddedItems.Count > 0)
                            {
                                foreach (var n in nodeChoosers)
                                {
                                    if (n != sender)
                                    {
                                        n.Deselect();
                                    }
                                }
                            }
                        };
                        styleChooser.SelectionChanged += OnSelectionChanged;

                        nodeChoosers.Add(styleChooser);
                        accordionItem.Content            = styleChooser;
                        styleChooser.HorizontalAlignment = HorizontalAlignment.Stretch;
                    }

                    StyleChooser chooser = (StyleChooser)accordionItem.Content;
                    ObservableCollection <INode> itemSource = (ObservableCollection <INode>)chooser.ItemsSource;
                    itemSource.Add(node);
                }
                var nodeChooser = nodeChoosers.FirstOrDefault();
                if (nodeChooser != null)
                {
                    nodeChooser.SelectFirst();
                }

                HeaderedContentControl edgeTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                edgeTypesAccordionItem.Header = "Edge Types";
                StyleChooserAccordion.Items.Add(edgeTypesAccordionItem);
                var edgeStyleChooser = new StyleChooser();
                edgeStyleChooser.ItemType = typeof(IEdgeStyle);
                var edgeStyles = new ObservableCollection <IEdgeStyle>();
                edgeStyleChooser.ItemsSource = edgeStyles;

                edgeStyleChooser.SelectionChanged += OnSelectionChanged;


                edgeTypesAccordionItem.Content = edgeStyleChooser;

                foreach (var edge in graph.Edges)
                {
                    edgeStyles.Add(edge.Style);
                }

                edgeStyleChooser.SelectFirst();

                var labelTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                labelTypesAccordionItem.Header = "Label Types";
                StyleChooserAccordion.Items.Add(labelTypesAccordionItem);
                var labelStyleChooser = new StyleChooser();
                labelStyleChooser.ItemType = typeof(ILabelStyle);
                var labelStyles = new ObservableCollection <ILabelStyle>();
                labelStyleChooser.ItemsSource   = labelStyles;
                labelTypesAccordionItem.Content = labelStyleChooser;

                labelStyleChooser.SelectionChanged += OnSelectionChanged;

                foreach (var label in graph.Labels)
                {
                    if (label.Owner is INode && Equals("Dummy", label.Owner.Tag))
                    {
                        var style = label.Style;
                        if (style is NodeStyleLabelStyleAdapter)
                        {
                            // unwrap from NodeStyleLabelStyleAdapter
                            style = ((NodeStyleLabelStyleAdapter)style).LabelStyle;
                        }

                        // adjust the default flow direction of SimpleLabelStyles to the flowdirection of the current application.
                        if (style is DefaultLabelStyle)
                        {
                            ((DefaultLabelStyle)style).FlowDirection = this.FlowDirection;
                        }
                        if (style is LabelStyle)
                        {
                            ((LabelStyle)style).FlowDirection = this.FlowDirection;
                        }
                        labelStyles.Add(label.Style);
                    }
                }
                labelStyleChooser.SelectFirst();

                var portTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                portTypesAccordionItem.Header = "Port Types";
                StyleChooserAccordion.Items.Add(portTypesAccordionItem);
                var portStyleChooser = new StyleChooser();
                portStyleChooser.ItemType = typeof(IPortStyle);
                var portStyles = new ObservableCollection <IPortStyle>();
                portStyleChooser.ItemsSource   = portStyles;
                portTypesAccordionItem.Content = portStyleChooser;

                portStyleChooser.SelectionChanged += OnSelectionChanged;

                foreach (var port in graph.Ports)
                {
                    if (Equals("Dummy", port.Owner.Tag) && port.Tag != null)
                    {
                        portStyles.Add(port.Style);
                    }
                }
                // clear tags except for group nodes - no one needs them....
                foreach (var node in graph.Nodes)
                {
                    if (!Equals("Group Nodes", node.Tag))
                    {
                        node.Tag = null;
                    }
                }
                foreach (var edge in graph.Edges)
                {
                    edge.Tag = null;
                }
            }
        }
Пример #28
0
        public void DictionaryMapper_Success()
        {
            var converters       = new Dictionary <string, IConverter>();
            var converterConfig1 = new ConverterConfiguration()
            {
                Id = ID_CONVERTER_1,
            };
            var converter1 = new AllUpperCaseConverter();

            converter1.Configure(converterConfig1);
            converters.Add(converter1.Id, converter1);

            var leftSideMap1 = new Dictionary <string, List <string> >()
            {
                { "FirstName", new List <string>()
                  {
                      "FirstName"
                  } }
            };

            // Create the converters we are targeting
            var targetConverters = new List <SourceTargetConverter>();

            targetConverters.Add(new SourceTargetConverter()
            {
                Id = ID_CONVERTER_1, LeftSideMap = leftSideMap1, CombineInputOutput = false
            });
            // Now create the targeted mapping
            var targetMappings = new List <SourceTargetMapping>();

            targetMappings.Add(new SourceTargetMapping()
            {
                PrimaryKey       = "FirstName",
                TargetConverters = targetConverters
            });
            var mapperConfig = new MapperConfiguration()
            {
                Id                   = "1234",
                TransformerId        = "6678",
                SourceTargetMappings = targetMappings,
                DataType             = TYPE_MOCKUSER
            };
            var mapper = new DictionaryMapper();

            mapper.Configure(mapperConfig, converters);

            var dataToConvert = new Dictionary <string, object>()
            {
                { "FirstName", "Jane" },
                { "LastName", "Doe" },
                { "Email", "*****@*****.**" },
                { "LastLogin", "06-25-2018 09:03:45.123456" }
            };
            var dataPoint = new KeyValuePair <string, object>("AD User", dataToConvert);
            var dataRow   = new EntityCollection();

            dataRow.Entities.Add(dataPoint.Key, dataPoint.Value);

            var data = mapper.Map(new List <IEntityCollection> {
                dataRow
            });

            data.Count.Should().Be(1);
            var user = data[0] as MockUser;

            user.FirstName.Should().Be("JANE");
        }
        /// <summary>
        /// Initializes the graph from the supplied GraphML file and creates the model from it.
        /// </summary>
        /// <remarks>
        /// While this reads the graph from a GraphML file and constructs the model from an already-finished graph, a
        /// real-world application would likely create the model from whichever data source is available and then create
        /// the graph from it.
        /// </remarks>
        private void InitGraphAndModel()
        {
            var graph = new DefaultGraph
            {
                NodeDefaults = { Style            = new NodeControlNodeStyle("NodeStyle")
                                 {
                                     OutlineShape = new Ellipse()
                                 } },
                EdgeDefaults = { Style = new EdgeSegmentControlEdgeStyle("EdgeStyle") }
            };
            var ioh = new GraphMLIOHandler();

            // Parse node kinds and other info
            IMapper <INode, NodeKind> nodeKinds = new DictionaryMapper <INode, NodeKind>();
            IMapper <INode, NodeInfo> nodeInfos = new DictionaryMapper <INode, NodeInfo>();

            ioh.AddInputMapper("NetworkMonitoring.NodeKind", nodeKinds);
            ioh.AddInputMapper("NetworkMonitoring.NodeInfo", nodeInfos);

            ioh.Read(graph, @"Resources\network.graphml");

            foreach (var node in graph.Nodes)
            {
                // Create and attach the model node to the graph node.
                var modelNode = new ModelNode
                {
                    Name    = nodeInfos[node].Name,
                    Ip      = nodeInfos[node].Ip,
                    Enabled = true,
                    Kind    = nodeKinds[node]
                };
                node.Tag = modelNode;

                // Add the label
                var label = graph.AddLabel(node, "", FreeLabelModel.Instance.CreateDefaultParameter(), nodeLabelStyle, tag: modelNode);
                // Attach event handler for changing label visibility, so that the graph redraws accordingly.
                // Since visibility can change via clicking on the node *and* from within the label, we have to use an event
                // handler on the model node here.
                modelNode.PropertyChanged += delegate(object sender, PropertyChangedEventArgs args) {
                    if (args.PropertyName == "LabelVisible")
                    {
                        GraphControl.Invalidate();
                    }
                };
            }

            foreach (var edge in graph.Edges)
            {
                // Create and attach the model edge to the graph edge
                var modelEdge = new ModelEdge
                {
                    Source = (ModelNode)edge.GetSourceNode().Tag,
                    Target = (ModelNode)edge.GetTargetNode().Tag
                };
                edge.Tag = modelEdge;

                // Add the edge label
                var label = graph.AddLabel(edge, "", NinePositionsEdgeLabelModel.CenterCentered, edgeLabelStyle, tag: modelEdge);
            }

            // Create the mappings from model items to graph elements.
            modelNodeToINode = graph.Nodes.ToDictionary(node => (ModelNode)node.Tag);
            modelEdgeToIEdge = graph.Edges.ToDictionary(edge => (ModelEdge)edge.Tag);

            model = new NetworkModel(modelNodeToINode.Keys, modelEdgeToIEdge.Keys);
            GraphControl.Graph = graph;
        }
        /// <summary>
        /// Set up the input mode and other aspects of interaction.
        /// </summary>
        private void InitializeInteraction()
        {
            incrementalElements = new DictionaryMapper <INode, bool> {
                DefaultValue = false
            };

            var inputMode = new GraphEditorInputMode {
                ShowHandleItems = GraphItemTypes.Bend | GraphItemTypes.Edge | GraphItemTypes.Label | GraphItemTypes.Port,
                AllowAddLabel   = false
            };

            // deletion: notify configuration about removed elements and remove the elements from the maps, too
            inputMode.DeletingSelection += (sender, e) => {
                var selection = (IGraphSelection)e.Selection;
                CurrentConfig.EdgeRemoved = true;
                var graph = e.Context.GetGraph();
                foreach (var node in selection.SelectedNodes)
                {
                    foreach (var edge in graph.EdgesAt(node))
                    {
                        if (!selection.IsSelected(edge.Opposite(node)))
                        {
                            incrementalNodesMapper[(INode)edge.Opposite(node)] = true;
                        }
                    }
                }
                foreach (var edge in selection.SelectedEdges)
                {
                    if (!selection.IsSelected(edge.GetSourceNode()))
                    {
                        incrementalNodesMapper[edge.GetSourceNode()] = true;
                        incrementalElements[edge.GetSourceNode()]    = true;
                    }
                    if (!selection.IsSelected(edge.GetTargetNode()))
                    {
                        incrementalNodesMapper[edge.GetTargetNode()] = true;
                        incrementalElements[edge.GetTargetNode()]    = true;
                    }
                }

                CurrentConfig.IncrementalElements = incrementalElements;
            };

            // after deletion: update the graph information panel
            // and run a layout and the current algorithm
            inputMode.DeletedSelection += async(sender, e) => {
                UpdateGraphInformation();
                await RunLayout(true, false, true);
            };

            // edge creation: update the graph information panel
            // and add the new edge to the elements to be updated;
            // run a new layout and a new algorithm
            inputMode.CreateEdgeInputMode.EdgeCreated += async(sender, e) => {
                UpdateGraphInformation();
                var edge = e.Item;
                incrementalNodesMapper[edge.GetSourceNode()] = true;
                incrementalNodesMapper[edge.GetTargetNode()] = true;

                incrementalElements[edge.GetSourceNode()] = true;
                incrementalElements[edge.GetTargetNode()] = true;

                CurrentConfig.IncrementalElements = incrementalElements;

                await RunLayout(true, false, true);
            };

            // same for new nodes
            inputMode.NodeCreated += (sender, e) => {
                UpdateGraphInformation();

                incrementalElements[e.Item]       = true;
                CurrentConfig.IncrementalElements = incrementalElements;

                // prevent a new layout from starting and disable the UI's buttons
                inLayout = true;
                SetUiDisabled(true);

                ApplyAlgorithm();

                // permit a new layout to start and enable the UI's buttons
                ReleaseLocks();
                SetUiDisabled(false);
            };

            inputMode.LabelTextChanged += (sender, e) => {
                // prevent a new layout from starting and disable the UI's buttons
                inLayout = true;
                SetUiDisabled(true);

                ApplyAlgorithm();

                // permit a new layout to start and enable the UI's buttons
                ReleaseLocks();
                SetUiDisabled(false);
            };

            // also we add a context menu
            inputMode.ContextMenuItems = GraphItemTypes.Node;
            inputMode.ContextMenuInputMode.ClearMenu = true;
            inputMode.PopulateItemContextMenu       += (o, args) => {
                if (CurrentConfig != null && configOptionsValid && !inLayout)
                {
                    CurrentConfig.PopulateContextMenu(args);
                }
            };
            graphControl.InputMode = inputMode;
        }