/// <summary> /// Send out the broadcast and parse the return string /// </summary> /// <returns>True if an ARE has been detected, otherwise false</returns> public bool Detect(MainWindow window) { Dictionary<string, string> foundedAREs = new Dictionary<string, string>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProps = nic.GetIPProperties(); // check if localAddr is in ipProps.UnicastAddresses if (nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); byte[] byteString = enc.GetBytes("AsTeRICS Broadcast"); UdpClient udpSend = null; try { udpSend = new UdpClient(receivePort, AddressFamily.InterNetwork); udpSend.MulticastLoopback = true; udpSend.EnableBroadcast = true; foreach (MulticastIPAddressInformation ipInfo in ipProps.MulticastAddresses) { Console.WriteLine(ipInfo.Address); if (ipInfo.Address.AddressFamily == AddressFamily.InterNetwork) { udpSend.JoinMulticastGroup(ipInfo.Address); break; } } IPEndPoint groupEp = new IPEndPoint(IPAddress.Broadcast, sendPort); udpSend.Connect(groupEp); udpSend.Send(byteString, byteString.Length); Thread.Sleep(50); // Sleeps are needed to give the system the time to close the ports. // Otherwise confilicts because of still open ports udpSend.Close(); Thread.Sleep(50); IPEndPoint recvEp = new IPEndPoint(IPAddress.Any, 0); UdpClient udpResponse = new UdpClient(receivePort); //Loop to give the ARE some time to respond for (int i = 0; i <= 10; i++) { if (udpResponse.Available > 0) { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, receivePort); Byte[] recvBytes = udpResponse.Receive(ref recvEp); //Console.WriteLine("Rxed " + recvBytes.Length + " bytes, " + enc.GetString(recvBytes)); String retString = enc.GetString(recvBytes); if (retString.Contains("AsTeRICS Broadcast Ret")) { hostname = retString.Substring(33, retString.IndexOf(" IP:") - 33); // Parsing the hostname out f the return string ipAdd = retString.Substring(retString.IndexOf(" IP:") + 4, retString.Length - retString.IndexOf(" IP:") - 4); if (!foundedAREs.ContainsKey(hostname)) { foundedAREs.Add(hostname, ipAdd); } } //break; } else { //Console.WriteLine("nothing received"); Thread.Sleep(200); // wait before the next attemt to read data from the port } } Thread.Sleep(100); udpResponse.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); //throw ex; } } } // if more than one ARE is detected, a selection dialog will be opend if (foundedAREs.Count > 1) { storageDialog = new StorageDialog(); foreach (string s in foundedAREs.Keys) { storageDialog.filenameListbox.Items.Add(s + " (" + foundedAREs[s] + ")"); } storageDialog.filenameListbox.SelectionChanged += filenameListbox_SelectionChanged; storageDialog.Title = Properties.Resources.MultipleAREsDialogTitle; storageDialog.filenameTextbox.Text = foundedAREs.Keys.First(); storageDialog.listLabel.Content = Properties.Resources.MultipleAREsDialogMsg; storageDialog.modelNameLabel.Content = Properties.Resources.MultipleAREsDialogSelected; storageDialog.cancelButton.Visibility = Visibility.Hidden; storageDialog.filenameTextbox.IsEnabled = false; storageDialog.Owner = window; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { hostname = storageDialog.filenameTextbox.Text; ipAdd = foundedAREs[hostname]; } } if (ipAdd.Equals("")) { return false; } else { return true; } }
/// <summary> /// Send out the broadcast and parse the return string /// </summary> /// <returns>True if an ARE has been detected, otherwise false</returns> public bool Detect(MainWindow window) { Dictionary <string, string> foundedAREs = new Dictionary <string, string>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProps = nic.GetIPProperties(); // check if localAddr is in ipProps.UnicastAddresses if (nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); byte[] byteString = enc.GetBytes("AsTeRICS Broadcast"); UdpClient udpSend = null; try { udpSend = new UdpClient(receivePort, AddressFamily.InterNetwork); udpSend.MulticastLoopback = true; udpSend.EnableBroadcast = true; foreach (MulticastIPAddressInformation ipInfo in ipProps.MulticastAddresses) { Console.WriteLine(ipInfo.Address); if (ipInfo.Address.AddressFamily == AddressFamily.InterNetwork) { udpSend.JoinMulticastGroup(ipInfo.Address); break; } } IPEndPoint groupEp = new IPEndPoint(IPAddress.Broadcast, sendPort); udpSend.Connect(groupEp); udpSend.Send(byteString, byteString.Length); Thread.Sleep(50); // Sleeps are needed to give the system the time to close the ports. // Otherwise confilicts because of still open ports udpSend.Close(); Thread.Sleep(50); IPEndPoint recvEp = new IPEndPoint(IPAddress.Any, 0); UdpClient udpResponse = new UdpClient(receivePort); //Loop to give the ARE some time to respond int iterations = 10; for (int i = 0; i < iterations; i++) { if (udpResponse.Available > 0) { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, receivePort); Byte[] recvBytes = udpResponse.Receive(ref recvEp); //Console.WriteLine("Rxed " + recvBytes.Length + " bytes, " + enc.GetString(recvBytes)); String retString = enc.GetString(recvBytes); if (retString.Contains("AsTeRICS Broadcast Ret")) { hostname = retString.Substring(33, retString.IndexOf(" IP:") - 33); // Parsing the hostname out f the return string ipAdd = retString.Substring(retString.IndexOf(" IP:") + 4, retString.Length - retString.IndexOf(" IP:") - 4); if (!foundedAREs.ContainsKey(hostname)) { foundedAREs.Add(hostname, ipAdd); } } //break; } else { //Console.WriteLine("nothing received"); Thread.Sleep(getTimeout() / iterations); // wait before the next attemt to read data from the port } } Thread.Sleep(100); udpResponse.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); //throw ex; } } } // if more than one ARE is detected, a selection dialog will be opend if (foundedAREs.Count > 1) { storageDialog = new StorageDialog(); foreach (string s in foundedAREs.Keys) { storageDialog.filenameListbox.Items.Add(s + " (" + foundedAREs[s] + ")"); } storageDialog.filenameListbox.SelectionChanged += filenameListbox_SelectionChanged; storageDialog.Title = Properties.Resources.MultipleAREsDialogTitle; storageDialog.filenameTextbox.Text = foundedAREs.Keys.First(); storageDialog.listLabel.Content = Properties.Resources.MultipleAREsDialogMsg; storageDialog.modelNameLabel.Content = Properties.Resources.MultipleAREsDialogSelected; storageDialog.cancelButton.Visibility = Visibility.Hidden; storageDialog.filenameTextbox.IsEnabled = false; storageDialog.Owner = window; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { hostname = storageDialog.filenameTextbox.Text; ipAdd = foundedAREs[hostname]; } } if (ipAdd.Equals("")) { return(false); } else { return(true); } }
/// <summary> /// Save the selected group to a file, so that it can be reused /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveGroupButton_Click(object sender, RoutedEventArgs e) { groupComponent groupToSave = null; foreach (componentType mc in selectedComponentList) { if (mc.ComponentType == ACS2.componentTypeDataTypes.group) { groupToSave = groupsList[mc.id]; break; } } if (groupToSave != null) { storageDialog = new StorageDialog(); string[] filesInGroupsFolder; if (ini.IniReadValue("Options", "useAppDataFolder").Equals("true")) { filesInGroupsFolder = Directory.GetFiles(Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\AsTeRICS\\ACS\\groups\\", "*.agr"); } else { filesInGroupsFolder = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\groups\\", "*.agr"); } foreach (string s in filesInGroupsFolder) { storageDialog.filenameListbox.Items.Add(s.Substring(s.LastIndexOf('\\') + 1)); } storageDialog.filenameListbox.SelectionChanged += filenameListbox_SelectionChanged; storageDialog.Title = Properties.Resources.GroupStoreDialogTitle; storageDialog.listLabel.Content = Properties.Resources.GroupStoreDialogListLabel; storageDialog.filenameTextbox.Text = "NewGroup.agr"; storageDialog.modelNameLabel.Content = Properties.Resources.GroupStoreDialogGroupName; storageDialog.Owner = this; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { try { model groupModelToSave; if (groupToSave != null) { ClearSelectedChannelList(); ClearSelectedEventChannelList(); ClearSelectedComponentList(); foreach (componentType componentInGroup in groupToSave.AddedComponentList) { AddSelectedComponent(deploymentComponentList[componentInGroup.id]); } // make a submodel, containing all grouging relevant data groupModelToSave = new model(); groupModelToSave.modelName = groupToSave.GroupID; // insert all selected components to the model LinkedList<componentType> t = new LinkedList<componentType>(); for (int i = 0; i < selectedComponentList.Count; i++) { componentType ct = selectedComponentList.ElementAt(i); t.AddLast(ct); } groupModelToSave.components = t.ToArray(); // adding a group element to save the aliases groupModelToSave.groups = new group[1]; foreach (group groupToAdd in deploymentModel.groups) { if (groupToAdd.id == groupToSave.ID) { groupModelToSave.groups[0] = groupToAdd; break; } } //get all selected channels where the source and target components //are also selected LinkedList<channel> copyChannels = new LinkedList<channel>(); foreach (channel c in groupToSave.AddedChannelsList) { bool sourceFound, targetFound; sourceFound = targetFound = false; foreach (componentType mc in groupModelToSave.components) { if (mc.id == c.source.component.id) sourceFound = true; if (mc.id == c.target.component.id) targetFound = true; if (sourceFound && targetFound) break; } if (sourceFound && targetFound) copyChannels.AddLast(c); } // Adding dummy channels to make the input and output ports of the group visible componentType groupComponent = deploymentComponentList[groupToSave.ID]; int index = 0; foreach (object o in groupComponent.ports) { channel c = new channel(); c.id = "bindingveigl." + index; if (o is inputPortType) { c.source.component.id = pasteDummyName; c.source.port.id = "out"; c.target.component.id = ((inputPortType)o).refs.componentID; c.target.port.id = ((inputPortType)o).refs.portID; } else { c.source.component.id = ((outputPortType)o).refs.componentID; c.source.port.id = ((outputPortType)o).refs.portID; c.target.component.id = pasteDummyName; c.target.port.id = "in"; } copyChannels.AddLast(c); index++; } groupModelToSave.channels = new channel[copyChannels.Count]; for (int i = 0; i < copyChannels.Count; i++) groupModelToSave.channels[i] = copyChannels.ElementAt(i); // get all selected Eventchannels index = 0; LinkedList<eventChannel> copyEventChannels = new LinkedList<eventChannel>(); LinkedList<EventListenerPort> foundEdgeListenerEvents = new LinkedList<EventListenerPort>(); LinkedList<EventTriggerPort> foundEdgeTriggerEvents = new LinkedList<EventTriggerPort>(); foreach (eventChannel ec in eventChannelList) { // search for each event channel on the edge of the group element if (!selectedComponentList.Contains(deploymentComponentList[ec.targets.target.component.id]) && selectedComponentList.Contains(deploymentComponentList[ec.sources.source.component.id])) { eventChannel newEc = new eventChannel(); newEc.id = "eventbindingveigl." + index; newEc.sources.source.component.id = ec.sources.source.component.id; newEc.sources.source.eventPort.id = ec.sources.source.eventPort.id; newEc.targets.target.component.id = pasteDummyName; newEc.targets.target.eventPort.id = "eventlistener"; index++; copyEventChannels.AddLast(newEc); // search for each event channel on the edge of the group element } else if (selectedComponentList.Contains(deploymentComponentList[ec.targets.target.component.id]) && !selectedComponentList.Contains(deploymentComponentList[ec.sources.source.component.id])) { eventChannel newEc = new eventChannel(); newEc.id = "eventbindingveigl." + index; newEc.sources.source.component.id = pasteDummyName; newEc.sources.source.eventPort.id = "eventtrigger"; newEc.targets.target.component.id = ec.targets.target.component.id; newEc.targets.target.eventPort.id = ec.targets.target.eventPort.id; index++; copyEventChannels.AddLast(newEc); } else if ((selectedComponentList.Contains(deploymentComponentList[ec.targets.target.component.id]) && selectedComponentList.Contains(deploymentComponentList[ec.sources.source.component.id]))) { copyEventChannels.AddFirst(ec); } } // Adding dummy eventchannels to make the input and output ports of the group visible foreach (EventListenerPort elp in groupComponent. EventListenerList) { eventChannel newEc = new eventChannel(); foreach (componentType mc in groupModelToSave.components) { if (elp.EventListenerId.StartsWith(mc.id)) { newEc.targets.target.component.id = mc.id; newEc.targets.target.eventPort.id = ((EventListenerPort)mc.EventListenerList[0]).EventListenerId; newEc.id = "eventbindingveigl." + index; newEc.sources.source.component.id = pasteDummyName; newEc.sources.source.eventPort.id = "eventtrigger"; index++; copyEventChannels.AddLast(newEc); break; } } } foreach (EventTriggerPort etp in groupComponent.EventTriggerList) { eventChannel newEc = new eventChannel(); foreach (componentType mc in groupModelToSave.components) { if (etp.EventTriggerId.StartsWith(mc.id)) { newEc.id = "eventbindingveigl." + index; newEc.sources.source.component.id = mc.id; newEc.sources.source.eventPort.id = ((EventTriggerPort)mc.EventTriggerList[0]).EventTriggerId; newEc.targets.target.component.id = pasteDummyName; newEc.targets.target.eventPort.id = "eventlistener"; index++; copyEventChannels.AddLast(newEc); break; } } } if (copyEventChannels.Count == 0) { groupModelToSave.eventChannels = null; } else { groupModelToSave.eventChannels = copyEventChannels.ToArray(); } groupModelToSave = CopyModel(groupModelToSave); // write group stream XmlSerializer x = new XmlSerializer(groupModelToSave.GetType()); string filename; if (ini.IniReadValue("Options", "useAppDataFolder").Equals("true")) { filename = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\AsTeRICS\\ACS\\groups\\" + storageDialog.filenameTextbox.Text; } else { filename = AppDomain.CurrentDomain.BaseDirectory + "\\groups\\" + storageDialog.filenameTextbox.Text; } if (!filename.EndsWith(".agr")) { filename += ".agr"; } FileStream str = new FileStream(filename, FileMode.Create); x.Serialize(str, groupModelToSave); str.Close(); // add new group to list of groups bool alreadyInMenu = false; foreach (RibbonApplicationSplitMenuItem i in groupDropDown.Items) { if (((string)i.CommandParameter) == filename) { alreadyInMenu = true; break; } } if (!alreadyInMenu) { 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 ex) { MessageBox.Show(Properties.Resources.StoreModelOnAREError, Properties.Resources.GroupStoreErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } } } else { MessageBox.Show(Properties.Resources.GroupStoreNoGroupSelected, Properties.Resources.GroupStoreErrorHeader, MessageBoxButton.OK, MessageBoxImage.Information); } }
/// <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> /// Delete a model on the ARE storage /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeleteModelOnStorage_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.DeleteStoredModelButton; storageDialog.Owner = this; storageDialog.filenameTextbox.IsEnabled = false; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { try { asapiClient.deleteModelFile(storageDialog.filenameTextbox.Text); } catch (Exception ex) { MessageBox.Show(Properties.Resources.DeleteModelOnAREError, Properties.Resources.DeleteModelOnAREErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } } } }
/// <summary> /// Storing the active model of the canvas into the ARE storage /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void StoreModelOnARE_Click(object sender, RoutedEventArgs e) { List<string> storedModels = null; // load the list of all stored models 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); } // Show the list of all stored models 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.StoreModelButton; if (saveFile != null) { storageDialog.filenameTextbox.Text = saveFile.Substring(saveFile.LastIndexOf('\\') + 1); } else { storageDialog.filenameTextbox.Text = "NewModel.acs"; } storageDialog.Owner = this; storageDialog.ShowDialog(); if (storageDialog.filenameTextbox.Text != null && storageDialog.filenameTextbox.Text != "") { try { asapiClient.storeModel(ConvertDeploymentModelToValidString(), storageDialog.filenameTextbox.Text); } catch (Exception ex) { MessageBox.Show(Properties.Resources.StoreModelOnAREError, Properties.Resources.StoreModelOnAREErrorHeader, MessageBoxButton.OK, MessageBoxImage.Error); traceSource.TraceEvent(TraceEventType.Error, 3, ex.Message); } } } }