OTX-Runtime for DotNet  
Sample Program

The Sample program demonstrates the main functionality of the OTX-Runtime API. It can be used as a reference for the expected runtime behavior of the API and the source code below is like a reference guide about the proper programming of the API.

Code Example

Code snippet of the OTX-Runtime API Sample Program.

7 using OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.OutputCustomImplementation;
8 using OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Setting;
9 using System;
10 using System.Collections.Generic;
11 using System.Diagnostics;
12 using System.Drawing;
13 using System.IO;
14 using System.Linq;
15 using System.Threading;
16 using System.Threading.Tasks;
17 using System.Windows.Forms;
19 
20 namespace OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample
21 {
22  public partial class SampleForm : Form
23  {
24  private const int VALUE_STRING_MAX_LENGTH = 1024;
25 
26  private UserSettings userSettings = UserSettings.Default;
27 
28  // TODO: handle multithreading
29  private List<IRuntimeContext> runtimeContexts = new List<IRuntimeContext>();
30  private Dictionary<IRuntimeContext, DateTime> runtimeContextsExecutionStartTime = new Dictionary<IRuntimeContext, DateTime>();
31 
32  private IProject project = null;
33  private IPlayerProject playerProject = null;
34  private IProcedure procedureToExecute = null;
35 
36  private TreeNode startupNode = null;
37 
38  private IRuntimeManager globalRuntimeManager = null;
39 
40  private HmiWindow hmiWindow;
41 
42  private DateTime lastTime = DateTime.Now;
43 
44  private DefaultCustomScreenImplementation customScreenImplementation;
45  private ContextVariableImplementation contextVariableImplementation;
46 
47  private StateVariableImplementation stateVariableImplementation;
48  private DefaultMeasureImplementation measureImplementation;
49  private DefaultExternalServiceProviderImplementation serviceProviderImplementation;
50 
51  private BasicScreenOutputImpl basicScreenOutputImpl;
52  private CustomScreenOutputImpl customScreenOutputImpl;
53  private LoggingOutputImpl loggingOutputImpl;
54  private ContextVariableOutputImpl contextVariableOutputImpl;
55 
56  private StateVariableOutputImpl stateVariableOutputImpl;
57  private MeasureOutputImpl measureOutputImpl;
58  private I18nOutputImpl i18NOutputImpl;
59  private ExternalServiceProviderOutputImpl serviceProviderOutputImpl;
60 
61  private SqlOutputImpl sqlOutputImpl;
62  private CommonDialogsOutputImpl commonDialogsOutputImpl;
63 
64  private SampleForm creatorForm;
65  private string title;
66  private string runtimeContextName;
67  private long procedureExecutionCount;
68  private long cyclicExecutionCount;
69 
70  private static string fileVersion;
71 
72  private static int defaultPollingTime = 500;
73  private static int defaultBatteryVoltageThreshold = 6000;
74  private bool useConnectionState = false;
75  private bool? KL15State = null;
76  private ExpectedState expectedConnectionState = ExpectedState.None;
77 
78  private bool isLoadding = false;
79 
80  private ushort defaultDiagPort = SampleConstants.DEFAULT_DM_PORT;
81  private ushort defaultRuntimePort = SampleConstants.DEFAULT_RT_PORT;
82  private string defaultDiagPipeName = SampleConstants.DEFAULT_DM_PIPE_NAME;
83  private string defaultRuntimePipeName = SampleConstants.DEFAULT_RT_PIPE_NAME;
84 
85  private readonly object printTextLock = new object();
86  private readonly object eventListenerLock = new object();
87 
88  private bool cyclicExecuteAsyncIsProcessing = false;
89  private System.Windows.Forms.Timer webServerTimer = new System.Windows.Forms.Timer();
90 
91  public static bool isAcceptEmptyLicenseValue;
92 
93  static SampleForm()
94  {
95  fileVersion = RuntimeConfig.Instance.Version;
96  String licenseKeyFromOTForOTPLicense = OpenTestSystem.Common.LicensingV5.Util.CreateLicenseKeyFromOTForOTPLicense();
97 
98  isAcceptEmptyLicenseValue = licenseKeyFromOTForOTPLicense.Equals("") ? false : true;
99 
100  if (!String.IsNullOrEmpty(licenseKeyFromOTForOTPLicense) && LicensingUtil.CheckLicenseKeyFormat(licenseKeyFromOTForOTPLicense))
101  {
102  LicenseManager.SetLicenseKey(licenseKeyFromOTForOTPLicense);
103  }
104  else
105  {
106  String licenseKey = Setting.UserSettings.Default.LicenseKey;
107  licenseKey = LicensingUtil.Decrypt(licenseKey);
108  if (LicensingUtil.CheckLicenseKeyFormat(licenseKey))
109  {
110  LicenseManager.SetLicenseKey(licenseKey);
111  }
112  else
113  {
114  MessageBox.Show("There is an invalid license key format. Please set your new key in license box.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
115  }
116  }
117  }
118 
119  public SampleForm(string title = SampleConstants.MAIN_INSTANCE_NAME, SampleForm creatorForm = null)
120  {
121  this.ShowInTaskbar = false;
122  this.title = title;
123  this.creatorForm = creatorForm;
124 
125  this.webServerTimer.Interval = 1000;
126  this.webServerTimer.Enabled = true;
127  this.webServerTimer.Tick += WebServerTimer_Tick;
128 
129  InitializeComponent();
130 
131  PrintText("Application started");
132  }
133 
134  private void SampleForm_Load(object sender, EventArgs e)
135  {
136  PrintText("Start Initialization...");
137 
138  CreateCustomImpl();
139  InitializeSampleDefaultValues();
140  this.UpdateWebServerButton();
141 
142  if (this.creatorForm != null)
143  {
144  this.checkBoxStartAllParents.Visible = true;
145  this.checkBoxStartAllParents.Checked = this.creatorForm.checkBoxStartAllParents.Checked;
146  }
147 
148  SetRuntimeContextName();
149  SetTitle(this.title);
150  SetLocation(this.creatorForm);
151 
152  this.toolTip1.SetToolTip(labelProcedureExecutionTimes, "Total procedure execution time.");
153  this.toolTip1.SetToolTip(textBoxTimeout, "Timeout for procedure execution in milliseconds. The default value 0 means without timeout.");
154  this.toolTip1.SetToolTip(checkBoxUseConnectionState, "Use expected connection state during procedure execution.");
155  this.toolTip1.SetToolTip(labelBatteryState, "State of the battery (KL 30)");
156  this.toolTip1.SetToolTip(checkBoxIgnition, "Expected ignition (KL 15) state during procedure execution");
157  this.toolTip1.SetToolTip(labelIgnitionState, "State of the ignition (KL 15)");
158  this.toolTip1.SetToolTip(buttonCheckBatteryIgnition, "Check current battery (KL30) and ignition (KL15) state.");
159  this.toolTip1.SetToolTip(textBoxPollingTime, "Time in milliseconds between the next check of the connection state during the procedure execution (Polling). The default value is 500 ms.");
160  this.toolTip1.SetToolTip(textBoxVoltageThreshold, "Voltage threshold in millivolt from which the battery voltage, see GetBatteryVoltage is enough for KL30 = On. The default value is 6000 mV.");
161 
162  PrintText("... Initialization finished.");
163  this.ShowInTaskbar = true;
164  }
165 
166  private void SampleForm_Shown(object sender, EventArgs e)
167  {
168  this.cbFilePath.SelectionLength = 0;
169  }
170 
171  private void SetRuntimeContextName()
172  {
173  if (this.creatorForm != null && !String.IsNullOrEmpty(this.creatorForm.runtimeContextName))
174  {
175  System.Text.RegularExpressions.Match regExpMatch = System.Text.RegularExpressions.Regex.Match(this.creatorForm.runtimeContextName, @"\d*$");
176  int number;
177  if (int.TryParse(regExpMatch.Value, out number))
178  {
179  number++;
180  this.textBoxRuntimeContextName.Text = this.creatorForm.runtimeContextName.Substring(0, regExpMatch.Index) + number.ToString();
181  }
182  }
183  }
184 
185  private void SetTitle(string title)
186  {
187  if (String.IsNullOrWhiteSpace(title))
188  title = SampleConstants.MAIN_INSTANCE_NAME;
189 
190  bool runningAsAdmin = System.Security.Principal.WindowsIdentity.GetCurrent().Owner.IsWellKnown(System.Security.Principal.WellKnownSidType.BuiltinAdministratorsSid);
191 
192  this.Text = String.Format(
193  "emotive OTX-Runtime API for DotNet - Reference Application - Version {0} - {1} Bit - {2} - Thread-ID {3}{4}",
194  fileVersion,
195  Environment.Is64BitProcess ? "64" : "32",
196  title,
197  Thread.CurrentThread.ManagedThreadId,
198  runningAsAdmin ? " - Administrator" : string.Empty
199  );
200 
201  if (!String.IsNullOrEmpty(this.cbFilePath.Text))
202  this.Text = this.Text + " - " + Path.GetFileName(this.cbFilePath.Text);
203 
204  if (!String.IsNullOrEmpty(this.runtimeContextName))
205  this.Text = this.Text + " - " + this.runtimeContextName;
206  }
207 
208  private const int FORM_OFFSET = 25;
209 
210  private void SetLocation(SampleForm creatorForm)
211  {
212  if (creatorForm != null)
213  {
214  int xOffset = FORM_OFFSET;
215  int yOffset = FORM_OFFSET;
216 
217  if (creatorForm.creatorForm != null)
218  {
219  xOffset = creatorForm.Location.X - creatorForm.creatorForm.Location.X;
220  yOffset = creatorForm.Location.Y - creatorForm.creatorForm.Location.Y;
221  }
222 
223  this.Location = new Point(creatorForm.Location.X + xOffset, creatorForm.Location.Y + yOffset);
224  this.Size = creatorForm.Size;
225  }
226  }
227 
228  private void CreateCustomImpl()
229  {
230  CreateDefaultCustomImpl();
231  CreateOutputWindowCustomImpl();
232  }
233 
234  private void CreateDefaultCustomImpl()
235  {
236  PrintText("Create default custom implementation");
237 
238  customScreenImplementation = new DefaultCustomScreenImplementation();
239  customScreenImplementation.KeyDown += CustomScreenImplementation_KeyDown;
240 
241  contextVariableImplementation = new ContextVariableImplementation();
242  contextVariableImplementation.ContextVariableRead += ContextVariableRead;
243 
244  stateVariableImplementation = new StateVariableImplementation();
245  stateVariableImplementation.StateVariableValueChanged += StateVariableValueChanged;
246 
247  measureImplementation = new DefaultMeasureImplementation();
248  serviceProviderImplementation = new DefaultExternalServiceProviderImplementation();
249  }
250 
251  private void CreateOutputWindowCustomImpl()
252  {
253  PrintText("Create output window custom implementation");
254 
255  basicScreenOutputImpl = new BasicScreenOutputImpl();
256  customScreenOutputImpl = new CustomScreenOutputImpl();
257  loggingOutputImpl = new LoggingOutputImpl();
258  contextVariableOutputImpl = new ContextVariableOutputImpl();
259 
260  stateVariableOutputImpl = new StateVariableOutputImpl();
261  measureOutputImpl = new MeasureOutputImpl();
262  i18NOutputImpl = new I18nOutputImpl();
263  serviceProviderOutputImpl = new ExternalServiceProviderOutputImpl();
264 
265  sqlOutputImpl = new SqlOutputImpl();
266  commonDialogsOutputImpl = new CommonDialogsOutputImpl();
267 
268  basicScreenOutputImpl.LogEvent += PrintText;
269  customScreenOutputImpl.LogEvent += PrintText;
270  loggingOutputImpl.LogEvent += PrintText;
271  contextVariableOutputImpl.LogEvent += PrintText;
272 
273  stateVariableOutputImpl.LogEvent += PrintText;
274  measureOutputImpl.LogEvent += PrintText;
275  i18NOutputImpl.LogEvent += PrintText;
276  serviceProviderOutputImpl.LogEvent += PrintText;
277 
278  sqlOutputImpl.LogEvent += PrintText;
279  commonDialogsOutputImpl.LogEvent += PrintText;
280  }
281 
282  private void InitializeSampleDefaultValues()
283  {
284  PrintText("Initialize default values");
285 
286  this.comboBoxTraceLevel.Items.AddRange(Enum.GetNames(typeof(TraceLevels)));
287 
288  // Avoid changing order
289  treeViewOtxProject.ImageList = imageList1;
290 
291  textBoxRtPortPipe.Name = SampleConstants.RT_PORT_PIPE_TEXT_BOX_NAME;
292  textBoxDiagPortPipe.Name = SampleConstants.DM_PORT_PIPE_TEXT_BOX_NAME;
293 
294  LoadSetting();
295 
296  this.EnableConnectionState();
297  }
298 
299  private void LoadSetting()
300  {
301  SaveSettingUtil.Reload();
302  try
303  {
304  cbFilePath.Text = userSettings.Ptx_Ppx_Directory;
305  cbFilePath.Text = userSettings.Ptx_Ppx_Directory;
306  if (!String.IsNullOrEmpty(userSettings.Ptx_Ppx_DirectoryList))
307  {
308  this.cbFilePath.Items.AddRange(userSettings.Ptx_Ppx_DirectoryList.Split(';'));
309  }
310  AddComboBoxFileOrPath(this.cbFilePath);
311 
312  SetupTraceLevel();
313  SetupTraceFolder();
314  SetupTraceFileMaxCountAndSize();
315 
316  // Avoid changing order of this line
317  SetupDefaultPortAndPipeName();
318 
319  SetupCustomImplType();
320  SetupWindowSize();
321  SetupWindowLocation();
322 
323  checkBoxAsyncExecution.Checked = userSettings.Asynchron;
324  checkBoxCyclicExecution.Checked = userSettings.Cyclic;
325  checkBoxCyclicReload.Checked = userSettings.CyclicReload;
326  checkBoxNewRuntimeManager.Checked = userSettings.NewRunTimeManager;
327  checkBoxAdd2Output.Checked = userSettings.AddMessageToOutput;
328  checkBoxStartAllParents.Checked = userSettings.StartAllParents;
329 
330  SetupTimeOut();
331  checkBoxUseConnectionState.Checked = userSettings.ConnectionState;
332  checkBoxIgnition.CheckState = userSettings.Ignition == 1 ? CheckState.Checked : (userSettings.Ignition == 0 ? CheckState.Unchecked : CheckState.Indeterminate);
333  SetupPollingTime();
334  SetupVoltageThreshold();
335 
336  this.textBoxRuntimeContextName.Text = userSettings.RuntimeContextName.ToString();
337  }
338  catch (System.Exception e)
339  {
340  PrintText(e.Message);
341  userSettings.Reset();
342  }
343  }
344 
345  bool isPathChanging = false;
346  private void AddComboBoxFileOrPath(ComboBox comboBox)
347  {
348  if (comboBox != null && !isPathChanging)
349  {
350  isPathChanging = true;
351 
352  string path = comboBox.Text;
353 
354  if (Directory.Exists(path) || File.Exists(path))
355  {
356  while (comboBox.Items.Contains(path))
357  {
358  comboBox.Items.Remove(path);
359  }
360 
361  while (comboBox.Items.Contains(path.TrimEnd(new char[] { '/', '\\' })))
362  {
363  comboBox.Items.Remove(path.TrimEnd(new char[] { '/', '\\' }));
364  }
365 
366  path = path.TrimEnd(new char[] { '/', '\\' });
367 
368  comboBox.Items.Insert(0, path);
369  comboBox.Text = path;
370  comboBox.SelectAll();
371  }
372 
373  isPathChanging = false;
374  }
375  }
376 
377  private void SetupTraceFileMaxCountAndSize()
378  {
379  textBoxTraceFileMaxCount.Text = userSettings.TraceFileMaxCount.ToString();
380  textBoxTraceFileMaxSize.Text = userSettings.TraceFileMaxSize.ToString();
381  }
382 
383  private void SetupDefaultPortAndPipeName()
384  {
385  defaultDiagPort = userSettings.DiagManagerPort;
386  defaultRuntimePort = userSettings.RuntimePort;
387 
388  defaultDiagPipeName = userSettings.DiagManagerPipeName;
389  defaultRuntimePipeName = userSettings.RuntimePipeName;
390 
391  IpcTypes ipcTypes = IpcTypes.SOCKET;
392  Enum.TryParse<IpcTypes>(userSettings.IpcType, out ipcTypes);
393 
394  if (comboBoxIpcType.Items.Count == 0)
395  {
396  comboBoxIpcType.Items.Add(IpcTypes.SOCKET);
397  comboBoxIpcType.Items.Add(IpcTypes.PIPE);
398  }
399 
400  comboBoxIpcType.SelectedItem = ipcTypes;
401  }
402 
403  private void SetupTraceLevel()
404  {
405  RuntimeConfig.Instance.TraceLevel = userSettings.TraceLevels;
406  comboBoxTraceLevel.SelectedItem = RuntimeConfig.Instance.TraceLevel.ToString();
407  }
408 
409  private void SetupTraceFolder()
410  {
411  if (userSettings.TracingDirectory != string.Empty)
412  RuntimeConfig.Instance.TraceFolder = userSettings.TracingDirectory;
413 
414  textBoxTraceFolder.Text = RuntimeConfig.Instance.TraceFolder;
415  }
416 
417  private void SetupCustomImplType()
418  {
419  if (userSettings.CustomImplTypes == CustomImplTypes.OutputImpl)
420  {
421  radioButtonOuputWindow.Checked = true;
422  }
423  else if (userSettings.CustomImplTypes == CustomImplTypes.NoCustom)
424  {
425  radioButtonNoCustomImplementation.Checked = true;
426  }
427  else
428  {
429  radioButtonDefaultImplementation.Checked = true;
430  }
431  }
432 
433  private void SetupWindowSize()
434  {
435  int width = userSettings.WindowWidth;
436  int height = userSettings.WindowHeight;
437  this.Size = new Size(width, height);
438  }
439 
440  private void SetupWindowLocation()
441  {
442  int locationX = userSettings.WindowLocationX;
443  int locationY = userSettings.WindowLocationY;
444  Point location = new Point(locationX, locationY);
445 
446  if (CheckFormIsInBound(location))
447  {
448  this.Location = location;
449  return;
450  }
451 
452  this.CenterToScreen();
453  }
454 
455  private bool CheckFormIsInBound(Point location)
456  {
457  try
458  {
459  Screen formContainScreens = Screen.AllScreens.Where(screen => screen.Bounds.Contains(location) == true).FirstOrDefault();
460 
461  return formContainScreens != null;
462  }
463  catch (System.Exception)
464  {
465  return false;
466  }
467  }
468 
469  private void SetupTimeOut()
470  {
471  string timeOutString = userSettings.TimeOut.ToString();
472  this.textBoxTimeout.Text = timeOutString;
473  }
474 
475  private void SetupPollingTime()
476  {
477  string pollingTimeString = userSettings.PollingTime.ToString();
478  this.textBoxPollingTime.Text = pollingTimeString;
479  }
480 
481  private void SetupVoltageThreshold()
482  {
483  string voltageThreshold = userSettings.VoltageThreshold.ToString();
484  this.textBoxVoltageThreshold.Text = voltageThreshold;
485  }
486 
487  private void comboBoxIpcType_SelectedValueChanged(object sender, EventArgs e)
488  {
489  // Avoid RuntimeManager creation on DiagManager's port changed in this method
490  textBoxDiagPortPipe.TextChanged -= textBoxPortPipe_TextChanged;
491  var ipcType = (IpcTypes)comboBoxIpcType.SelectedItem;
492 
493  switch (ipcType)
494  {
495  case IpcTypes.SOCKET:
496 
497  portPipeLabel.Text = "Runner / DiagManager Ports";
498 
499  textBoxDiagPortPipe.Text = defaultDiagPort.ToString();
500  textBoxDiagPortPipe.TextChanged += textBoxPortPipe_TextChanged;
501 
502  textBoxRtPortPipe.Text = defaultRuntimePort.ToString();
503  break;
504 
505  case IpcTypes.PIPE:
506 
507  portPipeLabel.Text = "Runner / DiagManager Pipes";
508 
509  textBoxDiagPortPipe.Text = defaultDiagPipeName;
510  textBoxDiagPortPipe.TextChanged += textBoxPortPipe_TextChanged;
511 
512  textBoxRtPortPipe.Text = defaultRuntimePipeName;
513  break;
514 
515  default:
516  break;
517  }
518  }
519 
520  private void textBoxPortPipe_TextChanged(object sender, EventArgs e)
521  {
522  PrintText("Create RuntimeManager...");
523 
524  try
525  {
526  this.globalRuntimeManager = CreateRuntimeManager();
527  }
528  catch (System.Exception ex)
529  {
530  switch ((sender as TextBox).Name)
531  {
532  case SampleConstants.RT_PORT_PIPE_TEXT_BOX_NAME:
533 
534  PrintText(String.Format("Invalid Otx Runtime {0}", IpcPortPipeString()));
535  break;
536 
537  case SampleConstants.DM_PORT_PIPE_TEXT_BOX_NAME:
538 
539  PrintText(String.Format("Invalid Diag Manager {0}", IpcPortPipeString()));
540  break;
541 
542  default:
543  break;
544  }
545 
546  PrintException(ex);
547  PrintText("No RuntimeManager created");
548  }
549 
550  if (this.globalRuntimeManager == null)
551  {
552  PrintText("RuntimeManager is null.");
553  }
554  }
555 
556  private IRuntimeManager CreateRuntimeManager()
557  {
558  IRuntimeManager runtimeManager = null;
559  try
560  {
561  string ipcType = "";
562  switch ((IpcTypes)comboBoxIpcType.SelectedItem)
563  {
564  case IpcTypes.SOCKET:
565 
566  runtimeManager = CreateSocketRuntimeManager();
567  ipcType = "Socket";
568  break;
569 
570  case IpcTypes.PIPE:
571 
572  runtimeManager = CreatePipeRuntimeManager();
573  ipcType = "Pipe";
574  break;
575  }
576 
577  PrintText($"... {ipcType} RuntimeManager created (MinBinVersion: {RuntimeConfig.Instance.MinBinVersion})");
578 
579  InitializeRuntimeEvents(runtimeManager);
580  SetCustomImplementation(runtimeManager);
581  }
582  catch (InvalidLicenseException ex)
583  {
584  PrintException(ex);
585  PrintText("... No RuntimeManager created.");
586 
587  return runtimeManager;
588  }
589 
590  return runtimeManager;
591  }
592 
593  private string IpcPortPipeString()
594  {
595  switch ((IpcTypes)comboBoxIpcType.SelectedItem)
596  {
597  case IpcTypes.SOCKET:
598  return SampleConstants.PORT_STRING;
599  case IpcTypes.PIPE:
600  return SampleConstants.PIPE_STRING;
601  default:
602  // Should not reach here
603  return string.Empty;
604  }
605  }
606 
607  private IRuntimeManager CreateSocketRuntimeManager()
608  {
609  ushort rtPort = Convert.ToUInt16(textBoxRtPortPipe.Text);
610 
611  if (NoDiag())
612  {
613  return RuntimeManagerFactory.CreateSocketRuntimeManager(rtPort);
614  }
615  else
616  {
617  ushort diagPort = Convert.ToUInt16(textBoxDiagPortPipe.Text);
618  return RuntimeManagerFactory.CreateSocketRuntimeManager(rtPort, diagPort);
619  }
620  }
621 
622  private IRuntimeManager CreatePipeRuntimeManager()
623  {
624  if (NoDiag())
625  {
626  return RuntimeManagerFactory.CreatePipeRuntimeManager(textBoxRtPortPipe.Text);
627  }
628  else
629  {
630  return RuntimeManagerFactory.CreatePipeRuntimeManager(textBoxRtPortPipe.Text, textBoxDiagPortPipe.Text);
631  }
632  }
633 
634  private bool NoDiag()
635  {
636  return String.IsNullOrWhiteSpace(textBoxDiagPortPipe.Text);
637  }
638 
639  private void InitializeRuntimeEvents(IRuntimeManager runtimeManager)
640  {
641  if (runtimeManager == null)
642  return;
643 
644  runtimeManager.ProcedurePending -= ProcedurePending;
645  runtimeManager.ProcedureStarted -= ProcedureStarted;
646  runtimeManager.ProcedurePaused -= ProcedurePaused;
647  runtimeManager.ProcedureContinued -= ProcedureContinued;
648  runtimeManager.ProcedureFinished -= ProcedureFinished;
649  runtimeManager.ProcedureAborted -= ProcedureAborted;
650  runtimeManager.ProcedureStopped -= ProcedureStopped;
651  runtimeManager.ProcedureTimeout -= ProcedureTimeout;
652  runtimeManager.DiagConnectionStateChanged -= DiagConnectionStateChanged;
653  runtimeManager.InOutParameterValueChanged -= InOutParameterValueChanged;
654 
655  runtimeManager.ProcedurePending += ProcedurePending;
656  runtimeManager.ProcedureStarted += ProcedureStarted;
657  runtimeManager.ProcedurePaused += ProcedurePaused;
658  runtimeManager.ProcedureContinued += ProcedureContinued;
659  runtimeManager.ProcedureFinished += ProcedureFinished;
660  runtimeManager.ProcedureAborted += ProcedureAborted;
661  runtimeManager.ProcedureStopped += ProcedureStopped;
662  runtimeManager.ProcedureTimeout += ProcedureTimeout;
663  runtimeManager.DiagConnectionStateChanged += DiagConnectionStateChanged;
664  runtimeManager.InOutParameterValueChanged += InOutParameterValueChanged;
665 
666  PrintText("Initialization of runtime events finished");
667  }
668 
669  private void radioButtonCustomImpl_CheckedChanged(object sender = null, System.EventArgs e = null)
670  {
671  if (this.globalRuntimeManager == null)
672  return;
673 
674  if (sender != null && (sender as RadioButton).Checked == false)
675  return;
676 
677  this.SetCustomImplementation(this.globalRuntimeManager);
678  }
679 
680  private void SetCustomImplementation(IRuntimeManager runtimeManager)
681  {
682  if (runtimeManager == null)
683  return;
684 
685  var currentCustomImpl = GetCurrentCustomImpl();
686 
687  switch (currentCustomImpl)
688  {
689  case CustomImplTypes.OutputImpl:
690 
691  SetOutputWindowImplementation(runtimeManager);
692  break;
693 
694  case CustomImplTypes.DefaultCustomImpl:
695 
696  SetDefaultCustomImplementation(runtimeManager);
697  break;
698 
699  case CustomImplTypes.NoCustom:
700 
701  RemoveCustomImplementation(runtimeManager);
702  break;
703 
704  default:
705  break;
706  }
707 
708  if (currentCustomImpl != CustomImplTypes.None)
709  {
710  PrintText("Set up custom implementation finished");
711  }
712  }
713 
714  private CustomImplTypes GetCurrentCustomImpl()
715  {
716  if (radioButtonOuputWindow.Checked)
717  return CustomImplTypes.OutputImpl;
718  else if (radioButtonDefaultImplementation.Checked)
719  return CustomImplTypes.DefaultCustomImpl;
720  else if (radioButtonNoCustomImplementation.Checked)
721  return CustomImplTypes.NoCustom;
722 
723  return CustomImplTypes.None;
724  }
725 
726  private void SetOutputWindowImplementation(IRuntimeManager runtimeManager)
727  {
728  if (runtimeManager == null)
729  return;
730 
731  runtimeManager.SetCustomImplementation(basicScreenOutputImpl);
732  runtimeManager.SetCustomImplementation(customScreenOutputImpl);
733  runtimeManager.SetCustomImplementation(loggingOutputImpl);
734  runtimeManager.SetCustomImplementation(contextVariableOutputImpl);
735 
736  runtimeManager.SetCustomImplementation(stateVariableOutputImpl);
737  runtimeManager.SetCustomImplementation(measureOutputImpl);
738  runtimeManager.SetCustomImplementation(i18NOutputImpl);
739  runtimeManager.SetCustomImplementation(serviceProviderOutputImpl);
740 
741  runtimeManager.SetCustomImplementation((ISqlImplementation)null); // TODO: create?
742  runtimeManager.SetCustomImplementation(commonDialogsOutputImpl);
743  }
744 
745  private void SetDefaultCustomImplementation(IRuntimeManager runtimeManager)
746  {
747  if (runtimeManager == null)
748  return;
749 
750  runtimeManager.SetCustomImplementation((IBasicScreenImplementation)null); // TODO: create?
751  runtimeManager.SetCustomImplementation(customScreenImplementation);
752  runtimeManager.SetCustomImplementation((ILoggingImplementation)null); // TODO: create?
753  runtimeManager.SetCustomImplementation(contextVariableImplementation);
754 
755  runtimeManager.SetCustomImplementation(stateVariableImplementation);
756  runtimeManager.SetCustomImplementation(measureImplementation);
757  runtimeManager.SetCustomImplementation((Ii18nImplementation)null); // TODO: create?
758  runtimeManager.SetCustomImplementation(serviceProviderImplementation);
759 
760  runtimeManager.SetCustomImplementation(sqlOutputImpl);
761  runtimeManager.SetCustomImplementation((ICommonDialogsImplementation)null); // TODO: create?
762  }
763 
764  private void RemoveCustomImplementation(IRuntimeManager runtimeManager)
765  {
766  if (runtimeManager == null)
767  return;
768 
769  runtimeManager.SetCustomImplementation((IBasicScreenImplementation)null);
770  runtimeManager.SetCustomImplementation((ICustomScreenImplementation)null);
771  runtimeManager.SetCustomImplementation((ILoggingImplementation)null);
772  runtimeManager.SetCustomImplementation((IContextVariableImplementation)null);
773 
774  runtimeManager.SetCustomImplementation((IStateVariableImplementation)null);
775  runtimeManager.SetCustomImplementation((IMeasureImplementation)null);
776  runtimeManager.SetCustomImplementation((Ii18nImplementation)null);
777  runtimeManager.SetCustomImplementation((IExternalServiceProviderImplementation)null);
778 
779  runtimeManager.SetCustomImplementation((ISqlImplementation)null);
780  runtimeManager.SetCustomImplementation((ICommonDialogsImplementation)null);
781  }
782 
783  private void ProcedurePending(IRuntimeContext context)
784  {
785  if (InvokeRequired)
786  {
787  Invoke(new MethodInvoker(delegate ()
788  {
789  ProcedurePending(context);
790  }));
791  return;
792  }
793 
794  lock (eventListenerLock)
795  {
796  this.PrintText(string.Format("Event ProcedurePending occurred - {0} - ExecutionState = {1}", context.Procedure.FullName, context.ExecutionState.ToString()));
797  UpdateExecutionState(context);
798  ShowConnectionStateMessage(context);
799  }
800  }
801 
802  private void ProcedureStarted(IRuntimeContext context)
803  {
804  if (InvokeRequired)
805  {
806  Invoke(new MethodInvoker(delegate ()
807  {
808  ProcedureStarted(context);
809  }));
810  return;
811  }
812 
813  lock (eventListenerLock)
814  {
815  this.PrintText(string.Format("Event ProcedureStarted occurred - {0} - ExecutionState = {1} - RuntimeId = {2} - ProcessId = {3}", context.Procedure.FullName, context.ExecutionState.ToString(), context.RuntimeId, context.ProcessId));
816  UpdateExecutionState(context);
817  }
818  }
819 
820  private void ProcedurePaused(IRuntimeContext context, ExecutionStateChangeReason reason)
821  {
822  if (InvokeRequired)
823  {
824  Invoke(new MethodInvoker(delegate ()
825  {
826  ProcedurePaused(context, reason);
827  }));
828  return;
829  }
830 
831  lock (eventListenerLock)
832  {
833  this.PrintText(string.Format("Event ProcedurePaused occurred - {0} - ExecutionState = {1} - ExecutionStateChangeReason = {2}", context.Procedure.FullName, context.ExecutionState.ToString(), reason.ToString()));
834  UpdateExecutionState(context, reason);
835  if (reason == ExecutionStateChangeReason.UnexpectedDiagConnectionState)
836  {
837  ShowConnectionStateMessage(context);
838  }
839  }
840  }
841 
842  private void ProcedureContinued(IRuntimeContext context)
843  {
844  if (InvokeRequired)
845  {
846  Invoke(new MethodInvoker(delegate ()
847  {
848  ProcedureContinued(context);
849  }));
850  return;
851  }
852 
853  lock (eventListenerLock)
854  {
855  this.PrintText(string.Format("Event ProcedureContinued occurred - {0} - ExecutionState = {1}", context.Procedure.FullName, context.ExecutionState.ToString()));
856  UpdateExecutionState(context);
857  }
858  }
859 
860  private void ProcedureStopped(IRuntimeContext context)
861  {
862  if (InvokeRequired)
863  {
864  Invoke(new MethodInvoker(delegate ()
865  {
866  ProcedureStopped(context);
867  }));
868  return;
869  }
870 
871  lock (eventListenerLock)
872  {
873  this.PrintText(string.Format("Event ProcedureStopped occurred - {0} - ExecutionState = {1}", context.Procedure.FullName, context.ExecutionState.ToString()));
874  UpdateExecutionState(context);
875  }
876  }
877 
878  private void ProcedureTimeout(IRuntimeContext context)
879  {
880  if (InvokeRequired)
881  {
882  Invoke(new MethodInvoker(delegate ()
883  {
884  ProcedureTimeout(context);
885  }));
886  return;
887  }
888 
889  lock (eventListenerLock)
890  {
891  cyclicExecuteAsyncIsProcessing = false;
892  this.PrintText(string.Format("Event ProcedureTimeout occurred - {0} - ExecutionState = {1}", context.Procedure.FullName, context.ExecutionState.ToString()));
893  UpdateExecutionState(context);
894  }
895  }
896 
897  private void DiagConnectionStateChanged(ClampState batteryState, ClampState ignitionState)
898  {
899  if (InvokeRequired)
900  {
901  Invoke(new MethodInvoker(delegate ()
902  {
903  DiagConnectionStateChanged(batteryState, ignitionState);
904  }));
905  return;
906  }
907 
908  lock (eventListenerLock)
909  {
910  this.PrintText(string.Format("Event DiagConnectionStateChanged occurred - BatteryState = {0}, IgnitionState = {1}", batteryState.ToString(), ignitionState.ToString()));
911  System.Media.SystemSounds.Beep.Play();
912 
913  SetBatteryIgnitionState(batteryState, ignitionState);
914  }
915  }
916 
917  // TODO: refactor. handle multithread?
918  private void ProcedureFinished(IRuntimeContext context)
919  {
920  if (InvokeRequired)
921  {
922  Invoke(new MethodInvoker(delegate ()
923  {
924  ProcedureFinished(context);
925  }));
926  return;
927  }
928 
929  lock (eventListenerLock)
930  {
931  IProcedureParameter procedureParameter;
932  string procedureName = context.Procedure.FullName;
933  string parameterOuput;
934 
935  for (int i = 0; i < context.Procedure.Parameters.Count(); i++)
936  {
937  procedureParameter = context.Procedure.Parameters.ElementAt(i);
938  parameterOuput = "Parameter Changed - " + procedureParameter.Name + "(" + procedureParameter.DataType + ") = ";
939 
940  if (procedureParameter.Value != null)
941  {
942  parameterOuput += ShortenedValueString(procedureParameter);
943  }
944  else
945  {
946  parameterOuput += null;
947  }
948 
949  this.PrintText(parameterOuput);
950  }
951 
952  UpdateGridviewParameter(context.Procedure);
953 
954  this.PrintText(string.Format("ProcedureFinished({0}) ExecutionState({1}) - Execution duration {2} - Running time {3} - Used memory {4})",
955  context.Procedure.FullName,
956  context.ExecutionState.ToString(),
957  (DateTime.Now - this.runtimeContextsExecutionStartTime[context]).ToString("mm':'ss','fff"),
958  TimeSpan.FromMilliseconds(context.ExecutionTime).ToString("mm':'ss','fff"),
959  string.Format("{0:0,0} kB", context.ProcessMemory / 1024))
960  );
961 
962  UpdateExecutionState(context);
963 
964  cyclicExecuteAsyncIsProcessing = false;
965  }
966  }
967 
968  private void ProcedureAborted(IRuntimeContext context)
969  {
970  if (InvokeRequired)
971  {
972  Invoke(new MethodInvoker(delegate ()
973  {
974  ProcedureAborted(context);
975  }));
976  return;
977  }
978 
979  this.PrintText(string.Format("ProcedureAborted({0}) ExecutionState({1})", context.Procedure.FullName, context.ExecutionState.ToString()));
980 
981  if (context.HasRuntimeException)
982  {
983  PrintException(context.RuntimeException, "Reason: API ");
984  }
985 
986  if (context.HasOtxException)
987  {
988  PrintException(context.OtxException, "Reason: OTX ");
989  }
990  cyclicExecuteAsyncIsProcessing = false;
991  UpdateExecutionState(context);
992  }
993 
994  private void UpdateExecutionState(IRuntimeContext context, ExecutionStateChangeReason? reason = null)
995  {
996  if (context != null)
997  {
998  switch (context.ExecutionState)
999  {
1000  case ExecutionState.Running:
1001 
1002  this.procedureExecutionCount++;
1003 
1004  AddRuntimeContext(context);
1005  DisplayProcedureExecutionState(context);
1006 
1007  this.buttonExecuteMain.Enabled = checkBoxAsyncExecution.Checked;
1008  this.buttonExecuteSelectedProcedure.Enabled = checkBoxAsyncExecution.Checked;
1009 
1010  UpdateExecutionStateButtons(true);
1011  UpdatePauseButton(true);
1012 
1013  break;
1014 
1015  case ExecutionState.Paused:
1016 
1017  this.procedureExecutionCount--;
1018  if (reason == ExecutionStateChangeReason.Explicit)
1019  {
1020  DisplayProcedureExecutionState(context);
1021  }
1022 
1023  UpdatePauseButton(false, reason == ExecutionStateChangeReason.Explicit);
1024 
1025  break;
1026 
1027  case ExecutionState.Pending:
1028 
1029  DisplayProcedureExecutionState(context);
1030  UpdateExecutionStateButtons(true);
1031  UpdatePauseButton(true, false);
1032 
1033  break;
1034 
1035  case ExecutionState.Finished:
1036 
1037  this.procedureExecutionCount--;
1038 
1039  RemoveRuntimeContext(context);
1040  DisplayProcedureExecutionState(context);
1041 
1042  this.buttonExecuteMain.Enabled = !checkBoxCyclicExecution.Checked;
1043  this.buttonExecuteSelectedProcedure.Enabled = !checkBoxCyclicExecution.Checked;
1044 
1045  UpdateExecutionStateButtons(false);
1046  UpdatePauseButton(true, false);
1047 
1048  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
1049  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
1050 
1051  break;
1052 
1053  case ExecutionState.Stopped:
1054 
1055  this.procedureExecutionCount--;
1056 
1057  RemoveRuntimeContext(context);
1058  DisplayProcedureExecutionState(context);
1059 
1060  this.buttonExecuteMain.Enabled = true;
1061  this.buttonExecuteSelectedProcedure.Enabled = true;
1062 
1063  UpdateExecutionStateButtons(false);
1064  UpdatePauseButton(true, false);
1065 
1066  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
1067  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
1068 
1069  break;
1070 
1071  case ExecutionState.Aborted:
1072 
1073  this.procedureExecutionCount--;
1074 
1075  RemoveRuntimeContext(context);
1076  DisplayProcedureExecutionState(context);
1077 
1078  this.buttonExecuteMain.Enabled = true;
1079  this.buttonExecuteSelectedProcedure.Enabled = true;
1080 
1081  UpdateExecutionStateButtons(false);
1082  UpdatePauseButton(true, false);
1083 
1084  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
1085  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
1086 
1087  break;
1088  case ExecutionState.Timeout:
1089 
1090  System.Media.SystemSounds.Hand.Play();
1091 
1092  this.procedureExecutionCount--;
1093 
1094  RemoveRuntimeContext(context);
1095  DisplayProcedureExecutionState(context);
1096 
1097  this.buttonExecuteMain.Enabled = true;
1098  this.buttonExecuteSelectedProcedure.Enabled = true;
1099 
1100  UpdateExecutionStateButtons(false);
1101  UpdatePauseButton(true, false);
1102 
1103  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
1104  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
1105 
1106  break;
1107  }
1108 
1109  StartStopUpdateGuiTimer();
1110  }
1111  }
1112 
1113  private void StartStopUpdateGuiTimer()
1114  {
1115  if (this.procedureExecutionCount <= 0)
1116  {
1117  this.updateGuiTimer.Enabled = false;
1118  this.labelSeparator1.Visible = false;
1119  this.labelProcedureExecutionTimes.Visible = false;
1120  }
1121  else if (!this.updateGuiTimer.Enabled)
1122  {
1123  this.updateGuiTimer.Enabled = true;
1124  }
1125  }
1126 
1127  private void updateGuiTimer_Tick(object sender, EventArgs e)
1128  {
1129  DisplayProcedureExecutionTimes();
1130  }
1131 
1132  private void DisplayProcedureExecutionTimes()
1133  {
1134  string text = string.Empty;
1135 
1136  if (this.runtimeContextsExecutionStartTime.Count > 0)
1137  {
1138  foreach (var item in this.runtimeContextsExecutionStartTime)
1139  {
1140  var duration = DateTime.Now - item.Value;
1141  text += string.Format("{0}: {1} | ", item.Key.Procedure.Name, duration.ToString("mm':'ss"));
1142  }
1143  text = text.TrimEnd(new char[] { ' ', '|' });
1144  }
1145 
1146  this.labelProcedureExecutionTimes.Text = text;
1147  this.labelSeparator1.Visible = true;
1148  this.labelProcedureExecutionTimes.Visible = true;
1149  }
1150 
1151  private void InOutParameterValueChanged(IRuntimeContext context, IProcedureInOutParameter parameter)
1152  {
1153  if (InvokeRequired)
1154  {
1155  Invoke(new MethodInvoker(delegate ()
1156  {
1157  InOutParameterValueChanged(context, parameter);
1158  }));
1159  return;
1160  }
1161 
1162  lock (eventListenerLock)
1163  {
1164  try
1165  {
1166  string valueStr = ShortenedValueString(parameter);
1167  string message = String.Format("Parameter '{0}' new value = {1}", parameter.Name, valueStr);
1168  PrintText(message);
1169  UpdateGridviewParameter(parameter);
1170  }
1171  catch (InvalidCastException ex)
1172  {
1173  PrintText(ex.Message);
1174  }
1175  }
1176  }
1177 
1178  private static string ShortenedValueString(IProcedureParameter parameter)
1179  {
1180  try
1181  {
1182  var valueStr = ValueConverter.Value2String(parameter.Value);
1183  if (valueStr.Length > VALUE_STRING_MAX_LENGTH)
1184  return valueStr.Substring(0, VALUE_STRING_MAX_LENGTH) + "...";
1185 
1186  return valueStr;
1187  }
1188  catch
1189  { }
1190 
1191  return string.Empty;
1192  }
1193 
1194  private void UpdatePauseButton(bool pauseAvailable, bool enabled = true)
1195  {
1196  this.buttonPause.Enabled = enabled;
1197  this.buttonPause.Checked = !pauseAvailable;
1198  this.buttonPause.Image = pauseAvailable
1199  ? global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.Pause
1200  : global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.Continue;
1201  }
1202 
1203  private void UpdateExecutionStateButtons(bool wasExecuted)
1204  {
1205  if (this.useConnectionState)
1206  {
1207  this.labelTimeout.Enabled = !wasExecuted;
1208  this.textBoxTimeout.Enabled = !wasExecuted;
1209  this.checkBoxUseConnectionState.Enabled = !wasExecuted;
1210  this.labelExpectedState.Enabled = !wasExecuted;
1211  this.checkBoxIgnition.Enabled = !wasExecuted;
1212  this.labelPollingTime.Enabled = !wasExecuted;
1213  this.textBoxPollingTime.Enabled = !wasExecuted;
1214  this.labelVoltageThreshold.Enabled = !wasExecuted;
1215  this.textBoxVoltageThreshold.Enabled = !wasExecuted;
1216  }
1217 
1218  if (wasExecuted)
1219  {
1220  if (checkBoxAsyncExecution.Checked == false)
1221  {
1222  this.buttonExecuteMain.Enabled = false;
1223  this.buttonExecuteSelectedProcedure.Enabled = false;
1224  }
1225 
1226  this.buttonStop.Enabled = true;
1227  }
1228  else
1229  {
1230  if (project != null && project.MainProcedure != null)
1231  {
1232  this.buttonExecuteMain.Enabled = true;
1233  }
1234 
1235  this.buttonExecuteSelectedProcedure.Enabled = true;
1236 
1237  this.buttonStop.Enabled = false;
1238  }
1239  }
1240 
1241  private void DisplayProcedureExecutionState(IRuntimeContext context, string errorMessage = "")
1242  {
1243  if (string.IsNullOrEmpty(errorMessage))
1244  {
1245  this.labelIconProcedureExecutionState.Image = global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.Info16;
1246 
1247  if (this.procedureExecutionCount <= 0)
1248  {
1249  this.procedureExecutionCount = 0;
1250  if (context.ExecutionState == ExecutionState.Paused)
1251  {
1252  this.labelProcedureExecutionState.Text = "Execution is paused, click \"Continue\"...";
1253  }
1254  else
1255  {
1256  this.labelProcedureExecutionState.Text = "Select a procedure and click \"Start\"...";
1257  }
1258  }
1259  else if (this.procedureExecutionCount == 1)
1260  {
1261  this.labelProcedureExecutionState.Text = "1 Procedure is running";
1262  }
1263  else
1264  {
1265  this.labelProcedureExecutionState.Text = string.Format("{0} Procedures are running", this.procedureExecutionCount);
1266  }
1267  }
1268  else
1269  {
1270  this.labelIconProcedureExecutionState.Image = global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.Error16;
1271  this.labelProcedureExecutionState.Text = errorMessage;
1272  }
1273  }
1274  private void SyncWithParent(object parentControl, object control = null, bool newThread = false)
1275  {
1276  if (parentControl != null)
1277  {
1278  if (this.creatorForm != null && this.checkBoxStartAllParents.Checked)
1279  {
1280  if (parentControl is Button)
1281  {
1282  if (newThread)
1283  {
1284  ThreadPool.QueueUserWorkItem(state => ParentButtonClick(parentControl as Button));
1285  }
1286  else
1287  {
1288  ParentButtonClick(parentControl as Button);
1289  }
1290  }
1291  else if (parentControl is TextBox && control != null)
1292  {
1293  string text = (control as TextBox).Text;
1294  if (newThread)
1295  {
1296  ThreadPool.QueueUserWorkItem(state => ParentTextBoxSetText(parentControl as TextBox, text));
1297  }
1298  else
1299  {
1300  ParentTextBoxSetText(parentControl as TextBox, text);
1301  }
1302  }
1303  else if (parentControl is CheckBox && control != null)
1304  {
1305  CheckState checkState = (control as CheckBox).CheckState;
1306  if (newThread)
1307  {
1308  ThreadPool.QueueUserWorkItem(state => ParentCheckBoxSetCheckState(parentControl as CheckBox, checkState));
1309  }
1310  else
1311  {
1312  ParentCheckBoxSetCheckState(parentControl as CheckBox, checkState);
1313  }
1314  }
1315  else if (parentControl is ComboBox && control != null)
1316  {
1317  int index = (control as ComboBox).SelectedIndex;
1318  if (newThread)
1319  {
1320  ThreadPool.QueueUserWorkItem(state => ParentComboBoxSetIndex(parentControl as ComboBox, index));
1321  }
1322  else
1323  {
1324  ParentComboBoxSetIndex(parentControl as ComboBox, index);
1325  }
1326  }
1327  else if (parentControl is NumericUpDown && control != null)
1328  {
1329  int value = decimal.ToInt32((control as NumericUpDown).Value);
1330  if (newThread)
1331  ThreadPool.QueueUserWorkItem(state => ParentNumericUpDownSetValue(parentControl as NumericUpDown, value));
1332  else
1333  ParentNumericUpDownSetValue(parentControl as NumericUpDown, value);
1334  }
1335  }
1336  }
1337  }
1338 
1339  private void ParentButtonClick(Button button)
1340  {
1341  if (button.InvokeRequired)
1342  {
1343  this.creatorForm.Invoke(new Action(() => button.PerformClick()));
1344  }
1345  else
1346  {
1347  button.PerformClick();
1348  }
1349  }
1350 
1351  private void ParentTextBoxSetText(TextBox textBox, string text)
1352  {
1353  if (textBox.InvokeRequired)
1354  {
1355  this.creatorForm.Invoke(new Action(() => textBox.Text = text));
1356  }
1357  else
1358  {
1359  textBox.Text = text;
1360  }
1361  }
1362 
1363  private void ParentCheckBoxSetCheckState(CheckBox checkBox, CheckState checkState)
1364  {
1365  if (checkBox.InvokeRequired)
1366  {
1367  this.creatorForm.Invoke(new Action(() => checkBox.CheckState = checkState));
1368  }
1369  else
1370  {
1371  checkBox.CheckState = checkState;
1372  }
1373  }
1374 
1375  private void ParentComboBoxSetIndex(ComboBox comboBox, int index)
1376  {
1377  if (comboBox.InvokeRequired)
1378  {
1379  this.creatorForm.Invoke(new Action(() => comboBox.SelectedIndex = index));
1380  }
1381  else
1382  {
1383  comboBox.SelectedIndex = index;
1384  }
1385  }
1386 
1387  private void buttonBrowseTraceFolder_Click(object sender, EventArgs e)
1388  {
1389  folderBrowserDialog1.SelectedPath = this.textBoxTraceFolder.Text;
1390  folderBrowserDialog1.ShowNewFolderButton = true;
1391 
1392  DialogResult result = folderBrowserDialog1.ShowDialog();
1393  if (result == DialogResult.OK)
1394  {
1395  this.textBoxTraceFolder.Text = folderBrowserDialog1.SelectedPath;
1396  }
1397  }
1398 
1399  private void buttonOpenTraceFolder_Click(object sender, EventArgs e)
1400  {
1401  string path = this.textBoxTraceFolder.Text;
1402  if (Directory.Exists(path))
1403  {
1404  Process.Start(path);
1405  }
1406  }
1407 
1408  // This will not automatically update GUI if it is modified internally
1409  private void textBoxTraceFolder_TextChanged(object sender, EventArgs e)
1410  {
1411  if (this.globalRuntimeManager == null)
1412  return;
1413 
1414  string path = this.textBoxTraceFolder.Text;
1415 
1416  if (path != RuntimeConfig.Instance.TraceFolder)
1417  {
1418  if (Directory.Exists(path))
1419  {
1420  RuntimeConfig.Instance.TraceFolder = textBoxTraceFolder.Text;
1421  this.buttonOpenTraceFolder.Enabled = true;
1422 
1423  PrintText("Set trace folder to " + RuntimeConfig.Instance.TraceFolder);
1424  }
1425  else
1426  {
1427  this.buttonOpenTraceFolder.Enabled = false;
1428  }
1429  }
1430  else
1431  {
1432  this.buttonOpenTraceFolder.Enabled = true;
1433  }
1434 
1435  SyncWithParent(this.creatorForm?.textBoxTraceFolder, this.textBoxTraceFolder);
1436  }
1437 
1438  // This will not automatically update GUI if it is modified internally
1439  private void comboBoxTraceLevel_SelectedValueChanged(object sender, EventArgs e)
1440  {
1441  if (this.globalRuntimeManager == null)
1442  return;
1443 
1444  var traceLevel = (TraceLevels)comboBoxTraceLevel.SelectedIndex;
1445  if (traceLevel == RuntimeConfig.Instance.TraceLevel)
1446  return;
1447 
1448  RuntimeConfig.Instance.TraceLevel = traceLevel;
1449  PrintText("Updated trace level");
1450  }
1451 
1452  private void buttonBrowseFile_Click(object sender, EventArgs e)
1453  {
1454  DialogResult result = openFileDialog1.ShowDialog();
1455  if (result == DialogResult.OK)
1456  {
1457  cbFilePath.Text = openFileDialog1.FileName;
1458 
1459  this.buttonReload.PerformClick();
1460  }
1461  }
1462 
1463  private void cbFilePath_TextChanged(object sender, EventArgs e)
1464  {
1465  AddComboBoxFileOrPath(cbFilePath);
1466 
1467  if (String.IsNullOrWhiteSpace(cbFilePath.Text) || !File.Exists(cbFilePath.Text.Trim()))
1468  {
1469  buttonReload.Enabled = false;
1470  }
1471  else
1472  {
1473  buttonReload.Enabled = true;
1474  }
1475 
1476  SyncWithParent(this.creatorForm?.cbFilePath, this.cbFilePath);
1477  }
1478 
1479  private void cbFilePath_SelectedValueChanged(object sender, EventArgs e)
1480  {
1481  if (String.IsNullOrWhiteSpace(cbFilePath.Text) || !File.Exists(cbFilePath.Text.Trim()))
1482  {
1483  buttonReload.Enabled = false;
1484  }
1485  else
1486  {
1487  buttonReload.Enabled = true;
1488  this.buttonReload.PerformClick();
1489  }
1490 
1491  SyncWithParent(this.creatorForm?.cbFilePath, this.cbFilePath);
1492  }
1493 
1494  private void buttonReload_Click(object sender, EventArgs e)
1495  {
1496  this.LoadContextFile(this.globalRuntimeManager);
1497 
1498  SyncWithParent(this.creatorForm?.buttonReload);
1499  }
1500 
1501  private void LoadContextFile(IRuntimeManager runtimeManager)
1502  {
1503  PrintText("Load '" + cbFilePath.Text + "'...");
1504 
1505  if (runtimeManager == null)
1506  {
1507  PrintText("... No RuntimeManager exists!");
1508  return;
1509  }
1510 
1511  if (String.IsNullOrWhiteSpace(cbFilePath.Text.Trim()))
1512  {
1513  PrintText("... wrong file name.");
1514  return;
1515  }
1516 
1517  SetTitle(this.title);
1518 
1519  try
1520  {
1521  // TODO: move these 3 set up away
1522  this.isLoadding = true;
1523  this.playerProject = null;
1524  this.project = null;
1525  this.contextVariableImplementation.ResetAllValues();
1526  this.stateVariableImplementation.ResetAllValues();
1527  ClearSampleGUI();
1528 
1529  if (Path.GetExtension(cbFilePath.Text.Trim()).Contains("ptx"))
1530  {
1531  this.project = LoadPtx(runtimeManager);
1532 
1533  if (this.project != null) // TODO: might be obsolete in the future
1534  {
1535  PrintText("... Project '" + project.Name + "' successfully loaded.");
1536 
1537  ClearCustomImplemetationCaches();
1538 
1539  this.LoadPackage(this.project);
1540 
1541  ReadSettings(this.project.Settings);
1542 
1543  this.isLoadding = false;
1544  return;
1545  }
1546  }
1547  else if (Path.GetExtension(cbFilePath.Text.Trim()).Contains("ppx"))
1548  {
1549  this.playerProject = LoadPpx(runtimeManager);
1550 
1551  if (this.playerProject != null) // TODO: might be obsolete in the future
1552  {
1553  ClearCustomImplemetationCaches();
1554 
1555  PrintText("... Player '" + playerProject.Name + "' successfully loaded.");
1556 
1557  foreach (IProject item in this.playerProject.Projects)
1558  {
1559  project = item; // TODO: what is this?
1560  this.LoadPackage(item);
1561  }
1562 
1563  ReadSettings(this.playerProject.Settings);
1564 
1565  this.isLoadding = false;
1566  return;
1567  }
1568  }
1569  }
1570  catch (System.Exception ex)
1571  {
1572  PrintException(ex);
1573  }
1574 
1575  this.isLoadding = false;
1576  }
1577 
1578  private void ClearSampleGUI()
1579  {
1580  this.treeViewOtxProject.Nodes.Clear();
1581  this.gridViewParameter.Rows.Clear();
1582  this.gridViewContext.Rows.Clear();
1583  this.gridViewState.Rows.Clear();
1584  this.gridViewSettings.Rows.Clear();
1585  }
1586 
1587  private void ClearCustomImplemetationCaches()
1588  {
1589  if (this.contextVariableImplementation != null)
1590  this.contextVariableImplementation.ResetAllValues();
1591 
1592  if (this.contextVariableOutputImpl != null)
1593  this.contextVariableOutputImpl.ResetAllValues();
1594 
1595  if (this.stateVariableImplementation != null)
1596  this.stateVariableImplementation.ResetAllValues();
1597 
1598  //TODO: if (this.stateVariableOutputImpl != null)
1599  }
1600 
1601  // TODO: refactor
1602  private IProject LoadPtx(IRuntimeManager runtimeManager)
1603  {
1604  IProject project = null;
1605 
1606  if (runtimeManager.IsProtected(cbFilePath.Text))
1607  {
1608  project = runtimeManager.LoadPtx(cbFilePath.Text, txtPassword.Text.Trim());
1609  }
1610  else
1611  {
1612  project = runtimeManager.LoadPtx(cbFilePath.Text);
1613  }
1614 
1615  if (project.MainProcedure != null)
1616  {
1617  buttonExecuteMain.Enabled = true;
1618  }
1619 
1620  return project;
1621  }
1622 
1623  // TODO: refactor
1624  private IPlayerProject LoadPpx(IRuntimeManager runtimeManager)
1625  {
1626  IPlayerProject playerProject = null;
1627 
1628  if (runtimeManager.IsProtected(cbFilePath.Text))
1629  {
1630  playerProject = runtimeManager.LoadPpx(cbFilePath.Text, txtPassword.Text.Trim());
1631  }
1632  else
1633  {
1634  playerProject = runtimeManager.LoadPpx(cbFilePath.Text);
1635  }
1636 
1637  return playerProject;
1638  }
1639 
1640  // TODO: refactor
1641  private void LoadPackage(IProject project)
1642  {
1643  PrintText("Browse project...");
1644 
1645  IPackage[] packages = project.Packages;
1646  if (packages == null)
1647  {
1648  IDocument document = project.StartupDocument;
1649  this.treeViewOtxProject.Nodes.Add(CreateDocumentNode(document));
1650  }
1651  else
1652  {
1653  string treeNodeText = project.Name;
1654  if (!String.IsNullOrWhiteSpace(project.Version))
1655  treeNodeText = String.Format("{0} ({1})", treeNodeText, project.Version);
1656 
1657  TreeNode root = new TreeNode(treeNodeText);
1658  root.ImageKey = root.SelectedImageKey = "ODFProject.bmp"; // TODO: move
1659  foreach (IPackage pack in packages)
1660  {
1661  root.Nodes.Add(this.CreatePackageNode(pack));
1662  }
1663 
1664  this.treeViewOtxProject.Nodes.Add(root);
1665  }
1666 
1667  this.treeViewOtxProject.Enabled = this.gridViewParameter.Enabled = true;
1668  this.treeViewOtxProject.ExpandAll();
1669  this.treeViewOtxProject.SelectedNode = startupNode;
1670  this.treeViewOtxProject.Focus();
1671 
1672  PrintText("... project browsing finished.");
1673  }
1674 
1675  // TODO: refactor
1676  private TreeNode CreateDocumentNode(IDocument doc)
1677  {
1678  TreeNode documentNode = new TreeNode(doc.Name);
1679  documentNode.Tag = doc;
1680  documentNode.ImageKey = documentNode.SelectedImageKey = "DocumentOTX16.bmp";
1681  if (doc.IsStartup)
1682  {
1683  documentNode.Text += " (StartUp)";
1684  }
1685 
1686  foreach (IProcedure p in doc.Procedures)
1687  {
1688  TreeNode procedureNode = CreateProcedureNode(p);
1689  documentNode.Nodes.Add(procedureNode);
1690  if (doc.IsStartup && p.Name == "main")
1691  {
1692  startupNode = procedureNode;
1693  buttonExecuteMain.Enabled = true;
1694  }
1695  else if (startupNode == null)
1696  {
1697  startupNode = procedureNode;
1698  }
1699  }
1700 
1701  return documentNode;
1702  }
1703 
1704  // TODO: refactor
1705  private TreeNode CreateProcedureNode(IProcedure procedure)
1706  {
1707  if (checkBoxCyclicReload.Checked &&
1708  procedureToExecute != null &&
1709  procedureToExecute.FullName == procedure.FullName)
1710  {
1711  procedureToExecute = procedure;
1712  }
1713 
1714  TreeNode procedureNode = new TreeNode(procedure.Name);
1715  procedureNode.ImageKey = procedureNode.SelectedImageKey = "Procedure.bmp"; // TODO: move
1716  procedureNode.Tag = procedure;
1717  return procedureNode;
1718  }
1719 
1720  // TODO: refactor
1721  private TreeNode CreatePackageNode(IPackage pack)
1722  {
1723  TreeNode packageNode = new TreeNode(pack.Name);
1724  packageNode.Tag = pack;
1725  packageNode.ImageKey = packageNode.SelectedImageKey = "Package.bmp"; // TODO: move
1726 
1727  List<IDocument> documents = pack.Documents.ToList();
1728  foreach (IDocument doc in documents)
1729  {
1730  packageNode.Nodes.Add(CreateDocumentNode(doc));
1731  }
1732 
1733  foreach (IPackage package in pack.Packages)
1734  {
1735  packageNode.Nodes.Add(this.CreatePackageNode(package));
1736  }
1737 
1738  return packageNode;
1739  }
1740 
1741  // Commit new value for gridView's data source (only apply for DataGridViewCheckBoxCell and DataGridViewComboBoxCell)
1742  private void gridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
1743  {
1744  DataGridView gridView = sender as DataGridView;
1745  string columnName;
1746 
1747  if (gridView == this.gridViewParameter)
1748  {
1749  columnName = dataGridViewTextBoxColumnValue.Name;
1750  }
1751  else if (gridView == this.gridViewContext)
1752  {
1753  columnName = dataGridViewTextBoxColumnContextValue.Name;
1754  }
1755  else
1756  {
1757  return;
1758  }
1759 
1760  if (!this.isLoadding && e.RowIndex >= 0 && gridView.Columns[e.ColumnIndex].Name == columnName &&
1761  (
1762  gridView.Rows[e.RowIndex].Cells[columnName] is DataGridViewCheckBoxCell ||
1763  gridView.Rows[e.RowIndex].Cells[columnName] is DataGridViewComboBoxCell
1764  )
1765  )
1766  {
1767  // Force a validation to set the value after CheckBox click
1768  this.Validate(false);
1769  }
1770  }
1771 
1772  // Convert parameter's value into valid string then display it on gridview
1773  void gridViewParameter_CellValidated(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
1774  {
1775  DataGridView gridView = sender as DataGridView;
1776  if (!this.isLoadding && gridView != null && e.RowIndex >= 0 && gridView.Columns[e.ColumnIndex].Name == dataGridViewTextBoxColumnValue.Name)
1777  {
1778  IProcedureParameter parameter = gridView.Rows[e.RowIndex].Tag as IProcedureParameter;
1779  if (parameter.Value != null)
1780  {
1781  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnValue.Name].Value = ConvertValue2String(parameter.Value);
1782  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnDetails.Name].Value = GetDetails(parameter.Value);
1783  }
1784  }
1785  }
1786 
1787  // Trigger if the "value" cell is changed, convert new string into new value,
1788  // then set into corresponding parameter (only apply for IProcedureInParameter and IProcedureInOutParameter)
1789  void gridViewParameter_CellValidating(object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
1790  {
1791  DataGridView gridView = sender as DataGridView;
1792  if (!this.isLoadding && gridView != null && e.RowIndex >= 0 &&
1793  gridView.Columns[e.ColumnIndex].Name == dataGridViewTextBoxColumnValue.Name &&
1794  !gridView.Rows[e.RowIndex].ReadOnly &&
1795  e.FormattedValue != null)
1796  {
1797  IProcedureParameter parameter = gridView.Rows[e.RowIndex].Tag as IProcedureParameter;
1798  if (e.FormattedValue.ToString() == ValueConverter.Value2String(parameter.Value) || e.FormattedValue.ToString() == ConvertValue2String(parameter.Value))
1799  {
1800  return;
1801  }
1802 
1803  object value = null;
1804 
1805  try
1806  {
1807  value = ValueConverter.String2Value(e.FormattedValue.ToString(), parameter.DataType);
1808  }
1809  catch (System.Exception ex)
1810  {
1811  //string errorMsg = ex.GetType().FullName;
1812  //errorMsg += Environment.NewLine;
1813  //errorMsg += ex.Message;
1814  //gridView.Rows[e.RowIndex].Cells[1].ErrorText = errorMsg;
1815  PrintException(ex);
1816  // e.Cancel = true;
1817  return;
1818  }
1819 
1820  if (value == null)
1821  {
1822  System.Media.SystemSounds.Exclamation.Play();
1823  }
1824  else
1825  {
1826  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnDataType.Name].ErrorText = string.Empty;
1827  if (parameter is IProcedureInParameter)
1828  (parameter as IProcedureInParameter).Value = value;
1829  else if (parameter is IProcedureInOutParameter)
1830  (parameter as IProcedureInOutParameter).Value = value;
1831  }
1832  }
1833  }
1834 
1835  //private void GridViewParameter_CellEndEdit(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
1836  //{
1837  // DataGridView gridView = sender as DataGridView;
1838  // gridView.Rows[e.RowIndex].Cells[1].ErrorText = string.Empty;
1839  //}
1840 
1841  void gridViewContextVariable_CellValidated(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
1842  {
1843  DataGridView gridView = sender as DataGridView;
1844  if (!this.isLoadding && gridView != null &&
1845  e.RowIndex >= 0 &&
1846  gridView.Columns[e.ColumnIndex].Name == dataGridViewTextBoxColumnContextValue.Name)
1847  {
1848  IContextVariable context = gridView.Rows[e.RowIndex].Tag as IContextVariable;
1849  if (gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag != null)
1850  {
1851  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Value = ConvertValue2String(gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag);
1852  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextDetails.Name].Value = GetDetails(gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag);
1853  }
1854  }
1855  }
1856 
1857  // TODO: refactor. consider update to use together with Parameter validating?
1858  void gridViewContextVariable_CellValidating(object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
1859  {
1860  DataGridView gridView = sender as DataGridView;
1861  if (!this.isLoadding && gridView != null &&
1862  e.RowIndex >= 0 &&
1863  gridView.Columns[e.ColumnIndex].Name == dataGridViewTextBoxColumnContextValue.Name &&
1864  !gridView.Rows[e.RowIndex].ReadOnly &&
1865  e.FormattedValue != null)
1866  {
1867  IContextVariable context = gridView.Rows[e.RowIndex].Tag as IContextVariable;
1868  if (e.FormattedValue.ToString() == ValueConverter.Value2String(gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag) || e.FormattedValue.ToString() == ConvertValue2String(gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag))
1869  {
1870  return;
1871  }
1872 
1873  object value = null;
1874 
1875  try
1876  {
1877  value = ValueConverter.String2Value(e.FormattedValue.ToString(), context.DataType);
1878  }
1879  catch (System.Exception ex)
1880  {
1881  //string errorMsg = ex.GetType().FullName;
1882  //errorMsg += Environment.NewLine;
1883  //errorMsg += ex.Message;
1884  //gridView.Rows[e.RowIndex].Cells[1].ErrorText = errorMsg;
1885  PrintException(ex);
1886  // e.Cancel = true;
1887  return;
1888  }
1889 
1890  if (value == null)
1891  {
1892  System.Media.SystemSounds.Exclamation.Play();
1893  }
1894  else
1895  {
1896  //we will save value with fullName of context, if not the bug of #10798 occurs.
1897  //Because the name of context variable in imported document may have the same name.
1898  string fullNameContextVariable = context.Document.FullName + '.' + context.Name;
1899  this.contextVariableImplementation.SetValue(fullNameContextVariable, value);
1900  this.contextVariableOutputImpl.SetValue(fullNameContextVariable, value);
1901  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag = value;//used at gridViewContextVariable_CellValidated
1902  gridView.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumnContextDataType.Name].ErrorText = string.Empty; //refresh error text
1903  }
1904  }
1905  }
1906 
1907  //private void gridViewContextVariable_CellEndEdit(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
1908  //{
1909  // DataGridView gridView = sender as DataGridView;
1910  // gridView.Rows[e.RowIndex].Cells[1].ErrorText = string.Empty;
1911  //}
1912 
1913  private void treeViewOtxProject_AfterSelect(object sender, TreeViewEventArgs e)
1914  {
1915  TreeNode node = e.Node;
1916  if (node != null)
1917  {
1918  // TODO: move to different method
1919  this.gridViewParameter.Rows.Clear();
1920  this.gridViewContext.Rows.Clear();
1921  this.gridViewState.Rows.Clear();
1922 
1923  if (node.Tag is IProcedure)
1924  {
1925  IProcedure procedure = node.Tag as IProcedure;
1926  ClearCustomImplemetationCaches();
1927  UpdateGridview(procedure);
1928 
1929  buttonExecuteSelectedProcedure.Enabled = true;
1930  this.project = GetProject(procedure); // TODO: why update this???
1931  return;
1932  }
1933  }
1934 
1935  buttonExecuteSelectedProcedure.Enabled = false;
1936  }
1937 
1938  // TODO: refactor
1939  private IProject GetProject(IProcedure procedure)
1940  {
1941  if (procedure != null)
1942  {
1943  IPackage package = procedure.Document.Package;
1944  if (package != null)
1945  {
1946  while (package.Parent != null)
1947  {
1948  package = package.Parent;
1949  }
1950 
1951  return package.Project;
1952  }
1953  }
1954  return null;
1955  }
1956 
1957  private void treeViewOtxProject_DrawNode(object sender, DrawTreeNodeEventArgs e)
1958  {
1959  e.DrawDefault = true;
1960  }
1961 
1962  // TODO: refactor
1963  private void buttonReadSettings_Click(object sender, EventArgs e)
1964  {
1965  Dictionary<string, string> settings = null;
1966  if (this.playerProject != null)
1967  {
1968  settings = this.playerProject.Settings;
1969  }
1970  else if (this.project != null)
1971  {
1972  settings = this.project.Settings;
1973  }
1974  ReadSettings(settings);
1975  }
1976 
1977  private void ReadSettings(Dictionary<string, string> settings)
1978  {
1979  if (settings != null)
1980  {
1981  PrintText("Read settings");
1982 
1983  gridViewSettings.Rows.Clear();
1984 
1985  foreach (KeyValuePair<string, string> setting in settings)
1986  {
1987  object[] values = new object[] { setting.Key, setting.Value };
1988  this.gridViewSettings.Rows.Add(values);
1989  }
1990  }
1991  }
1992 
1993  // TODO: refactor
1994  private void buttonWriteSettings_Click(object sender, EventArgs e)
1995  {
1996  string nameSetting;
1997  string valueSetting;
1998  int selectedSettingPosition = 0;
1999  Dictionary<string, string> newSettings = new Dictionary<string, string>();
2000 
2001  if (this.gridViewSettings.SelectedRows.Count != 0)
2002  {
2003  selectedSettingPosition = this.gridViewSettings.SelectedRows[0].Index;
2004  }
2005 
2006  try
2007  {
2008  if (project != null || playerProject != null)
2009  {
2010  foreach (DataGridViewRow row in this.gridViewSettings.Rows)
2011  {
2012  nameSetting = row.Cells[this.dataGridViewTextBoxColumnSettingName.Name].Value.ToString();
2013  valueSetting = row.Cells[this.dataGridViewTextBoxColumnSettingValue.Name].Value?.ToString();
2014 
2015  newSettings.Add(nameSetting, valueSetting);
2016  }
2017 
2018  if (playerProject != null)
2019  {
2020  playerProject.Settings = newSettings;
2021  ReadSettings(playerProject.Settings); //Refresh gridViewSettings
2022  }
2023  else
2024  {
2025  project.Settings = newSettings;
2026  ReadSettings(project.Settings); //Refresh gridViewSettings
2027  }
2028  //focus on previous selected row
2029  this.gridViewSettings.Rows[selectedSettingPosition].Selected = true;
2030  this.gridViewSettings.Rows[selectedSettingPosition].Cells[dataGridViewTextBoxColumnSettingValue.Name].Selected = true;
2031 
2032  PrintText("Write settings finished");
2033  }
2034  }
2035  catch (System.Exception ex)
2036  {
2037  PrintException(ex);
2038  }
2039  }
2040 
2041  private void checkBoxCyclicExecution_CheckedChanged(object sender, EventArgs e)
2042  {
2043  this.checkBoxCyclicReload.Enabled = this.checkBoxNewRuntimeManager.Enabled = this.checkBoxCyclicExecution.Checked;
2044 
2045  if (!this.checkBoxCyclicExecution.Checked)
2046  {
2047  this.checkBoxCyclicReload.Checked = this.checkBoxNewRuntimeManager.Checked = false;
2048  }
2049 
2050  SyncWithParent(this.creatorForm?.checkBoxCyclicExecution, this.checkBoxCyclicExecution);
2051  }
2052 
2053  private void checkBoxAsyncExecution_CheckedChanged(object sender, EventArgs e)
2054  {
2055  SyncWithParent(this.creatorForm?.checkBoxAsyncExecution, this.checkBoxAsyncExecution);
2056  }
2057 
2058  private void checkBoxNewRuntimeManager_CheckedChanged(object sender, EventArgs e)
2059  {
2060  if (this.checkBoxNewRuntimeManager.Checked)
2061  {
2062  this.checkBoxCyclicReload.Checked = true;
2063  }
2064 
2065  SyncWithParent(this.creatorForm?.checkBoxNewRuntimeManager, this.checkBoxNewRuntimeManager);
2066  }
2067 
2068  private void checkBoxCyclicReload_CheckedChanged(object sender, EventArgs e)
2069  {
2070  SyncWithParent(this.creatorForm?.checkBoxCyclicReload, this.checkBoxCyclicReload);
2071  }
2072 
2073  // TODO: refactor
2074  private void buttonExecuteSelectedProcedure_Click(object sender, EventArgs e)
2075  {
2076  try
2077  {
2078  if (treeViewOtxProject.SelectedNode != null && treeViewOtxProject.SelectedNode.Tag is IProcedure)
2079  {
2080  IDocument document = treeViewOtxProject.SelectedNode.Parent.Tag as IDocument;
2081  List<string> listItemsReviewed = new List<string>();
2082 
2083  this.procedureToExecute = treeViewOtxProject.SelectedNode.Tag as IProcedure;
2084  this.ExecuteProcedure();
2085  }
2086  else
2087  {
2088  PrintText("Please select Procedure to execute");
2089  }
2090 
2091  }
2092  catch (System.Exception ex)
2093  {
2094  PrintException(ex);
2095  }
2096 
2097  SyncWithParent(this.creatorForm?.buttonExecuteSelectedProcedure, null, true);
2098  }
2099 
2100 
2101  // TODO: refactor
2102  private void buttonExecuteMain_Click(object sender, EventArgs e)
2103  {
2104  try
2105  {
2106  if (project != null)
2107  {
2108  treeViewOtxProject.SelectedNode = startupNode;
2109  this.procedureToExecute = project.MainProcedure;
2110  this.ExecuteProcedure();
2111  }
2112  else
2113  {
2114  PrintText("There is no project has been loaded. Please reload the project");
2115  }
2116  }
2117  catch (System.Exception ex)
2118  {
2119  PrintException(ex);
2120  }
2121 
2122  SyncWithParent(this.creatorForm?.buttonExecuteMain, null, true);
2123  }
2124 
2125  // TODO: refactor
2126  private async void ExecuteProcedure()
2127  {
2128  PrintText("Start procedure execution...");
2129 
2130  if (checkBoxAsyncExecution.Checked == false)
2131  {
2132  this.buttonExecuteMain.Enabled = false;
2133  this.buttonExecuteSelectedProcedure.Enabled = false;
2134  }
2135 
2136  try
2137  {
2138  if (this.globalRuntimeManager != null && procedureToExecute != null)
2139  {
2140  this.buttonStop.Enabled = true;
2141 
2142  CheckBatteryIgnitionState(this.globalRuntimeManager);
2143 
2144  if (checkBoxCyclicExecution.Checked)
2145  {
2146  ThreadPool.QueueUserWorkItem(state => DoCyclic());
2147  }
2148  else
2149  {
2150  //OtxDiagManager.OtxDiagApi.License.LicenseManager.SetLicenseKey(SampleConstants.LICENSE_KEY);
2151  if (checkBoxAsyncExecution.Checked)
2152  {
2153  this.globalRuntimeManager.ExecuteAsync(textBoxRuntimeContextName.Text.Trim(), procedureToExecute, this.expectedConnectionState, (ulong)Convert.ToInt32(this.textBoxTimeout.Text));
2154  }
2155  else
2156  {
2157  await Task.Run(() => this.globalRuntimeManager.Execute(textBoxRuntimeContextName.Text.Trim(), procedureToExecute, this.expectedConnectionState, (ulong)Convert.ToInt32(this.textBoxTimeout.Text)));
2158  }
2159  }
2160  }
2161  else
2162  {
2163  PrintText("RuntimeManager is null or no Procedure is selected to run.");
2164  }
2165  }
2166  catch (System.Exception ex)
2167  {
2168  PrintException(ex);
2169 
2170  UpdateButtonStateAfterThrowException();
2171  }
2172  }
2173 
2174  private void UpdateButtonStateAfterThrowException()
2175  {
2176  this.buttonExecuteMain.Enabled = !checkBoxCyclicExecution.Checked;
2177  this.buttonExecuteSelectedProcedure.Enabled = !checkBoxCyclicExecution.Checked;
2178 
2179  UpdateExecutionStateButtons(false);
2180  UpdatePauseButton(true, false);
2181 
2182  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
2183  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
2184  }
2185 
2186  // TODO: refactor
2187  private void DoCyclic()
2188  {
2189  DateTime startTime = DateTime.Now;
2190 
2191  int cyclic = 0;
2192  try
2193  {
2194  while (checkBoxCyclicExecution.Checked)
2195  {
2196  IRuntimeManager runtimeManager = null;
2197  IRuntimeContext runtimeContext = null;
2198 
2199  cyclic++;
2200  this.cyclicExecutionCount++;
2201 
2202  if (this.checkBoxNewRuntimeManager.Checked)
2203  {
2204  runtimeManager = CreateRuntimeManager();
2205  }
2206  else
2207  {
2208  runtimeManager = this.globalRuntimeManager;
2209  }
2210 
2211  CheckCyclicReloadOrNewRuntimeManager(runtimeManager);
2212 
2213  cyclicExecuteAsyncIsProcessing = true;
2214  CheckBatteryIgnitionState(this.globalRuntimeManager);
2215 
2216  if (this.checkBoxAsyncExecution.Checked)
2217  {
2218  runtimeContext = runtimeManager.ExecuteAsync(textBoxRuntimeContextName.Text.Trim(), procedureToExecute, this.expectedConnectionState, (ulong)Convert.ToInt32(this.textBoxTimeout.Text));
2219  if (runtimeContext != null)
2220  {
2221  //Let it break for a little bit to avoid freezing the GUI
2222  Application.DoEvents();
2223  Thread.Sleep(50);
2224  }
2225  }
2226  else
2227  {
2228  runtimeContext = runtimeManager.Execute(textBoxRuntimeContextName.Text.Trim(), procedureToExecute, this.expectedConnectionState, (ulong)Convert.ToInt32(this.textBoxTimeout.Text));
2229  }
2230 
2231  if (runtimeContext.ExecutionState == ExecutionState.Stopped)
2232  {
2233  this.cyclicExecutionCount = 0;
2234  break;
2235  }
2236  }
2237  }
2238  catch (System.Exception ex)
2239  {
2240  PrintException(ex);
2241 
2242  UpdateButtonStateAfterThrowException();
2243  }
2244 
2245  //TODO: Do we need to load this again?
2246  Invoke(new MethodInvoker(delegate ()
2247  {
2248  if (this.checkBoxNewRuntimeManager.Checked)
2249  {
2250  LoadContextFile(this.globalRuntimeManager);
2251  }
2252  }));
2253 
2254  PrintText("Cyclic execution finished");
2255 
2256  var duration = DateTime.Now - startTime;
2257  string text = String.Format("Execution Statistics: Duration {0} (hh:mm:ss) with {1} cycles and {2:0} ms per cycle", duration.ToString(@"hh\:mm\:ss"), cyclic, duration.TotalMilliseconds / cyclic);
2258 
2259  this.cyclicExecutionCount -= cyclic;
2260  if (this.cyclicExecutionCount < 0)
2261  {
2262  this.cyclicExecutionCount = 0;
2263  }
2264 
2265  if (this.checkBoxAdd2Output.Checked)
2266  {
2267  PrintText(text);
2268  }
2269  else
2270  {
2271  MessageBox.Show(text);
2272  }
2273  }
2274  private void WaitCyclicExecuteAsyncIsProcessing()
2275  {
2276  if (this.checkBoxCyclicReload.Checked || this.checkBoxNewRuntimeManager.Checked)
2277  {
2278  // OR while (!(runtimeContext.IsFinished || runtimeContext.IsStopped))
2279  while (cyclicExecuteAsyncIsProcessing)
2280  {
2281  //detail in #10461
2282  Application.DoEvents();
2283  Thread.Sleep(50);
2284  }
2285  }
2286  }
2287 
2288  private void CheckCyclicReloadOrNewRuntimeManager(IRuntimeManager runtimeMgr, bool waitCyclic = true)
2289  {
2290  if (waitCyclic)
2291  {
2292  WaitCyclicExecuteAsyncIsProcessing();
2293  }
2294 
2295  if (InvokeRequired)
2296  {
2297  Invoke(new MethodInvoker(delegate ()
2298  {
2299  CheckCyclicReloadOrNewRuntimeManager(runtimeMgr, false);
2300  }));
2301  return;
2302  }
2303 
2304  if (this.checkBoxCyclicReload.Checked || this.checkBoxNewRuntimeManager.Checked)
2305  {
2306  LoadContextFile(runtimeMgr);
2307  }
2308 
2309  if (this.checkBoxCyclicExecution.Checked)
2310  {
2311  this.checkBoxCyclicExecution.Text = "Cyclic (" + this.cyclicExecutionCount + ")";
2312  }
2313  else
2314  {
2315  this.checkBoxCyclicExecution.Text = "Cyclic";
2316  }
2317  }
2318 
2319  // TODO: refactor
2320  private void buttonStop_Click(object sender, EventArgs e)
2321  {
2322  if (this.globalRuntimeManager != null)
2323  {
2324  PrintText(String.Format("Try to stop all running procedures..."));
2325  this.globalRuntimeManager.StopAll();
2326  this.procedureExecutionCount = 0;
2327  }
2328 
2329  // To make sure that cyclic execution will stop in some cases
2330  this.checkBoxCyclicExecution.Checked = false;
2331 
2332  SyncWithParent(this.creatorForm?.buttonStop);
2333  }
2334 
2335  private void PrintException(System.Exception ex, string additionalText = "")
2336  {
2337  PrintText(String.Format("!!! {2}{0}: {1}", ex.GetType().Name, ex.Message, additionalText));
2338  System.Media.SystemSounds.Hand.Play();
2339  }
2340 
2341  private void PrintText(string text)
2342  {
2343  if (InvokeRequired)
2344  {
2345  this.Invoke(new Action(() => PrintText(text)));
2346  return;
2347  }
2348 
2349  if (!this.checkBoxAdd2Output.Checked)
2350  {
2351  return;
2352  }
2353 
2354  // TODO: handle multithreading?
2355  lock (printTextLock)
2356  {
2357  if (this.listBoxOuput.Items.Count >= 10000)
2358  {
2359  buttonClearOutput_Click(null, null);
2360  }
2361 
2362  string prefixString = GetTimeAndDurationStringSinceLastTimeAndUpdateLastTime();
2363  string itemToAdd = prefixString + text + "\t\t";
2364 
2365  this.listBoxOuput.Items.Add(itemToAdd);
2366  this.listBoxOuput.SelectedItems.Clear();
2367  this.listBoxOuput.TopIndex = listBoxOuput.Items.Count - 1;
2368 
2369  if (this.listBoxOuput.Items.Count >= 7500)
2370  {
2371  this.labelOutputOverflow.Visible = true;
2372  }
2373 
2374  // If many procedures are running simultaneously,
2375  // Stop button or other controls cannot receive events. This code allows controls to receive events.
2376  Application.DoEvents();
2377  }
2378  }
2379 
2380  private string GetTimeAndDurationStringSinceLastTimeAndUpdateLastTime()
2381  {
2382  DateTime now = DateTime.Now;
2383  var duration = now - this.lastTime;
2384 
2385  this.lastTime = now;
2386 
2387  string timeDurationString = String.Format("{0:HH:mm:ss.fff} {1,6:#,##0} ms ", now, duration.TotalMilliseconds);
2388  return timeDurationString;
2389  }
2390 
2391  private void buttonCopyRow_Click(object sender, EventArgs e)
2392  {
2393  if (this.listBoxOuput.SelectedItems != null)
2394  {
2395  string text = string.Empty;
2396  foreach (string row in this.listBoxOuput.SelectedItems)
2397  {
2398  text += row.Trim('\t') + "\n";
2399  }
2400 
2401  Clipboard.SetText(text);
2402  }
2403  }
2404 
2405  private void buttonClearOutput_Click(object sender, EventArgs e)
2406  {
2407  this.listBoxOuput.Items.Clear();
2408  this.labelOutputOverflow.Visible = false;
2409  this.buttonCopyRow.Enabled = false;
2410  }
2411 
2412  // TODO: refactor
2413  private void UpdateGridview(IProcedure procedure)
2414  {
2415  if (procedure == null ||
2416  procedure.Parameters == null)
2417  {
2418  return;
2419  }
2420 
2421  UpdateGridviewParameter(procedure);
2422 
2423  IDocument document = procedure.Document;
2424  if (document != null)
2425  {
2426  List<string> listItemsReviewed = new List<string>();
2427  UpdateGridViewContextVariable(document, false, listItemsReviewed);
2428 
2429  listItemsReviewed.Clear();
2430  UpdateGridViewStateVariable(document, false, listItemsReviewed);
2431  }
2432  }
2433 
2434  private void UpdateGridviewParameter(IProcedure procedure)
2435  {
2436  foreach (IProcedureParameter param in procedure.Parameters)
2437  {
2438  UpdateGridviewParameter(param);
2439  }
2440  }
2441 
2442  // TODO: refactor
2443  private void UpdateGridviewParameter(IProcedureParameter parameter)
2444  {
2445  if (parameter == null)
2446  {
2447  return;
2448  }
2449 
2450  bool bValueWasSet = false;
2451 
2452  // Update existing value
2453  string collumnName = dataGridViewTextBoxColumnName.Name;
2454  string collumnValue = dataGridViewTextBoxColumnValue.Name;
2455  string collumnDetails = dataGridViewTextBoxColumnDetails.Name;
2456  foreach (DataGridViewRow row in this.gridViewParameter.Rows)
2457  {
2458  if (row.Cells[collumnName].Value.Equals(parameter.Name))
2459  {
2460  try
2461  {
2462  if (parameter.Value != null)
2463  {
2464  row.Cells[collumnValue].Value = ConvertValue2String(parameter.Value);
2465  }
2466  }
2467  catch (System.Exception ex)
2468  {
2469  row.Cells[collumnValue].ErrorText = ex.Message;
2470  }
2471 
2472  bValueWasSet = true;
2473  break;
2474  }
2475  }
2476 
2477  // Add value if not exist
2478  if (!bValueWasSet)
2479  {
2480  string direction = parameter is IProcedureInParameter ? "In" : (parameter is IProcedureInOutParameter ? "InOut" : "Out");
2481  object[] values = new object[] { parameter.Name, direction, parameter.DataType };
2482  int index = this.gridViewParameter.Rows.Add(values);
2483 
2484  this.gridViewParameter.Rows[index].Tag = parameter;
2485 
2486  this.gridViewParameter.Rows[index].ReadOnly = parameter is IProcedureOutParameter || parameter.InitValue == null;
2487 
2488  if (parameter.DataType.Equals("Boolean"))
2489  {
2490  gridViewParameter.Rows[index].Cells[collumnValue] = new DataGridViewCheckBoxCell();
2491  DataGridViewCheckBoxCell cell = gridViewParameter.Rows[index].Cells[collumnValue] as DataGridViewCheckBoxCell;
2492  cell.Value = ConvertValue2String(parameter.Value);
2493  }
2494  else
2495  {
2496  try
2497  {
2498  if (parameter.Value != null)
2499  {
2500  gridViewParameter.Rows[index].Cells[collumnValue].Value = ConvertValue2String(parameter.Value);
2501  }
2502  }
2503  catch (System.Exception ex)
2504  {
2505  gridViewParameter.Rows[index].Cells[collumnValue].ErrorText = ex.Message;
2506  }
2507  }
2508 
2509  gridViewParameter.Rows[index].Cells[collumnDetails].Value = GetDetails(parameter.Value);
2510  }
2511  }
2512 
2513  private string ConvertValue2String(object value)
2514  {
2515  if (value == null)
2516  {
2517  return string.Empty;
2518  }
2519 
2520  return ValueConverter.Value2String(value);
2521  }
2522 
2523  private string GetDetails(object value)
2524  {
2525  if (value == null)
2526  {
2527  return string.Empty;
2528  }
2529 
2530  if (value is TranslationKey translationKey)
2531  {
2532  if (!string.IsNullOrEmpty(translationKey.TextIdMappingName))
2533  {
2534  return string.Format("MappingName: {0}", translationKey.TextIdMappingName);
2535  }
2536  }
2537  else if (value is EnumerationElement enumerationElement)
2538  {
2539  if (enumerationElement.TranslationKey != null)
2540  {
2541  if (!string.IsNullOrEmpty(enumerationElement.TranslationKey.TextId) && !string.IsNullOrEmpty(enumerationElement.TranslationKey.TextIdMappingName))
2542  {
2543  return string.Format("TextId: {0}, MappingName: {1}", enumerationElement.TranslationKey.TextId, enumerationElement.TranslationKey.TextIdMappingName);
2544  }
2545  else if (!string.IsNullOrEmpty(enumerationElement.TranslationKey.TextId))
2546  {
2547  return string.Format("TextId: {0}", enumerationElement.TranslationKey.TextId);
2548  }
2549 
2550  return string.Format("MappingName: {0}", enumerationElement.TranslationKey.TextIdMappingName);
2551  }
2552  }
2553 
2554  return string.Empty;
2555  }
2556 
2557  // TODO: refactor
2558  private void UpdateGridViewContextVariable(IDocument document, bool withPrefix, List<string> listItemsReviewed)
2559  {
2560  string @namespace = string.Concat(document.Package.Name, ".", document.Name);
2561  if (listItemsReviewed.Contains(@namespace))
2562  {
2563  return;
2564  }
2565 
2566  listItemsReviewed.Add(@namespace);
2567  foreach (IContextVariable contextVariable in document.ContextVariables)
2568  {
2569  if (contextVariable == null)
2570  {
2571  return;
2572  }
2573 
2574  bool bValueWasSet = false;
2575 
2576  // Update existing value
2577  foreach (DataGridViewRow row in this.gridViewContext.Rows)
2578  {
2579  if (row.Cells[this.dataGridViewTextBoxColumnContextName.Name].Value != null && row.Cells[this.dataGridViewTextBoxColumnContextName.Name].Value.Equals(withPrefix ? (document.Package.FullName + "." + document.Name + "." + contextVariable.Name) : contextVariable.Name))
2580  {
2581  if (radioButtonDefaultImplementation.Checked)
2582  {
2583  object contextVariableValue = this.contextVariableImplementation.GetValue(null, contextVariable, null);
2584  row.Cells[this.dataGridViewTextBoxColumnContextValue.Name].Value = contextVariableValue != null ? ConvertValue2String(contextVariableValue) : null;
2585  }
2586  else
2587  {
2588  row.Cells[this.dataGridViewTextBoxColumnContextValue.Name].Value = contextVariable.InitValue != null ? ConvertValue2String(contextVariable.InitValue) : null;
2589  }
2590 
2591  bValueWasSet = true;
2592  break;
2593  }
2594  }
2595 
2596  // Add value if not exist
2597  if (!bValueWasSet)
2598  {
2599  object[] values = null;
2600  values = new object[] { withPrefix ? (document.Package.FullName + "." + document.Name + "." + contextVariable.Name) : contextVariable.Name, contextVariable.DataType };
2601  int index = this.gridViewContext.Rows.Add(values);
2602 
2603  object contextVariableValue = contextVariable.InitValue;
2604 
2605  this.gridViewContext.Rows[index].Tag = contextVariable;
2606  this.gridViewContext.Rows[index].ReadOnly = contextVariable.InitValue == null;
2607  this.gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name].Tag = contextVariable.InitValue;
2608  if (contextVariable.DataType.Equals("Boolean"))
2609  {
2610  gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name] = new DataGridViewCheckBoxCell();
2611  DataGridViewCheckBoxCell cell = gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name] as DataGridViewCheckBoxCell;
2612  cell.Value = ConvertValue2String(contextVariableValue);
2613  }
2614  else
2615  {
2616  try
2617  {
2618  if (contextVariableValue != null)
2619  {
2620  gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name].Value = ConvertValue2String(contextVariableValue);
2621  }
2622  else
2623  {
2624  gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name].Value = null;
2625  }
2626  }
2627  catch (System.Exception ex)
2628  {
2629  gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextValue.Name].ErrorText = ex.Message;
2630  }
2631  }
2632 
2633  gridViewContext.Rows[index].Cells[dataGridViewTextBoxColumnContextDetails.Name].Value = GetDetails(contextVariableValue);
2634  }
2635  }
2636 
2637  try
2638  {
2639  foreach (IDocument importDoc in document.Imports)
2640  {
2641  UpdateGridViewContextVariable(importDoc, true, listItemsReviewed);
2642  }
2643  }
2644  catch (System.Exception ex)
2645  {
2646  PrintException(ex);
2647  }
2648  }
2649 
2650  // TODO: refactor this
2651  private void StateVariableValueChanged(IStateVariable stateVariable, object value)
2652  {
2653  if (this.InvokeRequired)
2654  {
2655  this.Invoke(new Action(() => StateVariableValueChanged(stateVariable, value)));
2656  return;
2657  }
2658 
2659  string mappingStr = String.Format("[MappedTo: {0}{1}]",
2660  stateVariable.MappingName,
2661  (stateVariable.MappingIndex > -1 ? "[" + stateVariable.MappingIndex + "]" : String.Empty));
2662  string strValue = "null";
2663  try
2664  {
2665  strValue = ValueConverter.Value2String(value);
2666  }
2667  catch
2668  {
2669  }
2670 
2671  string outputLog = String.Format("StateVariableChanged({0} {1}.{2}{3} = {4})",
2672  stateVariable.DataType,
2673  stateVariable.Document.FullName,
2674  stateVariable.Name,
2675  mappingStr,
2676  strValue);
2677  PrintText(outputLog);
2678  UpdateGridViewStateVariable(stateVariable);
2679  }
2680 
2681  private void ContextVariableRead(IContextVariable contextVariable, object value)
2682  {
2683  if (this.InvokeRequired)
2684  {
2685  this.Invoke(new Action(() => ContextVariableRead(contextVariable, value)));
2686  return;
2687  }
2688 
2689  string mappingStr = String.Format("[MappedTo: {0}{1}]",
2690  contextVariable.MappingName,
2691  (contextVariable.MappingIndex > -1 ? "[" + contextVariable.MappingIndex + "]" : String.Empty));
2692  string strValue = "null";
2693  try
2694  {
2695  strValue = ValueConverter.Value2String(value);
2696  }
2697  catch
2698  {
2699  }
2700  string outputLog = String.Format("ContextVariableRead({0} {1}.{2}{3} = {4})",
2701  contextVariable.DataType,
2702  contextVariable.Document.FullName,
2703  contextVariable.Name,
2704  mappingStr,
2705  strValue);
2706 
2707  PrintText(outputLog);
2708  }
2709 
2710  private void UpdateGridViewStateVariable(IDocument document, bool withPrefix, List<string> listItemsReviewed)
2711  {
2712  string @namespace = string.Concat(document.Package.Name, ".", document.Name);
2713  if (listItemsReviewed.Contains(@namespace))
2714  {
2715  return;
2716  }
2717 
2718  listItemsReviewed.Add(@namespace);
2719  foreach (IStateVariable stateVariable in document.StateVariables)
2720  {
2721  object[] values = null;
2722  values = new object[] { withPrefix ? (document.Package.FullName + "." + document.Name + "." + stateVariable.Name) : stateVariable.Name, stateVariable.DataType };
2723  int index = this.gridViewState.Rows.Add(values);
2724 
2725  this.gridViewState.Rows[index].Tag = stateVariable;
2726 
2727  if (stateVariable.DataType.Equals("Boolean"))
2728  {
2729  gridViewState.Rows[index].Cells[dataGridViewTextBoxColumnStateValue.Name] = new DataGridViewCheckBoxCell();
2730  DataGridViewCheckBoxCell cell = gridViewState.Rows[index].Cells[dataGridViewTextBoxColumnStateValue.Name] as DataGridViewCheckBoxCell;
2731  cell.Value = ConvertValue2String(stateVariable.InitValue);
2732  }
2733  else
2734  {
2735  try
2736  {
2737  if (stateVariable.InitValue != null)
2738  {
2739  gridViewState.Rows[index].Cells[dataGridViewTextBoxColumnStateValue.Name].Value = ConvertValue2String(stateVariable.InitValue);
2740  }
2741  }
2742  catch (System.Exception ex)
2743  {
2744  gridViewState.Rows[index].Cells[dataGridViewTextBoxColumnStateValue.Name].ErrorText = ex.Message;
2745  }
2746  }
2747 
2748  if (stateVariable.InitValue != null)
2749  {
2750  gridViewState.Rows[index].Cells[dataGridViewTextBoxColumnStateDetails.Name].Value = GetDetails(stateVariable.InitValue);
2751  }
2752  }
2753 
2754  try
2755  {
2756  foreach (IDocument importDoc in document.Imports)
2757  {
2758  UpdateGridViewStateVariable(importDoc, true, listItemsReviewed);
2759  }
2760  }
2761  catch (System.Exception ex)
2762  {
2763  PrintException(ex);
2764  }
2765  }
2766 
2767 
2768  // TODO: refactor
2769  private void UpdateGridViewStateVariable(IStateVariable stateVar)
2770  {
2771  if (stateVar == null)
2772  {
2773  return;
2774  }
2775 
2776  // Update existing value
2777  foreach (DataGridViewRow row in this.gridViewState.Rows)
2778  {
2779  if (row.Cells[this.dataGridViewTextBoxColumnStateName.Name].Value != null && row.Tag == stateVar)
2780  {
2781  object stateVariableValue = null;
2782 
2783  if (radioButtonDefaultImplementation.Checked)
2784  stateVariableValue = this.stateVariableImplementation.GetValue(stateVar);
2785  else
2786  stateVariableValue = stateVar.InitValue;
2787 
2788  if (stateVariableValue != null)
2789  {
2790  try
2791  {
2792  row.Cells[this.dataGridViewTextBoxColumnStateValue.Name].Value = ConvertValue2String(stateVariableValue);
2793  }
2794  catch (System.Exception ex)
2795  {
2796  row.Cells[this.dataGridViewTextBoxColumnStateValue.Name].ErrorText = ex.Message;
2797  }
2798 
2799  row.Cells[this.dataGridViewTextBoxColumnStateDetails.Name].Value = GetDetails(stateVariableValue);
2800  }
2801  else
2802  {
2803  row.Cells[this.dataGridViewTextBoxColumnStateValue.Name].Value = null;
2804  row.Cells[this.dataGridViewTextBoxColumnStateDetails.Name].Value = string.Empty;
2805  }
2806  break;
2807  }
2808  }
2809 
2810  Application.DoEvents();
2811  }
2812 
2813  private void buttonNewInstance_Click(object sender, EventArgs e)
2814  {
2815  Form form = new SampleForm(SampleConstants.CHILD_INSTANCE_NAME, this);
2816  form.Show();
2817  }
2818 
2819  private void buttonNewInstanceNewThread_Click(object sender, EventArgs e)
2820  {
2821  Thread thread = new Thread(new ThreadStart(NewInstanceInThread));
2822  thread.SetApartmentState(ApartmentState.STA);
2823  thread.Start();
2824  }
2825 
2826  private void NewInstanceInThread()
2827  {
2828  Application.Run(new SampleForm(SampleConstants.CHILD_INSTANCE_NAME, this));
2829  }
2830 
2831  private void buttonHmi_Click(object sender, EventArgs e)
2832  {
2833  if (this.buttonHmi.Checked)
2834  {
2835  hmiWindow = new HmiWindow();
2836  hmiWindow.FormClosing += HmiWindow_FormClosing;
2837  hmiWindow.SizeChanged += HmiWindow_SizeChanged;
2838  hmiWindow.Activated += HmiWindow_Activated;
2839  hmiWindow.Show();
2840 
2841  hmiWindow.Size = new Size(userSettings.HmiWindowWidth, userSettings.HmiWindowHeight);
2842  hmiWindow.Location = new Point(this.Location.X + this.Size.Width, this.Location.Y);
2843  if (this.creatorForm != null && this.creatorForm.hmiWindow != null)
2844  {
2845  this.hmiWindow.Size = this.creatorForm.hmiWindow.Size;
2846  }
2847 
2848  hmiWindow.BringToFront();
2849 
2850  customScreenImplementation.HmiScreenContainer = this.hmiWindow.HmiControl;
2851  }
2852  else if (this.hmiWindow != null)
2853  {
2854  this.hmiWindow.Close();
2855  }
2856 
2857  SyncWithParent(this.creatorForm?.buttonHmi, this.buttonHmi);
2858  }
2859 
2860  private void HmiWindow_FormClosing(object sender, FormClosingEventArgs e)
2861  {
2862  customScreenImplementation.HmiScreenContainer = null;
2863  this.hmiWindow = null;
2864 
2865  this.buttonHmi.Checked = false;
2866  }
2867 
2868  private void HmiWindow_Activated(object sender, EventArgs e)
2869  {
2870  if (customScreenImplementation != null)
2871  {
2872  customScreenImplementation.ActivateHmiScreen();
2873  }
2874  }
2875 
2876  private void HmiWindow_SizeChanged(object sender, EventArgs e)
2877  {
2878  userSettings.HmiWindowWidth = this.hmiWindow.Width;
2879  userSettings.HmiWindowHeight = this.hmiWindow.Height;
2880 
2881  if (customScreenImplementation != null)
2882  {
2883  customScreenImplementation.RefreshHmiScreen();
2884  }
2885  }
2886 
2887  private void CustomScreenImplementation_KeyDown(Runtime.Api.Custom.KeyEventArgs e)
2888  {
2889  string key = "Unknown";
2890  if (e is WpfKeyEventArgs)
2891  {
2892  WpfKeyEventArgs wpfArgs = e as WpfKeyEventArgs;
2893  key = wpfArgs.Key.ToString();
2894  if (wpfArgs.ModifierKey == System.Windows.Input.ModifierKeys.Alt &&
2895  wpfArgs.Key == System.Windows.Input.Key.F4)
2896  {
2897  hmiWindow?.Close();
2898  }
2899  else if (wpfArgs.Key == System.Windows.Input.Key.F10 || wpfArgs.Key == System.Windows.Input.Key.LeftAlt || wpfArgs.Key == System.Windows.Input.Key.RightAlt)
2900  {
2901  e.Handled = true;
2902  }
2903  }
2904  else if (e is FormKeyEventArgs)
2905  {
2906  FormKeyEventArgs formArgs = e as FormKeyEventArgs;
2907  if (formArgs.ModifierKey == Keys.Alt &&
2908  formArgs.Key == Keys.F4)
2909  {
2910  hmiWindow?.Close();
2911  }
2912  else if (formArgs.Key == Keys.F10 || formArgs.Key == Keys.Alt)
2913  {
2914  e.Handled = true;
2915  }
2916  key = formArgs.Key.ToString();
2917  }
2918 
2919  this.PrintText("CustomScreenImplementation_KeyDown(" + key + ")");
2920  }
2921 
2922  // TODO: refactor
2923  private void SampleForm_FormClosing(object sender, FormClosingEventArgs e)
2924  {
2925  // Remove Event
2926  if (this.globalRuntimeManager != null)
2927  {
2928  this.globalRuntimeManager.StopAll();
2929  this.globalRuntimeManager.ProcedurePending -= ProcedurePending;
2930  this.globalRuntimeManager.ProcedureStarted -= ProcedureStarted;
2931  this.globalRuntimeManager.ProcedurePaused -= ProcedurePaused;
2932  this.globalRuntimeManager.ProcedureContinued -= ProcedureContinued;
2933  this.globalRuntimeManager.ProcedureFinished -= ProcedureFinished;
2934  this.globalRuntimeManager.ProcedureStopped -= ProcedureStopped;
2935  this.globalRuntimeManager.ProcedureAborted -= ProcedureAborted;
2936  this.globalRuntimeManager.InOutParameterValueChanged -= InOutParameterValueChanged;
2937  }
2938 
2939  this.stateVariableImplementation.StateVariableValueChanged -= StateVariableValueChanged;
2940 
2941  basicScreenOutputImpl.LogEvent -= PrintText;
2942  customScreenOutputImpl.LogEvent -= PrintText;
2943  loggingOutputImpl.LogEvent -= PrintText;
2944  contextVariableOutputImpl.LogEvent -= PrintText;
2945 
2946  stateVariableOutputImpl.LogEvent -= PrintText;
2947  measureOutputImpl.LogEvent -= PrintText;
2948  i18NOutputImpl.LogEvent -= PrintText;
2949  serviceProviderOutputImpl.LogEvent -= PrintText;
2950 
2951  sqlOutputImpl.LogEvent -= PrintText;
2952  commonDialogsOutputImpl.LogEvent -= PrintText;
2953 
2954  SaveSettings();
2955  }
2956 
2957  private void SaveSettings()
2958  {
2959  if (this.creatorForm == null)
2960  {
2961  // Only main form
2962  userSettings.Ptx_Ppx_Directory = cbFilePath.Text.Trim();
2963  userSettings.Ptx_Ppx_DirectoryList = string.Join(";", this.cbFilePath.Items.Cast<Object>().Select(item => item.ToString()).ToArray());
2964 
2965  userSettings.TraceFileMaxCount = Convert.ToInt32(this.textBoxTraceFileMaxCount.Text.Trim());
2966  userSettings.TraceFileMaxSize = Convert.ToInt32(this.textBoxTraceFileMaxSize.Text.Trim());
2967  userSettings.TraceLevels = RuntimeConfig.Instance.TraceLevel;
2968  userSettings.TracingDirectory = textBoxTraceFolder.Text.Trim();
2969 
2970  userSettings.WindowWidth = this.Size.Width;
2971  userSettings.WindowHeight = this.Size.Height;
2972  userSettings.WindowLocationX = this.Location.X;
2973  userSettings.WindowLocationY = this.Location.Y;
2974  userSettings.CustomImplTypes = GetCurrentCustomImpl();
2975  SaveSocketPortOrPipeName();
2976 
2977  userSettings.Asynchron = checkBoxAsyncExecution.Checked;
2978  userSettings.Cyclic = checkBoxCyclicExecution.Checked;
2979  userSettings.CyclicReload = checkBoxCyclicReload.Checked;
2980  userSettings.NewRunTimeManager = checkBoxNewRuntimeManager.Checked;
2981  userSettings.AddMessageToOutput = checkBoxAdd2Output.Checked;
2982  userSettings.StartAllParents = checkBoxStartAllParents.Checked;
2983 
2984  userSettings.TimeOut = (ulong)Convert.ToInt32(this.textBoxTimeout.Text.Trim());
2985  userSettings.ConnectionState = checkBoxUseConnectionState.Checked;
2986  userSettings.Ignition = checkBoxIgnition.CheckState == CheckState.Checked ? 1 : (checkBoxIgnition.CheckState == CheckState.Unchecked ? 0 : -1);
2987  userSettings.PollingTime = Convert.ToInt32(this.textBoxPollingTime.Text.Trim());
2988  userSettings.VoltageThreshold = Convert.ToInt32(this.textBoxVoltageThreshold.Text.Trim());
2989 
2990  userSettings.RuntimeContextName = this.textBoxRuntimeContextName.Text.Trim();
2991 
2992  SaveSettingUtil.Save();
2993  }
2994  }
2995 
2996  private void SaveSocketPortOrPipeName()
2997  {
2998  var ipcType = (IpcTypes)comboBoxIpcType.SelectedItem;
2999 
3000  switch (ipcType)
3001  {
3002  case IpcTypes.SOCKET:
3003  {
3004  try
3005  {
3006  userSettings.DiagManagerPort = Convert.ToUInt16(textBoxDiagPortPipe.Text.Trim());
3007  userSettings.RuntimePort = Convert.ToUInt16(textBoxRtPortPipe.Text.Trim());
3008  userSettings.IpcType = IpcTypes.SOCKET.ToString();
3009  }
3010  catch (System.Exception)
3011  {
3012  userSettings.DiagManagerPort = SampleConstants.DEFAULT_DM_PORT;
3013  userSettings.RuntimePort = SampleConstants.DEFAULT_RT_PORT;
3014  }
3015  break;
3016  }
3017 
3018  case IpcTypes.PIPE:
3019  {
3020  string diagManagerPipeName = textBoxDiagPortPipe.Text.Trim();
3021  string runtimePipeName = textBoxRtPortPipe.Text.Trim();
3022 
3023  userSettings.DiagManagerPipeName = (diagManagerPipeName != string.Empty) ? diagManagerPipeName : SampleConstants.DEFAULT_DM_PIPE_NAME;
3024  userSettings.RuntimePipeName = (runtimePipeName != string.Empty) ? runtimePipeName : SampleConstants.DEFAULT_RT_PIPE_NAME;
3025  userSettings.IpcType = IpcTypes.PIPE.ToString();
3026  break;
3027  }
3028 
3029  default:
3030  break;
3031  }
3032  }
3033 
3034  private void textBoxRuntimeContextName_TextChanged(object sender, EventArgs e)
3035  {
3036  this.runtimeContextName = this.textBoxRuntimeContextName.Text = this.textBoxRuntimeContextName.Text.Trim();
3037  SetTitle(this.title);
3038  }
3039 
3040  private void listBoxOuput_SelectedIndexChanged(object sender, EventArgs e)
3041  {
3042  this.buttonCopyRow.Enabled = this.listBoxOuput.SelectedItems.Count > 0;
3043  }
3044 
3045  private void buttonPause_Click(object sender, EventArgs e)
3046  {
3047  lock (this.runtimeContexts)
3048  {
3049  if (this.buttonPause.Checked)
3050  {
3051  foreach (IRuntimeContext runtimeContext in this.runtimeContexts)
3052  {
3053  if (runtimeContext.ExecutionState == ExecutionState.Running)
3054  {
3055  runtimeContext.Pause();
3056  }
3057  }
3058  }
3059  else
3060  {
3061  foreach (IRuntimeContext runtimeContext in this.runtimeContexts)
3062  {
3063  if (runtimeContext.ExecutionState == ExecutionState.Paused)
3064  {
3065  runtimeContext.Continue();
3066  }
3067  }
3068  }
3069  }
3070 
3071  SyncWithParent(this.creatorForm?.buttonPause, this.buttonPause);
3072  }
3073 
3074  private void AddRuntimeContext(IRuntimeContext context)
3075  {
3076  lock (this.runtimeContexts)
3077  {
3078  if (!this.runtimeContexts.Contains(context))
3079  {
3080  this.runtimeContexts.Add(context);
3081  }
3082 
3083  if (!runtimeContextsExecutionStartTime.ContainsKey(context))
3084  {
3085  runtimeContextsExecutionStartTime.Add(context, DateTime.Now);
3086  }
3087  }
3088  }
3089 
3090  private void RemoveRuntimeContext(IRuntimeContext context)
3091  {
3092  lock (this.runtimeContexts)
3093  {
3094  if (this.runtimeContexts.Contains(context))
3095  {
3096  this.runtimeContexts.Remove(context);
3097  }
3098 
3099  if (runtimeContextsExecutionStartTime.ContainsKey(context))
3100  {
3101  runtimeContextsExecutionStartTime.Remove(context);
3102  }
3103  }
3104  }
3105 
3106  private bool IsPauseEnabled()
3107  {
3108  lock (this.runtimeContexts)
3109  {
3110  foreach (IRuntimeContext runtimeContext in this.runtimeContexts)
3111  {
3112  if (runtimeContext.ExecutionState == ExecutionState.Running)
3113  {
3114  return true;
3115  }
3116  }
3117 
3118  return false;
3119  }
3120  }
3121 
3122  private bool IsContinueEnable()
3123  {
3124  lock (this.runtimeContexts)
3125  {
3126  foreach (IRuntimeContext runtimeContext in this.runtimeContexts)
3127  {
3128  if (runtimeContext.ExecutionState == ExecutionState.Paused)
3129  {
3130  return true;
3131  }
3132  }
3133 
3134  return false;
3135  }
3136  }
3137 
3138  private void SetExpectedState()
3139  {
3140  if (this.useConnectionState)
3141  {
3142  if (this.KL15State == null)
3143  {
3144  this.expectedConnectionState = ExpectedState.BatteryOn;
3145  }
3146  else if (this.KL15State.Value)
3147  {
3148  this.expectedConnectionState = ExpectedState.IgnitionOn;
3149  }
3150  else
3151  {
3152  this.expectedConnectionState = ExpectedState.IgnitionOff;
3153  }
3154  }
3155  else
3156  {
3157  this.expectedConnectionState = ExpectedState.None;
3158  }
3159  }
3160 
3161  private void checkBoxUseConnectionState_CheckedChanged(object sender, EventArgs e)
3162  {
3163  this.useConnectionState = this.checkBoxUseConnectionState.Checked;
3164  this.EnableConnectionState();
3165  this.SetExpectedState();
3166 
3167  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBattery16;
3168  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnition16;
3169 
3170  SyncWithParent(this.creatorForm?.checkBoxUseConnectionState, this.checkBoxUseConnectionState);
3171  }
3172 
3173  private void CheckBoxKL15_CheckStateChanged(object sender, System.EventArgs e)
3174  {
3175  switch (this.checkBoxIgnition.CheckState)
3176  {
3177  case CheckState.Checked:
3178  this.KL15State = true;
3179  break;
3180  case CheckState.Unchecked:
3181  this.KL15State = false;
3182  break;
3183  default:
3184  this.KL15State = null;
3185  break;
3186  }
3187 
3188  this.SetExpectedState();
3189 
3190  SyncWithParent(this.creatorForm?.checkBoxIgnition, this.checkBoxIgnition);
3191  }
3192 
3193  private void EnableConnectionState()
3194  {
3195  this.labelExpectedState.Enabled = this.useConnectionState;
3196  this.labelBatteryState.Enabled = this.useConnectionState;
3197  this.checkBoxIgnition.Enabled = this.useConnectionState;
3198  this.labelPollingTime.Enabled = this.useConnectionState;
3199  this.textBoxPollingTime.Enabled = this.useConnectionState;
3200  this.labelVoltageThreshold.Enabled = this.useConnectionState;
3201  this.textBoxVoltageThreshold.Enabled = this.useConnectionState;
3202  this.buttonCheckBatteryIgnition.Enabled = this.useConnectionState;
3203  }
3204 
3205  private void buttonCheckBatteryIgnition_Click(object sender, EventArgs e)
3206  {
3207  CheckBatteryIgnitionState(this.globalRuntimeManager);
3208 
3209  SyncWithParent(this.creatorForm?.buttonCheckBatteryIgnition, this.buttonCheckBatteryIgnition);
3210  }
3211 
3212  private void textBoxPollingTime_TextChanged(object sender, EventArgs e)
3213  {
3214  try
3215  {
3216  if (Convert.ToInt32(this.textBoxPollingTime.Text) <= 0)
3217  {
3218  this.textBoxPollingTime.Text = defaultPollingTime.ToString();
3219  }
3220  }
3221  catch
3222  {
3223  this.textBoxPollingTime.Text = defaultPollingTime.ToString();
3224  }
3225 
3226  SyncWithParent(this.creatorForm?.textBoxPollingTime, this.textBoxPollingTime);
3227  }
3228 
3229  private void textBoxBatteryVoltageThreshold_TextChanged(object sender, EventArgs e)
3230  {
3231  try
3232  {
3233  if (Convert.ToInt32(this.textBoxVoltageThreshold.Text) <= 0)
3234  {
3235  this.textBoxVoltageThreshold.Text = defaultBatteryVoltageThreshold.ToString();
3236  }
3237  }
3238  catch
3239  {
3240  this.textBoxVoltageThreshold.Text = defaultBatteryVoltageThreshold.ToString();
3241  }
3242 
3243  SyncWithParent(this.creatorForm?.textBoxVoltageThreshold, this.textBoxVoltageThreshold);
3244  }
3245 
3246  private void CheckBatteryIgnitionState(IRuntimeManager runtimeManager)
3247  {
3248  if (this.useConnectionState)
3249  {
3250  runtimeManager.DiagConnectionState.PollingTime = Convert.ToInt32(this.textBoxPollingTime.Text);
3251  runtimeManager.DiagConnectionState.BatteryVoltageThreshold = Convert.ToInt32(this.textBoxVoltageThreshold.Text);
3252  ClampState batteryState = runtimeManager.DiagConnectionState.BatteryState;
3253  ClampState ignitionState = runtimeManager.DiagConnectionState.IgnitionState;
3254 
3255  SetBatteryIgnitionState(batteryState, ignitionState);
3256 
3257  PrintText("Check DiagConnection State - BatteryState = " + batteryState.ToString() + ", IgnitionState = " + ignitionState.ToString());
3258  }
3259  }
3260 
3261  private void SetBatteryIgnitionState(ClampState batteryState, ClampState ignitionState)
3262  {
3263  switch (batteryState)
3264  {
3265  case ClampState.NotAvailable:
3266  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBatteryNotAvailable16;
3267  break;
3268  case ClampState.Off:
3269  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBatteryOff16;
3270  break;
3271  case ClampState.On:
3272  this.labelBatteryState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconBatteryOn16;
3273  break;
3274  }
3275 
3276  switch (ignitionState)
3277  {
3278  case ClampState.NotAvailable:
3279  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnitionNotAvailable16;
3280  break;
3281  case ClampState.Off:
3282  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnitionOff16;
3283  break;
3284  case ClampState.On:
3285  this.labelIgnitionState.Image = OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.IconIgnitionOn16;
3286  break;
3287  }
3288  }
3289 
3290  private void ShowConnectionStateMessage(IRuntimeContext runtimeContext)
3291  {
3292  if (runtimeContext != null)
3293  {
3294  System.Media.SystemSounds.Beep.Play();
3295 
3296  switch (this.expectedConnectionState)
3297  {
3298  case ExpectedState.BatteryOn:
3299  this.PrintText("----------------------------------------------------------------------------------------------------------------------------------------------");
3300  this.PrintText("-- Not expected connection state: Either it is not possible to communicate with the VCI or the battery is not connected. Please connect it! --");
3301  this.PrintText("----------------------------------------------------------------------------------------------------------------------------------------------");
3302  break;
3303  case ExpectedState.IgnitionOff:
3304  this.PrintText("------------------------------------------------------------------------------------");
3305  this.PrintText("-- Not expected connection state: The ignition must be OFF. Please switch it OFF! --");
3306  this.PrintText("------------------------------------------------------------------------------------");
3307  break;
3308  case ExpectedState.IgnitionOn:
3309  this.PrintText("----------------------------------------------------------------------------------");
3310  this.PrintText("-- Not expected connection state: The ignition must be ON. Please switch it ON! --");
3311  this.PrintText("----------------------------------------------------------------------------------");
3312  break;
3313  default:
3314  break;
3315  }
3316  }
3317  }
3318 
3319  private void checkBoxAdd2Output_CheckedChanged(object sender, EventArgs e)
3320  {
3321  SyncWithParent(this.creatorForm?.checkBoxAdd2Output, this.checkBoxAdd2Output);
3322  }
3323 
3324  private void ParentNumericUpDownSetValue(NumericUpDown numericUpDown, int value)
3325  {
3326  var action = new Action(() => numericUpDown.Value = value);
3327  if (numericUpDown.InvokeRequired)
3328  this.creatorForm.Invoke(action);
3329  else
3330  action.Invoke();
3331  }
3332 
3333  private void comboBoxTraceLevel_SelectedIndexChanged(object sender, EventArgs e)
3334  {
3335  SyncWithParent(this.creatorForm?.comboBoxTraceLevel, this.comboBoxTraceLevel);
3336  }
3337  private void txtPassword_TextChanged(object sender, EventArgs e)
3338  {
3339  SyncWithParent(this.creatorForm?.txtPassword, this.txtPassword);
3340  }
3341 
3342  private void textBoxTimeout_TextChanged(object sender, EventArgs e)
3343  {
3344  SyncWithParent(this.creatorForm?.textBoxTimeout, this.textBoxTimeout);
3345  }
3346 
3347  private void textBoxTraceFileMaxSize_TextChanged(object sender, EventArgs e)
3348  {
3349  if (globalRuntimeManager == null)
3350  return;
3351 
3352  PrintText("Set TraceFileMaxSize to " + this.textBoxTraceFileMaxSize.Text);
3353 
3354  try
3355  {
3356  RuntimeConfig.Instance.TraceFileMaxSize = Convert.ToInt32(this.textBoxTraceFileMaxSize.Text);
3357  SyncWithParent(this.creatorForm?.textBoxTraceFileMaxSize, this.textBoxTraceFileMaxSize);
3358  }
3359 
3360  catch (System.Exception ex)
3361  {
3362  PrintException(ex);
3363  this.textBoxTraceFileMaxSize.Text = RuntimeConfig.Instance.TraceFileMaxSize.ToString();
3364  }
3365  }
3366 
3367  private void textBoxTraceFileMaxCount_TextChanged(object sender, EventArgs e)
3368  {
3369  if (globalRuntimeManager == null)
3370  return;
3371 
3372  PrintText("Set TraceFileMaxCount to " + this.textBoxTraceFileMaxCount.Text);
3373 
3374  try
3375  {
3376  RuntimeConfig.Instance.TraceFileMaxCount = Convert.ToInt32(this.textBoxTraceFileMaxCount.Text);
3377  SyncWithParent(this.creatorForm?.textBoxTraceFileMaxCount, this.textBoxTraceFileMaxCount);
3378  }
3379  catch (System.Exception ex)
3380  {
3381  PrintException(ex);
3382  this.textBoxTraceFileMaxCount.Text = RuntimeConfig.Instance.TraceFileMaxCount.ToString();
3383  }
3384  }
3385 
3386  private void WebServerTimer_Tick(object sender, EventArgs e)
3387  {
3388  this.UpdateWebServerButton();
3389  }
3390 
3391  int isStartWebSever = -1;
3392  private void UpdateWebServerButton()
3393  {
3394  if (this.InvokeRequired)
3395  {
3396  this.Invoke(new Action(() => UpdateWebServerButton()));
3397  return;
3398  }
3399 
3400  if (customScreenImplementation == null)
3401  {
3402  this.buttonStartStopWebServer.Enabled = false;
3403  return;
3404  }
3405 
3406  this.buttonStartStopWebServer.Enabled = true;
3407  if (DefaultCustomScreenImplementation.IsStartedHtmlWebserver()) // Has Start WebServer
3408  {
3409  if (isStartWebSever == 1)
3410  {
3411  return;
3412  }
3413 
3414  this.buttonStartStopWebServer.Image = global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.StopWebServer;
3415  isStartWebSever = 1;
3416  }
3417  else
3418  {
3419  if (isStartWebSever == 0)
3420  {
3421  return;
3422  }
3423 
3424  this.buttonStartStopWebServer.Image = global::OpenTestSystem.Otx.Runtime2.Api.DotNet.Sample.Properties.Resources.StartWebServer;
3425  isStartWebSever = 0;
3426  }
3427  }
3428 
3429  private void buttonStartStopWebServer_Click(object sender, EventArgs e)
3430  {
3431  if (this.InvokeRequired)
3432  {
3433  this.Invoke(new Action(() => buttonStartStopWebServer_Click(sender, e)));
3434  return;
3435  }
3436 
3437  if (customScreenImplementation == null)
3438  {
3439  return;
3440  }
3441 
3442  if (!DefaultCustomScreenImplementation.IsStartedHtmlWebserver()) // No Start WebServer
3443  {
3444  customScreenImplementation.StartHtmlWebServer();
3445  }
3446  else
3447  {
3448  customScreenImplementation.StopHtmlWebServer();
3449  }
3450  }
3451 
3452  private void buttonLicense_Click(object sender, EventArgs e)
3453  {
3454  LicenseForm licenseForm = new LicenseForm(this);
3455  licenseForm.ShowDialog(this);
3456  }
3457 
3458  public void ReloadRuntimeManager()
3459  {
3460  try
3461  {
3462  String licenseKeyFromOTForOTPLicense = OpenTestSystem.Common.LicensingV5.Util.CreateLicenseKeyFromOTForOTPLicense();
3463  if (!String.IsNullOrEmpty(licenseKeyFromOTForOTPLicense) && LicensingUtil.CheckLicenseKeyFormat(licenseKeyFromOTForOTPLicense))
3464  {
3465  LicenseManager.SetLicenseKey(licenseKeyFromOTForOTPLicense);
3466  }
3467 
3468  this.globalRuntimeManager = CreateRuntimeManager();
3469 
3470  // TODO: update GUI if license is not valid
3471  }
3472  catch (System.Exception ex)
3473  {
3474  PrintException(ex);
3475  PrintText("No RuntimeManager created");
3476  }
3477  }
3478  }
3479 }
Namespace containing all interfaces for custom implementations
Definition: IBasicScreenImplementation.cs:7
Namespace which contains all supported data types
Definition: BlackBox.cs:5
Namespace containing exceptions
Definition: ConnectionStateException.cs:7
Namespace containing all objects related to licensing
Definition: IpcLicenseCheckerBase.cs:10
Namespace for browsing at OTX data structure.
Definition: IContextVariable.cs:5
Namespace containing main entries: IProject and IPlayerProject.
Definition: IPlayerProject.cs:5
Namespace containing the programming interface for browsing and execution of OTX procedures in own ap...
Definition: ApiConstants.cs:5
ExecutionStateChangeReason
Reason, why a procedure execution state was changed, e.g. Paused or Running
Definition: ExecutionStateChangeReason.cs:13
ClampState
Contains the state of a clamp
Definition: ClampState.cs:13
ExecutionState
Contains the state of the runtime context.
Definition: ExecutionState.cs:7
ExpectedState
Contains the expected state of the diagnostic connection
Definition: ExpectedState.cs:13
Namespace containing all objects for browsing and execution of OTX procedures
Definition: ApiConstants.cs:5
Namespace containing all objects which are standardized according to ISO 13209 (OTX)
Namespace containing all objects related to testing inside automotive industry