/// <summary> /// Creates an empty form. /// </summary> public SubscribeEventsDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); BrowseCTRL.BrowseTV.CheckBoxes = true; BrowseCTRL.BrowseTV.AfterCheck += new TreeViewEventHandler(BrowseTV_AfterCheck); m_PublishStatusChanged = new EventHandler(OnPublishStatusChanged); ItemsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Items"); m_dataset.Tables[0].Columns.Add("MonitoredItem", typeof(MonitoredItem)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("NodeAttribute", typeof(string)); m_dataset.Tables[0].Columns.Add("MonitoringMode", typeof(MonitoringMode)); m_dataset.Tables[0].Columns.Add("SamplingInterval", typeof(double)); m_dataset.Tables[0].Columns.Add("DiscardOldest", typeof(bool)); m_dataset.Tables[0].Columns.Add("OperationStatus", typeof(StatusCode)); ItemsDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Constructs a new instance. /// </summary> public SubscribeDataListViewCtrl() { InitializeComponent(); m_PublishStatusChanged = new EventHandler(OnPublishStatusChanged); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); m_dataset.Tables[0].Columns.Add("MonitoredItem", typeof(MonitoredItem)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("NodeAttribute", typeof(string)); m_dataset.Tables[0].Columns.Add("IndexRange", typeof(string)); m_dataset.Tables[0].Columns.Add("DataEncoding", typeof(QualifiedName)); m_dataset.Tables[0].Columns.Add("MonitoringMode", typeof(MonitoringMode)); m_dataset.Tables[0].Columns.Add("SamplingInterval", typeof(double)); m_dataset.Tables[0].Columns.Add("QueueSize", typeof(uint)); m_dataset.Tables[0].Columns.Add("DiscardOldest", typeof(bool)); m_dataset.Tables[0].Columns.Add("Filter", typeof(MonitoringFilter)); m_dataset.Tables[0].Columns.Add("OperationStatus", typeof(StatusCode)); m_dataset.Tables[0].Columns.Add("DataValue", typeof(DataValue)); m_dataset.Tables[0].Columns.Add("DataType", typeof(string)); m_dataset.Tables[0].Columns.Add("Value", typeof(Variant)); m_dataset.Tables[0].Columns.Add("StatusCode", typeof(StatusCode)); m_dataset.Tables[0].Columns.Add("SourceTimestamp", typeof(string)); m_dataset.Tables[0].Columns.Add("ServerTimestamp", typeof(string)); ResultsDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Constructs a new instance. /// </summary> public CallRequestListViewCtrl() { InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Arguments"); m_dataset.Tables[0].Columns.Add("Argument", typeof(Argument)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("Name", typeof(string)); m_dataset.Tables[0].Columns.Add("DataType", typeof(string)); m_dataset.Tables[0].Columns.Add("Value", typeof(Variant)); m_dataset.Tables[0].Columns.Add("Result", typeof(string)); ResultsDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Constructs the object. /// </summary> public EditComplexValueCtrl() { InitializeComponent(); MaxDisplayTextLength = 100; ValuesDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Values"); m_dataset.Tables[0].Columns.Add("AccessInfo", typeof(AccessInfo)); m_dataset.Tables[0].Columns.Add("Name", typeof(string)); m_dataset.Tables[0].Columns.Add("DataType", typeof(string)); m_dataset.Tables[0].Columns.Add("Value", typeof(string)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); ValuesDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Constructs a new instance. /// </summary> public TypeFieldsListViewCtrl() { InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); m_dataset.Tables[0].Columns.Add("InstanceDeclaration", typeof(InstanceDeclaration)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("BrowsePath", typeof(string)); m_dataset.Tables[0].Columns.Add("DataType", typeof(string)); m_dataset.Tables[0].Columns.Add("Description", typeof(string)); m_dataset.Tables[0].Columns.Add("Value", typeof(Variant)); ResultsDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Creates a new instance. /// </summary> public ReferenceListCtrl() { InitializeComponent(); BrowseDirection = BrowseDirection.Both; ReferencesDV.AutoGenerateColumns = false; ReferencesDV.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("References"); m_dataset.Tables[0].Columns.Add("Reference", typeof(ReferenceDescription)); m_dataset.Tables[0].Columns.Add("TargetName", typeof(string)); m_dataset.Tables[0].Columns.Add("ReferenceType", typeof(string)); m_dataset.Tables[0].Columns.Add("IsForward", typeof(bool)); m_dataset.Tables[0].Columns.Add("NodeClass", typeof(string)); m_dataset.Tables[0].Columns.Add("TargetType", typeof(string)); m_dataset.Tables[0].Columns.Add("Image", typeof(Image)); ReferencesDV.DataSource = m_dataset.Tables[0].DefaultView; }
/// <summary> /// Constructs a new instance. /// </summary> public WriteRequestListViewCtrl() { InitializeComponent(); ResultsDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Requests"); m_dataset.Tables[0].Columns.Add("WriteValue", typeof(WriteValue)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("NodeName", typeof(string)); m_dataset.Tables[0].Columns.Add("Attribute", typeof(string)); m_dataset.Tables[0].Columns.Add("IndexRange", typeof(string)); m_dataset.Tables[0].Columns.Add("DataType", typeof(string)); m_dataset.Tables[0].Columns.Add("Value", typeof(Variant)); m_dataset.Tables[0].Columns.Add("StatusCode", typeof(StatusCode)); m_dataset.Tables[0].Columns.Add("SourceTimestamp", typeof(string)); m_dataset.Tables[0].Columns.Add("ServerTimestamp", typeof(string)); m_dataset.Tables[0].Columns.Add("Result", typeof(StatusCode)); ResultsDV.DataSource = m_dataset.Tables[0]; }
/// <summary> /// Constructs a new instance. /// </summary> public EventFilterListViewCtrl() { InitializeComponent(); FilterDV.AutoGenerateColumns = false; ImageList = new ClientUtils().ImageList; m_dataset = new DataSet(); m_dataset.Tables.Add("Events"); m_dataset.Tables[0].Columns.Add("Field", typeof(FilterDeclarationField)); m_dataset.Tables[0].Columns.Add("Icon", typeof(Image)); m_dataset.Tables[0].Columns.Add("BrowsePath", typeof(string)); m_dataset.Tables[0].Columns.Add("SelectField", typeof(bool)); m_dataset.Tables[0].Columns.Add("DisplayInList", typeof(bool)); m_dataset.Tables[0].Columns.Add("FilterEnabled", typeof(bool)); m_dataset.Tables[0].Columns.Add("FilterOperator", typeof(FilterOperator)); m_dataset.Tables[0].Columns.Add("FilterValue", typeof(Variant)); m_dataset.Tables[0].Columns.Add("Index", typeof(int)); m_dataset.Tables[0].DefaultView.Sort = "Index"; FilterDV.DataSource = m_dataset.Tables[0].DefaultView; }
private void MainForm_Load( object sender, EventArgs e ) { ClassEditControl scout = new ClassEditControl( "Scout" ); scout.ClassImage = Properties.Resources.scout; // heavy ClassEditControl heavy = new ClassEditControl( "Heavy" ); heavy.ClassImage = Properties.Resources.heavy; // medic ClassEditControl medic = new ClassEditControl( "Medic" ); medic.ClassImage = Properties.Resources.medic; // soldier ClassEditControl soldier = new ClassEditControl( "Soldier" ); soldier.ClassImage = Properties.Resources.soldier; // engi ClassEditControl engineer = new ClassEditControl( "Engineer" ); engineer.ClassImage = Properties.Resources.engineer; // spy ClassEditControl spy = new ClassEditControl( "Spy" ); spy.ClassImage = Properties.Resources.spy; // sniper ClassEditControl sniper = new ClassEditControl( "Sniper" ); sniper.ClassImage = Properties.Resources.sniper; // demo ClassEditControl demo = new ClassEditControl( "Demoman" ); demo.ClassImage = Properties.Resources.demoman; // pyro ClassEditControl pyro = new ClassEditControl( "Pyro" ); pyro.ClassImage = Properties.Resources.pyro; flowLayoutPanel1.Controls.Add( scout ); flowLayoutPanel1.Controls.Add( heavy ); flowLayoutPanel1.Controls.Add( medic ); flowLayoutPanel1.Controls.Add( soldier ); flowLayoutPanel1.Controls.Add( engineer ); flowLayoutPanel1.Controls.Add( spy ); flowLayoutPanel1.Controls.Add( sniper ); flowLayoutPanel1.Controls.Add( demo ); flowLayoutPanel1.Controls.Add( pyro ); toolStripStatusLabel1.Text = "Initializing steamworks..."; try { int error; client = ( SteamClient008 )Steamworks.CreateInterface( SteamClient008.InterfaceVersion, out error ); if ( client == null ) throw new InvalidOperationException( "Unable to create ISteamClient." ); pipe = client.CreateSteamPipe(); if ( pipe == SteamPipeHandle.InvalidHandle ) throw new InvalidOperationException( "Unable to create steam pipe." ); user = client.ConnectToGlobalUser( pipe ); clientEngine = ( ClientEngine )Steamworks.CreateInterface( ClientEngine.InterfaceVersion, out error ); if ( clientEngine == null ) throw new InvalidOperationException( "Unable to create IClientEngine." ); } catch (Exception ex) { MessageBox.Show( this, "Unable to initialize steamworks. Please ensure the following:\n\n" + " * steamclient.dll, tier0_s.dll, vstdlib_s.dll, are present in the running directory\n" + " * You are logged into steam and are online.\n\nAdditional Details: " + ex.Message, "TF2 Stats Suite" ); this.Close(); return; } toolStripStatusLabel1.Text = "Loading stats..."; statsAcc = new StatsAccessor( client, pipe, user, 440 ); steamUser = ( SteamUser012 )client.GetISteamUser( user, pipe, SteamUser012.InterfaceVersion ); clientUtils = ( ClientUtils )clientEngine.GetIClientUtils( pipe, ClientUtils.InterfaceVersion ); clientUtils.SetAppIDForCurrentPipe( new AppID( 440 ) ); foreach ( ClassEditControl cec in flowLayoutPanel1.Controls ) { toolStripStatusLabel1.Text = "Loading stats for '" + cec.Class + "'..."; cec.LoadStats( statsAcc ); Application.DoEvents(); } toolStripStatusLabel1.Text = "Stats fully loaded!"; }
/// <summary> /// /// </summary> /// <exception cref="ApiException">Thrown when fails to make API call</exception> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns><see cref="Task"/><<see cref="ApiResponse{T}"/>> where T : <see cref="InlineResponseDefault"/></returns> public async Task <ApiResponse <InlineResponseDefault> > FooGetWithHttpInfoAsync(System.Threading.CancellationToken?cancellationToken = null) { try { using (HttpRequestMessage request = new HttpRequestMessage()) { UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/foo"; request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { "application/json" }; string accept = ClientUtils.SelectHeaderAccept(accepts); if (accept != null) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); } request.Method = HttpMethod.Get; using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { DateTime requestedAt = DateTime.UtcNow; string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); if (ApiResponded != null) { try { ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/foo")); } catch (Exception e) { Logger.LogError(e, "An error occured while invoking ApiResponded."); } } ApiResponse <InlineResponseDefault> apiResponse = new ApiResponse <InlineResponseDefault>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) { apiResponse.Content = Newtonsoft.Json.JsonConvert.DeserializeObject <InlineResponseDefault>(apiResponse.RawContent, ClientUtils.JsonSerializerSettings); } return(apiResponse); } } } catch (Exception e) { Logger.LogError(e, "An error occured while sending the request to the server."); throw; } }
/// <summary> /// Updates the display with a new value for a monitored variable. /// </summary> private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); return; } try { EventFieldList notification = e.NotificationValue as EventFieldList; if (notification == null) { return; } // check the type of event. NodeId eventTypeId = ClientUtils.FindEventType(monitoredItem, notification); // ignore unknown events. if (NodeId.IsNull(eventTypeId)) { return; } // construct the audit object. SystemCycleStatusEventState status = ClientUtils.ConstructEvent( m_session, monitoredItem, notification, m_knownEventTypes, m_eventTypeMappings) as SystemCycleStatusEventState; if (e == null) { return; } ListViewItem item = new ListViewItem(String.Empty); item.SubItems.Add(String.Empty); // Source item.SubItems.Add(String.Empty); // Type item.SubItems.Add(String.Empty); // CycleId item.SubItems.Add(String.Empty); // Step item.SubItems.Add(String.Empty); // Time item.SubItems.Add(String.Empty); // Message // look up the condition type metadata in the local cache. INode type = m_session.NodeCache.Find(status.TypeDefinitionId); // Source if (status.SourceName != null) { item.SubItems[0].Text = Utils.Format("{0}", status.SourceName.Value); } else { item.SubItems[0].Text = null; } // Type if (type != null) { item.SubItems[1].Text = Utils.Format("{0}", type); } else { item.SubItems[1].Text = null; } // CycleId if (status.CycleId != null) { item.SubItems[2].Text = Utils.Format("{0}", status.CycleId.Value); } else { item.SubItems[2].Text = null; } // Step if (status.CurrentStep != null && status.CurrentStep.Value != null) { item.SubItems[3].Text = Utils.Format("{0}", status.CurrentStep.Value.Name); } else { item.SubItems[3].Text = null; } // Time if (status.Time != null) { item.SubItems[4].Text = Utils.Format("{0:HH:mm:ss.fff}", status.Time.Value.ToLocalTime()); } else { item.SubItems[4].Text = null; } // Message if (status.Message != null) { item.SubItems[5].Text = Utils.Format("{0}", status.Message.Value); } else { item.SubItems[5].Text = null; } item.Tag = status; EventsLV.Items.Add(item); // adjust the width of the columns. for (int ii = 0; ii < EventsLV.Columns.Count; ii++) { EventsLV.Columns[ii].Width = -2; } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void OnUnEdit() { ButtonImage.color = ClientUtils.GetColorFromColorDict(AllColors.ColorType.BuildButtonDefaultColor); }
/// <summary> /// Updates the application after connecting to or disconnecting from the server. /// </summary> private void Server_ConnectComplete(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; if (m_session == null) { StartBTN.Enabled = false; return; } // set a suitable initial state. if (m_session != null && !m_connectedOnce) { m_connectedOnce = true; } // this client has built-in knowledge of the information model used by the server. NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.Methods); string[] browsePaths = new string[] { "1:My Process/1:State", "1:My Process", "1:My Process/1:Start" }; List <NodeId> nodes = ClientUtils.TranslateBrowsePaths( m_session, ObjectIds.ObjectsFolder, wellKnownNamespaceUris, browsePaths); // subscribe to the state if available. if (nodes.Count > 0 && !NodeId.IsNull(nodes[0])) { m_subscription = new Subscription(); m_subscription.PublishingEnabled = true; m_subscription.PublishingInterval = 1000; m_subscription.Priority = 1; m_subscription.KeepAliveCount = 10; m_subscription.LifetimeCount = 20; m_subscription.MaxNotificationsPerPublish = 1000; m_session.AddSubscription(m_subscription); m_subscription.Create(); MonitoredItem monitoredItem = new MonitoredItem(); monitoredItem.StartNodeId = nodes[0]; monitoredItem.AttributeId = Attributes.Value; monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); m_subscription.AddItem(monitoredItem); m_subscription.ApplyChanges(); } // save the object/method if (nodes.Count > 2) { m_objectNode = nodes[1]; m_methodNode = nodes[2]; } InitialStateTB.Text = "1"; FinalStateTB.Text = "100"; StartBTN.Enabled = true; } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e) { //Change Mould string message = "Do you want to select this Mould?"; var result = MessageBox.Show(message, (string)"Change Mould", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { //Show the Serial Number of the selected Mould if (comboBox1.SelectedIndex == 0) { //Change the values of Change_Mould and Mould_Changed try { bool arr = true; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Change_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_Changed"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection values = Read_Value("ns=3;s=Mould_1_SN"); label8.Text = (string)values[0].Value; //Update the value of Mould_tobeused try { string arr = "1"; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_tobeused"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Update the value of Actual_Mould try { int arr = 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } else if (comboBox1.SelectedIndex == 1) { //Change the values of Change_Mould and Mould_Changed try { bool arr = true; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Change_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_Changed"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection values = Read_Value("ns=3;s=Mould_2_SN"); label8.Text = (string)values[0].Value; //Update the value of Mould_tobeused try { string arr = "2"; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_tobeused"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Update the value of Actual_Mould try { int arr = 2; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } button1.Enabled = false; } else if (result == DialogResult.No) { comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged_1; comboBox1.SelectedText = _comboBoxIndex; comboBox1.Text = _comboBoxIndex; comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged_1; } }
void monitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { //This part of the code is needed to manage issues related to windows forms if (this.InvokeRequired) { this.BeginInvoke(new MonitoredItemNotificationEventHandler(monitoredItem_Notification), monitoredItem, e); return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } //is call because of atual_state? if (monitoredItem.ClientHandle == Actual_State_handle) { double value = (double)notification.Value.WrappedValue.Value; Actual_State = value; //update screen label4.Text = Actual_State.ToString(); if (Actual_State > 1) { try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Start_Piece"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); if (StatusCode.IsBad(results[0])) { throw new ServiceResultException(results[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } if (Actual_State == 8) { button1.Enabled = true; } } //is call because of Change_Mould? if (monitoredItem.ClientHandle == Change_Mould_handle) { bool value = (bool)notification.Value.WrappedValue.Value; //update screen if (value == false) { button1.Enabled = true; } } }
/// <summary> /// Updates the application after connecting to or disconnecting from the server. /// </summary> private void Server_ConnectComplete(object sender, EventArgs e) { try { m_session = ConnectServerCTRL.Session; // set a suitable initial state. if (m_session != null && !m_connectedOnce) { m_connectedOnce = true; } // browse the instances in the server. //BrowseCTRL.Initialize(m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); //verify if Session is established if (m_session != null) { //verify if the Subscription was not already created if (m_subscription == null) { //create the subscritpion m_subscription = new Subscription(m_session.DefaultSubscription); m_subscription.PublishingEnabled = true; m_subscription.PublishingInterval = 1000; //1000msec interval m_session.AddSubscription(m_subscription); m_subscription.Create(); } //Add Start_Piece to monitored items monitoredItem = new MonitoredItem(m_subscription.DefaultItem); monitoredItem.StartNodeId = "ns=3;s=Start_Piece"; monitoredItem.AttributeId = Attributes.Value; monitoredItem.MonitoringMode = MonitoringMode.Reporting; monitoredItem.SamplingInterval = 1000; monitoredItem.QueueSize = 0; monitoredItem.DiscardOldest = true; //get handle number Start_Piece_handle = monitoredItem.ClientHandle; //define event handler for this item, and then add to subscription monitoredItem.Notification += new MonitoredItemNotificationEventHandler(monitoredItem_Notification); m_subscription.AddItem(monitoredItem); m_subscription.ApplyChanges(); //Add Change_Mould to monitored items monitoredItem = new MonitoredItem(m_subscription.DefaultItem); monitoredItem.StartNodeId = "ns=3;s=Change_Mould"; monitoredItem.AttributeId = Attributes.Value; monitoredItem.MonitoringMode = MonitoringMode.Reporting; monitoredItem.SamplingInterval = 1000; monitoredItem.QueueSize = 0; monitoredItem.DiscardOldest = true; //get handle number Change_Mould_handle = monitoredItem.ClientHandle; //define event handler for this item, and then add to subscription monitoredItem.Notification += new MonitoredItemNotificationEventHandler(monitoredItem_Notification); m_subscription.AddItem(monitoredItem); m_subscription.ApplyChanges(); //Add Actual_State to monitored items monitoredItem = new MonitoredItem(m_subscription.DefaultItem); monitoredItem.StartNodeId = "ns=3;s=Actual_State"; monitoredItem.AttributeId = Attributes.Value; monitoredItem.MonitoringMode = MonitoringMode.Reporting; monitoredItem.SamplingInterval = 1000; monitoredItem.QueueSize = 0; monitoredItem.DiscardOldest = true; //get handle number Actual_State_handle = monitoredItem.ClientHandle; //define event handler for this item, and then add to subscription monitoredItem.Notification += new MonitoredItemNotificationEventHandler(monitoredItem_Notification); m_subscription.AddItem(monitoredItem); m_subscription.ApplyChanges(); DataValueCollection results = Read_Value("ns=3;s=Mould_1"); DataValueCollection results1 = Read_Value("ns=3;s=Mould_2"); string Mould_1Value = (string)results[0].Value; string Mould_2Value = (string)results1[0].Value; comboBox1.Items.Add(Mould_1Value); comboBox1.Items.Add(Mould_2Value); //comboBox1.Text = Mould_1Value; //Open connection to DB string connectionString = "SERVER=" + DB_server + ";" + "DATABASE=" + DB_database + ";" + "UID=" + DB_uid + ";" + "PASSWORD="******";"; DB_connection = new MySqlConnection(connectionString); try { DB_connection.Open(); } catch (MySqlException ex) { MessageBox.Show(ex.Message); }; } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private List <SlideUpdatedResultDto> UpdateListOfSlides(SlideTagExCollection slideTags) { var result = new List <SlideUpdatedResultDto>(); if (slideTags != null) { for (int i = 0; i < slideTags.Count; i++) { SlideTagEx slideTagEx = slideTags[i]; string sourceFilename = ClientUtils.UndecorateFileName(slideTagEx.SourceFilename); string status = string.Empty; string lastModDate = slideTagEx.SourceLastModDate.ToString(Message.DateFormat); string source = string.Format("{0} - Slide {1}", sourceFilename, slideTagEx.SourceSlideNum); switch (slideTagEx.SlideStatus) { case TagUpdateStatus.Updated: status = "Updated"; break; case TagUpdateStatus.New: status = "New"; break; case TagUpdateStatus.MissingOrDeleted: status = "Deleted"; lastModDate = string.Empty; source = sourceFilename; break; case TagUpdateStatus.NoChange: status = "No change"; break; case TagUpdateStatus.Added: status = "Added"; lastModDate = string.Empty; source = string.Empty; break; case TagUpdateStatus.Moved: status = "Moved"; break; case TagUpdateStatus.Local: lastModDate = string.Empty; source = string.Empty; break; } bool isUpdated = Helper.IsSlideUpdated(slideTagEx.SlideStatus); result.Add(new SlideUpdatedResultDto { Tag = slideTagEx, PptSlideIndex = slideTagEx.PptSlideIndex == 0 ? slideTagEx.SourceSlideNum : slideTagEx.PptSlideIndex, Status = status, LastModDate = lastModDate, Source = source, Id = slideTagEx.Slide.Id.ToString(), IsUpdated = isUpdated }); } } return(result.OrderBy(x => x.PptSlideIndex).ToList()); }
public BrowseTypesDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); }
public PerformanceTestDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); }
public FindNodeDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); }
private void ParseXml(XmlTextReader reader) { bool success = false; try { try { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { string s = reader.LocalName; if (reader.LocalName.Equals(ResXResourceWriter.AssemblyStr)) { ParseAssemblyNode(reader); } else if (reader.LocalName.Equals(ResXResourceWriter.DataStr)) { ParseDataNode(reader, false); } else if (reader.LocalName.Equals(ResXResourceWriter.ResHeaderStr)) { ParseResHeaderNode(reader); } else if (reader.LocalName.Equals(ResXResourceWriter.MetadataStr)) { ParseDataNode(reader, true); } } } success = true; } catch (SerializationException se) { Point pt = GetPosition(reader); string newMessage = string.Format(SR.SerializationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, se.Message); XmlException xml = new XmlException(newMessage, se, pt.Y, pt.X); SerializationException newSe = new SerializationException(newMessage, xml); throw newSe; } catch (TargetInvocationException tie) { Point pt = GetPosition(reader); string newMessage = string.Format(SR.InvocationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, tie.InnerException.Message); XmlException xml = new XmlException(newMessage, tie.InnerException, pt.Y, pt.X); TargetInvocationException newTie = new TargetInvocationException(newMessage, xml); throw newTie; } catch (XmlException e) { throw new ArgumentException(string.Format(SR.InvalidResXFile, e.Message), e); } catch (Exception e) { if (ClientUtils.IsSecurityOrCriticalException(e)) { throw; } else { Point pt = GetPosition(reader); XmlException xmlEx = new XmlException(e.Message, e, pt.Y, pt.X); throw new ArgumentException(string.Format(SR.InvalidResXFile, xmlEx.Message), xmlEx); } } } finally { if (!success) { resData = null; resMetadata = null; } } bool validFile = false; if (resHeaderMimeType == ResXResourceWriter.ResMimeType) { Type readerType = typeof(ResXResourceReader); Type writerType = typeof(ResXResourceWriter); string readerTypeName = resHeaderReaderType; string writerTypeName = resHeaderWriterType; if (readerTypeName != null && readerTypeName.IndexOf(',') != -1) { readerTypeName = readerTypeName.Split(',')[0].Trim(); } if (writerTypeName != null && writerTypeName.IndexOf(',') != -1) { writerTypeName = writerTypeName.Split(',')[0].Trim(); } if (readerTypeName != null && writerTypeName != null && readerTypeName.Equals(readerType.FullName) && writerTypeName.Equals(writerType.FullName)) { validFile = true; } } if (!validFile) { resData = null; resMetadata = null; throw new ArgumentException(SR.InvalidResXFileReaderWriterTypes); } }
private void button1_Click(object sender, EventArgs e) { try { int[] arr = { 1, 2 }; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; if (comboBox1.SelectedIndex == 0) { valueToWrite.Value.Value = arr[0]; } else if (comboBox1.SelectedIndex == 1) { valueToWrite.Value.Value = arr[1]; } valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Start the production of the piece DataValueCollection results = Read_Value("ns=3;s=Start_Piece"); bool Start_PieceValue = (bool)results[0].Value; try { bool[] arr = { true, false }; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Start_Piece"; valueToWrite.AttributeId = Attributes.Value; if (Start_PieceValue) { valueToWrite.Value.Value = arr[1]; } else { valueToWrite.Value.Value = arr[0]; } valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Disable Start Piece button until piece is made button1.Enabled = false; //Assign a Serial Number to the pieces if (comboBox1.SelectedIndex == 0) { try { int arr = Piece_SN_Value + 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Piece_SN"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection results1 = Read_Value("ns=3;s=Piece_SN"); Piece_SN_Value = (int)results1[0].Value; } else if (comboBox1.SelectedIndex == 1) { try { int arr = Piece_SN_Value + 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Piece_SN"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection results1 = Read_Value("ns=3;s=Piece_SN"); Piece_SN_Value = (int)results1[0].Value; } label6.Text = Piece_SN_Value.ToString(); //Read the value of the Serial Number of the Machine DataValueCollection results4 = Read_Value("ns=3;s=Machine_SN"); string Machine_SN_Value = (string)results4[0].Value; //Read the value of the Serial Number of the Mould if (comboBox1.SelectedIndex == 0) { results3 = Read_Value("ns=3;s=Mould_1_SN"); try { int arr = 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } else if (comboBox1.SelectedIndex == 1) { results3 = Read_Value("ns=3;s=Mould_2_SN"); try { int arr = 2; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } string Mould_SN_Value = (string)results3[0].Value; DataValueCollection read = Read_Value("ns=3;s=Operator_ID"); int Operator_ID_Value = (int)read[0].Value; //when new piece is made then update DB //format of convertion from real number to string NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberGroupSeparator = ""; nfi.NumberDecimalDigits = 2; //Execute command string query = Utils.Format("INSERT INTO db_project.table1 (Piece_SN, Machine_SN, Mould_SN, Operator_ID) VALUES({0},{1},{2},{3});", Piece_SN_Value.ToString("N", nfi), Machine_SN_Value, Mould_SN_Value, Operator_ID_Value.ToString("N", nfi)); MySqlCommand cmd = new MySqlCommand(query, DB_connection); cmd.ExecuteNonQuery(); }
/// <summary> /// To test special tags To test special tags and operation ID starting with number /// </summary> /// <exception cref="ApiException">Thrown when fails to make API call</exception> /// <param name="modelClient">client model</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns><see cref="Task"/><<see cref="ApiResponse{T}"/>> where T : <see cref="ModelClient"/></returns> public async Task <ApiResponse <ModelClient> > Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken?cancellationToken = null) { try { #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' if (modelClient == null) { throw new ArgumentNullException(nameof(modelClient)); } #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' using (HttpRequestMessage request = new HttpRequestMessage()) { UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress.Host; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/another-fake/dummy"; if ((modelClient as object) is System.IO.Stream stream) { request.Content = new StreamContent(stream); } else { request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(modelClient, ClientUtils.JsonSerializerSettings)); } request.RequestUri = uriBuilder.Uri; string[] contentTypes = new string[] { "application/json" }; string contentType = ClientUtils.SelectHeaderContentType(contentTypes); if (contentType != null) { request.Content.Headers.Add("ContentType", contentType); } string[] accepts = new string[] { "application/json" }; string accept = ClientUtils.SelectHeaderAccept(accepts); if (accept != null) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); } request.Method = HttpMethod.Patch; using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { DateTime requestedAt = DateTime.UtcNow; string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); if (ApiResponded != null) { try { ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/another-fake/dummy")); } catch (Exception e) { Logger.LogError(e, "An error occured while invoking ApiResponded."); } } ApiResponse <ModelClient> apiResponse = new ApiResponse <ModelClient>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) { apiResponse.Content = Newtonsoft.Json.JsonConvert.DeserializeObject <ModelClient>(apiResponse.RawContent, ClientUtils.JsonSerializerSettings); } return(apiResponse); } } } catch (Exception e) { Logger.LogError(e, "An error occured while sending the request to the server."); throw; } }
/// <summary> /// Handles the Click event of the Monitoring_DeleteMI control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Monitoring_DeleteMI_Click(object sender, EventArgs e) { try { // check if operation is currently allowed. if (MonitoredItemsLV.SelectedItems.Count == 0) { return; } // collect the items to delete. List <ListViewItem> itemsToDelete = new List <ListViewItem>(); for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++) { MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem; if (monitoredItem != null) { monitoredItem.Notification -= m_MonitoredItem_Notification; itemsToDelete.Add(MonitoredItemsLV.SelectedItems[ii]); if (m_subscription != null) { m_subscription.RemoveItem(monitoredItem); } } } // update the server. if (m_subscription != null) { m_subscription.ApplyChanges(); // check the status. for (int ii = 0; ii < itemsToDelete.Count; ii++) { MonitoredItem monitoredItem = itemsToDelete[ii].Tag as MonitoredItem; if (ServiceResult.IsBad(monitoredItem.Status.Error)) { itemsToDelete[ii].SubItems[8].Text = monitoredItem.Status.Error.StatusCode.ToString(); continue; } } } // remove the items. for (int ii = 0; ii < itemsToDelete.Count; ii++) { itemsToDelete[ii].Remove(); } MonitoredItemsLV.Columns[0].Width = -2; MonitoredItemsLV.Columns[1].Width = -2; MonitoredItemsLV.Columns[8].Width = -2; } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
public ItemValuesDlg() { // Required for Windows Form Designer support InitializeComponent(); Icon = ClientUtils.GetAppIcon(); }
/// <summary> /// Displays the attributes and properties in the attributes view. /// </summary> /// <param name="sourceId">The NodeId of the Node to browse.</param> private void DisplayAttributes(NodeId sourceId) { try { AttributesLV.Items.Clear(); ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); // attempt to read all possible attributes. for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = sourceId; nodeToRead.AttributeId = ii; nodesToRead.Add(nodeToRead); } int startOfProperties = nodesToRead.Count; // find all of the pror of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription(); nodeToBrowse1.NodeId = sourceId; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = 0; nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse1); // fetch property references from the server. ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false); if (references == null) { return; } for (int ii = 0; ii < references.Count; ii++) { // ignore external references. if (references[ii].NodeId.IsAbsolute) { continue; } ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)references[ii].NodeId; nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); } // read all values. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // process results. for (int ii = 0; ii < results.Count; ii++) { string name = null; string datatype = null; string value = null; // process attribute value. if (ii < startOfProperties) { // ignore attributes which are invalid for the node. if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid) { continue; } // get the name of the attribute. name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId); // display any unexpected error. if (StatusCode.IsBad(results[ii].StatusCode)) { datatype = Utils.Format("{0}", Attributes.GetDataTypeId(nodesToRead[ii].AttributeId)); value = Utils.Format("{0}", results[ii].StatusCode); } // display the value. else { TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value); datatype = typeInfo.BuiltInType.ToString(); if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions) { datatype += "[]"; } value = Utils.Format("{0}", results[ii].Value); } } // process property value. else { // ignore properties which are invalid for the node. if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown) { continue; } // get the name of the property. name = Utils.Format("{0}", references[ii - startOfProperties]); // display any unexpected error. if (StatusCode.IsBad(results[ii].StatusCode)) { datatype = String.Empty; value = Utils.Format("{0}", results[ii].StatusCode); } // display the value. else { TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value); datatype = typeInfo.BuiltInType.ToString(); if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions) { datatype += "[]"; } value = Utils.Format("{0}", results[ii].Value); } } // add the attribute name/value to the list view. ListViewItem item = new ListViewItem(name); item.SubItems.Add(datatype); item.SubItems.Add(value); AttributesLV.Items.Add(item); } // adjust width of all columns. for (int ii = 0; ii < AttributesLV.Columns.Count; ii++) { AttributesLV.Columns[ii].Width = -2; } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Creates an empty form. /// </summary> private MainForm() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); }
/// <summary> /// Changes the monitoring mode for the currently selected monitored items. /// </summary> private void Monitoring_MonitoringMode_Click(object sender, EventArgs e) { try { // check if operation is currently allowed. if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0) { return; } // determine the monitoring mode being requested. MonitoringMode monitoringMode = MonitoringMode.Disabled; if (sender == Monitoring_MonitoringMode_ReportingMI) { monitoringMode = MonitoringMode.Reporting; } if (sender == Monitoring_MonitoringMode_SamplingMI) { monitoringMode = MonitoringMode.Sampling; } // update the monitoring mode. List <MonitoredItem> itemsToChange = new List <MonitoredItem>(); for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++) { MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem; if (monitoredItem != null) { itemsToChange.Add(monitoredItem); } } // apply the changes to the server. m_subscription.SetMonitoringMode(monitoringMode, itemsToChange); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) { ListViewItem item = itemsToChange[ii].Handle as ListViewItem; if (item != null) { item.SubItems[8].Text = String.Empty; if (ServiceResult.IsBad(itemsToChange[ii].Status.Error)) { item.SubItems[8].Text = itemsToChange[ii].Status.Error.StatusCode.ToString(); } item.SubItems[2].Text = itemsToChange[ii].Status.MonitoringMode.ToString(); } } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
public async Task <ApiResponse <Dictionary <string, int>?> > GetInventoryWithHttpInfoAsync(System.Threading.CancellationToken?cancellationToken = null) { try { using (HttpRequestMessage request = new HttpRequestMessage()) { UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = HttpClient.BaseAddress !.Host; uriBuilder.Scheme = ClientUtils.SCHEME; uriBuilder.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; List <TokenBase> tokens = new List <TokenBase>(); ApiKeyToken apiKey = (ApiKeyToken)await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); tokens.Add(apiKey); apiKey.UseInHeader(request, "api_key"); request.RequestUri = uriBuilder.Uri; string[] accepts = new string[] { "application/json" }; string?accept = ClientUtils.SelectHeaderAccept(accepts); if (accept != null) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); } request.Method = HttpMethod.Get; using (HttpResponseMessage responseMessage = await HttpClient.SendAsync(request, cancellationToken.GetValueOrDefault()).ConfigureAwait(false)) { DateTime requestedAt = DateTime.UtcNow; string responseContent = await responseMessage.Content.ReadAsStringAsync(cancellationToken.GetValueOrDefault()).ConfigureAwait(false); if (ApiResponded != null) { try { ApiResponded.Invoke(this, new ApiResponseEventArgs(requestedAt, DateTime.UtcNow, responseMessage.StatusCode, "/store/inventory")); } catch (Exception e) { Logger.LogError(e, "An error occured while invoking ApiResponded."); } } ApiResponse <Dictionary <string, int>?> apiResponse = new ApiResponse <Dictionary <string, int>?>(responseMessage, responseContent); if (apiResponse.IsSuccessStatusCode) { apiResponse.Content = System.Text.Json.JsonSerializer.Deserialize <Dictionary <string, int> >(apiResponse.RawContent, ClientUtils.JsonSerializerOptions); } else if (apiResponse.StatusCode == (HttpStatusCode)429) { foreach (TokenBase token in tokens) { token.BeginRateLimit(); } } return(apiResponse); } } } catch (Exception e) { Logger.LogError(e, "An error occured while sending the request to the server."); throw; } }
/// <summary> /// Changes the sampling interval for the currently selected monitored items. /// </summary> private void Monitoring_SamplingInterval_Click(object sender, EventArgs e) { try { // check if operation is currently allowed. if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0) { return; } // determine the sampling interval being requested. double samplingInterval = 0; if (sender == Monitoring_SamplingInterval_1000MI) { samplingInterval = 1000; } else if (sender == Monitoring_SamplingInterval_2500MI) { samplingInterval = 2500; } else if (sender == Monitoring_SamplingInterval_5000MI) { samplingInterval = 5000; } // update the monitoring mode. List <MonitoredItem> itemsToChange = new List <MonitoredItem>(); for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++) { MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem; if (monitoredItem != null) { monitoredItem.SamplingInterval = (int)samplingInterval; itemsToChange.Add(monitoredItem); } } // apply the changes to the server. m_subscription.ApplyChanges(); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) { ListViewItem item = itemsToChange[ii].Handle as ListViewItem; if (item != null) { item.SubItems[8].Text = String.Empty; if (ServiceResult.IsBad(itemsToChange[ii].Status.Error)) { item.SubItems[8].Text = itemsToChange[ii].Status.Error.StatusCode.ToString(); } item.SubItems[3].Text = itemsToChange[ii].Status.SamplingInterval.ToString(); } } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Constructs a new instance. /// </summary> public EventListViewCtrl() { InitializeComponent(); EventsDV.AutoGenerateColumns = true; ImageList = new ClientUtils().ImageList; }
/// <summary> /// Changes the deadband for the currently selected monitored items. /// </summary> private void Monitoring_Deadband_Click(object sender, EventArgs e) { try { // check if operation is currently allowed. if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0) { return; } // determine the filter being requested. DataChangeFilter filter = new DataChangeFilter(); filter.Trigger = DataChangeTrigger.StatusValue; if (sender == Monitoring_Deadband_Absolute_5MI) { filter.DeadbandType = (uint)DeadbandType.Absolute; filter.DeadbandValue = 5.0; } else if (sender == Monitoring_Deadband_Absolute_10MI) { filter.DeadbandType = (uint)DeadbandType.Absolute; filter.DeadbandValue = 10.0; } else if (sender == Monitoring_Deadband_Absolute_25MI) { filter.DeadbandType = (uint)DeadbandType.Absolute; filter.DeadbandValue = 25.0; } else if (sender == Monitoring_Deadband_Percentage_1MI) { filter.DeadbandType = (uint)DeadbandType.Percent; filter.DeadbandValue = 1.0; } else if (sender == Monitoring_Deadband_Percentage_5MI) { filter.DeadbandType = (uint)DeadbandType.Percent; filter.DeadbandValue = 5.0; } else if (sender == Monitoring_Deadband_Percentage_10MI) { filter.DeadbandType = (uint)DeadbandType.Percent; filter.DeadbandValue = 10.0; } else { filter = null; } // update the monitoring mode. List <MonitoredItem> itemsToChange = new List <MonitoredItem>(); for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++) { MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem; if (monitoredItem != null) { monitoredItem.Filter = filter; itemsToChange.Add(monitoredItem); } } // apply the changes to the server. m_subscription.ApplyChanges(); // update the display. for (int ii = 0; ii < itemsToChange.Count; ii++) { ListViewItem item = itemsToChange[ii].Handle as ListViewItem; if (item != null) { item.SubItems[8].Text = String.Empty; if (ServiceResult.IsBad(itemsToChange[ii].Status.Error)) { itemsToChange[ii].Filter = null; item.SubItems[8].Text = itemsToChange[ii].Status.Error.StatusCode.ToString(); } item.SubItems[4].Text = DeadbandFilterToText(itemsToChange[ii].Status.Filter); } } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private async void ShowMember(NodeId sourceId) { textBox_nodeId.Text = sourceId.ToString(); // dataGridView1.Rows.Clear(); int index = 0; ReferenceDescriptionCollection references; try { references = await Task.Run(() => { return(GetReferenceDescriptionCollection(sourceId)); }); } catch (Exception exception) { ClientUtils.HandleException(Text, exception); return; } if (references?.Count > 0) { // 获取所有要读取的子节点 List <NodeId> nodeIds = new List <NodeId>(); for (int ii = 0; ii < references.Count; ii++) { ReferenceDescription target = references[ii]; nodeIds.Add((NodeId)target.NodeId); } DateTime dateTimeStart = DateTime.Now; // 获取所有的值 DataValue[] dataValues = await Task.Run(() => { return(ReadOneNodeFiveAttributes(nodeIds)); }); label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms"; // 显示 for (int jj = 0; jj < dataValues.Length; jj += 5) { AddDataGridViewNewRow(dataValues, jj, index++, nodeIds[jj / 5]); } } else { // 子节点没有数据的情况 try { DateTime dateTimeStart = DateTime.Now; DataValue dataValue = CommonMethods.opcUaClient.ReadNode(sourceId); if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension) { // 数组显示 AddDataGridViewArrayRow(sourceId, out index); } else { // 显示单个数本身 label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms"; AddDataGridViewNewRow(ReadOneNodeFiveAttributes(new List <NodeId>() { sourceId }), 0, index++, sourceId); } } catch (Exception exception) { ClientUtils.HandleException(Text, exception); return; } } ClearDataGridViewRows(index); }
public override void OnDragDrop(Glyph g, DragEventArgs e) { ToolStripItem currentDropItem = ToolStripDesigner.s_dragItem; // Ensure that the list item index is contained in the data. if (e.Data is ToolStripItemDataObject && currentDropItem != null) { ToolStripItemDataObject data = (ToolStripItemDataObject)e.Data; // Get the PrimarySelection before the Drag operation... ToolStripItem selectedItem = data.PrimarySelection; IDesignerHost designerHost = (IDesignerHost)currentDropItem.Site.GetService(typeof(IDesignerHost)); Debug.Assert(designerHost != null, "Invalid DesignerHost"); //Do DragDrop only if currentDropItem has changed. if (currentDropItem != selectedItem && designerHost != null) { ArrayList components = data.DragComponents; ToolStrip parentToolStrip = currentDropItem.GetCurrentParent() as ToolStrip; int primaryIndex = -1; string transDesc; bool copy = (e.Effect == DragDropEffects.Copy); if (components.Count == 1) { string name = TypeDescriptor.GetComponentName(components[0]); if (name == null || name.Length == 0) { name = components[0].GetType().Name; } transDesc = string.Format(copy ? SR.BehaviorServiceCopyControl : SR.BehaviorServiceMoveControl, name); } else { transDesc = string.Format(copy ? SR.BehaviorServiceCopyControls : SR.BehaviorServiceMoveControls, components.Count); } DesignerTransaction designerTransaction = designerHost.CreateTransaction(transDesc); try { IComponentChangeService changeSvc = (IComponentChangeService)currentDropItem.Site.GetService(typeof(IComponentChangeService)); if (changeSvc != null) { if (parentToolStrip is ToolStripDropDown dropDown) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]); } else { changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]); } } // If we are copying, then we want to make a copy of the components we are dragging if (copy) { // Remember the primary selection if we had one if (selectedItem != null) { primaryIndex = components.IndexOf(selectedItem); } ToolStripKeyboardHandlingService keyboardHandlingService = GetKeyBoardHandlingService(selectedItem); if (keyboardHandlingService != null) { keyboardHandlingService.CopyInProgress = true; } components = DesignerUtils.CopyDragObjects(components, currentDropItem.Site) as ArrayList; if (keyboardHandlingService != null) { keyboardHandlingService.CopyInProgress = false; } if (primaryIndex != -1) { selectedItem = components[primaryIndex] as ToolStripItem; } } if (e.Effect == DragDropEffects.Move || copy) { ISelectionService selSvc = GetSelectionService(currentDropItem); if (selSvc != null) { // Insert the item. if (parentToolStrip is ToolStripOverflow) { parentToolStrip = (((ToolStripOverflow)parentToolStrip).OwnerItem).Owner; } int indexOfItemUnderMouseToDrop = parentToolStrip.Items.IndexOf(ToolStripDesigner.s_dragItem); if (indexOfItemUnderMouseToDrop != -1) { int indexOfPrimarySelection = 0; if (selectedItem != null) { indexOfPrimarySelection = parentToolStrip.Items.IndexOf(selectedItem); } if (indexOfPrimarySelection != -1 && indexOfItemUnderMouseToDrop > indexOfPrimarySelection) { indexOfItemUnderMouseToDrop--; } foreach (ToolStripItem item in components) { parentToolStrip.Items.Insert(indexOfItemUnderMouseToDrop, item); } } selSvc.SetSelectedComponents(new IComponent[] { selectedItem }, SelectionTypes.Primary | SelectionTypes.Replace); } } if (changeSvc != null) { ToolStripDropDown dropDown = parentToolStrip as ToolStripDropDown; if (dropDown != null) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null); } else { changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null); } //fire extra changing/changed events. if (copy) { if (dropDown != null) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]); changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null); } else { changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]); changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null); } } } //If Parent is DropDown... we have to manage the Glyphs .... foreach (ToolStripItem item in components) { if (item is ToolStripDropDownItem) { if (designerHost.GetDesigner(item) is ToolStripMenuItemDesigner itemDesigner) { itemDesigner.InitializeDropDown(); } } if (item.GetCurrentParent() is ToolStripDropDown dropDown && !(dropDown is ToolStripOverflow)) { if (dropDown.OwnerItem is ToolStripDropDownItem ownerItem) { if (designerHost.GetDesigner(ownerItem) is ToolStripMenuItemDesigner ownerDesigner) { ownerDesigner.InitializeBodyGlyphsForItems(false, ownerItem); ownerDesigner.InitializeBodyGlyphsForItems(true, ownerItem); } } } } // Refresh on SelectionManager... BehaviorService bSvc = GetBehaviorService(currentDropItem); if (bSvc != null) { bSvc.SyncSelection(); } } catch (Exception ex) { if (designerTransaction != null) { designerTransaction.Cancel(); designerTransaction = null; } if (ClientUtils.IsCriticalException(ex)) { throw; } } finally { if (designerTransaction != null) { designerTransaction.Commit(); designerTransaction = null; } } } } }
/// <summary> /// 固定地址且不允许更改的实例化 /// </summary> public FrmOpcView(string server) { InitializeComponent(); Icon = ClientUtils.GetAppIcon(); textBox1.Text = server; }
private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e) { try { if (m_session == null) { return; } if (m_subscription != null) { m_session.RemoveSubscription(m_subscription); m_subscription = null; } ReferenceDescription boiler = (ReferenceDescription)BoilerCB.SelectedItem; if (boiler == null) { return; } m_subscription = new Subscription(); m_subscription.PublishingEnabled = true; m_subscription.PublishingInterval = 1000; m_subscription.Priority = 1; m_subscription.KeepAliveCount = 10; m_subscription.LifetimeCount = 20; m_subscription.MaxNotificationsPerPublish = 1000; m_session.AddSubscription(m_subscription); m_subscription.Create(); NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.Boiler); string[] browsePaths = new string[] { "1:PipeX001/1:FTX001/1:Output", "1:DrumX001/1:LIX001/1:Output", "1:PipeX002/1:FTX002/1:Output", "1:LCX001/1:SetPoint", }; List <NodeId> nodes = ClientUtils.TranslateBrowsePaths( m_session, (NodeId)boiler.NodeId, wellKnownNamespaceUris, browsePaths); Control[] controls = new Control[] { InputPipeFlowTB, DrumLevelTB, OutputPipeFlowTB, DrumLevelSetPointTB }; for (int ii = 0; ii < nodes.Count; ii++) { controls[ii].Text = "---"; if (nodes[ii] != null) { MonitoredItem monitoredItem = new MonitoredItem(); monitoredItem.StartNodeId = nodes[ii]; monitoredItem.AttributeId = Attributes.Value; monitoredItem.Handle = controls[ii]; monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); m_subscription.AddItem(monitoredItem); } } m_subscription.ApplyChanges(); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) { if (value is CultureInfo ci) { // special-case CultureInfo, cannot use CultureInfoConverter for serialization nodeInfo.ValueData = ci.Name; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(CultureInfo), _typeNameConverter); } else if (value is string str) { nodeInfo.ValueData = str; } else if (value is byte[] bytes) { nodeInfo.ValueData = ToBase64WrappedString(bytes); nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(byte[]), _typeNameConverter); } else { Type valueType = (value is null) ? typeof(object) : value.GetType(); if (value is not null && !valueType.IsSerializable) { throw new InvalidOperationException(string.Format(SR.NotSerializableType, _name, valueType.FullName)); } TypeConverter tc = TypeDescriptor.GetConverter(valueType); bool toString = tc.CanConvertTo(typeof(string)); bool fromString = tc.CanConvertFrom(typeof(string)); try { if (toString && fromString) { nodeInfo.ValueData = tc.ConvertToInvariantString(value); nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, _typeNameConverter); return; } } catch (Exception ex) { // Some custom type converters will throw in ConvertTo(string) // to indicate that this object should be serialized through ISerializable // instead of as a string. This is semi-wrong, but something we will have to // live with to allow user created Cursors to be serializable. if (ClientUtils.IsCriticalException(ex)) { throw; } } bool toByteArray = tc.CanConvertTo(typeof(byte[])); bool fromByteArray = tc.CanConvertFrom(typeof(byte[])); if (toByteArray && fromByteArray) { byte[] data = (byte[])tc.ConvertTo(value, typeof(byte[])); nodeInfo.ValueData = ToBase64WrappedString(data); nodeInfo.MimeType = ResXResourceWriter.ByteArraySerializedObjectMimeType; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, _typeNameConverter); return; } if (value is null) { nodeInfo.ValueData = string.Empty; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), _typeNameConverter); } else { if (_binaryFormatter is null) { _binaryFormatter = new BinaryFormatter { Binder = new ResXSerializationBinder(_typeNameConverter) }; } using (MemoryStream ms = new MemoryStream()) { #pragma warning disable SYSLIB0011 // Type or member is obsolete _binaryFormatter.Serialize(ms, value); #pragma warning restore SYSLIB0011 // Type or member is obsolete nodeInfo.ValueData = ToBase64WrappedString(ms.ToArray()); } nodeInfo.MimeType = ResXResourceWriter.DefaultSerializedObjectMimeType; } } }
override protected void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { try { var tEventTag = monitoredItem.Handle as TheOPCEvent; if (tEventTag == null) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Internal error: invalid monitored item handle in Event", eMsgLevel.l1_Error, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); return; } var tEventHost = tEventTag.GetHostThing(); if (tEventHost == null) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Event host thing not found", eMsgLevel.l1_Error, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); return; } EventFieldList notification = e.NotificationValue as EventFieldList; if (notification == null) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Internal error: notification is not an EventFieldList", eMsgLevel.l1_Error, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); return; } // check the type of event. NodeId eventTypeId = ClientUtils.FindEventType(monitoredItem, notification); if (MyOPCServer.EnableOPCDataLogging) { var logInfo = new Dictionary <string, object> { { "ReceiveTime", DateTimeOffset.Now }, { "TagId", DisplayName }, { "EventTypeId", eventTypeId }, { "Value", notification.EventFields.Aggregate("", (s, ef) => $"{s} [{ef.TypeInfo},{ef.Value}]") }, { "Server", notification.Message.PublishTime }, { "MonitoredItem", monitoredItem?.ClientHandle }, { "SequenceNumber", notification.Message?.SequenceNumber }, }; TheOPCTag.LogOPCData(logInfo, MyOPCServer.GetLogAddress(), $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}"); } // ignore unknown events. if (NodeId.IsNull(eventTypeId)) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Unknown eventTypeId", eMsgLevel.l1_Error, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}: received {eventTypeId}")); return; } EventFilter filter = monitoredItem.Status.Filter as EventFilter; bool isRefreshEvent = false; var eventData = new Dictionary <string, object>(); DateTimeOffset sourceTime = DateTimeOffset.Now; string conditionId = null; bool? bRetain = null; int index = 0; foreach (var field in filter.SelectClauses) { var value = index < notification?.EventFields.Count ? notification?.EventFields[index].Value : null; if (value is ExtensionObject || value is ExtensionObject[]) { value = MyOPCServer.DecodeExtensionObjectToJson(value, out var ignored); } var name = field?.BrowsePath?.Count > 0 ? field.BrowsePath[0].Name : null; if (value is NodeId) { if (name == "EventType") { var eventType = value as NodeId; if (eventType == Opc.Ua.ObjectTypeIds.RefreshStartEventType) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Received Refresh Start event", eMsgLevel.l4_Message, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); _currentConditionsByConditionId.Clear(); if (_bRefreshing) { // Two overlapping refresh starts received TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Received more than one Refresh Start event", eMsgLevel.l2_Warning, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); } _bRefreshing = true; _lastRefreshStartTime = DateTimeOffset.Now; isRefreshEvent = true; } else if (eventType == Opc.Ua.ObjectTypeIds.RefreshEndEventType) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Received Refresh End event", eMsgLevel.l4_Message, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); if (!_bRefreshing) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Received Refresh End event without matching start event", eMsgLevel.l2_Warning, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); // refresh end received without refresh start } _bRefreshing = false; isRefreshEvent = true; if (EventInfo.AggregateRetainedConditions) { WriteAggregatedConditionsToProperty(tEventHost, TheCommonUtils.CDate(notification.Message.PublishTime)); } } } value = value.ToString(); } if (name == null) { if (field.TypeDefinitionId == Opc.Ua.ObjectTypeIds.BaseEventType) { name = "ConditionId"; } } if (name != null) { if (aliasMap.TryGetValue(index, out var alias)) { eventData[alias] = value; } else { eventData[name] = value; } switch (name) { case "ConditionId": conditionId = value?.ToString(); break; case "Retain": bRetain = TheCommonUtils.CBool(value); break; case "Time": sourceTime = TheCommonUtils.CDate(value); break; } } index++; } if (!isRefreshEvent) { var eventInfoProperties = EventInfo.GetPropertyNames(); var filteredEventProps = EventInfo.Properties?.Count > 0 ? eventData.Where(pk => !requiredEventFields.Contains(pk.Key) || eventInfoProperties.Contains(pk.Key)) //.Select(kv => //{ // if (aliasMap.TryGetValue(kv.Key, out var alias)) // { // return new KeyValuePair<string, object>(alias, kv.Value); // } // return kv; //}) .ToDictionary(kv => kv.Key, kv => kv.Value) : eventData; //if (_bRefreshing) //{ // filteredEventProps["Refresh"] = true; //} if (!EventInfo.AggregateRetainedConditions) { // Raw events // TODO avoid resending events due to a refresh? var eventAsJson = TheCommonUtils.SerializeObjectToJSONString(filteredEventProps); TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Received raw event {eventAsJson}", eMsgLevel.l6_Debug, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); tEventHost.GetBaseThing().SetProperty(DisplayName, eventAsJson, TheCommonUtils.CDate(notification.Message.PublishTime)); } else { // Aggregated Condition State if (conditionId != null) { if (bRetain == false) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Removed current event {conditionId}", eMsgLevel.l6_Debug, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); _currentConditionsByConditionId.RemoveNoCare(conditionId); } else { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Added current event {conditionId}", eMsgLevel.l6_Debug, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}")); _currentConditionsByConditionId[conditionId] = filteredEventProps; } if (!_bRefreshing) { WriteAggregatedConditionsToProperty(tEventHost, TheCommonUtils.CDate(notification.Message.PublishTime)); } } } // Legacy format: do we still need to support this? Existing event support was not really usable... //foreach (var eventField in eventData) //{ // string propertyName; // if (tEventHost is TheOPCUATagThing) // TODO Create a TheOPCUAEventThing // { // // If this is a dedicated event thing, use the original value name // // TODO Is this really what we want to do or do we also want to use the full browsepath for dedicated event things? // throw new NotImplementedException("Should never get here"); // //propertyName = field.BrowsePath[0].Name; // } // else // { // // This is an external, multi-event thing: use the browsepath to avoid collisions with properties from multiple events // propertyName = DisplayName + "." + eventField.Key; // } // SetPropertyFromVariant(tEventHost, propertyName, eventField.Value, sourceTime); //} } } catch (Exception ex) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyOPCServer.GetBaseThing().EngineName, $"Internal error processing event notification", eMsgLevel.l1_Error, $"{DisplayName} {GetNodeIdForLogs()} {EventInfo.AggregateRetainedConditions}: {ex.ToString()}")); } }
public string GetValueTypeName(ITypeResolutionService typeResolver) { // the type name here is always a FQN if (!string.IsNullOrEmpty(_typeName)) { return (_typeName == MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), _typeNameConverter) ? MultitargetUtil.GetAssemblyQualifiedName(typeof(object), _typeNameConverter) : _typeName); } string result = FileRefType; Type objectType = null; // do we have a fileref? if (result is not null) { // try to resolve this type objectType = ResolveType(FileRefType, typeResolver); } else if (_nodeInfo is not null) { // we don't have a fileref, try to resolve the type of the datanode result = _nodeInfo.TypeName; // if typename is null, the default is just a string if (string.IsNullOrEmpty(result)) { // we still don't know... do we have a mimetype? if yes, our only option is to // deserialize to know what we're dealing with... very inefficient... if (!string.IsNullOrEmpty(_nodeInfo.MimeType)) { object insideObject = null; try { insideObject = GenerateObjectFromDataNodeInfo(_nodeInfo, typeResolver); } catch (Exception ex) { // it'd be better to catch SerializationException but the underlying type resolver // can throw things like FileNotFoundException which is kinda confusing, so I am catching all here.. if (ClientUtils.IsCriticalException(ex)) { throw; } // something went wrong, type is not specified at all or stream is corrupted // return system.object result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), _typeNameConverter); } if (insideObject is not null) { result = MultitargetUtil.GetAssemblyQualifiedName(insideObject.GetType(), _typeNameConverter); } } else { // no typename, no mimetype, we have a string... result = MultitargetUtil.GetAssemblyQualifiedName(typeof(string), _typeNameConverter); } } else { objectType = ResolveType(_nodeInfo.TypeName, typeResolver); } } if (objectType is not null) { if (objectType == typeof(ResXNullRef)) { result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), _typeNameConverter); } else { result = MultitargetUtil.GetAssemblyQualifiedName(objectType, _typeNameConverter); } } return(result); }
//private void FormBrowseServer_FormClosing(object sender, FormClosingEventArgs e) //{ // CommonMethods.opcUaClient.Disconnect(); //} #endregion #region OPC UA client /// <summary> /// Opc客户端的核心类 /// </summary> // private OpcUaClient m_OpcUaClient = null; /// <summary> /// 初始化 /// </summary> private void OpcUaClientInitialization() { //CommonMethods.opcUaClient = new OpcUaClient(); //await CommonMethods.opcUaClient.ConnectServer("opc.tcp://118.24.36.220:62547/DataAccessServer"); CommonMethods.opcUaClient.OpcStatusChange += M_OpcUaClient_OpcStatusChange1; CommonMethods.opcUaClient.ConnectComplete += M_OpcUaClient_ConnectComplete; //浏览根节点 try { // populate the browse view. PopulateBranch(ObjectIds.ObjectsFolder, BrowseNodesTV.Nodes); BrowseNodesTV.Enabled = true; } catch (Exception exception) { ClientUtils.HandleException(Text, exception); } //if (CommonMethods.opcUaClient != null) //{ // RemoveAllSubscript(); // if (button2.BackColor != Color.LimeGreen) // { // button2.BackColor = Color.LimeGreen; // // 判断当前的选择 // // if (string.IsNullOrEmpty(textBox_nodeId.Text)) return; // ReferenceDescriptionCollection references; // try // { // references = await Task.Run(() => // { // return GetReferenceDescriptionCollection(new NodeId(textBox_nodeId.Text)); // }); // } // catch (Exception exception) // { // ClientUtils.HandleException(Text, exception); // return; // } // subNodeIds = new List<string>(); // if (references?.Count > 0) // { // isSingleValueSub = false; // // 获取所有要订阅的子节点 // for (int ii = 0; ii < references.Count; ii++) // { // ReferenceDescription target = references[ii]; // subNodeIds.Add(((NodeId)target.NodeId).ToString()); // } // } // else // { // isSingleValueSub = true; // // 子节点没有数据的情况 // subNodeIds.Add(textBox_nodeId.Text); // } // CommonMethods.opcUaClient.AddSubscription("subTest", subNodeIds.ToArray(), SubCallBack); // } // else // { // button2.BackColor = SystemColors.Control; // } //} }