/// <summary> /// Save the deployment model (actual drawing) as xml-file to the local HDD /// </summary> /// <param name="saveAs">If true, a file name dialog will be opened</param> /// <returns>True, if file was saved successfully</returns> private bool SaveLocalCommand(bool saveAs) { if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 0)) { deploymentModel.eventChannels = null; } else if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 1) && (deploymentModel.eventChannels[0] == null)) { deploymentModel.eventChannels = null; } XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream str = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(str, RemoveGroupingElementsInDeployment(deploymentModel)); str.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); // old, working code: xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); if (!File.Exists(ini.IniReadValue("model", "deployment_schema"))) { xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "deployment_schema")); } else { xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); } // if valid, xml-file will be written if (xmlError.Equals("")) { try { if (saveAs || saveFile == null) { System.Windows.Forms.SaveFileDialog saveLocalXML = new System.Windows.Forms.SaveFileDialog(); //saveLocalXML.InitialDirectory = "c:\\temp\\"; saveLocalXML.Filter = "AsTeRICS-Files (*.acs)|*.acs|All files (*.*)|*.*"; saveLocalXML.FilterIndex = 1; saveLocalXML.RestoreDirectory = true; SetSaveFile(null); if (saveLocalXML.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SetSaveFile(saveLocalXML.FileName); str = new FileStream(saveFile, FileMode.Create); //x.Serialize(str, deploymentModel); x.Serialize(str, RemoveGroupingElementsInDeployment(deploymentModel)); str.Close(); modelHasBeenEdited = false; AddToRecentList(saveFile); return true; } } else { if (ini.IniReadValue("Options", "createBackupFile").Equals("true")) { File.Copy(saveFile, saveFile + ".backup", true); } str = new FileStream(saveFile, FileMode.Create); x.Serialize(str, RemoveGroupingElementsInDeployment(deploymentModel)); str.Close(); modelHasBeenEdited = false; return true; } } catch (Exception fileEx) { MessageBox.Show(Properties.Resources.SaveDialogErrorMessage, Properties.Resources.SaveDialogErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, fileEx.Message + "\n" + fileEx.StackTrace); } } else { MessageBox.Show(Properties.Resources.XmlValidErrorText, Properties.Resources.XmlValidErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } return false; }
/// <summary> /// Load a deployment model to the drawing board /// </summary> private void OpenLocalCommand(String inputFile) { if (inputFile == null) { System.Windows.Forms.OpenFileDialog openLocalXML = new System.Windows.Forms.OpenFileDialog(); //openLocalXML.InitialDirectory = "c:\\temp\\" ; openLocalXML.Filter = "AsTeRICS-Files (*.acs)|*.acs|All files (*.*)|*.*"; openLocalXML.FilterIndex = 1; openLocalXML.RestoreDirectory = true; if (openLocalXML.ShowDialog() == System.Windows.Forms.DialogResult.OK) { inputFile = openLocalXML.FileName; } } if (inputFile != null) { // check if the file is valid against the deployment_schema String xmlError; XmlValidation xv = new XmlValidation(); // old, working code: xmlError = xv.validateXml(inputFile, ini.IniReadValue("model", "deployment_schema")); if (!File.Exists(ini.IniReadValue("model", "deployment_schema"))) { xmlError = xv.validateXml(inputFile, AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "deployment_schema")); } else { xmlError = xv.validateXml(inputFile, ini.IniReadValue("model", "deployment_schema")); } if (xmlError.Equals("")) { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StreamReader sr2 = new StreamReader(inputFile); deploymentModel = (model)ser2.Deserialize(sr2); sr2.Close(); ResetPropertyDock(); ModelVersionUpdater.UpdateMissingGUI(this, deploymentModel, componentList); ModelVersionUpdater.UpdateToCurrentVersion(this, deploymentModel); LoadComponentsCommand(); // set the saveFile in order to still know the filename when trying to save the schema again SetSaveFile(inputFile); if (areStatus.Status == AREStatus.ConnectionStatus.Synchronised) { areStatus.Status = AREStatus.ConnectionStatus.Connected; } else if ((areStatus.Status == AREStatus.ConnectionStatus.Running) || (areStatus.Status == AREStatus.ConnectionStatus.Pause)) { areStatus.Status = AREStatus.ConnectionStatus.Synchronised; areStatus.Status = AREStatus.ConnectionStatus.Connected; } } else { MessageBox.Show(Properties.Resources.ReadXmlErrorText, Properties.Resources.ReadXmlErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); SetSaveFile(null); MessageBoxResult result = MessageBox.Show(Properties.Resources.UpdateModelVersionQuestion, Properties.Resources.UpdateModelVersionHeader, MessageBoxButton.YesNo, MessageBoxImage.Question); if (result.Equals(MessageBoxResult.Yes)) { ModelVersionUpdater.ParseErrorUpdate(xmlError, inputFile); } } AddToRecentList(inputFile); } }
/// <summary> /// Activating (setting to the run modus) a stored model of the ARE storage and downloading it to the ACS /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ActivateStoredModel_Click(object sender, RoutedEventArgs e) { List<string> storedModels = null; try { storedModels = asapiClient.listAllStoredModels(); } catch (Exception ex) { MessageBox.Show(Properties.Resources.LoadStoredModelsListError, Properties.Resources.LoadStoredModelsListErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } if (storedModels != null) { storageDialog = new StorageDialog(); foreach (string s in storedModels) { if (s.EndsWith(".acs")) { storageDialog.filenameListbox.Items.Add(s); } } storageDialog.filenameListbox.SelectionChanged += filenameListbox_SelectionChanged; storageDialog.Title = Properties.Resources.ActivateStoredModelButton; storageDialog.Owner = this; storageDialog.filenameTextbox.IsEnabled = false; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { try { string storedModel = asapiClient.getModelFromFile(storageDialog.filenameTextbox.Text); if (storedModel != null && storedModel != "") { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StringReader sr2 = new StringReader(storedModel); deploymentModel = (model)ser2.Deserialize(sr2); sr2.Close(); // Validate, if downlaoded schema is valid // Should be valid, is double-check XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream str = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(str, deploymentModel); str.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); // if valid, xml-file will be written if (xmlError.Equals("")) { LoadComponentsCommand(); SetSaveFile(storageDialog.filenameTextbox.Text); asapiClient.DeployFile(storageDialog.filenameTextbox.Text); areStatus.Status = AREStatus.ConnectionStatus.Synchronised; asapiClient.RunModel(); areStatus.Status = AREStatus.ConnectionStatus.Running; } else { deploymentModel = null; MessageBox.Show(Properties.Resources.ReadXmlErrorText, Properties.Resources.ReadXmlErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } } } catch (Exception ex) { MessageBox.Show(Properties.Resources.ActivateStoredModelError, Properties.Resources.ActivateStoredModelErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } } } }
/// <summary> /// Load the bundle-model (all available components) to the ribbon menu /// </summary> private void LoadBundle(String pathToBundleFile) { // check, if model is valid against the deployment_model schema String xmlError; string fName; try { if (pathToBundleFile == null) { if (File.Exists(ini.IniReadValue("model", "bundle_model_startup"))) { fName = ini.IniReadValue("model", "bundle_model_startup"); } else if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "bundle_model"))) { fName = AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "bundle_model"); } else { fName = ini.IniReadValue("model", "bundle_model"); } } else { fName = pathToBundleFile; } activeBundle = System.IO.Path.GetFileNameWithoutExtension(fName); if (activeBundle == "bundle") activeBundle = "default"; XmlValidation xv = new XmlValidation(); //xmlError = xv.validateXml(fName, ini.IniReadValue("model", "bundle_schema")); if (File.Exists(ini.IniReadValue("model", "bundle_schema"))) { xmlError = xv.validateXml(fName, ini.IniReadValue("model", "bundle_schema")); } else { xmlError = xv.validateXml(fName, AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "bundle_schema")); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.ReadBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); // called twice to be shown once. Some kind of initialisation problem traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); xmlError = "Error opening bundle file"; fName = ""; } // if valid, xml-file will be written if (xmlError.Equals("")) { try { XmlSerializer ser = new XmlSerializer(typeof(Asterics.ACS2.componentTypes)); //string fName; //if (File.Exists(ini.IniReadValue("model", "bundle_model"))) { // fName = ini.IniReadValue("model", "bundle_model"); //} //else { // fName = AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "bundle_model"); //} StreamReader sr = new StreamReader(fName); Asterics.ACS2.componentTypes allComponents = (Asterics.ACS2.componentTypes)ser.Deserialize(sr); sr.Close(); foreach (object o in allComponents.componentType) { if (o is Asterics.ACS2.componentTypesComponentType) { Asterics.ACS2.componentTypesComponentType comp = (Asterics.ACS2.componentTypesComponentType)o; comp.InitGraphPorts(comp.id); componentList.Add(comp.id, comp); } } foreach (Asterics.ACS2.componentTypesComponentType component in componentList.Values) { // making each element in the plugin selection focusable component.ComponentCanvas.Focusable = true; } // setting the ribbon 'components', adding the components to the // four categories actuatorDropDown.Items.Clear(); processorDropDown.Items.Clear(); sensorDropDown.Items.Clear(); specialDropDown.Items.Clear(); groupDropDown.Items.Clear(); Dictionary<string, RibbonSplitMenuItem> actuatorSubmenus = new Dictionary<string, RibbonSplitMenuItem>(); Dictionary<string, RibbonSplitMenuItem> processorSubmenus = new Dictionary<string, RibbonSplitMenuItem>(); Dictionary<string, RibbonSplitMenuItem> sensorSubmenus = new Dictionary<string, RibbonSplitMenuItem>(); Dictionary<string, RibbonSplitMenuItem> specialSubmenus = new Dictionary<string, RibbonSplitMenuItem>(); foreach (RibbonSplitMenuItem rsmi in actuatorSubmenus.Values) { if (rsmi != null) rsmi.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending)); } foreach (Asterics.ACS2.componentTypesComponentType component in componentList.Values) { RibbonApplicationSplitMenuItem i = new RibbonApplicationSplitMenuItem(); string header = component.id; header = TrimComponentName(header); i.Header = header; i.Click += AddComponentFromRibbonMenu; i.CommandParameter = component.id; RibbonSplitMenuItem rmi = new RibbonSplitMenuItem(); rmi.StaysOpenOnClick = true; rmi.Height = 37; rmi.Header = component.type.subtype; switch (component.type.Value) { case Asterics.ACS2.componentTypeDataTypes.actuator: if (component.type.subtype == null || component.type.subtype.Equals("")) actuatorDropDown.Items.Add(i); else { if (actuatorSubmenus.ContainsKey(component.type.subtype) == false) { rmi.Items.Add(i); actuatorDropDown.Items.Add(rmi); actuatorSubmenus.Add(component.type.subtype, rmi); } else { rmi = actuatorSubmenus[component.type.subtype]; rmi.Items.Add(i); } } break; case Asterics.ACS2.componentTypeDataTypes.processor: if (component.type.subtype == null || component.type.subtype.Equals("")) processorDropDown.Items.Add(i); else { if (processorSubmenus.ContainsKey(component.type.subtype) == false) { rmi.Items.Add(i); processorDropDown.Items.Add(rmi); processorSubmenus.Add(component.type.subtype, rmi); } else { rmi = processorSubmenus[component.type.subtype]; rmi.Items.Add(i); } } break; case Asterics.ACS2.componentTypeDataTypes.sensor: if (component.type.subtype == null || component.type.subtype.Equals("")) sensorDropDown.Items.Add(i); else { if (sensorSubmenus.ContainsKey(component.type.subtype) == false) { rmi.Items.Add(i); sensorDropDown.Items.Add(rmi); sensorSubmenus.Add(component.type.subtype, rmi); } else { rmi = sensorSubmenus[component.type.subtype]; rmi.Items.Add(i); } } break; case Asterics.ACS2.componentTypeDataTypes.special: if (component.type.subtype == null || component.type.subtype.Equals("")) specialDropDown.Items.Add(i); else { if (specialSubmenus.ContainsKey(component.type.subtype) == false) { rmi.Items.Add(i); specialDropDown.Items.Add(rmi); specialSubmenus.Add(component.type.subtype, rmi); } else { rmi = specialSubmenus[component.type.subtype]; rmi.Items.Add(i); } } break; } } // Sorting the lists alphabetically sensorDropDown.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending)); actuatorDropDown.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending)); processorDropDown.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending)); specialDropDown.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending)); // sort Submenus sortComponentSubmenu(actuatorSubmenus.Values.ToArray()); sortComponentSubmenu(sensorSubmenus.Values.ToArray()); sortComponentSubmenu(processorSubmenus.Values.ToArray()); sortComponentSubmenu(specialSubmenus.Values.ToArray()); //move others at the end of the submenus moveOthersMenuItemBack(sensorDropDown); moveOthersMenuItemBack(processorDropDown); moveOthersMenuItemBack(actuatorDropDown); moveOthersMenuItemBack(specialDropDown); if (pathToBundleFile != null) { MessageBox.Show(Properties.Resources.ReadBundleText, Properties.Resources.ReadBundleHeader, MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception e) { actuatorDropDown.Items.Clear(); processorDropDown.Items.Clear(); sensorDropDown.Items.Clear(); specialDropDown.Items.Clear(); groupDropDown.Items.Clear(); componentList.Clear(); if (pathToBundleFile == null) { MessageBox.Show(Properties.Resources.ReadBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show(Properties.Resources.ReadBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); // called twice to be shown once. Some kind of initialisation problem traceSource.TraceEvent(TraceEventType.Error, 3, e.Message); //Application.Current.Shutdown(); //Environment.Exit(0); } else { MessageBox.Show(Properties.Resources.ReadDownloadedBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); componentList.Clear(); LoadBundle(null); } } // loading the presaved groups string errorStr = "unknown"; try { string[] filesInGroupsFolder = null; if (ini.IniReadValue("Options", "useAppDataFolder").Equals("true")) { if (Directory.Exists(Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData)+"\\AsTeRICS\\ACS\\groups\\")) { filesInGroupsFolder = Directory.GetFiles(Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData)+"\\AsTeRICS\\ACS\\groups\\", "*.agr"); } } else { if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\groups\\")) { filesInGroupsFolder = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\groups\\", "*.agr"); } } if (filesInGroupsFolder != null) { foreach (string filename in filesInGroupsFolder) { errorStr = filename; RibbonApplicationSplitMenuItem i = new RibbonApplicationSplitMenuItem(); string header = filename.Substring(filename.LastIndexOf('\\') + 1); i.Header = header.Substring(0, header.LastIndexOf('.')); i.Click += AddGroupFromRibbonMenu; i.CommandParameter = filename; groupDropDown.Items.Add(i); } } } catch (Exception e) { MessageBox.Show(Properties.Resources.GroupingErrorReadingGroupFormat(errorStr), Properties.Resources.GroupingErrorReadingGroupHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, e.Message); } } else { actuatorDropDown.Items.Clear(); processorDropDown.Items.Clear(); sensorDropDown.Items.Clear(); specialDropDown.Items.Clear(); groupDropDown.Items.Clear(); componentList.Clear(); if (pathToBundleFile == null) { MessageBox.Show(Properties.Resources.ReadBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); MessageBox.Show(Properties.Resources.ReadBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); // called twice to be shown once. Some kind of initialisation problem traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); //Application.Current.Shutdown(); //Environment.Exit(0); } else { MessageBox.Show(Properties.Resources.ReadDownloadedBundleErrorText, Properties.Resources.ReadBundleErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); componentList.Clear(); LoadBundle(null); } } }
// Read the Application arguments - used after a .acs file has been double clicked to start ACS /// <summary> /// Function called, when the MainWindow will be loaded. Used to read the application arguments (filename) and load the file by using LoadComponentsCommand() /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MainWindow_Loaded(object sender, RoutedEventArgs e) { if (Application.Current.Properties["ArbitraryArgName"] != null) { string fname = Application.Current.Properties["ArbitraryArgName"].ToString(); // check if the file is valid against the deployment_schema String xmlError; XmlValidation xv = new XmlValidation(); string dsFile = ini.IniReadValue("model", "deployment_schema"); if (!File.Exists(dsFile)) { dsFile = AppDomain.CurrentDomain.BaseDirectory + ini.IniReadValue("model", "deployment_schema"); } xmlError = xv.validateXml(fname, dsFile); if (xmlError.Equals("")) { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StreamReader sr2 = new StreamReader(fname); deploymentModel = (model)ser2.Deserialize(sr2); sr2.Close(); ResetPropertyDock(); ModelVersionUpdater.UpdateMissingGUI(this, deploymentModel, componentList); ModelVersionUpdater.UpdateToCurrentVersion(this, deploymentModel); LoadComponentsCommand(); // set the saveFile in order to still know the filename when trying to save the schema again SetSaveFile(fname); AddToRecentList(fname); } else { MessageBox.Show(Properties.Resources.ReadXmlErrorText, Properties.Resources.ReadXmlErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, "xmlError Msg:" + xmlError); } } TimerCallback tcbFocus = this.DoFocusTimer; statusTimer = new Timer(tcbFocus, dockableComponentProperties, 300, Timeout.Infinite); }
/// <summary> /// Downlaod a deployment schema from the ARE to the ACS /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DownloadSchema_Click(object sender, RoutedEventArgs e) { bool doOverride = true; if ((undoStack.Count > 0 || redoStack.Count > 0) && (showOverrideLocalModelQuestion)) { CustomMessageBox messageBox = new CustomMessageBox(Properties.Resources.OverrideACSDialog, Properties.Resources.OverrideDialogHeader, CustomMessageBox.messageType.Warning, CustomMessageBox.resultType.YesNo); messageBox.Owner = this; messageBox.showCheckbox.IsChecked = showOverrideLocalModelQuestion; messageBox.ShowDialog(); showOverrideLocalModelQuestion = (bool)messageBox.showCheckbox.IsChecked; if (showOverrideLocalModelQuestion) { ini.IniWriteValue("Options", "showOverrideLocalModelQuestion", "true"); } else { ini.IniWriteValue("Options", "showOverrideLocalModelQuestion", "false"); } doOverride = (bool)messageBox.DialogResult; } if (doOverride) { try { String xmlModel = asapiClient.GetModel(); if (xmlModel != null && xmlModel != "") { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StringReader sr2 = new StringReader(xmlModel); deploymentModel = (model)ser2.Deserialize(sr2); sr2.Close(); // Validate, if downlaoded schema is valid // Should be valid, is double-check XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream str = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(str, deploymentModel); str.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); // if valid, xml-file will be written if (xmlError.Equals("")) { ResetPropertyDock(); ModelVersionUpdater.UpdateMissingGUI(this, deploymentModel, componentList); ModelVersionUpdater.UpdateToCurrentVersion(this, deploymentModel); LoadComponentsCommand(); areStatus.Status = AREStatus.ConnectionStatus.Synchronised; } else { MessageBox.Show(Properties.Resources.ReadXmlErrorText, Properties.Resources.ReadXmlErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } } else { CleanACS(); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.SynchronisationDownloadError, Properties.Resources.SynchronisationDownloadErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); CleanACS(); CheckASAPIConnection(); } SetSaveFile(null); } }
/// <summary> /// Download a model from ARE to the canvas and check, if the model is valid /// </summary> private void DownloadAndCheckModel() { try { String xmlModel = asapiClient.GetModel(); if (xmlModel != null && xmlModel != "") { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StringReader sr2 = new StringReader(xmlModel); deploymentModel = (model)ser2.Deserialize(sr2); sr2.Close(); // Validate, if downlaoded schema is valid // Should be valid, is double-check XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream str = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(str, deploymentModel); str.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); // if valid, xml-file will be written if (xmlError.Equals("")) { ResetPropertyDock(); LoadComponentsCommand(); areStatus.Status = AREStatus.ConnectionStatus.Synchronised; } else { MessageBox.Show(Properties.Resources.ReadXmlErrorText, Properties.Resources.ReadXmlErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } } else { CleanACS(); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.SynchronisationDownloadError, Properties.Resources.SynchronisationDownloadErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); CleanACS(); } SetSaveFile(null); }
/// <summary> /// Converting the active model to a string (and check validity of the model) /// </summary> /// <returns>The model as string</returns> private string ConvertDeploymentModelToValidString() { if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 0)) { deploymentModel.eventChannels = null; } else if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 1) && (deploymentModel.eventChannels[0] == null)) { deploymentModel.eventChannels = null; } // validation of the model before sending it to the ARE // model should be valid, this is a double-check XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream strVal = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(strVal, deploymentModel); strVal.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); // if valid, xml-file will be written if (xmlError.Equals("")) { x = new XmlSerializer(deploymentModel.GetType()); StringWriter str = new StringWriter(); x.Serialize(str, RemoveGroupingElementsInDeployment(deploymentModel)); return str.ToString(); } else { MessageBox.Show(Properties.Resources.XmlValidErrorText, Properties.Resources.XmlValidErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } return ""; }
/// <summary> /// Creating (drawing) a new, presaved group out of a menu selection (RibbonDropDown) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddGroupFromRibbonMenu(object sender, RoutedEventArgs e) { MenuItem mi = (MenuItem)e.Source; // check if the file is valid against the deployment_schema try { String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml((string)mi.CommandParameter, ini.IniReadValue("model", "deployment_schema")); if (xmlError.Equals("")) { XmlSerializer ser2 = new XmlSerializer(typeof(model)); StreamReader sr2 = new StreamReader((string)mi.CommandParameter); model groupToPaste = (model)ser2.Deserialize(sr2); sr2.Close(); foreach (componentType ct in groupToPaste.components) { bool found = false; if (((Asterics.ACS2.componentTypesComponentType)componentList[ct.type_id]).singleton) { foreach (componentType ct1 in deploymentComponentList.Values) { if (ct1.type_id == ct.type_id) { found = true; break; } } if (found) { MessageBox.Show(Properties.Resources.SingletonErrorHeaderFormat(ct.type_id), Properties.Resources.SingletonErrorDialogHeader, MessageBoxButton.OK, MessageBoxImage.Warning); return; } } } if (groupToPaste.groups == null) { throw new Exception("group element missing"); } // adapt names in the component, so they can be added without renaming in the PasteCopiedModel method // change id Dictionary<string, string> changedComponents = new Dictionary<string, string>(); foreach (componentType modelComp in groupToPaste.components) { bool namevalid = false; int i = 1; while (namevalid == false) { string modelID = modelComp.id + "." + i; bool foundInPasteGroup = false; foreach (componentType ct in groupToPaste.components) { if (ct.id == modelID) { foundInPasteGroup = true; break; } } if (!deploymentComponentList.ContainsKey(modelID) && !foundInPasteGroup) { if (groupToPaste.channels != null) { foreach (channel c in groupToPaste.channels) { if (c.source.component.id == modelComp.id) { c.source.component.id = modelID; } if (c.target.component.id == modelComp.id) { c.target.component.id = modelID; } } } if (groupToPaste.eventChannels != null) { foreach (eventChannel ec in groupToPaste.eventChannels) { if (ec.sources.source.component.id == modelComp.id) ec.sources.source.component.id = modelID; if (ec.targets.target.component.id == modelComp.id) ec.targets.target.component.id = modelID; } } changedComponents.Add(modelComp.id, modelID); modelComp.id = modelID; namevalid = true; } else i++; } } // adapting the alias to the new group port names if (groupToPaste.groups[0].portAlias != null) { foreach (portAlias alias in groupToPaste.groups[0].portAlias) { foreach (string oldCompName in changedComponents.Keys) { if (alias.portId.Contains(oldCompName)) { alias.portId = alias.portId.Replace(oldCompName, changedComponents[oldCompName]); break; } } } } //group[] backupGroups = groupToPaste.groups; //groupToPaste.groups = null; // add dummy element AddDummyToModel(pasteDummyName); PasteCopiedModel(groupToPaste, true,false); ClearSelectedComponentList(); foreach (string compId in changedComponents.Values) { AddSelectedComponent(deploymentComponentList[compId]); } // generate ID for new group int counter = 0; string compName = ""; do { counter++; compName = groupToPaste.groups[0].id + "." + counter; compName = TrimComponentName(compName); } while (deploymentComponentList.ContainsKey(compName)); string newGroupID = DoGrouping(compName, false, true); RemoveDummyFromModel(pasteDummyName); if (groupsList.ContainsKey(newGroupID)) { CommandObject co = new CommandObject(); co.Command = "Delete"; co.InvolvedObjects.Add(groupsList[newGroupID]); undoStack.Push(co); redoStack.Clear(); } componentType groupToUpdate = deploymentComponentList[compName]; // set the alias if (groupToPaste.groups[0].portAlias != null) { foreach (portAlias alias in groupToPaste.groups[0].portAlias) { foreach (object port in groupToUpdate.ports) { if ((port is inputPortType) && (((inputPortType)port).portTypeID == alias.portId)) { ((inputPortType)port).PortAliasForGroups = alias.portAlias1; ((inputPortType)port).PortLabel.Text = alias.portAlias1; break; } else if ((port is outputPortType) && (((outputPortType)port).portTypeID == alias.portId)) { ((outputPortType)port).PortAliasForGroups = alias.portAlias1; ((outputPortType)port).PortLabel.Text = alias.portAlias1; break; } } } } groupToUpdate.description = groupToPaste.groups[0].description; // store the group in the model /* group[] tempGroups = deploymentModel.groups; if (tempGroups == null) { tempGroups = new group[1]; } else { Array.Resize(ref tempGroups, deploymentModel.groups.Count() + 1); } deploymentModel.groups = tempGroups; //groupToPaste.groups[0].id = compName; //deploymentModel.groups[deploymentModel.groups.Count() - 1] = groupToPaste.groups[0]; group groupForDeployment = new group(); groupForDeployment.id = compName; groupForDeployment.componentId = new string[changedComponents.Count]; int i2 = 0; foreach (string key in changedComponents.Values) { groupForDeployment.componentId[i2] = key; i2++; } groupForDeployment.portAlias = groupToPaste.groups[0].portAlias; deploymentModel.groups[deploymentModel.groups.Count() - 1] = groupForDeployment; */ } else { throw new Exception("group element missing"); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.GroupingErrorReadingGroupFile, Properties.Resources.GroupingErrorReadingGroupHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } }
/// <summary> /// Upload a deployment schema from ACS to ARE /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UploadSchema_Click(object sender, RoutedEventArgs e) { bool isError = false; bool doOverride = false; // If a property has been edited and the focus has not been set to another element, the property will not be set. // Clicking ribbon elments did not remove focus from property editor, so the property will // not be set. Causes problems, saving, uplaoding, ... the model if (canvas.Children.Count > 0) { Keyboard.Focus(canvas.Children[0]); } else { Keyboard.Focus(canvas); } if (deploymentComponentList.Count == 0) { MessageBox.Show(Properties.Resources.EmptyModel, Properties.Resources.EmptyModelHeader, MessageBoxButton.OK, MessageBoxImage.Error); } else { String mustBeConnectedError = MustBeConnectedChecker(); if (mustBeConnectedError != "") { MessageBox.Show(mustBeConnectedError, Properties.Resources.MustBeConnectedCheckerHeader, MessageBoxButton.OK, MessageBoxImage.Error); } else { if (showOverrideModelQuestion) { CustomMessageBox messageBox = new CustomMessageBox(Properties.Resources.OverrideAREDialog, Properties.Resources.OverrideDialogHeader, CustomMessageBox.messageType.Warning, CustomMessageBox.resultType.YesNo); messageBox.Owner = this; messageBox.showCheckbox.IsChecked = showOverrideModelQuestion; messageBox.ShowDialog(); showOverrideModelQuestion = (bool)messageBox.showCheckbox.IsChecked; if (showOverrideModelQuestion) { ini.IniWriteValue("Options", "showOverrideModelQuestion", "true"); } else { ini.IniWriteValue("Options", "showOverrideModelQuestion", "false"); } doOverride = (bool)messageBox.DialogResult; } else { doOverride = true; } if (doOverride) { // Validation: the schema can not be sent to ARE, if the components are not available there. // Just the name of the components will be checked, not the data/version // uncomment, when asapiClient.GetAvailableComponentTypes() is implemented List<String> availableComponents; model deploymentModelWithoutGroups = RemoveGroupingElementsInDeployment(deploymentModel); try { availableComponents = asapiClient.GetAvailableComponentTypes(); foreach (componentType comp in deploymentModelWithoutGroups.components) { if (!availableComponents.Contains(comp.type_id)) { MessageBox.Show(Properties.Resources.SynchronisationComponentNotAvailableErrorFormat(comp.type_id), Properties.Resources.SynchronisationErrorDialogHeader, MessageBoxButton.OK, MessageBoxImage.Error); isError = true; } } } catch (Exception ex) { MessageBox.Show(Properties.Resources.SynchronisationAvailableComponentsError, Properties.Resources.SynchronisationErrorDialogHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); isError = true; CheckASAPIConnection(); } if (!isError) { try { if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 0)) { deploymentModel.eventChannels = null; } else if ((deploymentModel.eventChannels != null) && (deploymentModel.eventChannels.Length == 1) && (deploymentModel.eventChannels[0] == null)) { deploymentModel.eventChannels = null; } // validation of the model before sending it to the ARE // model should be valid, this is a double-check XmlSerializer x = new XmlSerializer(deploymentModel.GetType()); // firstly, write the data to a tempfile and use this temp file, checking valitity against schema FileStream strVal = new FileStream(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), FileMode.Create); x.Serialize(strVal, deploymentModelWithoutGroups); strVal.Close(); // check, if model is valid against the deployment_model schema String xmlError; XmlValidation xv = new XmlValidation(); xmlError = xv.validateXml(System.IO.Path.GetTempPath() + ini.IniReadValue("model", "tempfile"), ini.IniReadValue("model", "deployment_schema")); // if valid, xml-file will be written if (xmlError.Equals("")) { x = new XmlSerializer(deploymentModel.GetType()); StringWriter str = new StringWriter(); x.Serialize(str, deploymentModelWithoutGroups); asapiClient.DeployModel(str.ToString()); areStatus.Status = AREStatus.ConnectionStatus.Synchronised; } else { MessageBox.Show(Properties.Resources.XmlValidErrorText, Properties.Resources.XmlValidErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, xmlError); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.SynchronisationUploadError, Properties.Resources.SynchronisationUploadErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); CheckASAPIConnection(); } } } } } }