/// <summary> /// Provides the value of an expression /// </summary> /// <param name="expression"></param> /// <returns></returns> public Value GetExpressionValue(string expression) { Value retVal = null; EfsAccess.WaitOne(); try { Expression expressionTree = new Parser().Expression(EfsSystem.Instance.Dictionaries[0], expression); if (expressionTree != null) { Util.DontNotify(() => { retVal = ConvertOut(expressionTree.GetExpressionValue(new InterpretationContext(), null)); }); } } catch (Exception) { // TODO } finally { EfsAccess.ReleaseMutex(); } return(retVal); }
/// <summary> /// Sets the value of a specific variable /// </summary> /// <param name="variableName"></param> /// <param name="value"></param> public void SetVariableValue(string variableName, Value value) { EfsAccess.WaitOne(); try { if (Runner != null) { IVariable variable = EfsSystem.Instance.FindByFullName(variableName) as IVariable; if (variable != null) { Util.DontNotify(() => { Runner.CacheImpact = new CacheImpact(); SyntheticVariableUpdateAction action = new SyntheticVariableUpdateAction(variable, value.ConvertBack(variable.Type)); VariableUpdate variableUpdate = new VariableUpdate(action, null, null); Runner.EventTimeLine.AddModelEvent(variableUpdate, true); Runner.ClearCaches(); }); } else { throw new FaultException <EFSServiceFault> ( new EFSServiceFault("Cannot find variable " + variableName), new FaultReason(new FaultReasonText("Cannot find variable " + variableName))); } } } finally { EfsAccess.ReleaseMutex(); } }
private static void Main(string[] args) { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); XmlConfigurator.Configure(new FileInfo("logconfig.xml")); Options.Options.SetSettings(); EfsSystem.Instance.DictionaryChangesOnFileSystem += HandleInstanceDictionaryChangesOnFileSystem; MainWindow window = new MainWindow(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; { // TRICKY SECTION // This thread is mandatory otherwise WCF does not create a new thread to handle the service requests. // Since the call to Cycle is blocking, creating such threads is mandatory Thread thread = ThreadUtil.CreateThread("EFS Service", HostEfsService); thread.Start(); } // Opens the Dictionary files and check them bool shouldPlace = true; foreach (string fileName in args) { const bool allowErrors = false; OpenFileOperation openFileOperation = new OpenFileOperation(fileName, EfsSystem.Instance, allowErrors, true); openFileOperation.ExecuteUsingProgressDialog(GuiUtils.MdiWindow, "Opening file " + fileName, false); if (openFileOperation.Dictionary != null) { window.SetupWindows(openFileOperation.Dictionary, shouldPlace); shouldPlace = false; } else { Console.Out.WriteLine("Cannot open dictionary file " + fileName); } } CheckModelOperation checkModel = new CheckModelOperation(); checkModel.ExecuteUsingProgressDialog(GuiUtils.MdiWindow, "Checking model"); Application.Run(window); CloseEfsService(); } finally { Util.UnlockAllFiles(); } EfsSystem.Instance.Stop(); SynchronizerList.Stop(); }
/// <summary> /// Step once /// </summary> public void StepOnce() { Util.DontNotify(() => { CheckRunner(); if (EfsSystem.Runner != null) { EfsSystem.Runner.StepOnce(); EfsSystem.Instance.Context.HandleEndOfCycle(); } }); }
/// <summary> /// Performs the job as a background task /// </summary> public override void ExecuteWork() { Dictionary = Util.Load(System, new Util.LoadParams(FileName) { LockFiles = PleaseLockFiles, Errors = ErrorsDuringLoad, UpdateGuid = UpdateGuid, ConvertObsolete = Settings.Default.ConvertObsoleteVersionOfModelFile }); if (Dictionary == null) { MessageBox.Show(@"An error was detected preventing dictionary " + FileName + @" from loading.", @"File load error"); } }
/// <summary> /// Update the information stored in the position handler according to the test case /// </summary> protected override void UpdatePositionHandler() { Util.DontNotify(() => { PositionHandler.CleanPositions(); if ((TestCase != null) || SubSequence != null) { double currentTime = 0.0; foreach (Step step in Steps) { if (step.SubSteps.Count > 0) { foreach (SubStep subStep in step.SubSteps) { PositionSubStep(currentTime, subStep); currentTime += 1; } } else { StepActivation stepActivated = new StepActivation(step) { Time = currentTime }; PositionHandler.RegisterEvent(stepActivated); currentTime += 1; } } } else if (Translation != null) { double currentTime = 0.0; if (Translation.SubSteps.Count > 0) { foreach (SubStep subStep in Translation.SubSteps) { PositionSubStep(currentTime, subStep); currentTime += 1; } } } }); base.UpdatePositionHandler(); }
/// <summary> /// Refreshes the model of the tree view /// </summary> /// <param name="modifiedElement">The element that has been modified</param> public void RefreshModel(IModelElement modifiedElement) { BaseTreeNode selected = Selected; Util.DontNotify(() => { try { SuspendLayout(); // Ensure the root nodes are correct List <BaseTreeNode> rootNodes = BuildModel(); if (rootNodes.Count != Nodes.Count) { Nodes.Clear(); foreach (BaseTreeNode node in rootNodes) { Nodes.Add(node); } } // Refresh the selected node foreach (BaseTreeNode node in Nodes) { if (modifiedElement == null || (node.Model != null && node.Model.IsParent(modifiedElement))) { node.BuildOrRefreshSubNodes(modifiedElement); } } if (selected != null) { Select(selected.Model); } } finally { ResumeLayout(true); } }); }
/// <summary> /// Applies a specific statement on the model /// </summary> /// <param name="statementText"></param> public void ApplyStatement(string statementText) { EfsAccess.WaitOne(); try { if (Runner != null) { const bool silent = true; using (Parser parser = new Parser()) { Statement statement = parser.Statement(EfsSystem.Instance.Dictionaries[0], statementText, silent); if (statement != null) { Util.DontNotify(() => { Runner.CacheImpact = new CacheImpact(); Action action = (Action)acceptor.getFactory().createAction(); action.ExpressionText = statementText; VariableUpdate variableUpdate = new VariableUpdate(action, null, null); Runner.EventTimeLine.AddModelEvent(variableUpdate, true); Runner.ClearCaches(); }); } } } } catch (Exception) { // TODO } finally { EfsAccess.ReleaseMutex(); } }
/// <summary> /// Perform all functional tests defined in the .EFS file provided /// </summary> /// <param name="args"></param> /// <returns>the error code of the program</returns> private static int Main(string[] args) { int retVal = 0; EfsSystem efsSystem = EfsSystem.Instance; try { Console.Out.WriteLine("EFS Tester"); // Load the dictionaries provided as parameters Util.PleaseLockFiles = false; foreach (string arg in args) { Console.Out.WriteLine("Loading dictionary " + arg); Dictionary dictionary = Util.Load(efsSystem, new Util.LoadParams(arg) { LockFiles = false, Errors = null, UpdateGuid = false, ConvertObsolete = false }); if (dictionary == null) { Console.Out.WriteLine("Cannot load dictionary " + arg); return(-1); } } // Translate the sub sequences, if required Console.Out.WriteLine("Translating sub sequences"); foreach (Dictionary dictionary in efsSystem.Dictionaries) { foreach (Frame frame in dictionary.Tests) { foreach (SubSequence subSequence in frame.SubSequences) { if (subSequence.getCompleted()) { if (dictionary.TranslationDictionary != null) { subSequence.Translate(); } } } } } // Make sure everything is recompiled Console.Out.WriteLine("Recompiling everything"); efsSystem.Compiler.Compile_Synchronous(true); // Ensure the model is consistent Console.Out.WriteLine("Checking model"); foreach (Dictionary dictionary in efsSystem.Dictionaries) { RuleCheckerVisitor checker = new RuleCheckerVisitor(dictionary); checker.visit(dictionary); } // Dumps all errors found Util.IsThereAnyError isThereAnyError = new Util.IsThereAnyError(); if (isThereAnyError.ErrorsFound.Count > 0) { foreach (ElementLog error in isThereAnyError.ErrorsFound) { Console.Out.WriteLine(error.Log); } return(-1); } { // Perform functional test for last loaded dictionary Dictionary dictionary = efsSystem.Dictionaries.FindLast(x => true); Console.Out.WriteLine("Processing tests from dictionary " + dictionary.Name); foreach (Frame frame in dictionary.Tests) { Console.Out.WriteLine("Executing frame " + frame.FullName); foreach (SubSequence subSequence in frame.SubSequences) { Console.Out.WriteLine("Executing sub sequence " + subSequence.FullName); if (subSequence.getCompleted()) { Runner runner = new Runner(subSequence, false, true); runner.RunUntilStep(null); bool failed = false; foreach (ModelEvent evt in runner.FailedExpectations()) { Expect expect = evt as Expect; if (expect != null) { string message = expect.Message.Replace('\n', ' '); Console.Out.WriteLine(" failed :" + message); failed = true; } else { ModelInterpretationFailure modelInterpretationFailure = evt as ModelInterpretationFailure; if (modelInterpretationFailure != null) { Console.Out.WriteLine(" failed : " + modelInterpretationFailure.Message); failed = true; } } } if (failed) { Console.Out.WriteLine(" -> Failed"); retVal = -1; } else { Console.Out.WriteLine(" -> Success"); } } else { Console.Out.WriteLine(" -> Not executed because it is not marked as completed"); } } } } } finally { Util.UnlockAllFiles(); efsSystem.Stop(); } return(retVal); }
/// <summary> /// Handles the move event, which, in case of an arrow is selected to be modified, /// </summary> /// <param name="sender"></param> /// <param name="mouseEventArgs"></param> private void HandleMouseMove(object sender, MouseEventArgs mouseEventArgs) { GraphicElement element = ElementForLocation(mouseEventArgs.Location, null); if (element != null) { element.HandleMouseMove(sender, mouseEventArgs); } if (_changingArrow != null && _chaningArrowAction != ChangeAction.None) { BoxControl <TEnclosing, TBoxModel, TArrowModel> box = BoxForLocation(mouseEventArgs.Location, null); if (box != null) { switch (_chaningArrowAction) { case ChangeAction.InitialBox: if (_changingArrow.TypedModel.Source != box.Model) { _changingArrow.SetInitialBox(box.TypedModel); } break; case ChangeAction.TargetBox: if (_changingArrow.TypedModel.Target != box.Model) { if (_changingArrow.TypedModel.Source != null) { _changingArrow.SetTargetBox(box.TypedModel); } } break; } } } if (_movingBox != null) { Point mouseMoveLocation = mouseEventArgs.Location; int deltaX = mouseMoveLocation.X - _moveStartLocation.X; int deltaY = mouseMoveLocation.Y - _moveStartLocation.Y; if (Math.Abs(deltaX) > 5 || Math.Abs(deltaY) > 5) { IModelElement model = _movingBox.TypedModel; if (model != null && !_movingBoxHasMoved) { Context.SelectionCriteria criteria = GuiUtils.SelectionCriteriaBasedOnMouseEvent(mouseEventArgs); EfsSystem.Instance.Context.SelectElement(model, this, criteria); _movingBoxHasMoved = true; } Util.DontNotify(() => { int newX = _positionBeforeMove.X + deltaX; int newY = _positionBeforeMove.Y + deltaY; SetBoxPosition(_movingBox, newX, newY); UpdatePositions(); }); } } }
/// <summary> /// Performs a single cycle /// </summary> public void Cycle() { EfsAccess.WaitOne(); try { DateTime now = DateTime.Now; // Close inactive connections foreach (ConnectionStatus status in Connections) { TimeSpan delta = now - status.LastCycleRequest; if (delta > MaxDelta && !status.Suspended) { status.Active = false; } } // Launches the runner when all active client have selected their next step while (CheckLaunch()) { LastStep = NextStep(LastStep); if (Runner != null) { try { if (!AllListeners) { Util.DontNotify(() => { Runner.ExecuteOnePriority(convertStep2Priority(LastStep)); if (LastStep == Step.CleanUp) { EfsSystem.Instance.Context.HandleEndOfCycle(); ClearFunctionCaches(); } }); } } catch (Exception) { // Ignore } } while (PendingClients(LastStep)) { // Let the processes waiting for the end of this step run StepAccess[LastStep].ReleaseMutex(); EfsAccess.ReleaseMutex(); // Let the other processes wake up Thread.Sleep(1); // Wait until all processes for this step have executed their work StepAccess[LastStep].WaitOne(); EfsAccess.WaitOne(); } } } catch (Exception) { } finally { EfsAccess.ReleaseMutex(); } }
/// <summary> /// Displays the graph /// </summary> /// <returns></returns> public void Display() { Util.DontNotify(() => { GraphVisualiser.Reset(); String name = null; // Computes the expected end to display double expectedEndX = 0; Dictionary <Function, Graph> graphs = new Dictionary <Function, Graph>(); foreach (Function function in Functions) { InterpretationContext context = new InterpretationContext(function); if (function.FormalParameters.Count == 1) { Parameter parameter = (Parameter)function.FormalParameters[0]; Graph graph = function.CreateGraph(context, parameter, null); if (graph != null) { expectedEndX = Math.Max(expectedEndX, graph.ExpectedEndX()); graphs.Add(function, graph); } } } double expectedEndY = 0; Dictionary <Function, Surface> surfaces = new Dictionary <Function, Surface>(); foreach (Function function in Functions) { InterpretationContext context = new InterpretationContext(function); if (function.FormalParameters.Count == 2) { Surface surface = function.CreateSurface(context, null); if (surface != null) { expectedEndX = Math.Max(expectedEndX, surface.ExpectedEndX()); expectedEndY = Math.Max(expectedEndY, surface.ExpectedEndY()); surfaces.Add(function, surface); } } } try { int maxX = Int32.Parse(Tb_MaxX.Text); expectedEndX = Math.Min(expectedEndX, maxX); } catch (Exception) { } // Creates the graphs foreach (KeyValuePair <Function, Graph> pair in graphs) { Function function = pair.Key; Graph graph = pair.Value; if (function != null && graph != null) { EfsProfileFunction efsProfileFunction = new EfsProfileFunction(graph); if (function.Name.Contains("Gradient")) { GraphVisualiser.AddGraph(new EfsGradientProfileGraph(GraphVisualiser, efsProfileFunction, function.FullName)); } else { GraphVisualiser.AddGraph(new EfsProfileFunctionGraph(GraphVisualiser, efsProfileFunction, function.FullName)); } if (name == null) { name = function.Name; } } } // Creates the surfaces foreach (KeyValuePair <Function, Surface> pair in surfaces) { Function function = pair.Key; Surface surface = pair.Value; if (surface != null) { EfsSurfaceFunction efsSurfaceFunction = new EfsSurfaceFunction(surface); GraphVisualiser.AddGraph(new EfsSurfaceFunctionGraph(GraphVisualiser, efsSurfaceFunction, function.FullName)); if (name == null) { name = function.Name; } } } Train train = new Train(GraphVisualiser); train.InitializeTrain(TrainPosition.GetDistance(), TrainPosition.GetSpeed(), TrainPosition.GetUnderReadingAmount(), TrainPosition.GetOverReadingAmount()); GraphVisualiser.AddGraph(train); GraphVisualiser.Annotations.Add(train.TrainLineAnnotation); GraphVisualiser.Annotations.Add(train.TrainAnnotation); if (name != null) { try { double val = double.Parse(Tb_MinX.Text); GraphVisualiser.SetMinX(val); } catch (Exception) { } try { double val = double.Parse(Tb_MaxX.Text); GraphVisualiser.SetMaxX(val); } catch (Exception) { } if (Cb_AutoYSize.Checked) { GraphVisualiser.SetMaxY(double.NaN); } else { double height; if (double.TryParse(Tb_MaxY.Text, out height)) { GraphVisualiser.SetMaxY(height); } else { GraphVisualiser.SetMaxY(double.NaN); } } GraphVisualiser.SetMinY2(double.NaN); GraphVisualiser.SetMaxY2(double.NaN); double top, bottom; if (double.TryParse(Tb_MinGrad.Text, out bottom)) { GraphVisualiser.SetMinY2(bottom); } if (double.TryParse(Tb_MaxGrad.Text, out top)) { GraphVisualiser.SetMaxY2(top); } GraphVisualiser.DrawGraphs(expectedEndX); } }); }