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.

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