public void SimulationPropertySetterTest()
        {
            var simulation = MockRepository.GenerateStub<MySimulation>();
            var handler = new MySimulationHandler(simulation);

            // This should not throw, it's the first simulation.

            Assert.Throws<InvalidOperationException>(() => handler.Simulation = simulation);
        }
Example #2
0
        public override void Reallocate()
        {
            // This will allocate memory on the device. The CUDA context needs to be set up.
            MyKernelFactory.Instance.SetCurrent(0);

            // TODO(HonzaS): cache the ordered nodes if they have been ordered in model changes.
            foreach (MyNode node in MySimulationHandler.OrderNetworkNodes(m_project.Network))
            {
                node.ReallocateMemoryBlocks();
            }
        }
Example #3
0
        public MyProjectRunner(MyLogLevel level = MyLogLevel.DEBUG)
        {
            // why not to directly ask for TypeMap.GetInstance<MySimulation> ?
            // because in Typemap configuration, MySimulation is set to be singleton - this causes problems when MyProjectRunner
            // is instantiated multiple times - second and following instances obtain an instance of MySimulation from the first
            // MyProjectRunner instance. If the first MyProjectRunner instance was Shutdown-ed, the MySimulation instance is also
            // cleared and any following Shutdown on other MyProjectRunner instances will cause freeze/inifnite hang.
            // This code creates new MySimulation instance for each MyProjectRunner instance.
            // Other solution could be to not have a MySimulation as a singleton in TypeMap configuration - and it could work just OK,
            // because in BrainSim, the TypeMap's GetInstance on MySimulation is only on one place in MainForm. However, this may change
            // in future or the change itself may have other consequences, so for now I pick this solution, as it is safer.
            MySimulation simulation = new MyLocalSimulation(TypeMap.GetInstance <MyValidator>(), TypeMap.GetInstance <IMyExecutionPlanner>());

            SimulationHandler = new MySimulationHandler(simulation);
            m_resultIdCounter = 0;

            SimulationHandler.ProgressChanged += SimulationHandler_ProgressChanged;
            SimulationHandler.StepPerformed   += SimulationHandler_StepPerformed;

            m_monitors = new List <Tuple <int, uint, MonitorFunc> >();
            m_results  = new Hashtable();

            Project = new MyProject();

            var path = MyResources.GetEntryAssemblyPath();

            if (MyConfiguration.ModulesSearchPath.Count == 0)
            {
                MyConfiguration.SetupModuleSearchPath();
            }
            MyConfiguration.ProcessCommandParams();

            try
            {
                if (MyConfiguration.Modules.Count == 0)
                {
                    MyConfiguration.LoadModules();
                }
            }
            catch (Exception e)
            {
                MyLog.WARNING.WriteLine(e.Message);
                throw;
            }

            MyLog.Level = level;
        }
        public void SimulationStateChangedOnNodesTest()
        {
            var simulation = new MyLocalSimulation();
            var handler = new MySimulationHandler(simulation);

            MyProject project = new MyProject
            {
                Network = new MyNetwork()
            };
            project.CreateWorld(typeof(MyTestingWorld));

            var node = project.CreateNode<TestingNode>();
            node.Event = new AutoResetEvent(false);
            project.Network.AddChild(node);
            var connection = new MyConnection(project.Network.GroupInputNodes[0], project.Network.Children[0]);
            connection.Connect();

            project.Network.PrepareConnections();

            handler.Project = project;
            handler.UpdateMemoryModel();

            handler.StartSimulation(oneStepOnly: false);
            node.Event.WaitOne();
            Assert.Equal(MySimulationHandler.SimulationState.STOPPED, node.PreviousState);
            Assert.Equal(MySimulationHandler.SimulationState.RUNNING, node.CurrentState);

            handler.PauseSimulation();
            node.Event.WaitOne();
            Assert.Equal(MySimulationHandler.SimulationState.RUNNING, node.PreviousState);
            Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.CurrentState);

            handler.StartSimulation(oneStepOnly: true);
            node.Event.WaitOne();   // Here the sim goes from paused to RUNNING_STEP.
            Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.PreviousState);
            Assert.Equal(MySimulationHandler.SimulationState.RUNNING_STEP, node.CurrentState);
            node.Event.WaitOne();   // Here it goes to PAUSED.
            Assert.Equal(MySimulationHandler.SimulationState.RUNNING_STEP, node.PreviousState);
            Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.CurrentState);

            handler.StopSimulation();
            node.Event.WaitOne();
            Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.PreviousState);
            Assert.Equal(MySimulationHandler.SimulationState.STOPPED, node.CurrentState);

            handler.Finish();
        }
Example #5
0
        private void SetupAfterModelChange(IModelChanges modelChanges, List <MyNode> changersActivated)
        {
            // Clean up memory.
            IterateNodes(modelChanges.RemovedNodes, DestroyNode);

            // This must happen before UpdateMemoryModel() because some nodes touch kernels in UpdateMemoryBlocks().
            MyKernelFactory.Instance.SetCurrent(0);

            // Refresh topological ordering.
            List <MyNode> orderedNodes = MySimulationHandler.OrderNetworkNodes(m_project.Network);

            // Update the whole memory model.
            // TODO(HonzaS): This may break things, check.
            // We'll need to forbid changing of count after the simulation has started with the exception of added nodes.
            // However, the added nodes may lead to reallocation of blocks - deal with it.
            bool updatesNotConverged = UpdateMemoryModel(m_project, orderedNodes);

            Validator.ClearValidation();

            // Validate new nodes.
            IterateNodes(modelChanges.AddedNodes, ValidateNode);

            Validator.AssertError(!updatesNotConverged, m_project.Network, "Possible infinite loop in memory block sizes.");

            if (!Validator.ValidationSucessfull)
            {
                throw new InvalidOperationException("Validation failed for the changed model.");
            }

            // Reschedule.
            Schedule(m_project, modelChanges.AddedNodes);

            // Init nodes
            IterateNodes(modelChanges.AddedNodes, InitNode);

            // Allocate memory
            IEnumerable <MyWorkingNode> nodesToAllocate =
                modelChanges.AddedNodes.Where(node => MyMemoryManager.Instance.IsRegistered(node));

            IterateNodes(nodesToAllocate, AllocateNode);

            foreach (MyNode node in changersActivated)
            {
                EmitModelChanged(node);
            }
        }
Example #6
0
        private void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            if (!Visible && !(m_mainForm.Project.World is SchoolWorld))
                return;
            // time measurements
            if (m_currentLtStopwatch != null)
                if (e.NewState == MySimulationHandler.SimulationState.PAUSED)
                    m_currentLtStopwatch.Stop();
                else if (e.NewState == MySimulationHandler.SimulationState.RUNNING ||
                    e.NewState == MySimulationHandler.SimulationState.RUNNING_STEP)
                    m_currentLtStopwatch.Start();

            // workspace panel enable/disable
            if (e.NewState == MySimulationHandler.SimulationState.RUNNING ||
                    e.NewState == MySimulationHandler.SimulationState.RUNNING_STEP ||
                    e.NewState == MySimulationHandler.SimulationState.PAUSED)
            {
                disableLearningTaskPanel();
            }
            else
            {
                enableLearningTaskPanel();
            }

            // autosave
            if (e.NewState == MySimulationHandler.SimulationState.PAUSED ||
                e.NewState == MySimulationHandler.SimulationState.STOPPED)
                if (Properties.School.Default.AutosaveEnabled)
                {
                    if (String.IsNullOrEmpty(m_autosaveFilePath))
                    {
                        string filename = GetAutosaveFilename();
                        m_autosaveFilePath = Path.Combine(Properties.School.Default.AutosaveFolder, filename);
                    }
                    ExportDataGridViewData(m_autosaveFilePath);
                }

            if (e.NewState == MySimulationHandler.SimulationState.STOPPED)
                m_autosaveFilePath = null;

            // buttons
            UpdateButtons();
        }
        public MyProjectRunner(MyLogLevel level = MyLogLevel.DEBUG)
        {
            MySimulation simulation = TypeMap.GetInstance <MySimulation>();

            SimulationHandler = new MySimulationHandler(simulation);
            m_resultIdCounter = 0;

            SimulationHandler.ProgressChanged += SimulationHandler_ProgressChanged;
            SimulationHandler.StepPerformed   += SimulationHandler_StepPerformed;

            m_monitors = new List <Tuple <int, uint, MonitorFunc> >();
            m_results  = new Hashtable();

            Project = new MyProject();

            var path = MyResources.GetEntryAssemblyPath();

            if (MyConfiguration.ModulesSearchPath.Count == 0)
            {
                MyConfiguration.SetupModuleSearchPath();
            }
            MyConfiguration.ProcessCommandParams();

            try
            {
                if (MyConfiguration.Modules.Count == 0)
                {
                    MyConfiguration.LoadModules();
                }
            }
            catch (Exception e)
            {
                MyLog.WARNING.WriteLine(e.Message);
                throw;
            }

            MyLog.Level = level;
        }
 private void StateChanged(object sender, MySimulationHandler.StateEventArgs e)
 {
     if (e.NewState == MySimulationHandler.SimulationState.STOPPED || e.NewState == MySimulationHandler.SimulationState.PAUSED)
         OpenFile();
     m_continueEvent.Set();
 }
 public override void OnSimulationStateChanged(MySimulationHandler.StateEventArgs args)
 {
     PreviousState = args.OldState;
     CurrentState = args.NewState;
     if (Event != null)
         Event.Set();
 }
Example #10
0
 public void OnStateChanged(object sender, MySimulationHandler.StateEventArgs args)
 {
     foreach (MyWorkingNode node in NodePartitioning.SelectMany(nodeList => nodeList))
         node.OnSimulationStateChanged(args);
 }
Example #11
0
        void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            Active = e.NewState != MySimulationHandler.SimulationState.STOPPED;

            if (!Active)
            {
                peekLabel.Visible = false;
            }

            CloseButton =
                e.NewState == MySimulationHandler.SimulationState.PAUSED ||
                e.NewState == MySimulationHandler.SimulationState.STOPPED;

            if (Observer != null)
            {
                Observer.Active = Active;
            }

            Observer.TriggerViewReset();
            glControl.Invalidate();

            updateViewToolStripMenuItem.Enabled =
            snapshotToolStripMenuItem.Enabled =
                e.NewState == MySimulationHandler.SimulationState.PAUSED;
        }
 private void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
 {
     if (e.OldState != MySimulationHandler.SimulationState.STOPPED) return;
     richTextBox_messages.Clear();
     FindGuiNodes();
 }
Example #13
0
 void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
 {
     toolStrip1.Enabled = e.NewState == MySimulationHandler.SimulationState.STOPPED;
     updateModelButton.Enabled = toolStrip1.Enabled;
 }
Example #14
0
        //TODO: this should be done by data binding but menu items cannot do that (add this support)
        void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            runToolButton.Enabled = SimulationHandler.CanStart;            
            startToolStripMenuItem.Enabled = SimulationHandler.CanStart;            

            pauseToolButton.Enabled = SimulationHandler.CanPause;
            pauseToolStripMenuItem.Enabled = SimulationHandler.CanPause;

            stopToolButton.Enabled = SimulationHandler.CanStop;
            stopToolStripMenuItem.Enabled = SimulationHandler.CanStop;


            debugToolButton.Enabled = SimulationHandler.CanStartDebugging;
            debugToolStripMenuItem.Enabled = SimulationHandler.CanStartDebugging;

            stepOverToolButton.Enabled = SimulationHandler.CanStepOver;
            stepOverToolStripMenuItem.Enabled = SimulationHandler.CanStepOver;

            stepIntoToolStripMenuItem.Enabled = SimulationHandler.CanStepInto;
            stepOutToolStripMenuItem.Enabled = SimulationHandler.CanStepOut;

            reloadButton.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            simStatusLabel.Text = SimulationHandler.State.GetAttributeProperty((DescriptionAttribute x) => x.Description);           

            //TODO: this is awful, binding is needed here for sure            
            newProjectToolButton.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;
            newProjectToolStripMenuItem.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            openProjectToolButton.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;
            openProjectToolStripMenuItem.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            saveProjectToolButton.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;
            saveProjectAsToolStripMenuItem.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;
            saveProjectToolStripMenuItem.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            copySelectionToolStripMenuItem.Enabled = pasteSelectionToolStripMenuItem.Enabled =
                SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            worldList.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            NodePropertyView.CanEdit = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;

            updateMemoryBlocksToolStripMenuItem.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED;
            
            MemoryBlocksView.Enabled = SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED ||
                 SimulationHandler.State == MySimulationHandler.SimulationState.PAUSED;

            if (SimulationHandler.State == MySimulationHandler.SimulationState.STOPPED)
            {                
                stepStatusLabel.Text = String.Empty;
                statusStrip.BackColor = STATUS_BAR_BLUE;

                exportStateButton.Enabled = MyMemoryBlockSerializer.TempDataExists(Project);
                clearDataButton.Enabled = exportStateButton.Enabled;
            }
            else if (SimulationHandler.State == MySimulationHandler.SimulationState.PAUSED)
            {
                statusStrip.BackColor = Color.Chocolate;
            }
            else
            {
                statusStrip.BackColor = STATUS_BAR_BLUE_BUILDING;
            }
            RefreshUndoRedoButtons();
        }    
Example #15
0
        public MainForm()
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();

            MySimulation simulation = null;
            try
            {
                simulation = TypeMap.GetInstance<MySimulation>();
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occured when initializing simulation. Please make sure you have a supported CUDA-enabled graphics card and apropriate drivers." +
                        "Technical details: " + e.Message, "Simulation Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // this way you do not have to tweak form Close and Closing events and it works even with any worker threads still running
                Environment.Exit(1);
            }

            SimulationHandler = new MySimulationHandler(simulation);
            SimulationHandler.StateChanged += SimulationHandler_StateChanged;
            SimulationHandler.ProgressChanged += SimulationHandler_ProgressChanged;
            SimulationHandler.SimulationStopped += SimulationHandler_SimulationStopped;

            // must be created in advance to grab possible error logs
            ConsoleView = new ConsoleForm(this);

            var assemblyName = Assembly.GetExecutingAssembly().GetName();
            MyLog.INFO.WriteLine(assemblyName.Name + " version " + assemblyName.Version);

            MyConfiguration.SetupModuleSearchPath();
            MyConfiguration.ProcessCommandParams();

            try
            {
                MyConfiguration.LoadModules();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Fatal error occured during initialization", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            UndoManager = new UndoManager(Settings.Default.UndoHistorySize);

            Documentation = new MyDocProvider();

            foreach (MyModuleConfig module in MyConfiguration.Modules)
            {
                Documentation.LoadXMLDoc(module.Assembly);
            }

            NodePropertyView = new NodePropertyForm(this);

            MemoryBlocksView = new MemoryBlocksForm(this);

            TaskView = new TaskForm(this);
            TaskPropertyView = new TaskPropertyForm(this);

            DashboardPropertyView = new DashboardPropertyForm(this);
            SimulationHandler.StateChanged += DashboardPropertyView.OnSimulationStateChanged;

            // Link the Task and Node property views to the dashboard's PropertyChanged.
            DashboardPropertyView.PropertyValueChanged += RefreshPropertyViews;

            // Link the Node and Task property views' PropertyChanged to the dashboard so that it can refresh etc.
            NodePropertyView.PropertyChanged += DashboardPropertyView.OnPropertyExternallyChanged;
            TaskPropertyView.PropertyChanged += DashboardPropertyView.OnPropertyExternallyChanged;
            TaskView.PropertyChanged += DashboardPropertyView.OnPropertyExternallyChanged;

            GraphViews = new Dictionary<MyNodeGroup, GraphLayoutForm>();
            TextEditors = new Dictionary<IScriptableNode, TextEditForm>();

            ObserverViews = new List<ObserverForm>();

            ValidationView = new ValidationForm(this, TypeMap.GetInstance<MyValidator>());
            HelpView = new NodeHelpForm(this) { StartPosition = FormStartPosition.CenterScreen };

            DebugView = new DebugForm(this);

            PopulateWorldList();
            CreateNewProject();
            CreateNetworkView();

            m_views = new List<DockContent>() { NetworkView, DashboardPropertyView, NodePropertyView, MemoryBlocksView, TaskView,
                TaskPropertyView, ConsoleView, ValidationView, DebugView, HelpView };

            foreach (var form in UIPlugins.GetBrainSimUIExtensions(this))
                m_views.Add(form);

            foreach (DockContent view in m_views)
            {
                ToolStripMenuItem viewMenuItem = new ToolStripMenuItem(view.Text);
                viewMenuItem.Click += viewToolStripMenuItem_Click;
                viewMenuItem.Tag = view;
                viewMenuItem.Name = view.Text;

                viewToolStripMenuItem.DropDownItems.Add(viewMenuItem);
            }

            ((ToolStripMenuItem)viewToolStripMenuItem.DropDownItems.Find(HelpView.Text, false).First()).ShortcutKeys = Keys.F1;
            viewToolStripMenuItem.DropDownItems.Add(new ToolStripSeparator());

            showHideObserversMenuItem = new ToolStripMenuItem("Show/Hide all observers");
            showHideObserversMenuItem.ShortcutKeys = Keys.Control | Keys.H;
            showHideObserversMenuItem.Click += showHideObserversMenuItem_Click;
            showHideObserversMenuItem.Checked = true;

            viewToolStripMenuItem.DropDownItems.Add(showHideObserversMenuItem);

            ToolStripMenuItem resetViewsMenuItem = new ToolStripMenuItem("Reset Views Layout");
            resetViewsMenuItem.ShortcutKeys = Keys.Control | Keys.W;
            resetViewsMenuItem.Click += resetViewsMenuItem_Click;

            viewToolStripMenuItem.DropDownItems.Add(resetViewsMenuItem);

            ToolStripMenuItem nodeSettingsMenuItem = new ToolStripMenuItem("Configure node selection...");
            nodeSettingsMenuItem.ShortcutKeys = Keys.Control | Keys.L;
            nodeSettingsMenuItem.Click += nodeSettingsMenuItem_Click;

            viewToolStripMenuItem.DropDownItems.Add(nodeSettingsMenuItem);

            modeDropDownList.SelectedIndex = 0;

            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 0);
            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 10);
            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 20);
            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 50);
            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 100);
            AddTimerMenuItem(timerToolStripSplitButton, timerItem_Click, 500);

            timerItem_Click(timerToolStripSplitButton.DropDownItems[Settings.Default.StepDelay], EventArgs.Empty);

            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 0);
            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 20);
            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 100);
            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 500);
            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 1000);
            AddTimerMenuItem(observerTimerToolButton, observerTimerItem_Click, 5000);

            observerTimerItem_Click(observerTimerToolButton.DropDownItems[Settings.Default.ObserverPeriod], EventArgs.Empty);

            PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(MyWorkingNode))["DataFolder"];
            EditorAttribute editor = (EditorAttribute)descriptor.Attributes[typeof(EditorAttribute)];

            editor.GetType().GetField("typeName", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(editor,
                typeof(MyFolderDialog).AssemblyQualifiedName);

            editor.GetType().GetField("baseTypeName", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(editor,
                typeof(UITypeEditor).AssemblyQualifiedName);

            autosaveTextBox.Text = Settings.Default.AutosaveInterval.ToString();
            autosaveTextBox_Validating(this, new CancelEventArgs());

            autosaveButton.Checked = Settings.Default.AutosaveEnabled;
        }
Example #16
0
        void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            MySimulationHandler simulatinHandler = sender as MySimulationHandler;

            runToolButton.Enabled = simulatinHandler.CanStart;
            stepInButton.Enabled = simulatinHandler.CanStepInto;
            stepOutButton.Enabled = simulatinHandler.CanStepOut;
            stepOverButton.Enabled = simulatinHandler.CanStepOver;
            pauseToolButton.Enabled = simulatinHandler.CanPause;

            if (e.NewState == MySimulationHandler.SimulationState.PAUSED && simulatinHandler.Simulation.InDebugMode)
            {
                noDebugLabel.Visible = false;
                toolStrip.Enabled = true;

                if (m_executionPlan == null)
                {
                    UpdateDebugListView();
                }

                MyExecutionBlock currentBlock = simulatinHandler.Simulation.CurrentDebuggedBlocks[0];
                m_selectedNodeView = null;

                if (currentBlock != null && currentBlock.CurrentChild != null)
                {
                    m_selectedNodeView = debugTreeView.AllNodes.FirstOrDefault(node => (node.Tag is MyDebugNode && (node.Tag as MyDebugNode).Executable == currentBlock.CurrentChild));

                };

                debugTreeView.Invalidate();
                //debugTreeView.Invoke((MethodInvoker)(() => debugTreeView.SelectedNode = m_selectedNodeView));
            }
            else if (e.NewState == MySimulationHandler.SimulationState.STOPPED)
            {
                m_executionPlan = null;
                debugTreeView.Model = null;
                noDebugLabel.Visible = true;
                toolStrip.Enabled = false;

                if (this.IsFloat)
                {
                    this.Hide();
                }
            }
        }
        public void FileCanBeReadWhenSimulationIsNotRunning()
        {
            string directory = Path.GetFullPath(@"Data\");
            const string fileName = "csv_file_test.brain";

            m_outputFileFullPath = Path.GetTempFileName();
            var outputFileName = Path.GetFileName(m_outputFileFullPath);
            var outputFileDirectory = Path.GetDirectoryName(m_outputFileFullPath);

            string projectPath = directory + fileName;

            var simulation = new MyLocalSimulation();

            // TODO(HonzaS): This should not be required!
            // The referenced assemblies get loaded only if a Type is required here. But since the serializer
            // is just looking for types by name, it doesn't force the runtime to load all of the assemblies.
            // In this case, we would miss the BasicNodes if the following line was deleted.
            // Two solutions: 1) Use the Managed Extensibility Framework or 2) load all referenced assemblies
            // explicitely (as a part of the BS testing framework).
            var csvNode = new MyCsvFileWriterNode();

            MyProject project = MyProject.Deserialize(File.ReadAllText(projectPath), Path.GetDirectoryName(projectPath));

            var handler = new MySimulationHandler(simulation)
            {
                Project = project
            };

            // The CSV node
            MyNode node = project.Network.GetChildNodeById(6);

            PropertyInfo fileNameProperty = node.GetType().GetProperty("OutputFile", BindingFlags.Instance | BindingFlags.Public);
            fileNameProperty.SetValue(node, outputFileName);

            PropertyInfo directoryProperty = node.GetType().GetProperty("OutputDirectory", BindingFlags.Instance | BindingFlags.Public);
            directoryProperty.SetValue(node, outputFileDirectory);

            handler.UpdateMemoryModel();

            handler.StateChanged += StateChanged;

            try
            {
                handler.StartSimulation();
                m_continueEvent.WaitOne();

                Assert.Throws<IOException>(() =>
                {
                    File.Open(m_outputFileFullPath, FileMode.Open, FileAccess.ReadWrite);
                });

                // Every time we change simulation state, the StateChanged method gets notified.
                // We're changing the state several times here and the StateChanged methods checks that
                // the file that the Csv node uses is available for writing.

                // First, go through start->pause->stop.
                handler.PauseSimulation();
                m_continueEvent.WaitOne();

                handler.StopSimulation();
                m_continueEvent.WaitOne();

                // Now, try start->stop only.
                handler.StartSimulation();
                m_continueEvent.WaitOne();

                handler.StopSimulation();
                m_continueEvent.WaitOne();

                // The file should have been successfully opened three times - every time the simulation was paused or stopped.
                Assert.Equal(3, m_openCount);
            }
            finally
            {
                handler.Finish();
                File.Delete(m_outputFileFullPath);
                m_outputFileFullPath = null;
            }
        }
Example #18
0
 private void SimulationHandler_SimulationStopped(object sender, MySimulationHandler.SimulationStoppedEventArgs args)
 {
     ValidationView.UpdateListView();
     foreach (GraphLayoutForm graphView in GraphViews.Values)
         graphView.ReloadContent();
 }
        public MyProjectRunner(MyLogLevel level = MyLogLevel.DEBUG)
        {
            MySimulation simulation = TypeMap.GetInstance<MySimulation>();
            SimulationHandler = new MySimulationHandler(simulation);
            m_resultIdCounter = 0;

            SimulationHandler.ProgressChanged += SimulationHandler_ProgressChanged;
            SimulationHandler.StepPerformed += SimulationHandler_StepPerformed;

            m_monitors = new List<Tuple<int, uint, MonitorFunc>>();
            m_results = new Hashtable();

            Project = new MyProject();

            var path = MyResources.GetEntryAssemblyPath();

            if (MyConfiguration.ModulesSearchPath.Count == 0)
                MyConfiguration.SetupModuleSearchPath();
            MyConfiguration.ProcessCommandParams();

            try
            {
                if (MyConfiguration.Modules.Count == 0)
                    MyConfiguration.LoadModules();
            }
            catch (Exception e)
            {
                MyLog.WARNING.WriteLine(e.Message);
                throw;
            }

            MyLog.Level = level;
        }
Example #20
0
 void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
 {
     //UpdateConsole();
 }
Example #21
0
        void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            scintilla.Enabled = e.NewState == MySimulationHandler.SimulationState.STOPPED;

            SetupEditorStyle();
        }
        void SimulationHandler_StateChanged(object sender, MySimulationHandler.StateEventArgs e)
        {
            nodesToolStrip.Enabled = e.NewState == MySimulationHandler.SimulationState.STOPPED;
            updateModelButton.Enabled = nodesToolStrip.Enabled;

            if (e.NewState == MySimulationHandler.SimulationState.STOPPED)
                ResetNodeColours();
        }
Example #23
0
 public void OnStateChanged(object sender, MySimulationHandler.StateEventArgs args)
 {
     foreach (MyWorkingNode node in AllNodes)
         node.OnSimulationStateChanged(args);
 }