Exemple #1
0
        private void comboBoxConnection_SelectedIndexChanged(object sender, EventArgs e)
        {
            NetGraph selected = comboBoxConnection.SelectedItem as NetGraph;

            if (selected != null)
            {
                BasePipelineNode selectedNode = comboBoxNodes.SelectedItem as BasePipelineNode;

                comboBoxNodes.Items.Clear();
                AddGraphToComboBox(selected);

                if (selectedNode != null)
                {
                    foreach (BasePipelineNode node in comboBoxNodes.Items)
                    {
                        if (node.Name == selectedNode.Name)
                        {
                            comboBoxNodes.SelectedItem = node;
                            break;
                        }
                    }
                }
            }
            else
            {
                comboBoxNodes.Items.Clear();
            }
        }
Exemple #2
0
        public static IEnumerable <DataFrame> ParseFrames(IEnumerable <DataFrame> frames, string selectionPath, ScriptContainer container, string classname)
        {
            BasePipelineNode        input;
            ParseWithPipelineNode   output;
            IEnumerable <DataFrame> ret = new DataFrame[0];
            NetGraph graph = BuildGraph(container, classname, selectionPath, out input, out output);

            try
            {
                foreach (DataFrame frame in frames)
                {
                    input.Input(frame);
                }
                input.Shutdown(null);

                output.EventFlag.WaitOne(500);

                ret = output.Frames;
            }
            finally
            {
                ((IDisposable)graph).Dispose();
            }

            return(ret);
        }
Exemple #3
0
        private FilePacketLogger GetLogFile(NetGraph graph)
        {
            FilePacketLogger logger = null;

            lock (_fileLogs)
            {
                if (_fileLogs.ContainsKey(graph.Uuid))
                {
                    logger = _fileLogs[graph.Uuid].Logger;
                }
                else
                {
                    long   currLogIndex = Interlocked.Increment(ref _currentLogIndex);
                    string fileName     = Path.Combine(redirectLogControl.BaseDirectory,
                                                       String.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"),
                                                                     GeneralUtils.SanitizeFilename(graph.NetworkDescription, '_') + currLogIndex.ToString() + ".log"));

                    try
                    {
                        FileRedirectLogEntry redirect = new FileRedirectLogEntry(graph.NetworkDescription, fileName);
                        _fileLogs.Add(graph.Uuid, redirect);

                        logger = redirect.Logger;
                    }
                    catch (IOException ex)
                    {
                        eventLogControl.Logger.LogException(ex);
                    }
                }
            }

            return(logger);
        }
Exemple #4
0
        /// <summary>
        /// Method called for a new connection
        /// </summary>
        /// <param name="graph">The new connection graph</param>
        private void OnNewConnection(NetGraph graph)
        {
            bool connAdded = false;

            lock (_connections)
            {
                if (_state == (int)ServiceState.Running)
                {
                    _connections.Add(new ConnectionEntry(this, graph, _defaultTimeout, _afterData));
                    connAdded = true;
                }
            }

            if (connAdded)
            {
                NewConnectionEvent?.Invoke(this, new ConnectionEventArgs(graph));

                if (_logger != null)
                {
                    _logger.LogVerbose(CANAPE.Net.Properties.Resources.NetworkServiceBase_ConnectionEstablished,
                                       graph.NetworkDescription);
                }
            }
            else
            {
                // We are not running don't add it, just kill
                try
                {
                    ((IDisposable)graph).Dispose();
                }
                catch
                {
                }
            }
        }
Exemple #5
0
        void UpdateGraph(ListViewItem item)
        {
            NetGraph graph       = item.Tag as NetGraph;
            TimeSpan currentSpan = new TimeSpan(DateTime.UtcNow.Ticks);

            item.SubItems[2].Text = String.Format("{0}s", (long)currentSpan.Subtract(graph.CreatedTicks).TotalSeconds);
        }
Exemple #6
0
 /// <summary>
 /// Build a NetGraph object from the nodes
 /// </summary>
 /// <param name="name">The name of the graph</param>
 /// <param name="logger">A logger object</param>
 /// <param name="parent">The parent graph, null if not available</param>
 /// <param name="globalMeta">Global meta dictionary</param>
 /// <param name="meta">Local meta dictionary</param>
 /// <param name="connectionProperties">Properties for connection</param>
 /// <returns>The constructed NetGraph</returns>
 public NetGraph Create(string name, Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, PropertyBag connectionProperties)
 {
     lock (_lockObject)
     {
         return(CreateGraph(name, logger, parent, globalMeta, meta, _nodes, _lines, _props, connectionProperties, new Dictionary <string, object>()));
     }
 }
Exemple #7
0
        private void AddGraphToComboBox(NetGraph graph)
        {
            foreach (KeyValuePair <Guid, BasePipelineNode> pair in graph.Nodes)
            {
                if (!pair.Value.Hidden)
                {
                    if (pair.Value is NetGraphContainerNode)
                    {
                        AddGraphToComboBox(((NetGraphContainerNode)pair.Value).ContainedGraph);
                    }
                    else if (pair.Value is LayerSectionNode)
                    {
                        LayerSectionNode node = pair.Value as LayerSectionNode;

                        if (node.IsMaster)
                        {
                            foreach (NetGraph subGraph in node.Graphs)
                            {
                                AddGraphToComboBox(subGraph);
                            }
                        }
                    }
                    else
                    {
                        comboBoxNodes.Items.Add(pair.Value);
                    }
                }
            }
        }
        /// <summary>
        /// Create a new pipeline node based on this factory
        /// </summary>
        /// <param name="graph">The netgraph associated with this node</param>
        /// <param name="logger">The logger associated with the graph</param>
        /// <param name="stateDictionary">A dictionary which can be used to store construction state</param>
        /// <returns>The new node</returns>
        public BasePipelineNode Create(Logger logger, NetGraph graph, Dictionary <string, object> stateDictionary)
        {
            BasePipelineNode node = null;

            try
            {
                node = OnCreate(logger, graph, stateDictionary);
                if (node != null)
                {
                    foreach (var pair in Properties)
                    {
                        node.Properties[pair.Key] = pair.Value;
                    }

                    node.Enabled   = Enabled;
                    node.Hidden    = Hidden;
                    node.LogInput  = LogInput;
                    node.LogOutput = LogOutput;
                }
            }
            catch (Exception e)
            {
                throw new NodeFactoryException(String.Format(CANAPE.Properties.Resources.BaseNodeFactory_Create, this.Label, e.Message), e);
            }

            return(node);
        }
Exemple #9
0
        private void CloseConnection(ConnectionEntry entry)
        {
            NetGraph graph = entry.Graph;

            lock (entry)
            {
                if (!graph.IsDisposed)
                {
                    ConnectionHistoryEntry history = new ConnectionHistoryEntry(graph.NetworkDescription, graph.Uuid, graph.Created, DateTime.Now);
                    bool noConnections             = false;

                    foreach (KeyValuePair <string, object> pair in graph.ConnectionProperties)
                    {
                        if (pair.Value.GetType().IsSerializable)
                        {
                            history.Properties[pair.Key] = pair.Value;
                        }
                    }

                    try
                    {
                        entry.Dispose();
                    }
                    catch
                    {
                        // Shouldn't throw but just in case
                    }

                    lock (_history)
                    {
                        _history.Add(history);
                    }

                    lock (_connections)
                    {
                        _connections.Remove(entry);
                        if (_connections.Count == 0)
                        {
                            noConnections = true;
                        }
                    }

                    if (CloseConnectionEvent != null)
                    {
                        CloseConnectionEvent(this, new ConnectionEventArgs(graph));
                    }

                    if (_logger != null)
                    {
                        _logger.LogVerbose(CANAPE.Net.Properties.Resources.NetworkServiceBase_ConnectionClosed, graph.NetworkDescription);
                    }

                    if ((_state == (int)ServiceState.StopPending) && noConnections)
                    {
                        CompleteStop();
                    }
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Called to create an instance
        /// </summary>
        /// <returns>The new instance</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary <string, object> stateDictionary)
        {
            DelayPipelineNode node = new DelayPipelineNode();

            node.PacketDelayMs = PacketDelayMs;

            return(node);
        }
Exemple #11
0
        /// <summary>
        /// Method called when a new client connects
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClientConnected(object sender, ClientConnectedEventArgs e)
        {
            NetGraph graph = ConnectClient(e.DataAdapter, e.Properties);

            if (graph == null)
            {
                e.DataAdapter.Dispose();
            }
        }
Exemple #12
0
        /// <summary>
        /// Close a connection
        /// </summary>
        /// <param name="graph">The graph to close</param>
        public void CloseConnection(NetGraph graph)
        {
            ConnectionEntry entry = GetConnection(graph);

            if (entry != null)
            {
                CloseConnection(entry);
            }
        }
Exemple #13
0
        /// <summary>
        /// Method called when being created
        /// </summary>
        /// <returns>The new node</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary <string, object> stateDictionary)
        {
            LogPacketPipelineNode node = new LogPacketPipelineNode();

            node.Tag            = Tag;
            node.Color          = Color;
            node.ConvertToBytes = ConvertToBytes;

            return(node);
        }
        /// <summary>
        /// Create the node if it doesn't exist
        /// </summary>
        /// <param name="logger">The logger to use when creating</param>
        /// <param name="graph">The associated netgraph</param>
        /// <param name="stateDictionary">The state dictionary</param>
        /// <returns>The created node</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary <string, object> stateDictionary)
        {
            // If this is not the linked node use the master to create it and store master
            if (!stateDictionary.ContainsKey(Id.ToString()))
            {
                stateDictionary[MasterFactory.Id.ToString()] = MasterFactory.Create(logger, graph, stateDictionary);
            }

            return((BasePipelineNode)stateDictionary[Id.ToString()]);
        }
Exemple #15
0
 void AddConnection(NetGraph netGraph)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new Action <NetGraph>(AddConnection), netGraph);
     }
     else
     {
         AddGraph(netGraph);
     }
 }
Exemple #16
0
 private string GetDescriptionString(NetGraph graph)
 {
     if (graph.Meta.ContainsKey("src") && graph.Meta.ContainsKey("dest"))
     {
         return(String.Format("{0} -> {1}", graph.Meta["src"].ToString(), graph.Meta["dest"].ToString()));
     }
     else
     {
         return("Unknown");
     }
 }
Exemple #17
0
        void AddGraph(NetGraph graph)
        {
            ListViewItem item = listViewConns.Items.Add(_connId.ToString());

            _connId++;
            TimeSpan currentSpan = new TimeSpan(DateTime.UtcNow.Ticks);

            item.SubItems.Add(graph.NetworkDescription);
            item.SubItems.Add(String.Format("{0}s", (long)currentSpan.Subtract(graph.CreatedTicks).TotalSeconds));
            item.Tag = graph;
        }
Exemple #18
0
        private static NetGraph CreateGraph(string name, Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta,
                                            IEnumerable <GraphNodeEntry> nodes, IEnumerable <GraphLineEntry> lines, Dictionary <string, string> props, PropertyBag connectionProperties,
                                            Dictionary <string, object> stateDictionary)
        {
            NetGraph       netGraph        = new NetGraph(logger, parent, globalMeta, meta, connectionProperties);
            HashSet <Guid> referencedNodes = new HashSet <Guid>();

            netGraph.Name = name != null ? name : String.Empty;

            foreach (GraphNodeEntry n in nodes)
            {
                BasePipelineNode pipeNode = n.Factory.Create(logger, netGraph, stateDictionary);
                if (pipeNode == null)
                {
                    throw new InvalidOperationException("One of the nodes failed to create");
                }

                pipeNode.Graph = netGraph;
                pipeNode.Name  = n.Factory.Label;
                pipeNode.Uuid  = n.Id;
                netGraph.AddNode(n.Factory.Id, pipeNode);
            }

            foreach (GraphLineEntry l in lines)
            {
                netGraph.Nodes[l.SourceNode].AddOutput(netGraph.Nodes[l.DestNode], l.PathName, l.WeakPath);
                referencedNodes.Add(l.DestNode);

                if (l.BiDirection)
                {
                    netGraph.Nodes[l.DestNode].AddOutput(netGraph.Nodes[l.SourceNode], l.PathName, l.WeakPath);
                }
            }

            foreach (KeyValuePair <string, string> pair in props)
            {
                netGraph.Meta[pair.Key] = pair.Value;
            }

            foreach (Guid uuid in referencedNodes)
            {
                BasePipelineNode node = netGraph.Nodes[uuid];

                node.SetupShutdownOutputs();

                //foreach (BasePipelineNode output in node.Outputs)
                //{
                //    output.AddShutdownInput(node);
                //}
            }

            return(netGraph);
        }
Exemple #19
0
        /// <summary>
        /// Set a timeout on a connection
        /// </summary>
        /// <param name="graph">The graph to set the timeout on</param>
        /// <param name="timeout">The timeout value in milliseconds</param>
        /// <param name="afterdata">True to timeout after last data received, otherwise absolute</param>
        public void SetTimeout(NetGraph graph, int timeout, bool afterdata)
        {
            ConnectionEntry entry = GetConnection(graph);

            if (entry != null)
            {
                lock (entry)
                {
                    entry.SetTimeout(timeout, afterdata);
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Helper method to get the layer binding from the graph
        /// </summary>
        /// <param name="graph">The graph</param>
        /// <returns>The network layer binding, if no service returns default</returns>
        public static NetworkLayerBinding GetLayerBinding(NetGraph graph)
        {
            ProxyNetworkService service = graph.ServiceProvider.GetService <ProxyNetworkService>();

            if (service != null)
            {
                return(service.DefaultBinding);
            }
            else
            {
                return(NetworkLayerBinding.Default);
            }
        }
Exemple #21
0
        /// <summary>
        /// Create the netgraph for a connection
        /// </summary>
        /// <param name="factory">The netgraph factory</param>
        /// <param name="meta">Current meta data</param>
        /// <param name="properties">Property bag</param>
        /// <returns>The created graph</returns>
        private NetGraph CreateNetGraph(NetGraphFactory factory, MetaDictionary meta, PropertyBag properties)
        {
            NetGraph g = factory == null?_factory.Create(_logger, null, _globalMeta, meta, properties) : factory.Create(_logger, null, _globalMeta, meta, properties);

            if (g != null)
            {
                g.LogPacketEvent  += new EventHandler <LogPacketEventArgs>(log_AddLogPacket);
                g.EditPacketEvent += new EventHandler <EditPacketEventArgs>(edit_InputReceived);
                g.GraphShutdown   += new EventHandler(graph_GraphShutdown);
            }

            return(g);
        }
Exemple #22
0
 private void RemoveFileLog(NetGraph g)
 {
     if (g != null)
     {
         lock (_fileLogs)
         {
             if (_fileLogs.ContainsKey(g.Uuid))
             {
                 _fileLogs[g.Uuid].Logger.Dispose();
                 _fileLogs.Remove(g.Uuid);
             }
         }
     }
 }
Exemple #23
0
        /// <summary>
        /// Create the netgraph for a connection
        /// </summary>
        /// <param name="factory">The netgraph factory</param>
        /// <param name="meta">Current meta data</param>
        /// <param name="properties">Property bag</param>
        /// <returns>The created graph</returns>
        private NetGraph CreateNetGraph(NetGraphFactory factory, MetaDictionary meta, PropertyBag properties)
        {
            NetGraph g = factory == null?_factory.Create(_logger, null, _globalMeta, meta, properties) : factory.Create(_logger, null, _globalMeta, meta, properties);

            if (g != null)
            {
                g.LogPacketEvent  += new EventHandler <LogPacketEventArgs>(log_AddLogPacket);
                g.EditPacketEvent += new EventHandler <EditPacketEventArgs>(edit_InputReceived);
                g.GraphShutdown   += new EventHandler(graph_GraphShutdown);

                // Add service to provider
                g.ServiceProvider.RegisterService(typeof(ProxyNetworkService), this);
                g.ServiceProvider.RegisterService(typeof(CredentialsManagerService), _credentialManager);
            }

            return(g);
        }
Exemple #24
0
 void RemoveConnection(NetGraph graph)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new Action <NetGraph>(RemoveConnection), graph);
     }
     else
     {
         foreach (ListViewItem item in listViewConns.Items)
         {
             if (item.Tag == graph)
             {
                 listViewConns.Items.Remove(item);
                 break;
             }
         }
     }
 }
Exemple #25
0
        private void SetupGraph(NetGraph graph)
        {
            listViewNetGraph.SuspendLayout();
            timerUpdateGraph.Enabled = false;

            listViewNetGraph.Items.Clear();

            List <ListViewItem> items = new List <ListViewItem>();

            AddGraphToList(items, graph);

            listViewNetGraph.Items.AddRange(items.ToArray());
            timerUpdateGraph.Enabled = true;
            listViewNetGraph.ResumeLayout();

            metaEditorControl.Meta = graph.Meta;
            propertyBagViewerControl.UpdateProperties(graph.ConnectionProperties);
        }
Exemple #26
0
        /// <summary>
        /// Create the test graph container
        /// </summary>
        /// <param name="logger">The logger to use</param>
        /// <param name="globals">Global meta</param>
        /// <returns>The new test graph container</returns>
        public override TestDocument.TestGraphContainer CreateTestGraph(Utils.Logger logger, MetaDictionary globals)
        {
            NetGraphFactory factory = _document.Factory;

            ClientEndpointFactory[] clients = factory.GetNodes <ClientEndpointFactory>();
            ServerEndpointFactory[] servers = factory.GetNodes <ServerEndpointFactory>();

            if ((clients.Length == 0) || (servers.Length == 0))
            {
                throw new ArgumentException("Graph must have a one client and one server endpoint to perform a test");
            }

            Guid inputNode  = _clientToServer ? clients[0].Id : servers[0].Id;
            Guid outputNode = _clientToServer ? servers[0].Id : clients[0].Id;

            NetGraph graph = factory.Create(logger, null, globals, new MetaDictionary(), new PropertyBag("Connection"));

            return(new TestDocument.TestGraphContainer(graph, graph.Nodes[inputNode], graph.Nodes[outputNode]));
        }
Exemple #27
0
        private void CancelInject()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(CancelInject));
            }
            else
            {
                timerCancel.Stop();

                if (_injectGraph != null)
                {
                    ((IDisposable)_injectGraph).Dispose();
                    _injectGraph = null;
                }

                btnInject.Text = CANAPE.Properties.Resources.InjectPacketControl_InjectButtonText;
            }
        }
Exemple #28
0
        private void DrawDebugInfo()
        {
            if (_debugFont == null)
            {
                _debugFont = Content.Load <SpriteFont>("Fonts/ConsoleFont");
            }

            if (_client != null)
            {
                var client  = _client;
                var session = client.Controller.Session;

                if (GraphsVisible)
                {
                    // Draw session info and netgraph.
                    var ngOffset = new Vector2(
                        GraphicsDevice.Viewport.Width - 240, GraphicsDevice.Viewport.Height - 180);
                    var sessionOffset = new Vector2(
                        GraphicsDevice.Viewport.Width - 370,
                        GraphicsDevice.Viewport.Height - 180);

                    SessionInfo.Draw("Client", session, sessionOffset, _debugFont, _spriteBatch);
                    NetGraph.Draw(session.Information, ngOffset, _debugFont, _spriteBatch);
                }
            }

            if (_server != null)
            {
                var server  = _server;
                var session = server.Controller.Session;

                if (GraphsVisible)
                {
                    // Draw session info and netgraph.
                    var ngOffset      = new Vector2(180, GraphicsDevice.Viewport.Height - 180);
                    var sessionOffset = new Vector2(60, GraphicsDevice.Viewport.Height - 180);

                    SessionInfo.Draw("Server", session, sessionOffset, _debugFont, _spriteBatch);
                    NetGraph.Draw(session.Information, ngOffset, _debugFont, _spriteBatch);
                }
            }
        }
Exemple #29
0
            public ConnectionEntry(ProxyNetworkService service, NetGraph graph, int timeout, bool afterData)
            {
                _service = service;
                Graph    = graph;

                if (timeout > 0)
                {
                    SetTimeout(timeout, afterData);
                }

                foreach (KeyValuePair <Guid, BasePipelineNode> node in graph.Nodes)
                {
                    IPipelineEndpoint ep = node.Value as IPipelineEndpoint;

                    if (ep != null)
                    {
                        ep.DataRecieved += ep_DataRecieved;
                    }
                }
            }
Exemple #30
0
        private static NetGraph BuildGraph(ScriptContainer container, string classname, string selectionPath, out BasePipelineNode input, out ParseWithPipelineNode output)
        {
            DynamicNodeFactory           factory          = new DynamicNodeFactory("", Guid.NewGuid(), container, classname, null);
            ParseWithPipelineNodeFactory parseWithFactory = new ParseWithPipelineNodeFactory();

            factory.SelectionPath = selectionPath;

            NetGraphBuilder builder = new NetGraphBuilder();

            builder.AddNode(factory);
            builder.AddNode(parseWithFactory);
            builder.AddLine(factory, parseWithFactory, null);

            NetGraph graph = builder.Factory.Create(Logger.GetSystemLogger(), null, new MetaDictionary(), new MetaDictionary(), new PropertyBag("Connection"));

            input  = graph.Nodes[factory.Id];
            output = (ParseWithPipelineNode)graph.Nodes[parseWithFactory.Id];

            return(graph);
        }
 /// <summary>
 /// creates graph by creating only one node
 /// </summary>
 /// <param name="parameter">not required for implementation</param>
 private void _CreateNewGraph(object parameter)
 {
     Graph = new NetGraph(true);
     // _existingVertices.GetOrAdd(new NetVertex(1));
     _VList.Add(1);
     Graph.AddVertex(new NetVertex(1));
     NotifyPropertyChanged("Graph");
     _IDCount = 1;
 }
        private void _OpenDefaultGraph()
        {
            string[] lines = null;
            // Create an open file dialog box and only show *.grf files.
            try
            {
                OpenFileDialog openDlg = new OpenFileDialog();
                openDlg.Filter = "Graph File |*.grf";
                //read all lines of file
                if (true == openDlg.ShowDialog())
                {
                    lines = File.ReadAllLines(openDlg.FileName);

                    _openedFileName = openDlg.FileName;

                    Graph = new NetGraph(true);

                    //following block of code try to read the file and create graph
                    // to fully understant this code please read the graph file in notepad

                    string[] IDs = lines[0].Split(',');

                    foreach (string id in IDs)
                    {
                        int currID = int.Parse(id);
                        _VList.Add(currID);
                        Graph.AddVertex(new NetVertex(currID));

                    }
                    _IDCount = _VList.Count;

                    string[] edges = lines[1].Split(',');
                    string[] temp;
                    int idTo, idFrom;
                    int from = 0, to = 0;
                    int count = Graph.VertexCount;
                    foreach (string part in edges)
                    {
                        temp = part.Split('-');
                        idFrom = int.Parse(temp[0]);
                        idTo = int.Parse(temp[1]);

                        for (int i = 0; i < count; i++)
                        {
                            if (Graph.Vertices.ElementAt(i).ID == idFrom) from = i;
                            if (Graph.Vertices.ElementAt(i).ID == idTo) to = i;
                        }

                        //   _AddNewGraphEdge(_existingVertices[--idTo], _existingVertices[--idFrom]);
                        _AddNewGraphEdge(Graph.Vertices.ElementAt(from), Graph.Vertices.ElementAt(to));
                    }
                    string[] commodities = lines[2].Split(',');
                    if (commodities.Length > 0) CommodityList.RemoveAt(0);
                    foreach (string part in commodities)
                    {
                        temp = part.Split('-');
                        from = int.Parse(temp[0]);
                        to = int.Parse(temp[1]);
                        if (from != to)
                        {
                            CommoditiesEntryViewModel cvm = new CommoditiesEntryViewModel();
                            cvm.OriginID = from;
                            cvm.DestinationID = to;
                            cvm.DemandVal = int.Parse(temp[2]);
                            cvm.CombList = _VList;
                            cvm.ParentList = CommodityList;
                            CommodityList.Add(cvm);
                        }
                    }
                    NotifyPropertyChanged("Graph");
                }
            }
            catch (IOException e)
            {
                ExceptionMessage.Show("Could Not Open File\n" + e.ToString());
                Graph = null;
            }
            catch (Exception ex)
            {
                ExceptionMessage.Show("Something wrong with the Data in the File\n" + ex.ToString());
                Graph = null;
            }
        }
        /// <summary>
        /// This method takes graph file data for networkx graph and 
        /// creates vertexes, edges. It also creates random commodities with
        /// valid paths. 
        /// </summary>
        /// <param name="lines">graph file text</param>
        private void _DrawGraphWithCommodities(string [] lines)
        {
            int CommodityNum = this._NumberOfCommoditiesVal;
            int MinComm = this._MinimumDemandVal;
            int MaxComm = this._MaximumDemandVal + 1;
            int nodeID = 0;
            bool CommoditySet = false;
            List<int> Origins = new List<int>();
            List<int> Destinations = new List<int>();
            List<float> Demands = new List<float>();
            int OriginID = 0, DestID = 0;
            float demand = 0;
            SortedSet<int> nodeList = new SortedSet<int>();
             //   HashSet<int> nodeList = new HashSet<int>();
            HashSet<int> edgeOutNodes = new HashSet<int>();
            Random random = new Random();
            Dictionary<int, LinkedList<int>> EdgeMap = new Dictionary<int, LinkedList<int>>();

            Graph = new NetGraph(true);
            try
            {
                foreach (string line in lines) //create and add vertex to the graph
                {
                    string[] IDs = line.Split(' ');

                    if (int.TryParse(IDs[0], out nodeID))
                    {
                        foreach (string id in IDs)
                        {
                            int currID = int.Parse(id);
                            if (nodeList.Add(currID))
                            {
                               // _VList.Add(currID);
                                Graph.AddVertex(new NetVertex(currID));
                            }
                        }
                    }
                }
                for (int i = 0; i < nodeList.Count; i++)
                {
                    _VList.Add(nodeList.ElementAt(i));
                }
                this._IDCount = this._VList.Count();
                int from = 0, to = 0, curID = 0;
                int count = Graph.VertexCount;
                bool valid = true;
                //create edges, and keep record of vertex with edges going out for each valid vertex
                foreach (string line in lines)
                {
                    string[] IDs = line.Split(' ');

                    if (int.TryParse(IDs[0], out nodeID))
                    {
                        EdgeMap.Add(nodeID, new LinkedList<int>());
                        for (int j = 1; j < IDs.Length; j++)
                        {
                            curID = int.Parse(IDs[j]);
                            valid = true;
                            if(EdgeMap.ContainsKey(curID))
                            {
                                foreach (int id in EdgeMap[curID])
                                {
                                    if (id == nodeID) valid = false;
                                }
                            }
                            if (valid)
                            {
                                edgeOutNodes.Add(nodeID);
                                EdgeMap[nodeID].AddLast(curID);
                                for (int i = 0; i < count; i++)
                                {
                                    if (Graph.Vertices.ElementAt(i).ID == nodeID) from = i;
                                    if (Graph.Vertices.ElementAt(i).ID == curID) to = i;
                                }
                                this._AddNewGraphEdge(Graph.Vertices.ElementAt(from), Graph.Vertices.ElementAt(to));
                            }
                        }
                    }
                }

                //commodity is choosed at random, if that commodity does not already exist
                //check if it has valid path. if it exists then just add demand to it.

                for (int i = 0; i < _NumberOfCommoditiesVal; i++)
                {
                    CommoditySet = false;
                    while (!CommoditySet)
                    {
                        OriginID = random.Next(0, edgeOutNodes.Count);
                        OriginID = edgeOutNodes.ElementAt(OriginID);
                        DestID = random.Next(0, nodeList.Count);
                        DestID = nodeList.ElementAt(DestID);
                        demand = random.Next(MinComm, MaxComm);

                        for (int j = 0; j < Origins.Count; j++)
                        {
                            if (Origins[j] == OriginID && Destinations[j] == DestID)
                            {
                                CommoditySet = true;
                                Demands[j] += demand;
                                break;
                            }
                        }

                        if (CommoditySet) break;
                        this._path = null;
                        if (this._HasPath(OriginID, DestID, nodeList.Count, EdgeMap))
                        {
                           // this._GetSimulationEdges(OriginID, DestID);
                            Origins.Add(OriginID);
                            Destinations.Add(DestID);
                            Demands.Add(demand);
                            CommoditySet = true;
                        }
                    }
                }

                if (Origins.Count > 0) CommodityList.Remove(CommodityList.ElementAt(0));
                for (int i = 0; i < Origins.Count; i++)
                {
                    CommoditiesEntryViewModel cvm = new CommoditiesEntryViewModel();
                    cvm.OriginID = Origins[i];
                    cvm.DestinationID = Destinations[i];
                    cvm.DemandVal = Demands[i];
                    cvm.CombList = _VList;
                    cvm.ParentList = CommodityList;
                    CommodityList.Add(cvm);

                }

                NotifyPropertyChanged("Graph");
            }
            catch (Exception ex)
            {
                ExceptionMessage.Show("Something wrong with the Data in the File\n" + ex.ToString());
                Graph = null;
            }
        }