diff --git a/.azurepipelines/ci.yml b/.azurepipelines/ci.yml index b8ca72a82..2d9645a03 100644 --- a/.azurepipelines/ci.yml +++ b/.azurepipelines/ci.yml @@ -8,7 +8,7 @@ jobs: - job: buildprep displayName: Prepare Build Jobs pool: - vmImage: 'windows-2019' + vmImage: 'windows-2022' variables: DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true @@ -31,7 +31,12 @@ jobs: - task: NuGetAuthenticate@1 - task: NuGetToolInstaller@1 inputs: - versionSpec: '>=5.8.x' + versionSpec: '>=7.0.x' + - task: UseDotNet@2 + displayName: 'Install .NET 10.0' + inputs: + packageType: 'sdk' + version: '10.0.x' - task: DotNetCoreCLI@2 displayName: Release Restore inputs: diff --git a/.azurepipelines/get-matrix.ps1 b/.azurepipelines/get-matrix.ps1 index c49229f88..1927963af 100644 --- a/.azurepipelines/get-matrix.ps1 +++ b/.azurepipelines/get-matrix.ps1 @@ -45,7 +45,7 @@ if ($AgentTable -eq $null -or $AgentTable.Count -eq 0) $agents = @{ windows = "windows-2022" linux = "ubuntu-22.04" - mac = "macOS-13" + mac = "macOS-15" } } else { diff --git a/.azurepipelines/sln.yml b/.azurepipelines/sln.yml index fe7c3b3c0..048b98c9f 100644 --- a/.azurepipelines/sln.yml +++ b/.azurepipelines/sln.yml @@ -8,9 +8,14 @@ jobs: vmImage: 'windows-2022' steps: - task: NuGetAuthenticate@1 + - task: UseDotNet@2 + displayName: 'Install .NET 10.0' + inputs: + packageType: 'sdk' + version: '10.0.x' - task: NuGetToolInstaller@1 inputs: - versionSpec: '>=5.8.x' + versionSpec: '>=7.0.x' - task: NuGetCommand@2 displayName: Restore Release inputs: diff --git a/.editorconfig b/.editorconfig index 00fa03f39..60ba7b2a6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -578,6 +578,9 @@ dotnet_diagnostic.CA1859.severity = silent # CA1861: Avoid constant arrays as arguments dotnet_diagnostic.CA1861.severity = silent +# CA1848: Use the LoggerMessage delegates +dotnet_diagnostic.CA1848.severity = suggestion + [**/Generated/*.cs] generated_code = true dotnet_diagnostic.severity = none diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 3800969e4..1935e13ec 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -48,10 +48,10 @@ jobs: # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main - - name: Setup .NET + - name: Set up .NET uses: actions/setup-dotnet@v5 with: - dotnet-version: '6.x' # SDK Version to use; + dotnet-version: '10.x' # Add MSBuild to the PATH: https://github.com/microsoft/setup-msbuild - name: Setup MSBuild.exe diff --git a/Samples/Client.Net4/Program.cs b/Samples/Client.Net4/Program.cs index 4d1a68a74..c3fd0c245 100644 --- a/Samples/Client.Net4/Program.cs +++ b/Samples/Client.Net4/Program.cs @@ -29,13 +29,29 @@ using System; using System.Windows.Forms; -using Opc.Ua.Configuration; +using Microsoft.Extensions.Logging; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Opc.Ua.Sample { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -46,7 +62,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationName = "UA Sample Client"; application.ApplicationType = ApplicationType.ClientAndServer; application.ConfigSectionName = "Opc.Ua.SampleClient"; @@ -66,11 +82,11 @@ static void Main() application.StartAsync(new SampleServer()).Wait(); // run the application interactively. - Application.Run(new SampleClientForm(application, null, application.ApplicationConfiguration)); + Application.Run(new SampleClientForm(application, null, application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Samples/Client.Net4/SampleClientForm.cs b/Samples/Client.Net4/SampleClientForm.cs index c52ff8439..3e95974fb 100644 --- a/Samples/Client.Net4/SampleClientForm.cs +++ b/Samples/Client.Net4/SampleClientForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -45,9 +45,10 @@ public SampleClientForm() public SampleClientForm( ApplicationInstance application, ClientForm masterForm, - ApplicationConfiguration configuration) + ApplicationConfiguration configuration, + ITelemetryContext telemetry) : - base(configuration.CreateMessageContext(), application, masterForm, configuration) + base(configuration.CreateMessageContext(), application, masterForm, configuration, telemetry) { InitializeComponent(); @@ -71,7 +72,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Client.Net4/UA Sample Client.csproj b/Samples/Client.Net4/UA Sample Client.csproj index c49c114e6..461631caa 100644 --- a/Samples/Client.Net4/UA Sample Client.csproj +++ b/Samples/Client.Net4/UA Sample Client.csproj @@ -137,10 +137,10 @@ - 9.0.8 + 10.0.0 - 1.5.377.21 + 1.5.378.11-preview 4.3.4 diff --git a/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs b/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs index d85043302..5982eac9d 100644 --- a/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/AttributeListCtrl.cs @@ -78,6 +78,7 @@ public async Task InitializeAsync(ISession session, ExpandedNodeId nodeId, Cance { ItemsLV.Items.Clear(); m_session = session; + Telemetry = session?.MessageContext?.Telemetry; if (m_session == null) { @@ -414,7 +415,7 @@ protected override async Task UpdateItemAsync(ListViewItem listItem, object item } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs b/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs index a15833218..6e458da79 100644 --- a/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/BrowseListCtrl.cs @@ -72,6 +72,7 @@ public async Task InitializeAsync(ISession session, ExpandedNodeId nodeId, Cance { ItemsLV.Items.Clear(); m_session = session; + Telemetry = session?.MessageContext?.Telemetry; if (m_session == null) { @@ -152,7 +153,7 @@ protected override async Task UpdateItemAsync(ListViewItem listItem, object item } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs index 5f8a92354..96414d50c 100644 --- a/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/BrowseTreeCtrl.cs @@ -136,6 +136,7 @@ public async Task InitializeAsync( m_viewId = viewId; m_referenceTypeId = referenceTypeId; m_browseDirection = browseDirection; + Telemetry = m_session?.MessageContext?.Telemetry; NodesTV.Nodes.Clear(); @@ -289,7 +290,7 @@ private async Task UpdateNodeAsync(TreeNode parent, ReferenceDescriptionCollecti } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -322,7 +323,7 @@ protected override async void SelectNode() } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -343,7 +344,7 @@ protected override async Task BeforeExpandAsync(TreeNode clickedNode, Canc } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); return false; } } @@ -386,7 +387,7 @@ private async void RootBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -407,7 +408,7 @@ private void BrowseDirectionCTRL_SelectedIndexChanged(object sender, EventArgs e } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -434,7 +435,7 @@ private void SelectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -469,7 +470,7 @@ private void SelectChildrenMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -490,7 +491,7 @@ private void ReferenceTypeCTRL_ReferenceSelectionChanged(object sender, Referenc } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs b/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs index 8513782b0..d6af82423 100644 --- a/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs +++ b/Samples/ClientControls.Net4/Browse/NodeListCtrl.cs @@ -93,6 +93,7 @@ public async Task InitializeAsync(ISession session, IList nodeIds, Cance { ItemsLV.Items.Clear(); m_session = session; + Telemetry = session?.MessageContext?.Telemetry; if (m_session == null || nodeIds == null || nodeIds.Count == 0) { @@ -173,12 +174,12 @@ protected override async void SelectItems() } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } /// - protected override void EnableMenuItems(ListViewItem clickedItem) + protected override void EnableMenuItems(ListViewItem clickedItem) { DeleteMI.Enabled = ItemsLV.SelectedItems.Count > 0; } @@ -228,7 +229,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -253,7 +254,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs index 8f47c10e4..b9dce748c 100644 --- a/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs +++ b/Samples/ClientControls.Net4/Browse/SelectNodesDlg.cs @@ -38,6 +38,7 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Client; namespace Opc.Ua.Client.Controls @@ -59,6 +60,7 @@ public SelectNodesDlg() #endregion #region Private Fields + private ITelemetryContext m_telemetry; #endregion #region Public Interface @@ -67,6 +69,7 @@ public SelectNodesDlg() /// public async Task> ShowDialogAsync(ISession session, NodeId rootId, IList nodeIds, CancellationToken ct = default) { + m_telemetry = session?.MessageContext?.Telemetry; await BrowseCTRL.InitializeAsync(session, rootId, null, null, BrowseDirection.Forward, ct); await ReferencesCTRL.InitializeAsync(session, rootId, ct); await AttributesCTRL.InitializeAsync(session, rootId, ct); @@ -89,7 +92,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -107,7 +110,7 @@ private async void BrowseCTRL_NodesSelectedAsync(object sender, BrowseTreeCtrl.N } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/ClientControls.Net4/ClientUtils.cs b/Samples/ClientControls.Net4/ClientUtils.cs index 0f18ea39f..b29a86665 100644 --- a/Samples/ClientControls.Net4/ClientUtils.cs +++ b/Samples/ClientControls.Net4/ClientUtils.cs @@ -33,6 +33,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -44,9 +45,17 @@ public partial class ClientUtils /// /// Handles an exception. /// - public static void HandleException(string caption, Exception e) + public static void HandleException(ITelemetryContext telemetry, string caption, Exception e) { - ExceptionDlg.Show(caption, e); + ExceptionDlg.Show(telemetry, caption, e); + } + + /// + /// Handles an exception. + /// + public static void HandleException(ILogger logger, string caption, Exception e) + { + ExceptionDlg.Show(logger, caption, e); } /// diff --git a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs index 20fbbc369..f06762165 100644 --- a/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/AttrributesListViewCtrl.cs @@ -328,7 +328,7 @@ private async void AttributesLV_DoubleClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session.MessageContext.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs b/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs index ef1efbc87..ad0524d2d 100644 --- a/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/BrowseNodeCtrl.cs @@ -70,10 +70,11 @@ public BrowseNodeCtrl() public async Task InitializeAsync( ISession session, NodeId rootId, + ITelemetryContext telemetry, CancellationToken ct, params NodeId[] referenceTypeIds) { - await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, telemetry, ct, referenceTypeIds); } /// diff --git a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs index 5b65d1b35..d506142d6 100644 --- a/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/BrowseTreeViewCtrl.cs @@ -40,6 +40,7 @@ using Opc.Ua.Client; using System.Threading.Tasks; using System.Threading; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -62,6 +63,8 @@ public BrowseTreeViewCtrl() #region Private Fields private ISession m_session; + private ITelemetryContext m_telemetry; + private ILogger m_logger; private NodeId m_rootId; private NodeId[] m_referenceTypeIds; private NodeId m_selectedNodeId; @@ -86,6 +89,7 @@ public BrowseTreeViewCtrl() public async Task InitializeAsync( ISession session, NodeId rootId, + ITelemetryContext telemetry, CancellationToken ct, params NodeId[] referenceTypeIds) { @@ -103,6 +107,8 @@ public async Task InitializeAsync( m_rootId = rootId; m_referenceTypeIds = referenceTypeIds; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); // save session. await ChangeSessionAsync(session, true); @@ -320,8 +326,7 @@ private void BrowseTV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_logger, this.Text, exception); } } @@ -336,7 +341,7 @@ private async void BrowseTV_AfterSelectAsync(object sender, TreeViewEventArgs e) if (BrowseTV.SelectedNode == null) { - if (m_AfterSelect != null) m_AfterSelect(this, new EventArgs()); + m_AfterSelect?.Invoke(this, new EventArgs()); return; } @@ -357,11 +362,11 @@ private async void BrowseTV_AfterSelectAsync(object sender, TreeViewEventArgs e) } // raise event. - if (m_AfterSelect != null) m_AfterSelect(this, new EventArgs()); + m_AfterSelect?.Invoke(this, new EventArgs()); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -447,7 +452,7 @@ private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEvent } catch (Exception exception) { - Utils.LogError(exception, "Error loading image."); + m_logger.LogError(exception, "Error loading image."); } } @@ -475,7 +480,7 @@ private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEvent } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -487,7 +492,7 @@ private void BrowseTV_MouseDown(object sender, MouseEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -499,7 +504,7 @@ private void Browse_RefreshMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs index b054e12da..9c6daa78e 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestDlg.cs @@ -64,7 +64,7 @@ public CallRequestDlg() /// /// Changes the session used for the call request. /// - public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { m_session = session; CallRequestCTRL.ChangeSession(session); @@ -101,7 +101,7 @@ private async void CallBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -115,7 +115,7 @@ private async void BackBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -134,7 +134,7 @@ private void CloseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs index 03cc78ff2..5ce977716 100644 --- a/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/CallRequestListViewCtrl.cs @@ -384,7 +384,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs b/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs index d3557b3bc..b1267b3c5 100644 --- a/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/ConnectServerCtrl.cs @@ -33,6 +33,7 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Client.ComplexTypes; namespace Opc.Ua.Client.Controls @@ -55,6 +56,8 @@ public ConnectServerCtrl() #endregion #region Private Fields + private ITelemetryContext m_telemetry; + private ILogger m_logger; private ApplicationConfiguration m_configuration; private ISession m_session; private SessionReconnectHandler m_reconnectHandler; @@ -295,28 +298,32 @@ private async Task ConnectInternalAsync( ITransportWaitingConnection connection, EndpointDescription endpointDescription, bool useSecurity, + ITelemetryContext telemetry, uint sessionTimeout = 0, CancellationToken ct = default) { + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + // disconnect from existing session. await InternalDisconnectAsync(ct); // select the best endpoint. if (endpointDescription == null) { - endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, DiscoverTimeout, ct); + endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, DiscoverTimeout, telemetry, ct); } EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); - m_session = await DefaultSessionFactory.Instance.CreateAsync(m_configuration, connection, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout, UserIdentity, PreferredLocales, ct); + m_session = await new DefaultSessionFactory(telemetry).CreateAsync(m_configuration, connection, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout, UserIdentity, PreferredLocales, ct); // set up keep alive callback. m_session.KeepAlive += Session_KeepAlive; // set up reconnect handler. - m_reconnectHandler = new SessionReconnectHandler(true, DefaultReconnectPeriodExponentialBackOff * 1000); + m_reconnectHandler = new SessionReconnectHandler(telemetry, true, DefaultReconnectPeriodExponentialBackOff * 1000); // raise an event. DoConnectComplete(null); @@ -330,7 +337,7 @@ private async Task ConnectInternalAsync( catch (Exception e) { UpdateStatus(true, DateTime.Now, "Connected, failed to load complex type system."); - Utils.LogWarning(e, "Failed to load complex type system."); + m_logger.LogWarning(e, "Failed to load complex type system."); } // return the new session. @@ -344,24 +351,28 @@ private async Task ConnectInternalAsync( private async Task ConnectInternalAsync( string serverUrl, bool useSecurity, + ITelemetryContext telemetry, uint sessionTimeout = 0, CancellationToken ct = default) { + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + // disconnect from existing session. await InternalDisconnectAsync(ct); // select the best endpoint. - var endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, serverUrl, useSecurity, DiscoverTimeout, ct); + var endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, serverUrl, useSecurity, DiscoverTimeout, telemetry, ct); var endpointConfiguration = EndpointConfiguration.Create(m_configuration); var endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); - m_session = await DefaultSessionFactory.Instance.CreateAsync(m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout == 0 ? DefaultSessionTimeout : sessionTimeout, UserIdentity, PreferredLocales, ct); + m_session = await new DefaultSessionFactory(telemetry).CreateAsync(m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName, sessionTimeout == 0 ? DefaultSessionTimeout : sessionTimeout, UserIdentity, PreferredLocales, ct); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // set up reconnect handler. - m_reconnectHandler = new SessionReconnectHandler(true, DefaultReconnectPeriodExponentialBackOff * 1000); + m_reconnectHandler = new SessionReconnectHandler(telemetry, true, DefaultReconnectPeriodExponentialBackOff * 1000); // raise an event. DoConnectComplete(null); @@ -375,7 +386,7 @@ private async Task ConnectInternalAsync( catch (Exception e) { UpdateStatus(true, DateTime.Now, "Connected, failed to load complex type system."); - Utils.LogError(e, "Failed to load complex type system."); + m_logger.LogError(e, "Failed to load complex type system."); } // return the new session. @@ -389,6 +400,7 @@ private async Task ConnectInternalAsync( /// Whether to use security. /// The new session object. public Task ConnectAsync( + ITelemetryContext telemetry, string serverUrl = null, bool useSecurity = false, uint sessionTimeout = 0, @@ -413,7 +425,7 @@ public Task ConnectAsync( UpdateStatus(false, DateTime.Now, "Connecting [{0}]", serverUrl); - return ConnectInternalAsync(serverUrl, useSecurity, sessionTimeout, ct); + return ConnectInternalAsync(serverUrl, useSecurity, telemetry, sessionTimeout, ct); } /// @@ -424,6 +436,7 @@ public Task ConnectAsync( public async Task ConnectAsync( ITransportWaitingConnection connection, bool useSecurity, + ITelemetryContext telemetry, int discoverTimeout = -1, uint sessionTimeout = 0, CancellationToken ct = default) @@ -442,12 +455,12 @@ public async Task ConnectAsync( { // Discovery uses the reverse connection and closes it // return and wait for next reverse hello - endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, discoverTimeout, ct); + endpointDescription = await CoreClientUtils.SelectEndpointAsync(m_configuration, connection, useSecurity, discoverTimeout, telemetry, ct); m_endpoints[connection.EndpointUrl] = endpointDescription; return null; } - return await ConnectInternalAsync(connection, endpointDescription, UseSecurityCK.Checked, sessionTimeout, ct); + return await ConnectInternalAsync(connection, endpointDescription, UseSecurityCK.Checked, telemetry, sessionTimeout, ct); } /// @@ -499,7 +512,7 @@ public void Disconnect() /// public void Discover(string hostName) { - string endpointUrl = new DiscoverServerDlg().ShowDialog(m_configuration, hostName); + string endpointUrl = new DiscoverServerDlg().ShowDialog(m_configuration, hostName, m_telemetry); if (endpointUrl != null) { @@ -529,7 +542,7 @@ private void DoConnectComplete(object state) /// /// Finds the endpoint that best matches the current settings. /// - private async Task SelectEndpointAsync(CancellationToken ct = default) + private async Task SelectEndpointAsync(ITelemetryContext telemetry, CancellationToken ct = default) { try { @@ -544,7 +557,7 @@ private async Task SelectEndpointAsync(CancellationToken ct } // return the selected endpoint. - return await CoreClientUtils.SelectEndpointAsync(m_configuration, discoveryUrl, UseSecurityCK.Checked, DiscoverTimeout, ct); + return await CoreClientUtils.SelectEndpointAsync(m_configuration, discoveryUrl, UseSecurityCK.Checked, DiscoverTimeout, telemetry, ct); } finally { @@ -626,14 +639,11 @@ private void Session_KeepAlive(ISession session, KeepAliveEventArgs e) UpdateStatus(false, e.CurrentTime, "Connected [{0}]", session.Endpoint.EndpointUrl); // raise any additional notifications. - if (m_KeepAliveComplete != null) - { - m_KeepAliveComplete(this, e); - } + m_KeepAliveComplete?.Invoke(this, e); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_logger, this.Text, exception); } } @@ -656,7 +666,7 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) Task.Run((Func)(async () => { try { - await this.ConnectAsync(serverUrl, useSecurity); + await this.ConnectAsync(m_telemetry, serverUrl, useSecurity); } catch (ServiceResultException sre) { @@ -675,7 +685,7 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_logger, this.Text, exception); } })); } @@ -713,14 +723,11 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } // raise any additional notifications. - if (m_ReconnectComplete != null) - { - m_ReconnectComplete(this, e); - } + m_ReconnectComplete?.Invoke(this, e); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_logger, this.Text, exception); } } @@ -748,7 +755,7 @@ private void CertificateValidator_CertificateValidation(CertificateValidator sen } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_logger, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs index f97593057..e00fa02f5 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditAnnotationDlg.cs @@ -107,7 +107,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session.MessageContext.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs index 3198d13d8..0612f439e 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValue2Dlg.cs @@ -270,7 +270,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion @@ -291,7 +291,7 @@ private void EncodingCB_Item_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -335,7 +335,7 @@ private async void RefreshBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -373,7 +373,7 @@ private async void UpdateBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs index c11634cd7..4db0a4a72 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValueCtrl.cs @@ -294,7 +294,7 @@ public void SetArraySize() array = matrix.ToArray(); } - SetTypeDlg.SetTypeResult result = new SetTypeDlg().ShowDialog(currentType, dimensions); + SetTypeDlg.SetTypeResult result = new SetTypeDlg().ShowDialog(m_session?.MessageContext?.Telemetry, currentType, dimensions); if (result == null) { @@ -661,10 +661,7 @@ private void ShowValue(AccessInfo parent) { ShowValueNoNotify(parent); - if (m_ValueChanged != null) - { - m_ValueChanged(this, null); - } + m_ValueChanged?.Invoke(this, null); } /// @@ -1403,7 +1400,7 @@ private void NavigationMENU_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -1426,7 +1423,7 @@ private void ValuesDV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -1447,7 +1444,7 @@ private void ValuesDV_CellValidating(object sender, DataGridViewCellValidatingEv } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); e.Cancel = true; } } @@ -1471,7 +1468,7 @@ private void ValuesDV_CellValueChanged(object sender, DataGridViewCellEventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } diff --git a/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs index ea64e4d61..53dfab656 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditComplexValueDlg.cs @@ -43,6 +43,7 @@ namespace Opc.Ua.Client.Controls /// public partial class EditComplexValueDlg : Form { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -107,6 +108,7 @@ public object ShowDialog( object value, string caption) { + m_telemetry = session?.MessageContext?.Telemetry; if (!String.IsNullOrEmpty(caption)) { this.Text = caption; @@ -186,7 +188,7 @@ private void ValueCTRL_ValueChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -198,7 +200,7 @@ private void BackBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -211,7 +213,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -223,7 +225,7 @@ private void SetTypeBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -235,7 +237,7 @@ private void SetTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs index d102982c9..4d6bb0d04 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditMonitoredItemDlg.cs @@ -43,6 +43,7 @@ namespace Opc.Ua.Client.Controls /// public partial class EditMonitoredItemDlg : Form { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -104,11 +105,12 @@ public override string ToString() /// /// Prompts the user to edit the monitored item. /// - public async Task ShowDialogAsync(ISession session, MonitoredItem monitoredItem, bool isEvent, CancellationToken ct = default) + public async Task ShowDialogAsync(ISession session, MonitoredItem monitoredItem, bool isEvent, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; if (!monitoredItem.Created) { - NodeBTN.Session = session; + NodeBTN.ChangeSession(session, telemetry); await NodeBTN.SetSelectedNodeIdAsync(monitoredItem.StartNodeId, ct); } @@ -296,7 +298,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs index 277850b6a..f9ab219e4 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditReadValueIdDlg.cs @@ -43,6 +43,7 @@ namespace Opc.Ua.Client.Controls /// public partial class EditReadValueIdDlg : Form { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -89,6 +90,7 @@ public override string ToString() /// public async Task ShowDialogAsync(ISession session, CancellationToken ct, params ReadValueId[] nodesToRead) { + m_telemetry = session.MessageContext.Telemetry; NodeBTN.Session = session; NodeBTN.SelectedReference = null; @@ -283,7 +285,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs index 92beccf00..35beb37e1 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditSubscriptionDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -41,6 +41,7 @@ namespace Opc.Ua.Client.Controls /// public partial class EditSubscriptionDlg : Form { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -61,6 +62,7 @@ public EditSubscriptionDlg() /// public bool ShowDialog(Subscription subscription) { + m_telemetry = subscription.Session.MessageContext.Telemetry; PublishingIntervalUP.Value = subscription.PublishingInterval; KeepAliveCountUP.Value = subscription.KeepAliveCount; LifetimeCountUP.Value = subscription.LifetimeCount; @@ -93,7 +95,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs index 40d6deb51..61c4c5f6f 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditValueCtrl.cs @@ -117,10 +117,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) Value = new Variant(value); - if (m_ValueChanged != null) - { - m_ValueChanged(this, e); - } + m_ValueChanged?.Invoke(this, e); } #endregion } diff --git a/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs b/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs index 318cea56e..d89868154 100644 --- a/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/EditWriteValueDlg.cs @@ -43,6 +43,7 @@ namespace Opc.Ua.Client.Controls /// public partial class EditWriteValueDlg : Form { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -67,9 +68,10 @@ public EditWriteValueDlg() /// /// Prompts the user to edit the write request parameters for the set of nodes provided. /// - public async Task ShowDialogAsync(ISession session, WriteValue nodeToWrite, CancellationToken ct = default) + public async Task ShowDialogAsync(ISession session, WriteValue nodeToWrite, ITelemetryContext telemetry, CancellationToken ct = default) { - NodeBTN.Session = session; + m_telemetry = telemetry; + NodeBTN.ChangeSession(session, telemetry); NodeBTN.SelectedReference = null; // fill in the control. @@ -174,7 +176,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs index 456d4fa53..6cab7713a 100644 --- a/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EventFilterListViewCtrl.cs @@ -195,7 +195,7 @@ private void FilterDV_CellDoubleClick(object sender, DataGridViewCellEventArgs e } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -234,7 +234,7 @@ private void FilterDV_CellContentClick(object sender, DataGridViewCellEventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -281,7 +281,7 @@ private void MoveUpMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -309,7 +309,7 @@ private void FilterDV_ColumnHeaderMouseClick(object sender, DataGridViewCellMous } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs index 3faa7f533..2dfea1b8e 100644 --- a/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/EventListViewCtrl.cs @@ -311,7 +311,7 @@ private void DetailsMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -327,7 +327,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -339,7 +339,7 @@ private void ClearMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs index a72bc62f6..c5bf91f23 100644 --- a/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/GdsDiscoverServersDlg.cs @@ -88,6 +88,7 @@ private enum Match #region Private Fields private ApplicationDescription m_application; + private ITelemetryContext m_telemetry; #endregion #region Private Constants @@ -116,8 +117,9 @@ private enum Match /// /// Shows the dialog. /// - public async Task ShowDialogAsync(ApplicationConfiguration configuration, bool showSearchPanel, CancellationToken ct = default) + public async Task ShowDialogAsync(ApplicationConfiguration configuration, bool showSearchPanel, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; List urls = new List(); foreach (EndpointDescription endpoint in configuration.ClientConfiguration.DiscoveryServers) @@ -136,11 +138,11 @@ public async Task ShowDialogAsync(ApplicationConfigurati try { - await ServerCTRL.ConnectAsync(ct: ct); + await ServerCTRL.ConnectAsync(telemetry, ct: ct); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } OkBTN.Visible = true; @@ -405,7 +407,7 @@ private async void SearchBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -417,7 +419,7 @@ private void CloseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -433,20 +435,20 @@ private async void ServerCTRL_ConnectCompleteAsync(object sender, EventArgs e) NodeId rootId = new NodeId(GdsId_Directory_Applications, namespaceIndex); NodeId[] referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.Organizes, Opc.Ua.ReferenceTypeIds.HasChild }; - await BrowseCTRL.InitializeAsync(session, rootId, default, referenceTypeIds); - SystemElementBTN.Session = session; + await BrowseCTRL.InitializeAsync(session, rootId, m_telemetry, default, referenceTypeIds); + SystemElementBTN.ChangeSession(session, m_telemetry); SystemElementBTN.RootId = rootId; SystemElementBTN.ReferenceTypeIds = referenceTypeIds; } else { await BrowseCTRL.ChangeSessionAsync(session); - SystemElementBTN.Session = session; + SystemElementBTN.ChangeSession(session, m_telemetry); } } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -456,11 +458,11 @@ private async void ServerCTRL_ReconnectCompleteAsync(object sender, EventArgs e) { ISession session = ServerCTRL.Session; await BrowseCTRL.ChangeSessionAsync(session); - SystemElementBTN.Session = session; + SystemElementBTN.ChangeSession(session, m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -474,7 +476,7 @@ private void BrowseCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -499,7 +501,7 @@ private void ServersLV_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -532,7 +534,7 @@ private async void BrowseCTRL_AfterSelectAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs index 5777f9981..8dcdca96c 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataDlg.cs @@ -46,6 +46,7 @@ namespace Opc.Ua.Client.Controls /// public partial class HistoryDataDlg : Form, ISessionForm { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -64,9 +65,10 @@ public HistoryDataDlg() /// /// Changes the session used. /// - public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { - return HistoryDataCTRL.ChangeSessionAsync(session, ct); + m_telemetry = telemetry; + return HistoryDataCTRL.ChangeSessionAsync(session, telemetry, ct); } /// @@ -90,7 +92,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -109,7 +111,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs index 0364872ed..03210fd86 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryDataListView.cs @@ -222,6 +222,7 @@ public override string ToString() #region Private Fields private ISession m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private NodeId m_nodeId; @@ -448,7 +449,7 @@ public double ProcessingInterval /// /// Changes the session. /// - public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public async Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { @@ -467,6 +468,7 @@ public async Task ChangeSessionAsync(ISession session, CancellationToken ct = de } m_session = session; + m_telemetry = telemetry; m_dataset.Clear(); LeftPN.Enabled = m_session != null; @@ -1049,7 +1051,7 @@ private async Task CreateSubscriptionAsync(CancellationToken ct = default) return; } - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.Handle = this; m_subscription.DisplayName = null; m_subscription.PublishingInterval = 1000; @@ -1062,7 +1064,7 @@ private async Task CreateSubscriptionAsync(CancellationToken ct = default) m_session.AddSubscription(m_subscription); await m_subscription.CreateAsync(ct); - m_monitoredItem = new MonitoredItem(); + m_monitoredItem = new MonitoredItem(m_telemetry); m_monitoredItem.StartNodeId = m_nodeId; m_monitoredItem.AttributeId = Attributes.Value; m_monitoredItem.SamplingInterval = (int)SamplingIntervalNP.Value; @@ -1217,7 +1219,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -1682,6 +1684,7 @@ private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) Opc.Ua.ObjectIds.ObjectsFolder, null, "Select Variable", + m_telemetry, default, Opc.Ua.ReferenceTypeIds.Organizes, Opc.Ua.ReferenceTypeIds.Aggregates); @@ -1698,7 +1701,7 @@ private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1720,7 +1723,7 @@ private async void SubscribeCK_CheckedChangedAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1808,7 +1811,7 @@ private async void GoBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1820,7 +1823,7 @@ private async void NextBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1832,7 +1835,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2147,7 +2150,7 @@ private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion @@ -2161,7 +2164,7 @@ private void StartTimeDP_ValueChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2185,7 +2188,7 @@ private async void DetectLimitsBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2197,7 +2200,7 @@ private void StartTimeCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2209,7 +2212,7 @@ private void EndTimeCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2221,7 +2224,7 @@ private void MaxReturnValuesCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2243,7 +2246,7 @@ private void TimeShiftBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2304,7 +2307,7 @@ private async void InsertAnnotationMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -2336,7 +2339,7 @@ private void EditValueMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs index bb9327065..ed4f434be 100644 --- a/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/HistoryEventCtrl.cs @@ -87,6 +87,7 @@ public enum HistoryOperation #region Private Fields private Session m_session; + private ITelemetryContext m_telemetry; private NodeId m_nodeId; #endregion @@ -191,9 +192,10 @@ public DateTime EndTime /// /// Changes the session. /// - public void ChangeSession(Session session) + public void ChangeSession(Session session, ITelemetryContext telemetry) { m_session = session; + m_telemetry = telemetry; LeftPN.Enabled = m_session != null; } @@ -301,6 +303,7 @@ private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) Opc.Ua.ObjectIds.Server, null, "Select Notifier", + m_telemetry, default, Opc.Ua.ReferenceTypeIds.HasNotifier); @@ -316,7 +319,7 @@ private async void NodeIdBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -327,7 +330,7 @@ private void GoBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -338,7 +341,7 @@ private void NextBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -408,7 +411,7 @@ private void ReadTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion @@ -421,7 +424,7 @@ private void StartTimeDP_ValueChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -433,7 +436,7 @@ private void StartTimeCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -445,7 +448,7 @@ private void EndTimeCK_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -456,7 +459,7 @@ private void TimeShiftBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs b/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs index 401f61e4b..a514652c8 100644 --- a/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs +++ b/Samples/ClientControls.Net4/Common/Client/ISessionForm.cs @@ -45,6 +45,6 @@ public interface ISessionForm /// Changes the session being used by the form. /// /// The new session to use. A null value means the session has been disconnected. - Task ChangeSessionAsync(ISession session, CancellationToken ct = default); + Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default); } } diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs index a87b5d10d..266c4ec29 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestDlg.cs @@ -45,6 +45,7 @@ namespace Opc.Ua.Client.Controls /// public partial class ReadRequestDlg : Form, ISessionForm { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -63,8 +64,9 @@ public ReadRequestDlg() /// /// Changes the session used for the read request. /// - public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; ReadRequestCTRL.ChangeSession(session); return Task.CompletedTask; } @@ -91,7 +93,7 @@ private async void ReadBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -104,7 +106,7 @@ private void BackBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -123,7 +125,7 @@ private void CloseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs index 415debd92..60469c0fe 100644 --- a/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/ReadRequestListViewCtrl.cs @@ -262,7 +262,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -315,7 +315,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -336,7 +336,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs index 5678e1b41..bd516fe6c 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectNodeCtrl.cs @@ -60,6 +60,7 @@ public SelectNodeCtrl() #region Private Fields private event EventHandler m_NodeSelected; private ReferenceDescription m_selectedNode; + private ITelemetryContext m_telemetry; #endregion #region Public Interface @@ -102,6 +103,12 @@ public NodeId SelectedNode } } + public void ChangeSession(ISession session, ITelemetryContext telemetry) + { + Session = session; + m_telemetry = telemetry; + } + public void ClearSelectedNode() { m_selectedNode = new ReferenceDescription(); @@ -191,6 +198,7 @@ private async void BrowseBTN_ClickAsync(object sender, EventArgs e) RootId, View, null, + m_telemetry, default, ReferenceTypeIds); @@ -198,10 +206,7 @@ private async void BrowseBTN_ClickAsync(object sender, EventArgs e) { SelectedReference = reference; - if (m_NodeSelected != null) - { - m_NodeSelected(this, new EventArgs()); - } + m_NodeSelected?.Invoke(this, new EventArgs()); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs b/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs index 9e42ade21..6e9bf8032 100644 --- a/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SelectNodeDlg.cs @@ -65,6 +65,7 @@ public async Task ShowDialogAsync( ISession session, NodeId rootId, string caption, + ITelemetryContext telemetry, CancellationToken ct, params NodeId[] referenceTypeIds) { @@ -87,7 +88,7 @@ public async Task ShowDialogAsync( } // initialize the control. - await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, telemetry, ct, referenceTypeIds); // display the dialog. if (ShowDialog() != DialogResult.OK) @@ -114,6 +115,7 @@ public async Task ShowDialogAsync( NodeId rootId, ViewDescription view, string caption, + ITelemetryContext telemetry, CancellationToken ct, params NodeId[] referenceTypeIds) { @@ -136,7 +138,7 @@ public async Task ShowDialogAsync( } // initialize the control. - await BrowseCTRL.InitializeAsync(session, rootId, ct, referenceTypeIds); + await BrowseCTRL.InitializeAsync(session, rootId, telemetry,ct, referenceTypeIds); BrowseCTRL.View = view; // display the dialog. diff --git a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs index 705999bb7..bf15a977f 100644 --- a/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SetTypeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,7 @@ using System.Text; using Opc.Ua; using Opc.Ua.Client; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -61,6 +62,7 @@ public SetTypeDlg() #region Private Fields private SetTypeResult m_result; private TypeInfo m_typeInfo; + private ITelemetryContext m_telemetry; #endregion #region SetTypeResult Class @@ -95,9 +97,10 @@ public class SetTypeResult /// /// Displays the available areas in a tree view. /// - public SetTypeResult ShowDialog(TypeInfo typeInfo, int[] dimensions) + public SetTypeResult ShowDialog(ITelemetryContext telemetry, TypeInfo typeInfo, int[] dimensions) { m_typeInfo = typeInfo; + m_telemetry = telemetry; StructureTypeLB.Visible = false; StructureTypeTB.Visible = false; @@ -195,7 +198,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs index 65110e6ff..e200d611b 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataDlg.cs @@ -64,9 +64,9 @@ public SubscribeDataDlg() /// /// Changes the session used for the subscription. /// - public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { - SubscribeRequestCTRL.ChangeSession(session); + SubscribeRequestCTRL.ChangeSession(session, telemetry); m_session = session; return Task.CompletedTask; } @@ -117,7 +117,7 @@ private async void NextBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -131,7 +131,7 @@ private async void BackBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -150,7 +150,7 @@ private void CloseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs index b6f436e49..a0c765598 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeDataListViewCtrl.cs @@ -85,6 +85,7 @@ public SubscribeDataListViewCtrl() #region Private Fields private DataSet m_dataset; private ISession m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private DisplayState m_state; private EditComplexValueDlg m_EditComplexValueDlg; @@ -107,8 +108,9 @@ private enum DisplayState /// /// Changes the session used. /// - public void ChangeSession(ISession session) + public void ChangeSession(ISession session, ITelemetryContext telemetry) { + m_telemetry = telemetry; if (!Object.ReferenceEquals(session, m_session)) { m_session = session; @@ -484,7 +486,7 @@ private void OnPublishStatusChanged(object sender, PublishStateChangedEventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -529,7 +531,7 @@ private async void OnDataChangeAsync(Subscription subscription, DataChangeNotifi } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -564,7 +566,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) monitoredItem = new MonitoredItem(monitoredItem); } - if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false, m_telemetry)) { m_subscription.AddItem(monitoredItem); DataRow row = m_dataset.Tables[0].NewRow(); @@ -575,7 +577,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -597,7 +599,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, false, m_telemetry)) { DataRow row = (DataRow)monitoredItem.Handle; await UpdateRowAsync(row, monitoredItem); @@ -605,7 +607,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -625,7 +627,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -665,7 +667,7 @@ await m_EditComplexValueDlg.ShowDialogAsync( } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -684,7 +686,7 @@ private void ResultsDV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -734,7 +736,7 @@ private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -756,7 +758,7 @@ private async void Subscription_EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs index 174b7b092..651a4adda 100644 --- a/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/SubscribeEventsDlg.cs @@ -82,6 +82,7 @@ public SubscribeEventsDlg() private FilterDeclaration m_filter; private DisplayState m_state; private ISession m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private PublishStateChangedEventHandler m_PublishStatusChanged; #endregion @@ -99,8 +100,9 @@ private enum DisplayState /// /// Changes the session used. /// - public async Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public async Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; if (!Object.ReferenceEquals(session, m_session)) { m_session = session; @@ -223,7 +225,7 @@ public async Task NextAsync(CancellationToken ct = default) if (m_state == DisplayState.SelectEventType) { - await BrowseCTRL.InitializeAsync(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, ct, Opc.Ua.ReferenceTypeIds.HasSubtype); + await BrowseCTRL.InitializeAsync(m_session, Opc.Ua.ObjectTypeIds.BaseEventType, m_telemetry, ct, Opc.Ua.ReferenceTypeIds.HasSubtype); BrowseCTRL.SelectNode((m_filter == null || m_filter.EventTypeId == null) ? Opc.Ua.ObjectTypeIds.BaseEventType : m_filter.EventTypeId); await EventTypeCTRL.ShowTypeAsync(Opc.Ua.ObjectTypeIds.BaseEventType, ct); return; @@ -677,7 +679,7 @@ private void OnPublishStatusChanged(object sender, PublishStateChangedEventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -703,7 +705,7 @@ private void OnEvent(Subscription subscription, EventNotificationList notificati } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -715,7 +717,7 @@ private async void BackBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -727,7 +729,7 @@ private async void NextBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -739,7 +741,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -768,7 +770,7 @@ private async void SubscriptionStateTB_DropDownItemClickedAsync(object sender, T } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -788,7 +790,7 @@ private async void BrowseCTRL_AfterSelectAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -800,7 +802,7 @@ private void BrowseTV_AfterCheck(object sender, TreeViewEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -819,7 +821,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -850,7 +852,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) monitoredItem = new MonitoredItem(monitoredItem); } - if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true, m_telemetry)) { m_subscription.AddItem(monitoredItem); DataRow row = m_dataset.Tables[0].NewRow(); @@ -861,7 +863,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -888,7 +890,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true)) + if (await new EditMonitoredItemDlg().ShowDialogAsync(m_session, monitoredItem, true, m_telemetry)) { DataRow row = (DataRow)monitoredItem.Handle; await UpdateRowAsync(row, monitoredItem); @@ -896,7 +898,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -921,7 +923,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -936,7 +938,7 @@ private void ItemsDV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -991,7 +993,7 @@ private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/UserNamePasswordDlg.cs b/Samples/ClientControls.Net4/Common/Client/UserNamePasswordDlg.cs index 8ba5698c9..ae592bb3f 100644 --- a/Samples/ClientControls.Net4/Common/Client/UserNamePasswordDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/UserNamePasswordDlg.cs @@ -69,7 +69,7 @@ public UserIdentity ShowDialog(IUserIdentity identity, string caption) if (token != null) { UserNameTB.Text = token.UserName; - PasswordTB.Text = token.DecryptedPassword; + PasswordTB.Text = Encoding.UTF8.GetString(token.DecryptedPassword); } } @@ -78,7 +78,7 @@ public UserIdentity ShowDialog(IUserIdentity identity, string caption) return null; } - return new UserIdentity(UserNameTB.Text, PasswordTB.Text); + return new UserIdentity(UserNameTB.Text, Encoding.UTF8.GetBytes(PasswordTB.Text)); } } } diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs index 523235d0a..f65b5b95c 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestDlg.cs @@ -45,6 +45,7 @@ namespace Opc.Ua.Client.Controls /// public partial class WriteRequestDlg : Form, ISessionForm { + private ITelemetryContext m_telemetry; #region Constructors /// /// Creates an empty form. @@ -63,9 +64,10 @@ public WriteRequestDlg() /// /// Changes the session used for the read request. /// - public Task ChangeSessionAsync(ISession session, CancellationToken ct = default) + public Task ChangeSessionAsync(ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { - WriteRequestCTRL.ChangeSession(session); + m_telemetry = telemetry; + WriteRequestCTRL.ChangeSession(session, telemetry); return Task.CompletedTask; } @@ -90,7 +92,7 @@ private async void ReadBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -104,7 +106,7 @@ private async void WriteBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -118,7 +120,7 @@ private void BackBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -137,7 +139,7 @@ private void CloseBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs index f9f4d6cd0..06562c2d5 100644 --- a/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs +++ b/Samples/ClientControls.Net4/Common/Client/WriteRequestListViewCtrl.cs @@ -78,15 +78,17 @@ public WriteRequestListViewCtrl() #region Private Fields private DataSet m_dataset; private ISession m_session; + private ITelemetryContext m_telemetry; #endregion #region Public Members /// /// Changes the session used for the write request. /// - public void ChangeSession(ISession session) + public void ChangeSession(ISession session, ITelemetryContext telemetry) { m_session = session; + m_telemetry = telemetry; } /// @@ -293,7 +295,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -318,7 +320,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } // prompt use to edit new value. - WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, nodeToWrite); + WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, nodeToWrite, m_telemetry); if (result != null) { @@ -329,7 +331,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -343,7 +345,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) DataRowView source = row.DataBoundItem as DataRowView; WriteValue value = (WriteValue)source.Row[0]; - WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, value); + WriteValue result = await new EditWriteValueDlg().ShowDialogAsync(m_session, value, m_telemetry); if (result != null) { @@ -355,7 +357,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -400,7 +402,7 @@ private async void EditValueMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -416,7 +418,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs index 1cd666ae1..ffcd33da6 100644 --- a/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoverServerDlg.cs @@ -58,6 +58,7 @@ public DiscoverServerDlg() #region Private Fields private ApplicationConfiguration m_configuration; + private ITelemetryContext m_telemetry; #endregion #region Public Interface @@ -66,9 +67,9 @@ public DiscoverServerDlg() /// /// The client applicatio configuration. /// The selected endpoint url - public string ShowDialog(ApplicationConfiguration configuration) + public string ShowDialog(ApplicationConfiguration configuration, ITelemetryContext telemetry) { - return ShowDialog(configuration, null); + return ShowDialog(configuration, null, telemetry); } /// @@ -77,9 +78,10 @@ public string ShowDialog(ApplicationConfiguration configuration) /// The client applicatio configuration. /// The default host name. /// The selected endpoint url - public string ShowDialog(ApplicationConfiguration configuration, string hostName) + public string ShowDialog(ApplicationConfiguration configuration, string hostName, ITelemetryContext telemetry) { m_configuration = configuration; + m_telemetry = telemetry; if (String.IsNullOrEmpty(hostName)) { @@ -118,7 +120,7 @@ private async Task GetEndpointsAsync(string hostName, CancellationToke configuration.OperationTimeout = 20000; // Connect to the local discovery server and find the available servers. - using (DiscoveryClient client = DiscoveryClient.Create(new Uri(Utils.Format("opc.tcp://{0}:4840", hostName)), configuration)) + using (DiscoveryClient client = await DiscoveryClient.CreateAsync(new Uri(Utils.Format("opc.tcp://{0}:4840", hostName)), configuration, m_telemetry, DiagnosticsMasks.None, ct)) { ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); @@ -176,7 +178,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -188,7 +190,7 @@ private void ServersLB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -217,7 +219,7 @@ private async void FindBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs index 9164f4b87..3b82c10ee 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerListCtrl.cs @@ -38,6 +38,7 @@ using Opc.Ua.Client.Controls; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -70,6 +71,7 @@ public DiscoveredServerListCtrl() }; private ApplicationConfiguration m_configuration; + private ILogger m_logger; private int m_discoveryTimeout; private int m_discoverCount; private string m_discoveryUrl; @@ -99,10 +101,13 @@ public string DiscoveryUrl /// /// Displays a list of servers in the control. /// - public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration) + public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration, ITelemetryContext telemetry) { Interlocked.Exchange(ref m_configuration, configuration); + Telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + ItemsLV.Items.Clear(); foreach (ApplicationDescription server in endpoints.GetServers()) @@ -116,10 +121,13 @@ public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfig /// /// Displays a list of servers in the control. /// - public void Initialize(string hostname, ApplicationConfiguration configuration) + public void Initialize(string hostname, ApplicationConfiguration configuration, ITelemetryContext telemetry) { Interlocked.Exchange(ref m_configuration, configuration); + Telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + ItemsLV.Items.Clear(); if (String.IsNullOrEmpty(hostname)) @@ -230,7 +238,7 @@ private async Task OnDiscoverServersAsync(IList discoveryUrls, Cancellat } catch (Exception e) { - Utils.Trace(e, "Unexpected error discovering servers."); + m_logger.LogError(e, "Unexpected error discovering servers."); } } @@ -247,9 +255,12 @@ private async Task DiscoverServersAsync(Uri discoveryUrl, CancellationToke try { - client = DiscoveryClient.Create( + client = await DiscoveryClient.CreateAsync( discoveryUrl, - EndpointConfiguration.Create(m_configuration)); + EndpointConfiguration.Create(m_configuration), + Telemetry, + DiagnosticsMasks.None, + ct); ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); m_discoveryUrl = discoveryUrl.ToString(); @@ -258,7 +269,7 @@ private async Task DiscoverServersAsync(Uri discoveryUrl, CancellationToke } catch (Exception e) { - Utils.Trace("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({2}){1}", discoveryUrl, e.Message, e.GetType()); + m_logger.LogError("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({2}){1}", discoveryUrl, e.Message, e.GetType()); return false; } finally diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs index 583d06b95..946b3d869 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerListDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -58,15 +58,17 @@ public DiscoveredServerListDlg() private string m_hostname; private ApplicationDescription m_server; private ApplicationConfiguration m_configuration; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public ApplicationDescription ShowDialog(string hostname, ApplicationConfiguration configuration) + public ApplicationDescription ShowDialog(string hostname, ApplicationConfiguration configuration, ITelemetryContext telemetry) { m_configuration = configuration; + m_telemetry = telemetry; if (String.IsNullOrEmpty(hostname)) { @@ -76,8 +78,8 @@ public ApplicationDescription ShowDialog(string hostname, ApplicationConfigurati m_hostname = hostname; List hostnames = new List(); - HostNameCTRL.Initialize(hostname, hostnames); - ServersCTRL.Initialize(hostname, configuration); + HostNameCTRL.Initialize(m_telemetry, hostname, hostnames); + ServersCTRL.Initialize(hostname, configuration, telemetry); OkBTN.Enabled = false; @@ -99,7 +101,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -110,14 +112,14 @@ private void HostNameCTRL_HostSelected(object sender, SelectHostCtrlEventArgs e) if (m_hostname != e.Hostname) { m_hostname = e.Hostname; - ServersCTRL.Initialize(m_hostname, m_configuration); + ServersCTRL.Initialize(m_hostname, m_configuration, m_telemetry); m_server = null; OkBTN.Enabled = false; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -126,13 +128,13 @@ private void HostNameCTRL_HostConnected(object sender, SelectHostCtrlEventArgs e try { m_hostname = e.Hostname; - ServersCTRL.Initialize(m_hostname, m_configuration); + ServersCTRL.Initialize(m_hostname, m_configuration, m_telemetry); m_server = null; OkBTN.Enabled = false; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -152,7 +154,7 @@ private void ServersCTRL_ItemsSelected(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -175,7 +177,7 @@ private void ServersCTRL_ItemsPicked(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs index 867b0120f..e42cf103d 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListCtrl.cs @@ -38,6 +38,7 @@ using Opc.Ua.Client.Controls; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -70,6 +71,7 @@ public DiscoveredServerOnNetworkListCtrl() }; private ApplicationConfiguration m_configuration; + private ILogger m_logger; private int m_discoveryTimeout; private int m_discoverCount; private string m_discoveryUrl; @@ -104,9 +106,13 @@ public string DiscoveryUrl /// /// Displays a list of servers in the control. /// - public void Initialize(string hostname, NumericUpDown startingRecordId, NumericUpDown maxRecordsToReturn, TextBox capabilityFilterText, ApplicationConfiguration configuration) + public void Initialize(string hostname, NumericUpDown startingRecordId, NumericUpDown maxRecordsToReturn, TextBox capabilityFilterText, ApplicationConfiguration configuration, ITelemetryContext telemetry) { Interlocked.Exchange(ref m_configuration, configuration); + + Telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + ItemsLV.Items.Clear(); m_startingRecordIdUpDown = startingRecordId; m_maxRecordsToReturnUpDown = maxRecordsToReturn; @@ -216,7 +222,7 @@ private async Task OnDiscoverServersOnNetworkAsync(IList discoveryUrls, } catch (Exception e) { - Utils.LogError(e, "Unexpected error discovering servers."); + m_logger.LogError(e, "Unexpected error discovering servers."); } } @@ -232,9 +238,12 @@ private async Task DiscoverServersOnNetworkAsync(Uri discoveryUrl, Cancell try { - client = DiscoveryClient.Create( + client = await DiscoveryClient.CreateAsync( discoveryUrl, - EndpointConfiguration.Create(m_configuration)); + EndpointConfiguration.Create(m_configuration), + Telemetry, + DiagnosticsMasks.None, + ct); uint startingRecordId = (uint)0; uint maxRecordsToReturn = (uint)0; @@ -253,7 +262,7 @@ private async Task DiscoverServersOnNetworkAsync(Uri discoveryUrl, Cancell } catch (Exception e) { - Utils.LogError("Error retrieving FindServersOnNetwork parameters. Error=({0}){1}", e.GetType(), e.Message); + m_logger.LogError("Error retrieving FindServersOnNetwork parameters. Error=({0}){1}", e.GetType(), e.Message); return false; } @@ -265,7 +274,7 @@ private async Task DiscoverServersOnNetworkAsync(Uri discoveryUrl, Cancell } catch (Exception e) { - Utils.LogError("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({1}){2}", discoveryUrl, e.GetType(), e.Message); + m_logger.LogError("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({1}){2}", discoveryUrl, e.GetType(), e.Message); return false; } finally diff --git a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs index 96e8cab5b..0f7f909c2 100644 --- a/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs +++ b/Samples/ClientControls.Net4/Common/DiscoveredServerOnNetworkListDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -58,15 +58,17 @@ public DiscoveredServerOnNetworkListDlg() private string m_hostname; private ServerOnNetwork m_server; private ApplicationConfiguration m_configuration; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public ServerOnNetwork ShowDialog(string hostname, ApplicationConfiguration configuration) + public ServerOnNetwork ShowDialog(string hostname, ApplicationConfiguration configuration, ITelemetryContext telemetry) { m_configuration = configuration; + m_telemetry = telemetry; if (String.IsNullOrEmpty(hostname)) { @@ -76,8 +78,8 @@ public ServerOnNetwork ShowDialog(string hostname, ApplicationConfiguration conf m_hostname = hostname; List hostnames = new List(); - HostNameCTRL.Initialize(hostname, hostnames); - ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration); + HostNameCTRL.Initialize(m_telemetry, hostname, hostnames); + ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration, telemetry); OkBTN.Enabled = false; @@ -99,7 +101,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -110,14 +112,14 @@ private void HostNameCTRL_HostSelected(object sender, SelectHostCtrlEventArgs e) if (m_hostname != e.Hostname) { m_hostname = e.Hostname; - ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration); + ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration, m_telemetry); m_server = null; OkBTN.Enabled = false; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -126,13 +128,13 @@ private void HostNameCTRL_HostConnected(object sender, SelectHostCtrlEventArgs e try { m_hostname = e.Hostname; - ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration); + ServersCTRL.Initialize(m_hostname, this.StartingRecordUP, this.MaxRecordsUP, this.CapabilityFilterTB, m_configuration, m_telemetry); m_server = null; OkBTN.Enabled = false; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -152,7 +154,7 @@ private void ServersCTRL_ItemsSelected(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -175,7 +177,7 @@ private void ServersCTRL_ItemsPicked(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/EditArrayDlg.cs b/Samples/ClientControls.Net4/Common/EditArrayDlg.cs index 69c3ac9f6..eb5feb6c8 100644 --- a/Samples/ClientControls.Net4/Common/EditArrayDlg.cs +++ b/Samples/ClientControls.Net4/Common/EditArrayDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -68,14 +68,16 @@ public EditArrayDlg() #region Private Fields private DataSet m_dataset; private BuiltInType m_dataType; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Prompts the user to edit an array value. /// - public Array ShowDialog(Array value, BuiltInType dataType, bool readOnly, string caption) + public Array ShowDialog(ITelemetryContext telemetry, Array value, BuiltInType dataType, bool readOnly, string caption) { + m_telemetry = telemetry; if (caption != null) { this.Text = caption; @@ -138,7 +140,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -150,7 +152,7 @@ private void ArrayDV_CellValidating(object sender, DataGridViewCellValidatingEve } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); e.Cancel = true; } } @@ -170,7 +172,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -205,7 +207,7 @@ private void InsertMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs b/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs index 1972d387b..3dbc82537 100644 --- a/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs +++ b/Samples/ClientControls.Net4/Common/EditDataValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -54,14 +54,16 @@ public EditDataValueDlg() #region Private Fields private DataValue m_value; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Prompts the user to edit a value. /// - public Variant ShowDialog(Variant value, string caption) + public Variant ShowDialog(Variant value, string caption, ITelemetryContext telemetry) { + m_telemetry = telemetry; if (caption != null) { this.Text = caption; @@ -115,7 +117,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/EventListView.cs b/Samples/ClientControls.Net4/Common/EventListView.cs index fb7247d41..772a526ce 100644 --- a/Samples/ClientControls.Net4/Common/EventListView.cs +++ b/Samples/ClientControls.Net4/Common/EventListView.cs @@ -56,6 +56,7 @@ public EventListView() #region Private Methods private Session m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private FilterDeclaration m_filter; @@ -127,7 +128,7 @@ public FilterDeclaration Filter /// /// Changes the session. /// - public async Task ChangeSessionAsync(Session session, bool fetchRecent, CancellationToken ct = default) + public async Task ChangeSessionAsync(Session session, bool fetchRecent, ITelemetryContext telemetry, CancellationToken ct = default) { if (Object.ReferenceEquals(session, m_session)) { @@ -141,6 +142,7 @@ public async Task ChangeSessionAsync(Session session, bool fetchRecent, Cancella } m_session = session; + m_telemetry = telemetry; EventsLV.Items.Clear(); if (m_session != null && m_isSubscribed) @@ -327,7 +329,7 @@ public VariantCollection GetSelectedEvent(int index) /// private async Task CreateSubscriptionAsync(CancellationToken ct = default) { - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.Handle = this; m_subscription.DisplayName = null; m_subscription.PublishingInterval = 1000; @@ -340,7 +342,7 @@ private async Task CreateSubscriptionAsync(CancellationToken ct = default) m_session.AddSubscription(m_subscription); await m_subscription.CreateAsync(ct); - m_monitoredItem = new MonitoredItem(); + m_monitoredItem = new MonitoredItem(m_telemetry); m_monitoredItem.StartNodeId = m_areaId; m_monitoredItem.AttributeId = Attributes.EventNotifier; m_monitoredItem.SamplingInterval = 0; @@ -539,7 +541,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -722,7 +724,7 @@ private void ViewDetailsMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -764,7 +766,7 @@ private async void DeleteHistoryMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/HostListCtrl.cs b/Samples/ClientControls.Net4/Common/HostListCtrl.cs index 0734908b3..79ed50c35 100644 --- a/Samples/ClientControls.Net4/Common/HostListCtrl.cs +++ b/Samples/ClientControls.Net4/Common/HostListCtrl.cs @@ -39,6 +39,7 @@ using Opc.Ua.Configuration; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -65,14 +66,17 @@ public HostListCtrl() new object[] { "Name", HorizontalAlignment.Left, null }, new object[] { "Addresses", HorizontalAlignment.Left, null } }; + private ILogger m_logger = LoggerUtils.Null.Logger; #endregion #region Public Interface /// /// Displays a list of servers in the control. /// - public void Initialize(string domain) + public void Initialize(ITelemetryContext telemetry, string domain) { + Telemetry = telemetry; + m_logger = telemetry.CreateLogger(); ItemsLV.Items.Clear(); this.Instructions = Utils.Format("Discovering hosts on domain '{0}'.", domain); @@ -120,7 +124,7 @@ private void OnFetchAddresses(object state) } catch (Exception e) { - Utils.LogError(e, "Could not get ip addresses for host: {0}", hostname); + m_logger.LogError(e, "Could not get ip addresses for host: {HostName}", hostname); ThreadPool.QueueUserWorkItem(new WaitCallback(OnUpdateAddress), new object[] { listItem, e.Message }); } } diff --git a/Samples/ClientControls.Net4/Common/HostListDlg.cs b/Samples/ClientControls.Net4/Common/HostListDlg.cs index db5fc60f3..ab692125a 100644 --- a/Samples/ClientControls.Net4/Common/HostListDlg.cs +++ b/Samples/ClientControls.Net4/Common/HostListDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using System.Reflection; using Opc.Ua.Configuration; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -59,13 +60,15 @@ public HostListDlg() #region Private Fields private string m_domain; private string m_hostname; + private ILogger m_logger = LoggerUtils.Null.Logger; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public string ShowDialog(string domain) + public string ShowDialog(ITelemetryContext telemetry, string domain) { if (String.IsNullOrEmpty(domain)) { @@ -73,9 +76,11 @@ public string ShowDialog(string domain) } m_domain = domain; + m_logger = telemetry.CreateLogger(); + m_telemetry = telemetry; - DomainNameCTRL.Initialize(m_domain, null); - HostsCTRL.Initialize(m_domain); + DomainNameCTRL.Initialize(telemetry, m_domain, null); + HostsCTRL.Initialize(telemetry, m_domain); OkBTN.Enabled = false; if (ShowDialog() != DialogResult.OK) @@ -96,7 +101,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -107,14 +112,14 @@ private void DomainNameCTRL_HostSelected(object sender, SelectHostCtrlEventArgs if (m_domain != e.Hostname) { m_domain = e.Hostname; - HostsCTRL.Initialize(m_domain); + HostsCTRL.Initialize(m_telemetry, m_domain); m_hostname = null; OkBTN.Enabled = false; } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -123,13 +128,13 @@ private void DomainNameCTRL_HostConnected(object sender, SelectHostCtrlEventArgs try { m_domain = e.Hostname; - HostsCTRL.Initialize(m_domain); + HostsCTRL.Initialize(m_telemetry, m_domain); m_hostname = null; OkBTN.Enabled = false; } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -149,7 +154,7 @@ private void HostsCTRL_ItemsSelected(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -172,7 +177,7 @@ private void HostsCTRL_ItemsPicked(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs b/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs index 1afc0493d..06adec19f 100644 --- a/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs +++ b/Samples/ClientControls.Net4/Common/SelectHostCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -37,6 +37,7 @@ using System.Reflection; using Opc.Ua.Configuration; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -56,6 +57,8 @@ public SelectHostCtrl() #endregion #region Private Fields + private ILogger m_logger = LoggerUtils.Null.Logger; + private ITelemetryContext m_telemetry; private int m_selectedIndex; private bool m_selectDomains; private event EventHandler m_HostSelected; @@ -86,8 +89,10 @@ public string CommandText /// /// Displays a set of hostnames in the control. /// - public void Initialize(string defaultHost, IList hostnames) + public void Initialize(ITelemetryContext telemetry, string defaultHost, IList hostnames) { + m_logger = telemetry.CreateLogger(); + m_telemetry = telemetry; HostsCB.Items.Clear(); // add option to browse for hosts. @@ -150,10 +155,7 @@ private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) { if (HostsCB.SelectedIndex != 0) { - if (m_HostSelected != null) - { - m_HostSelected(this, new SelectHostCtrlEventArgs((string)HostsCB.SelectedItem)); - } + m_HostSelected?.Invoke(this, new SelectHostCtrlEventArgs((string)HostsCB.SelectedItem)); m_selectedIndex = HostsCB.SelectedIndex; return; @@ -162,7 +164,7 @@ private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) if (!m_selectDomains) { // prompt user to select a host. - string hostname = new HostListDlg().ShowDialog(null); + string hostname = new HostListDlg().ShowDialog(m_telemetry, null); if (hostname == null) { @@ -183,7 +185,7 @@ private void HostsCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -223,7 +225,7 @@ private void ConnectBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs b/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs index c16af3267..0850821db 100644 --- a/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs +++ b/Samples/ClientControls.Net4/Common/ViewNodeStateDlg.cs @@ -159,7 +159,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs index 86f967399..edd602dca 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateDlg.cs @@ -41,6 +41,8 @@ namespace Opc.Ua.Client.Controls /// public partial class CertificateDlg : Form { + private ITelemetryContext m_telemetry; + /// /// Contructs the object. /// @@ -57,8 +59,10 @@ public CertificateDlg() /// /// Displays the dialog. /// - public async Task ShowDialogAsync(CertificateIdentifier certificateIdentifier, CancellationToken ct = default) + public async Task ShowDialogAsync(CertificateIdentifier certificateIdentifier, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; + CertificateStoreCTRL.Telemetry = telemetry; CertificateStoreCTRL.StoreType = null; CertificateStoreCTRL.StorePath = null; PrivateKeyCB.SelectedIndex = 0; @@ -94,8 +98,9 @@ public async Task ShowDialogAsync(CertificateIdentifier certificateIdentif /// /// Displays the dialog. /// - public bool ShowDialog(X509Certificate2 certificate) + public bool ShowDialog(X509Certificate2 certificate, ITelemetryContext telemetry) { + CertificateStoreCTRL.Telemetry = telemetry; CertificateStoreCTRL.StoreType = null; CertificateStoreCTRL.StorePath = null; PrivateKeyCB.SelectedIndex = 0; @@ -117,7 +122,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs index 5f696c956..47357d52e 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListCtrl.cs @@ -203,11 +203,12 @@ internal void Initialize(CertificateIdentifierCollection certificates) /// /// Displays the applications in the control. /// - internal async Task InitializeAsync(CertificateStoreIdentifier id, IList thumbprints, CancellationToken ct = default) + internal async Task InitializeAsync(CertificateStoreIdentifier id, IList thumbprints, ITelemetryContext telemetry, CancellationToken ct = default) { ItemsLV.Items.Clear(); m_storeId = id; + Telemetry = telemetry; m_thumbprints = thumbprints; if (m_storeId == null || String.IsNullOrEmpty(m_storeId.StoreType) || String.IsNullOrEmpty(m_storeId.StorePath)) @@ -220,7 +221,7 @@ internal async Task InitializeAsync(CertificateStoreIdentifier id, IList try { // get the store. - using (ICertificateStore store = m_storeId.OpenStore()) + using (ICertificateStore store = m_storeId.OpenStore(telemetry)) { // only show certificates with the specified thumbprint. if (thumbprints != null) @@ -367,7 +368,7 @@ protected override async Task UpdateItemAsync(ListViewItem listItem, object item } listItem.SubItems[3].Text = buffer.ToString(); - listItem.SubItems[4].Text = X509Utils.GetApplicationUriFromCertificate(certificate); + listItem.SubItems[4].Text = X509Utils.GetApplicationUrisFromCertificate(certificate)[0]; listItem.SubItems[5].Text = String.Format("{0:yyyy-MM-dd}", certificate.NotAfter); } @@ -418,12 +419,12 @@ private async void ViewMI_ClickAsync(object sender, EventArgs e) id.StorePath = m_storeId.StorePath; } - await new ViewCertificateDlg().ShowDialogAsync(id); + await new ViewCertificateDlg().ShowDialogAsync(id, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -451,7 +452,7 @@ private async void DeleteMI_ClickAsync(object sender, EventArgs e) List itemsToDelete = new List(); bool yesToAll = false; - using (ICertificateStore store = m_storeId.OpenStore()) + using (ICertificateStore store = m_storeId.OpenStore(Telemetry)) { for (int ii = 0; ii < ItemsLV.SelectedItems.Count; ii++) { @@ -497,8 +498,8 @@ private async void DeleteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); - await InitializeAsync(m_storeId, m_thumbprints); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); + await InitializeAsync(m_storeId, m_thumbprints, Telemetry); } } @@ -532,7 +533,7 @@ private void CopyMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -558,7 +559,7 @@ private void PasteMI_Click(object sender, EventArgs e) if (id.Certificate != null) { - using (ICertificateStore store = m_storeId.OpenStore()) + using (ICertificateStore store = m_storeId.OpenStore(Telemetry)) { store.AddAsync(id.Certificate); } @@ -568,7 +569,7 @@ private void PasteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs index 9001ace14..2ec4ce33b 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -57,8 +57,11 @@ public CertificateListDlg() /// /// Displays the dialog. /// - public CertificateIdentifier ShowDialog(CertificateStoreIdentifier store, bool allowStoreChange) + public CertificateIdentifier ShowDialog(CertificateStoreIdentifier store, bool allowStoreChange, ITelemetryContext telemetry) { + m_telemetry = telemetry; + + CertificateStoreCTRL.Telemetry = telemetry; CertificateStoreCTRL.StoreType = CertificateStoreType.Directory; CertificateStoreCTRL.StorePath = String.Empty; CertificateStoreCTRL.ReadOnly = !allowStoreChange; @@ -91,7 +94,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -136,7 +139,7 @@ private void FilterBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -148,7 +151,7 @@ private void CertificatesCTRL_ItemsSelected(object sender, ListItemActionEventAr } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -159,14 +162,16 @@ private async void CertificateStoreCTRL_StoreChangedAsync(object sender, EventAr CertificateStoreIdentifier store = new CertificateStoreIdentifier(); store.StoreType = CertificateStoreCTRL.StoreType; store.StorePath = CertificateStoreCTRL.StorePath; - await CertificatesCTRL.InitializeAsync(store, null); + await CertificatesCTRL.InitializeAsync(store, null, m_telemetry); FilterBTN_Click(sender, e); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } + + private ITelemetryContext m_telemetry; } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateListFilter.cs b/Samples/ClientControls.Net4/Configuration/CertificateListFilter.cs index 96c99d0f1..33af06946 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateListFilter.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateListFilter.cs @@ -109,7 +109,7 @@ public bool Match(X509Certificate2 certificate) { if (!String.IsNullOrEmpty(m_subjectName)) { - if (!Utils.Match(certificate.Subject, "CN*" + m_subjectName + ",*", false)) + if (!Match(certificate.Subject, "CN*" + m_subjectName + ",*")) { return false; } @@ -117,7 +117,7 @@ public bool Match(X509Certificate2 certificate) if (!String.IsNullOrEmpty(m_issuerName)) { - if (!Utils.Match(certificate.Issuer, "CN*" + m_issuerName + ",*", false)) + if (!Match(certificate.Issuer, "CN*" + m_issuerName + ",*")) { return false; } @@ -131,7 +131,7 @@ public bool Match(X509Certificate2 certificate) for (int ii = 0; ii < domains.Count; ii++) { - if (Utils.Match(domains[ii], m_domain, false)) + if (Match(domains[ii], m_domain)) { found = true; break; @@ -223,8 +223,307 @@ public bool Match(X509Certificate2 certificate) return false; } } + + /// + /// Returns true if the target string matches the UA pattern string. + /// The pattern string may include UA wildcards %_\[]! + /// + /// String to check for a pattern match. + /// Pattern to match with the target string. + /// true if the target string matches the pattern, otherwise false. + public static bool Match(string target, string pattern) + { + if (string.IsNullOrEmpty(target)) + { + return false; + } + + if (string.IsNullOrEmpty(pattern)) + { + return true; + } + + List tokens = Parse(pattern); + + int targetIndex = 0; + + for (int ii = 0; ii < tokens.Count; ii++) + { + targetIndex = Match(target, targetIndex, tokens, ref ii); + + if (targetIndex < 0) + { + return false; + } + } + + return targetIndex >= target.Length; + } + #endregion + private static List Parse(string pattern) + { + var tokens = new List(); + + int ii = 0; + var buffer = new StringBuilder(); + + while (ii < pattern.Length) + { + char ch = pattern[ii]; + + if (ch == '\\') + { + ii++; + + if (ii >= pattern.Length) + { + break; + } + + buffer.Append(pattern[ii]); + ii++; + continue; + } + + if (ch == '_') + { + if (buffer.Length > 0) + { + tokens.Add(buffer.ToString()); + buffer.Length = 0; + } + + tokens.Add("_"); + ii++; + continue; + } + + if (ch == '%') + { + if (buffer.Length > 0) + { + tokens.Add(buffer.ToString()); + buffer.Length = 0; + } + + tokens.Add("%"); + ii++; + + while (ii < pattern.Length && pattern[ii] == '%') + { + ii++; + } + + continue; + } + + if (ch == '[') + { + if (buffer.Length > 0) + { + tokens.Add(buffer.ToString()); + buffer.Length = 0; + } + + buffer.Append(ch); + ii++; + while (ii < pattern.Length && pattern[ii] != ']') + { + if (pattern[ii] == '-' && ii > 0 && ii < pattern.Length - 1) + { + int start = Convert.ToInt32(pattern[ii - 1]) + 1; + int end = Convert.ToInt32(pattern[ii + 1]); + + while (start < end) + { + buffer.Append(Convert.ToChar(start)); + start++; + } + + buffer.Append(Convert.ToChar(end)); + ii += 2; + continue; + } + + buffer.Append(pattern[ii]); + ii++; + } + + buffer.Append(']'); + tokens.Add(buffer.ToString()); + buffer.Length = 0; + + ii++; + continue; + } + + buffer.Append(ch); + ii++; + } + + if (buffer.Length > 0) + { + tokens.Add(buffer.ToString()); + buffer.Length = 0; + } + + return tokens; + } + private static int Match( + string target, + int targetIndex, + IList tokens, + ref int tokenIndex) + { + if (tokens == null || tokenIndex < 0 || tokenIndex >= tokens.Count) + { + return -1; + } + + if (target == null || targetIndex < 0 || targetIndex >= target.Length) + { + if (tokens[tokenIndex] == "%" && tokenIndex == tokens.Count - 1) + { + return targetIndex; + } + + return -1; + } + + string token = tokens[tokenIndex]; + + if (token == "_") + { + if (targetIndex >= target.Length) + { + return -1; + } + + return targetIndex + 1; + } + + if (token == "%") + { + return SkipToNext(target, targetIndex, tokens, ref tokenIndex); + } + + if (token.StartsWith('[')) + { + bool inverse = false; + bool match = false; + + for (int ii = 1; ii < token.Length - 1; ii++) + { + if (token[ii] == '^') + { + inverse = true; + continue; + } + + if (!inverse && target[targetIndex] == token[ii]) + { + return targetIndex + 1; + } + + match |= inverse && target[targetIndex] == token[ii]; + } + + if (inverse && !match) + { + return targetIndex + 1; + } + + return -1; + } + + if (target[targetIndex..].StartsWith(token, StringComparison.Ordinal)) + { + return targetIndex + token.Length; + } + + return -1; + } + + private static int SkipToNext( + string target, + int targetIndex, + IList tokens, + ref int tokenIndex) + { + if (targetIndex >= target.Length - 1) + { + return targetIndex + 1; + } + + if (tokenIndex >= tokens.Count - 1) + { + return target.Length + 1; + } + + if (!tokens[tokenIndex + 1].StartsWith("[^", StringComparison.Ordinal)) + { + int nextTokenIndex = tokenIndex + 1; + + // skip over unmatched chars. + while (targetIndex < target.Length && + Match(target, targetIndex, tokens, ref nextTokenIndex) < 0) + { + targetIndex++; + nextTokenIndex = tokenIndex + 1; + } + + nextTokenIndex = tokenIndex + 1; + + // skip over duplicate matches. + while (targetIndex < target.Length && + Match(target, targetIndex, tokens, ref nextTokenIndex) >= 0) + { + targetIndex++; + nextTokenIndex = tokenIndex + 1; + } + + // return last match. + if (targetIndex <= target.Length) + { + return targetIndex - 1; + } + } + else + { + int start = targetIndex; + int nextTokenIndex = tokenIndex + 1; + + // skip over matches. + while (targetIndex < target.Length && + Match(target, targetIndex, tokens, ref nextTokenIndex) >= 0) + { + targetIndex++; + nextTokenIndex = tokenIndex + 1; + } + + // no match in string. + if (targetIndex < target.Length) + { + return -1; + } + + // try the next token. + if (tokenIndex >= tokens.Count - 2) + { + return target.Length + 1; + } + + tokenIndex++; + + return SkipToNext(target, start, tokens, ref tokenIndex); + } + + return -1; + } + + #region Private Fields private string m_subjectName; private string m_issuerName; diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs index 278de52e5..d1a1dc885 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -66,6 +66,11 @@ public CertificateStoreCtrl() #endregion #region Public Interface + /// + /// The Telemetry Context + /// + public ITelemetryContext Telemetry { get; set; } + /// /// Raised when the certificate store is changed in the control. /// @@ -214,7 +219,7 @@ private void StorePathCB_DropDown(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -246,7 +251,7 @@ private void BrowseStoreBTN_Click(object sender, EventArgs e) if (storeType == CertificateStoreType.X509Store) { - CertificateStoreIdentifier store = new CertificateStoreTreeDlg().ShowDialog(null); + CertificateStoreIdentifier store = new CertificateStoreTreeDlg().ShowDialog(null, Telemetry); if (store == null) { @@ -280,7 +285,7 @@ private void BrowseStoreBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -295,14 +300,11 @@ private void StoreTypeCB_SelectedIndexChanged(object sender, EventArgs e) StorePathCB.SelectedIndex = 0; } - if (m_StoreChanged != null) - { - m_StoreChanged(null, e); - } + m_StoreChanged?.Invoke(null, e); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -310,14 +312,11 @@ private void StorePathCB_TextChanged(object sender, EventArgs e) { try { - if (m_StoreChanged != null) - { - m_StoreChanged(null, e); - } + m_StoreChanged?.Invoke(null, e); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -337,7 +336,7 @@ private void StorePathCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreDlg.cs index 33292dc14..af7866c5c 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -52,11 +52,16 @@ public CertificateStoreDlg() this.Icon = ClientUtils.GetAppIcon(); } + private ITelemetryContext m_telemetry; + /// /// Displays the dialog. /// - public CertificateStoreIdentifier ShowDialog(CertificateStoreIdentifier store) + public CertificateStoreIdentifier ShowDialog(CertificateStoreIdentifier store, ITelemetryContext telemetry) { + m_telemetry = telemetry; + + CertificateStoreCTRL.Telemetry = telemetry; CertificateStoreCTRL.StoreType = CertificateStoreType.Directory; CertificateStoreCTRL.StorePath = null; @@ -85,7 +90,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -96,11 +101,11 @@ private void ViewBTN_Click(object sender, EventArgs e) CertificateStoreIdentifier store = new CertificateStoreIdentifier(); store.StoreType = CertificateStoreCTRL.StoreType; store.StorePath = CertificateStoreCTRL.StorePath; - new CertificateListDlg().ShowDialog(store, false); + new CertificateListDlg().ShowDialog(store, false, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs index 08ba9d9f6..e46e65164 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeCtrl.cs @@ -141,8 +141,9 @@ public CertificateListCtrl CertificateListCtrl /// /// Provides the configuration to use when displaying the control. /// - public void Initialize() + public void Initialize(ITelemetryContext telemetry) { + Telemetry = telemetry; NodesTV.Nodes.Clear(); TreeNode node = AddNode(null, new ContainerInfo(ContainerInfoType.Root, System.Net.Dns.GetHostName())); node.Nodes.Add(new TreeNode()); @@ -160,7 +161,7 @@ protected override async void SelectNode() if (m_certificateListCtrl != null) { - await m_certificateListCtrl.InitializeAsync(SelectedStore, null); + await m_certificateListCtrl.InitializeAsync(SelectedStore, null, Telemetry); } } @@ -307,7 +308,7 @@ protected override void NodesTV_DragDrop(object sender, DragEventArgs e) return; } - using (ICertificateStore store = id.OpenStore()) + using (ICertificateStore store = id.OpenStore(Telemetry)) { for (int ii = 0; ii < certificates.Length; ii++) { @@ -326,7 +327,7 @@ protected override void NodesTV_DragDrop(object sender, DragEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -446,7 +447,7 @@ private void CopyMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -479,7 +480,7 @@ private void PasteMI_Click(object sender, EventArgs e) { CertificateStoreIdentifier storeId = info.GetCertificateStore(); - using (ICertificateStore store = storeId.OpenStore()) + using (ICertificateStore store = storeId.OpenStore(Telemetry)) { store.AddAsync(id.Certificate); } @@ -491,7 +492,7 @@ private void PasteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs index e5dbeb68a..c253f928d 100644 --- a/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/CertificateStoreTreeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -43,6 +43,8 @@ namespace Opc.Ua.Client.Controls /// public partial class CertificateStoreTreeDlg : Form { + private ITelemetryContext m_telemetry; + /// /// Contructs the object. /// @@ -55,9 +57,10 @@ public CertificateStoreTreeDlg() /// /// Displays the dialog. /// - public CertificateStoreIdentifier ShowDialog(CertificateStoreIdentifier store) + public CertificateStoreIdentifier ShowDialog(CertificateStoreIdentifier stor, ITelemetryContext telemetry) { - ContainersCTRL.Initialize(); + m_telemetry = telemetry; + ContainersCTRL.Initialize(telemetry); if (ShowDialog() != DialogResult.OK) { @@ -76,7 +79,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -88,7 +91,7 @@ private void ContainersCTRL_NodeSelected(object sender, TreeNodeActionEventArgs } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs index 94ce1b9bc..5015ee37d 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseListCtrl.cs @@ -138,6 +138,15 @@ public event ListItemActionEventHandler ItemsRemoved remove { m_ItemsRemoved -= value; } } + /// + /// Raised whenever items are removed from the control. + /// + public ITelemetryContext Telemetry + { + get { return m_telemetry; } + set { m_telemetry = value; } + } + /// /// Returns the number of items in the control. /// @@ -193,6 +202,7 @@ public Array GetSelectedItems(System.Type type) private string m_instructions; private Point m_dragPosition; private bool m_enableDragging; + private ITelemetryContext m_telemetry; #endregion #region Protected Methods @@ -699,7 +709,7 @@ private void ItemsLV_MouseDown(object sender, System.Windows.Forms.MouseEventArg } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -715,7 +725,7 @@ private void ItemsLV_MouseUp(object sender, MouseEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -727,7 +737,7 @@ private void ItemsLV_DoubleClick(object sender, System.EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -739,7 +749,7 @@ private void ItemsLV_SelectedIndexChanged(object sender, System.EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -764,7 +774,7 @@ private async void ItemsLV_DragEnterAsync(object sender, DragEventArgs e) } catch (Exception ex) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), ex); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), ex); } } @@ -776,7 +786,7 @@ private async void ItemsLV_DragDropAsync(object sender, DragEventArgs e) } catch (Exception ex) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), ex); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), ex); } } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs index 6c9cae75a..d7ead966f 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/BaseTreeCtrl.cs @@ -87,11 +87,21 @@ public bool EnableDragging get { return m_enableDragging; } set { m_enableDragging = value; } } + + /// + /// Whether the control should allow items to be dragged. + /// + public ITelemetryContext Telemetry + { + get { return m_telemetry; } + set { m_telemetry = value; } + } #endregion #region Private Fields private event TreeNodeActionEventHandler m_NodePicked; private event TreeNodeActionEventHandler m_NodeSelected; + private ITelemetryContext m_telemetry; private bool m_enableDragging; #endregion @@ -232,7 +242,7 @@ private void NodesTV_AfterSelect(object sender, TreeViewEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -245,7 +255,7 @@ private async void NodesTV_BeforeExpandAsync(object sender, TreeViewCancelEventA } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } finally { @@ -261,7 +271,7 @@ private void NodesTV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -328,7 +338,7 @@ private void NodesTV_MouseDown(object sender, MouseEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs index 660e97fc8..a8ebde0d0 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ComplexValueEditDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -59,24 +59,27 @@ public ComplexValueEditDlg() #region Private Fields private object m_value; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public object ShowDialog(object value) + public object ShowDialog(object value, ITelemetryContext telemetry) { - return ShowDialog(value, null); + return ShowDialog(value, null, telemetry); } /// /// Displays the dialog. /// - public object ShowDialog(object value, MonitoredItem monitoredItem) + public object ShowDialog(object value, MonitoredItem monitoredItem, ITelemetryContext telemetry) { + m_telemetry = telemetry; m_value = Utils.Clone(value); + ValueCTRL.Telemetry = telemetry; ValueCTRL.MonitoredItem = monitoredItem; ValueCTRL.ShowValueAsync(m_value); @@ -98,7 +101,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs index f62a52ee9..cd8f391a3 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/DataListCtrl.cs @@ -65,7 +65,7 @@ public DataListCtrl() /// /// The columns to display in the control. /// - private readonly object[][] m_ColumnNames = new object[][] + private readonly object[][] m_ColumnNames = new object[][] { new object[] { "Name", HorizontalAlignment.Left, null }, new object[] { "Value", HorizontalAlignment.Left, null, 250 }, @@ -1499,7 +1499,7 @@ private async void ItemsLV_MouseClickAsync(object sender, MouseEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -1525,7 +1525,7 @@ private void UpdatesMI_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1540,7 +1540,7 @@ private void RefreshMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1552,7 +1552,7 @@ private void ClearMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1583,7 +1583,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } else { - value = new SimpleValueEditDlg().ShowDialog(state.Component, state.Component.GetType()); + value = new SimpleValueEditDlg().ShowDialog(state.Component, state.Component.GetType(), Telemetry); } if (value == null) @@ -1641,7 +1641,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1660,7 +1660,7 @@ private void PopupMenu_Opening(object sender, CancelEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs index 6619ebf2b..71cd78bb6 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/GuiUtils.cs @@ -37,6 +37,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -61,14 +62,27 @@ public GuiUtils() /// /// Displays the details of an exception. /// - public static void HandleException(string caption, MethodBase method, Exception e) + public static void HandleException(ITelemetryContext telemetry, string caption, MethodBase method, Exception e) { if (String.IsNullOrEmpty(caption)) { caption = method.Name; } - ExceptionDlg.Show(caption, e); + ExceptionDlg.Show(telemetry, caption, e); + } + + /// + /// Displays the details of an exception. + /// + public static void HandleException(ILogger logger, string caption, MethodBase method, Exception e) + { + if (String.IsNullOrEmpty(caption)) + { + caption = method.Name; + } + + ExceptionDlg.Show(logger, caption, e); } /// @@ -342,7 +356,7 @@ public static void HandleCertificateValidationError(string caption, CertificateV /// public static object GetDefaultValue(NodeId datatypeId, int valueRank) { - Type type = TypeInfo.GetSystemType(datatypeId, EncodeableFactory.GlobalFactory); + Type type = TypeInfo.GetSystemType(datatypeId, EncodeableFactory.Create()); if (type == null) { @@ -403,13 +417,13 @@ public static object GetDefaultValue(NodeId datatypeId, int valueRank) /// /// Displays a dialog that allows a use to edit a value. /// - public static object EditValue(Session session, object value) + public static object EditValue(Session session, object value, ITelemetryContext telemetry) { TypeInfo typeInfo = TypeInfo.Construct(value); if (typeInfo != null) { - return EditValue(session, value, (uint)typeInfo.BuiltInType, typeInfo.ValueRank); + return EditValue(session, value, (uint)typeInfo.BuiltInType, typeInfo.ValueRank, telemetry); } return null; @@ -418,7 +432,7 @@ public static object EditValue(Session session, object value) /// /// Displays a dialog that allows a use to edit a value. /// - public static object EditValue(Session session, object value, NodeId datatypeId, int valueRank) + public static object EditValue(Session session, object value, NodeId datatypeId, int valueRank, ITelemetryContext telemetry) { if (value == null) { @@ -427,7 +441,7 @@ public static object EditValue(Session session, object value, NodeId datatypeId, if (valueRank >= 0) { - return new ComplexValueEditDlg().ShowDialog(value); + return new ComplexValueEditDlg().ShowDialog(value, telemetry); } BuiltInType builtinType = TypeInfo.GetBuiltInType(datatypeId, session.TypeTree); @@ -467,12 +481,12 @@ public static object EditValue(Session session, object value, NodeId datatypeId, case BuiltInType.NodeId: { - return new NodeIdValueEditDlg().ShowDialog(session, (NodeId)value); + return new NodeIdValueEditDlg().ShowDialog(session, (NodeId)value, telemetry); } case BuiltInType.ExpandedNodeId: { - return new NodeIdValueEditDlg().ShowDialog(session, (ExpandedNodeId)value); + return new NodeIdValueEditDlg().ShowDialog(session, (ExpandedNodeId)value, telemetry); } case BuiltInType.DateTime: @@ -521,7 +535,7 @@ public static object EditValue(Session session, object value, NodeId datatypeId, } } - return new ComplexValueEditDlg().ShowDialog(value); + return new ComplexValueEditDlg().ShowDialog(value, telemetry); } /// diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs index d0d618dbd..4f38774c3 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdCtrl.cs @@ -76,6 +76,11 @@ public event EventHandler IdentifierChanged remove { m_IdentifierChanged -= value; } } + /// + /// The telemetry Context + /// + public ITelemetryContext Telemetry { get; set; } + /// /// The browser to used browse for a node id. /// @@ -173,31 +178,25 @@ private async void BrowseBTN_ClickAsync(object sender, EventArgs e) { try { - ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser.Session as Session, RootId, null, "", default, null); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser.Session as Session, RootId, null, "", Telemetry, default, null); if (reference != null && reference.NodeId != null) { NodeIdTB.Text = Utils.Format("{0}", reference.NodeId); m_reference = reference; - if (m_IdentifierChanged != null) - { - m_IdentifierChanged(this, null); - } + m_IdentifierChanged?.Invoke(this, null); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } private void NodeIdTB_TextChanged(object sender, EventArgs e) { - if (m_IdentifierChanged != null) - { - m_IdentifierChanged(this, null); - } + m_IdentifierChanged?.Invoke(this, null); } #endregion } diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs index 0a6269c6a..9dc8511ba 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/NodeIdValueEditDlg.cs @@ -60,10 +60,11 @@ public NodeIdValueEditDlg() /// /// Displays the dialog. /// - public NodeId ShowDialog(Session session, NodeId value) + public NodeId ShowDialog(Session session, NodeId value, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); + ValueCTRL.Telemetry = telemetry; ValueCTRL.Browser = new Browser(session); ValueCTRL.RootId = Objects.RootFolder; ValueCTRL.Identifier = value; @@ -79,10 +80,11 @@ public NodeId ShowDialog(Session session, NodeId value) /// /// Displays the dialog. /// - public ExpandedNodeId ShowDialog(Session session, ExpandedNodeId value) + public ExpandedNodeId ShowDialog(Session session, ExpandedNodeId value, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); + ValueCTRL.Telemetry = telemetry; ValueCTRL.Browser = new Browser(session); ValueCTRL.RootId = Objects.RootFolder; ValueCTRL.Identifier = ExpandedNodeId.ToNodeId(value, session.NamespaceUris); diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs index 1d5e743d7..e1bffdf2e 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/ReferenceTypeCtrl.cs @@ -37,6 +37,7 @@ using System.Reflection; using System.Threading.Tasks; using System.Threading; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -57,6 +58,7 @@ public ReferenceTypeCtrl() #endregion #region Private Fields + private ILogger m_logger = LoggerUtils.Null.Logger; private ISession m_session; private NodeId m_baseTypeId; private event EventHandler m_referenceSelectionChanged; @@ -70,6 +72,7 @@ public async Task InitializeAsync(ISession session, NodeId baseTypeId, Cancellat { m_session = session; m_baseTypeId = baseTypeId; + m_logger = session?.MessageContext?.Telemetry.CreateLogger(); if (NodeId.IsNull(m_baseTypeId)) { @@ -244,7 +247,7 @@ private async Task AddReferenceTypesAsync(ExpandedNodeId referenceTypeId, Refere } catch (Exception e) { - Utils.Trace(e, "Ignoring unknown reference type."); + m_logger.LogDebug(e, "Ignoring unknown reference type."); return; } } @@ -267,7 +270,7 @@ private void ReferenceTypesCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs b/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs index 6a2c226c9..7a742ec0b 100644 --- a/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/Common (OLD)/SimpleValueEditDlg.cs @@ -60,17 +60,19 @@ public SimpleValueEditDlg() #region Private Fields private object m_value; private Type m_type; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public object ShowDialog(object value, Type type) + public object ShowDialog(object value, Type type, ITelemetryContext telemetry) { if (type == null) throw new ArgumentNullException(nameof(type)); m_type = type; + m_telemetry = telemetry; this.Text = Utils.Format("{0} ({1})", this.Text, type.Name); @@ -140,7 +142,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs index b43a86fe6..ec96130b8 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectCertificateStoreCtrl.cs @@ -59,6 +59,11 @@ public SelectCertificateStoreCtrl() #endregion #region Public Interface + /// + /// The Telemetry Context + /// + public ITelemetryContext Telemetry { get; set; } + /// /// Gets or sets the control that is stores with the current certificate store. /// @@ -81,7 +86,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) store.StoreType = CertificateStoreIdentifier.DetermineStoreType(CertificateStoreControl.Text); store.StorePath = CertificateStoreControl.Text; - store = new CertificateStoreDlg().ShowDialog(store); + store = new CertificateStoreDlg().ShowDialog(store, Telemetry); if (store == null) { @@ -90,10 +95,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) CertificateStoreControl.Text = store.StorePath; - if (m_CertificateStoreSelected != null) - { - m_CertificateStoreSelected(this, new EventArgs()); - } + m_CertificateStoreSelected?.Invoke(this, new EventArgs()); } #endregion } diff --git a/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs index b7c51c024..9d614cdcd 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectFileCtrl.cs @@ -128,10 +128,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) FilePathControl.Text = dialog.FileName; - if (m_FileSelected != null) - { - m_FileSelected(this, new EventArgs()); - } + m_FileSelected?.Invoke(this, new EventArgs()); } #endregion } diff --git a/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs index bab7c5a0b..9ec239428 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectProfileCtrl.cs @@ -132,10 +132,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) Profiles = profiles; - if (m_ProfilesChanged != null) - { - m_ProfilesChanged(this, e); - } + m_ProfilesChanged?.Invoke(this, e); } #endregion } diff --git a/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs b/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs index d386547ea..243fda137 100644 --- a/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs +++ b/Samples/ClientControls.Net4/Configuration/SelectUrlsCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -56,6 +56,7 @@ public SelectUrlsCtrl() #region Private Fields private event EventHandler m_UrlsChanged; + private ITelemetryContext m_telemetry; private List m_urls; #endregion @@ -115,6 +116,16 @@ public event EventHandler UrlsChanged add { m_UrlsChanged += value; } remove { m_UrlsChanged -= value; } } + + /// + /// Telemetry context + /// + public ITelemetryContext Telemetry + { + get { return m_telemetry; } + set { m_telemetry = value; } + } + #endregion #region Event Handlers @@ -137,7 +148,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) } } - strings = new EditArrayDlg().ShowDialog(strings, BuiltInType.String, false, null) as string[]; + strings = new EditArrayDlg().ShowDialog(m_telemetry, strings, BuiltInType.String, false, null) as string[]; if (strings == null) { @@ -158,10 +169,7 @@ private void BrowseBTN_Click(object sender, EventArgs e) Urls = urls; - if (m_UrlsChanged != null) - { - m_UrlsChanged(this, e); - } + m_UrlsChanged?.Invoke(this, e); } #endregion } diff --git a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs index a35d21d55..4ef4aad48 100644 --- a/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs +++ b/Samples/ClientControls.Net4/Configuration/ViewCertificateDlg.cs @@ -57,16 +57,19 @@ public ViewCertificateDlg() #region Private Fields private string m_currentDirectory; private CertificateIdentifier m_certificate; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public async Task ShowDialogAsync(CertificateIdentifier certificate, CancellationToken ct = default) + public async Task ShowDialogAsync(CertificateIdentifier certificate, ITelemetryContext telemetry, CancellationToken ct = default) { m_certificate = certificate; + m_telemetry = telemetry; + CertificateStoreCTRL.Telemetry = telemetry; CertificateStoreCTRL.StoreType = null; CertificateStoreCTRL.StorePath = null; CertificateStoreCTRL.ReadOnly = true; @@ -139,7 +142,7 @@ public async Task ShowDialogAsync(CertificateIdentifier certificate, Cance } // fill in application uri. - string applicationUri = X509Utils.GetApplicationUriFromCertificate(data); + string applicationUri = X509Utils.GetApplicationUrisFromCertificate(data)[0]; if (!String.IsNullOrEmpty(applicationUri)) { @@ -188,7 +191,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); } } @@ -196,11 +199,11 @@ private async void DetailsBTN_ClickAsync(object sender, EventArgs e) { try { - await new CertificateDlg().ShowDialogAsync(m_certificate); + await new CertificateDlg().ShowDialogAsync(m_certificate, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); } } @@ -279,7 +282,7 @@ private async void ExportBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs index 66e0ad64a..5b948c217 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerDlg.cs @@ -37,6 +37,7 @@ using System.Security.Cryptography.X509Certificates; using Opc.Ua.Security.Certificates; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -327,6 +328,7 @@ private void BuildEndpointDescription() private Uri m_discoveryUrl; private bool m_showAllOptions; private StatusObject m_statusObject; + private ILogger m_logger = LoggerUtils.Null.Logger; #endregion #region Public Interface @@ -344,13 +346,16 @@ public int DiscoveryTimeout get { return m_discoveryTimeout; } set { Interlocked.Exchange(ref m_discoveryTimeout, value); } } + /// /// Displays the dialog. /// - public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration) + public ConfiguredEndpoint ShowDialog(ApplicationDescription server, ApplicationConfiguration configuration, ITelemetryContext telemetry) { if (server == null) throw new ArgumentNullException(nameof(server)); + m_logger = telemetry.CreateLogger(); + m_configuration = configuration; // construct a list of available endpoint descriptions for the application. @@ -1133,10 +1138,12 @@ private async Task OnDiscoverEndpointsAsync(ApplicationDescription server, Cance EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); endpointConfiguration.OperationTimeout = m_discoveryTimeout; - DiscoveryClient client = DiscoveryClient.Create( + DiscoveryClient client = await DiscoveryClient.CreateAsync( discoveryUrl, EndpointConfiguration.Create(m_configuration), - m_configuration); + m_configuration, + DiagnosticsMasks.None, + ct); try { @@ -1146,7 +1153,7 @@ private async Task OnDiscoverEndpointsAsync(ApplicationDescription server, Cance } catch (Exception e) { - Utils.Trace("Could not fetch endpoints from url: {0}. Reason={1}", discoveryUrl, e.Message); + m_logger.LogDebug("Could not fetch endpoints from url: {0}. Reason={1}", discoveryUrl, e.Message); return (false, e.Message); } finally @@ -1284,7 +1291,7 @@ private void OnUpdateEndpoints(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error updating endpoints."); + m_logger.LogDebug(e, "Unexpected error updating endpoints."); } } @@ -1430,7 +1437,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1478,7 +1485,7 @@ private void ProtocolCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1531,7 +1538,7 @@ private void SecurityModeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1571,7 +1578,7 @@ private void SecurityPolicyCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1651,7 +1658,7 @@ private void EndpointListLB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } finally { @@ -1711,7 +1718,7 @@ private void UpdateAdvancedEndpointInformation() } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1766,7 +1773,7 @@ private void UpdateStatus() if ((m_currentDescription.ServerCertificate != null) && (m_currentDescription.ServerCertificate.Length > 0)) { X509Certificate2 serverCertificate = new X509Certificate2(m_currentDescription.ServerCertificate); - String certificateApplicationUri = X509Utils.GetApplicationUriFromCertificate(serverCertificate); + String certificateApplicationUri = X509Utils.GetApplicationUrisFromCertificate(serverCertificate)[0]; if (certificateApplicationUri != m_currentDescription.Server.ApplicationUri) { @@ -1817,7 +1824,7 @@ private void UpdateStatus() } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_logger, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs index 0c1579cdf..0784f4a97 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListCtrl.cs @@ -77,9 +77,10 @@ public ConfiguredServerListCtrl() /// /// Displays a list of servers in the control. /// - public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration) + public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration, ITelemetryContext telemetry) { Interlocked.Exchange(ref m_configuration, configuration); + Telemetry = telemetry; ItemsLV.Items.Clear(); @@ -182,14 +183,14 @@ private void NewMI_Click(object sender, EventArgs e) { try { - ApplicationDescription server = new DiscoveredServerListDlg().ShowDialog(null, m_configuration); + ApplicationDescription server = new DiscoveredServerListDlg().ShowDialog(null, m_configuration, Telemetry); if (server == null) { return; } - ConfiguredEndpoint endpoint = new ConfiguredServerDlg().ShowDialog(server, m_configuration); + ConfiguredEndpoint endpoint = new ConfiguredServerDlg().ShowDialog(server, m_configuration, Telemetry); if (endpoint == null) { @@ -201,7 +202,7 @@ private void NewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -228,7 +229,7 @@ private async void ConfigureMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -248,7 +249,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs index 7515ea71a..71404503d 100644 --- a/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs +++ b/Samples/ClientControls.Net4/Endpoints/ConfiguredServerListDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -56,6 +56,7 @@ public ConfiguredServerListDlg() #region Private Fields private ConfiguredEndpoint m_endpoint; + private ITelemetryContext m_telemetry; private ApplicationConfiguration m_configuration; #endregion @@ -63,15 +64,16 @@ public ConfiguredServerListDlg() /// /// Displays the dialog. /// - public ConfiguredEndpoint ShowDialog(ApplicationConfiguration configuration, bool createNew) + public ConfiguredEndpoint ShowDialog(ApplicationConfiguration configuration, bool createNew, ITelemetryContext telemetry) { m_configuration = configuration; m_endpoint = null; + m_telemetry = telemetry; // create a default collection if none provided. if (createNew) { - ApplicationDescription server = new DiscoveredServerListDlg().ShowDialog(null, m_configuration); + ApplicationDescription server = new DiscoveredServerListDlg().ShowDialog(null, m_configuration, telemetry); if (server != null) { @@ -81,7 +83,7 @@ public ConfiguredEndpoint ShowDialog(ApplicationConfiguration configuration, boo return null; } - ServersCTRL.Initialize(null, configuration); + ServersCTRL.Initialize(null, configuration, telemetry); OkBTN.Enabled = false; @@ -103,7 +105,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -123,7 +125,7 @@ private void ServersCTRL_ItemsSelected(object sender, ListItemActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs b/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs index c27b82fd9..2a8d76b99 100644 --- a/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs +++ b/Samples/ClientControls.Net4/Endpoints/EndpointSelectorCtrl.cs @@ -62,6 +62,7 @@ public EndpointSelectorCtrl() private ConfiguredEndpointCollection m_endpoints; private event ConnectEndpointEventHandler m_ConnectEndpoint; private event EventHandler m_EndpointsChanged; + private ITelemetryContext m_telemetry; #endregion #region Public Interface @@ -129,10 +130,7 @@ public ConfiguredEndpoint SelectedEndpoint m_endpoints.Add(value); // raise notification. - if (m_EndpointsChanged != null) - { - m_EndpointsChanged(this, null); - } + m_EndpointsChanged?.Invoke(this, null); EndpointCB.SelectedIndex = EndpointCB.Items.Add(value); } @@ -141,12 +139,13 @@ public ConfiguredEndpoint SelectedEndpoint /// /// Initializes the control with a list of endpoints. /// - public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration) + public void Initialize(ConfiguredEndpointCollection endpoints, ApplicationConfiguration configuration, ITelemetryContext telemetry) { if (endpoints == null) throw new ArgumentNullException(nameof(endpoints)); m_endpoints = endpoints; m_configuration = configuration; + m_telemetry = telemetry; EndpointCB.Items.Clear(); EndpointCB.SelectedIndex = -1; @@ -191,14 +190,14 @@ private void ConnectButton_Click(object sender, EventArgs e) if (args.UpdateControl) { // must update the control because the display text may have changed. - Initialize(m_endpoints, m_configuration); + Initialize(m_endpoints, m_configuration, m_telemetry); SelectedEndpoint = endpoint; } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -213,7 +212,7 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) } // modify configuration. - ConfiguredEndpoint endpoint = new ConfiguredServerListDlg().ShowDialog(m_configuration, true); + ConfiguredEndpoint endpoint = new ConfiguredServerListDlg().ShowDialog(m_configuration, true, m_telemetry); if (endpoint == null) { @@ -224,13 +223,10 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) m_endpoints.Add(endpoint); // raise notification. - if (m_EndpointsChanged != null) - { - m_EndpointsChanged(this, null); - } + m_EndpointsChanged?.Invoke(this, null); // update dropdown. - Initialize(m_endpoints, m_configuration); + Initialize(m_endpoints, m_configuration, m_telemetry); // update selection. for (int ii = 0; ii < m_endpoints.Endpoints.Count; ii++) @@ -244,7 +240,7 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/ClientControls.Net4/ExceptionDlg.cs b/Samples/ClientControls.Net4/ExceptionDlg.cs index 281c4ef56..a33ba3944 100644 --- a/Samples/ClientControls.Net4/ExceptionDlg.cs +++ b/Samples/ClientControls.Net4/ExceptionDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,7 @@ using System.Data; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Client.Controls { @@ -44,12 +45,14 @@ public partial class ExceptionDlg : Form /// /// Initializes a new instance of the class. /// - public ExceptionDlg() + public ExceptionDlg(ILogger logger) { InitializeComponent(); + m_logger = logger; } private Exception m_exception; + private readonly ILogger m_logger; /// /// Replaces all special characters in the message. @@ -175,16 +178,25 @@ private void Show(bool showStackTrace) /// /// Displays the exception in a dialog. /// - public static void Show(string caption, Exception e) + public static void Show(ITelemetryContext telemetry, string caption, Exception e) + { + // check if running as a service. + ILogger logger = telemetry.CreateLogger("ExceptionDlg"); + Show(logger, caption, e); + } + + /// + /// Displays the exception in a dialog. + /// + public static void Show(ILogger logger, string caption, Exception e) { // check if running as a service. if (!Environment.UserInteractive) { - Utils.Trace(e, "Unexpected error in '{0}'.", caption); + logger.LogDebug(e, "Unexpected error in '{Caption}'.", caption); return; } - - new ExceptionDlg().ShowDialog(caption, e); + new ExceptionDlg(logger).ShowDialog(caption, e); } /// diff --git a/Samples/ClientControls.Net4/UA Client Controls.csproj b/Samples/ClientControls.Net4/UA Client Controls.csproj index 8f9783790..3773b6ed1 100644 --- a/Samples/ClientControls.Net4/UA Client Controls.csproj +++ b/Samples/ClientControls.Net4/UA Client Controls.csproj @@ -1016,17 +1016,20 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/Controls.Net4/ClientForm.cs b/Samples/Controls.Net4/ClientForm.cs index 4e652cb24..fb1d9b3a6 100644 --- a/Samples/Controls.Net4/ClientForm.cs +++ b/Samples/Controls.Net4/ClientForm.cs @@ -36,6 +36,7 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Client; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; @@ -55,6 +56,8 @@ public partial class ClientForm : Form private ApplicationConfiguration m_configuration; private ServiceMessageContext m_context; private ClientForm m_masterForm; + protected readonly ITelemetryContext m_telemetry; + private readonly ILogger m_logger; private List m_forms; #endregion @@ -68,7 +71,8 @@ public ClientForm( ServiceMessageContext context, ApplicationInstance application, ClientForm masterForm, - ApplicationConfiguration configuration) + ApplicationConfiguration configuration, + ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); @@ -77,6 +81,8 @@ public ClientForm( m_context = context; m_application = application; m_server = application.Server as Opc.Ua.Server.StandardServer; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); if (m_masterForm == null) { @@ -89,7 +95,7 @@ public ClientForm( // get list of cached endpoints. m_endpoints = m_configuration.LoadCachedEndpoints(true); m_endpoints.DiscoveryUrls = configuration.ClientConfiguration.WellKnownDiscoveryUrls; - EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration); + EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration, telemetry); // initialize control state. DisconnectAsync().GetAwaiter().GetResult(); @@ -102,7 +108,7 @@ public void OpenForm() { if (m_masterForm == null) { - ClientForm form = new ClientForm(m_context, m_application, this, m_configuration); + ClientForm form = new ClientForm(m_context, m_application, this, m_configuration, m_telemetry); m_forms.Add(form); form.FormClosing += new FormClosingEventHandler(Window_FormClosing); form.Show(); @@ -156,7 +162,7 @@ protected override async void OnClosing(CancelEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -195,11 +201,11 @@ private async void EndpointSelectorCTRL_ConnectEndpointAsync(object sender, Conn { try { - await ConnectAsync(e.Endpoint); + await ConnectAsync(e.Endpoint, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); e.UpdateControl = false; } } @@ -212,21 +218,21 @@ private void EndpointSelectorCTRL_OnChange(object sender, EventArgs e) } catch { - // GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + // GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } /// /// Connects to a server. /// - public async Task ConnectAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITelemetryContext telemetry, CancellationToken ct = default) { if (endpoint == null) { return; } - Session session = await SessionsCTRL.ConnectAsync(endpoint, ct); + Session session = await SessionsCTRL.ConnectAsync(endpoint, telemetry, ct); if (session != null) { @@ -234,12 +240,12 @@ public async Task ConnectAsync(ConfiguredEndpoint endpoint, CancellationToken ct m_reconnectHandler?.CancelReconnect(); Utils.SilentDispose(m_reconnectHandler); - m_reconnectHandler = new SessionReconnectHandler(true); + m_reconnectHandler = new SessionReconnectHandler(telemetry, true); session.TransferSubscriptionsOnReconnect = true; m_session = session; m_session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); - await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, m_telemetry, ct); StandardClient_KeepAlive(m_session, null); } } @@ -336,7 +342,7 @@ private void StandardClient_Server_ReconnectComplete(object sender, EventArgs e) } } - BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, m_telemetry); SessionsCTRL.Reload(m_session); @@ -344,7 +350,7 @@ private void StandardClient_Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -356,12 +362,12 @@ private async void MainForm_FormClosingAsync(object sender, FormClosingEventArgs if (m_masterForm == null) { - m_application.Stop(); + await m_application.StopAsync(); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -377,11 +383,12 @@ private async void PerformanceTestMI_ClickAsync(object sender, EventArgs e) _ = new PerformanceTestDlg().ShowDialog( m_configuration, m_endpoints, - await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true)); + await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true), + m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -389,7 +396,7 @@ private void DiscoverServersMI_Click(object sender, EventArgs e) { try { - ConfiguredEndpoint endpoint = new ConfiguredServerListDlg().ShowDialog(m_configuration, true); + ConfiguredEndpoint endpoint = new ConfiguredServerListDlg().ShowDialog(m_configuration, true, m_telemetry); if (endpoint != null) { @@ -399,7 +406,7 @@ private void DiscoverServersMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -407,7 +414,7 @@ private void DiscoveryServersOnNetworkMI_Click(object sender, EventArgs e) { try { - ServerOnNetwork serverOnNetwork = new DiscoveredServerOnNetworkListDlg().ShowDialog(null, m_configuration); + ServerOnNetwork serverOnNetwork = new DiscoveredServerOnNetworkListDlg().ShowDialog(null, m_configuration, m_telemetry); if (serverOnNetwork != null) { @@ -424,7 +431,7 @@ private void DiscoveryServersOnNetworkMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -437,7 +444,7 @@ private void NewWindowMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -447,16 +454,16 @@ private void Discovery_RegisterMI_Click(object sender, EventArgs e) { if (m_server != null) { - System.Threading.ThreadPool.QueueUserWorkItem(OnRegister, null); + _ = OnRegisterAsync(); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } - private void OnRegister(object sender) + private async Task OnRegisterAsync() { try { @@ -464,12 +471,12 @@ private void OnRegister(object sender) if (server != null) { - server.RegisterWithDiscoveryServer(); + await server.RegisterWithDiscoveryServerAsync(); } } catch (Exception exception) { - Utils.Trace(exception, "Could not register with the LDS"); + m_logger.LogTrace(exception, "Could not register with the LDS"); } } @@ -481,7 +488,7 @@ private void Task_TestMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Common/ArgumentListCtrl.cs b/Samples/Controls.Net4/Common/ArgumentListCtrl.cs index 4923e5dda..67bccbb51 100644 --- a/Samples/Controls.Net4/Common/ArgumentListCtrl.cs +++ b/Samples/Controls.Net4/Common/ArgumentListCtrl.cs @@ -78,7 +78,7 @@ public void Clear() /// /// Sets the nodes in the control. /// - public async Task UpdateAsync(Session session, NodeId methodId, bool inputArgs, CancellationToken ct = default) + public async Task UpdateAsync(Session session, NodeId methodId, bool inputArgs, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); if (methodId == null) throw new ArgumentNullException(nameof(methodId)); @@ -86,6 +86,7 @@ public async Task UpdateAsync(Session session, NodeId methodId, bool input Clear(); m_session = session; + Telemetry = telemetry; // find the method. MethodNode method = await session.NodeCache.FindAsync(methodId, ct) as MethodNode; @@ -250,7 +251,7 @@ protected override async Task UpdateItemAsync(ListViewItem listItem, object item } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -266,7 +267,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - object value = GuiUtils.EditValue(m_session, arguments[0].Value, arguments[0].DataType, arguments[0].ValueRank); + object value = GuiUtils.EditValue(m_session, arguments[0].Value, arguments[0].DataType, arguments[0].ValueRank, Telemetry); if (value != null) { @@ -277,7 +278,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -298,7 +299,7 @@ private async void ClearValueMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/AttributeListCtrl.cs b/Samples/Controls.Net4/Common/AttributeListCtrl.cs index 5315e9dcb..9e9d596b5 100644 --- a/Samples/Controls.Net4/Common/AttributeListCtrl.cs +++ b/Samples/Controls.Net4/Common/AttributeListCtrl.cs @@ -88,7 +88,7 @@ public void Clear() /// /// Sets the nodes in the control. /// - public async Task InitializeAsync(Session session, ExpandedNodeId nodeId, CancellationToken ct = default) + public async Task InitializeAsync(Session session, ExpandedNodeId nodeId, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); @@ -101,6 +101,7 @@ public async Task InitializeAsync(Session session, ExpandedNodeId nodeId, Cancel m_session = session; m_nodeId = (NodeId)nodeId; + Telemetry = telemetry; INode node = await m_session.NodeCache.FindAsync(m_nodeId, ct); @@ -561,7 +562,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) if (items != null && items.Length == 1) { - object value = GuiUtils.EditValue(m_session, items[0].Value); + object value = GuiUtils.EditValue(m_session, items[0].Value, Telemetry); if (!m_readOnly) { @@ -575,7 +576,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/CallMethodDlg.cs b/Samples/Controls.Net4/Common/CallMethodDlg.cs index 1028bfda4..c1fdfd4cd 100644 --- a/Samples/Controls.Net4/Common/CallMethodDlg.cs +++ b/Samples/Controls.Net4/Common/CallMethodDlg.cs @@ -64,7 +64,7 @@ public CallMethodDlg() /// /// Displays the dialog. /// - public async Task ShowAsync(Session session, NodeId objectId, NodeId methodId, CancellationToken ct = default) + public async Task ShowAsync(Session session, NodeId objectId, NodeId methodId, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); if (methodId == null) throw new ArgumentNullException(nameof(methodId)); @@ -80,8 +80,8 @@ public async Task ShowAsync(Session session, NodeId objectId, NodeId methodId, C m_objectId = objectId; m_methodId = methodId; - await InputArgumentsCTRL.UpdateAsync(session, methodId, true, ct); - await OutputArgumentsCTRL.UpdateAsync(session, methodId, false, ct); + await InputArgumentsCTRL.UpdateAsync(session, methodId, true, telemetry, ct); + await OutputArgumentsCTRL.UpdateAsync(session, methodId, false, telemetry, ct); Node target = await session.NodeCache.FindAsync(objectId, ct) as Node; Node method = await session.NodeCache.FindAsync(methodId, ct) as Node; @@ -144,7 +144,7 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -163,7 +163,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/DataValueListCtrl.cs b/Samples/Controls.Net4/Common/DataValueListCtrl.cs index 8873a4fb3..055c10e60 100644 --- a/Samples/Controls.Net4/Common/DataValueListCtrl.cs +++ b/Samples/Controls.Net4/Common/DataValueListCtrl.cs @@ -104,6 +104,7 @@ public async Task InitializeAsync( Clear(); m_session = session; + Telemetry = session?.MessageContext?.Telemetry; if (valueIds != null) { @@ -234,6 +235,7 @@ protected override void SelectItems() if (m_DataListCtrl != null) { + m_DataListCtrl.Telemetry = Telemetry; ValueItem[] values = GetSelectedItems(typeof(ValueItem)) as ValueItem[]; if (values != null && values.Length > 0) diff --git a/Samples/Controls.Net4/Common/FindNodeDlg.cs b/Samples/Controls.Net4/Common/FindNodeDlg.cs index 74e49577d..7cfe81cd1 100644 --- a/Samples/Controls.Net4/Common/FindNodeDlg.cs +++ b/Samples/Controls.Net4/Common/FindNodeDlg.cs @@ -97,7 +97,7 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/NodeListCtrl.cs b/Samples/Controls.Net4/Common/NodeListCtrl.cs index 55f51f7b4..38bf1fcf4 100644 --- a/Samples/Controls.Net4/Common/NodeListCtrl.cs +++ b/Samples/Controls.Net4/Common/NodeListCtrl.cs @@ -80,7 +80,7 @@ public void Clear() /// /// Sets the nodes in the control. /// - public async Task InitializeAsync(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask, CancellationToken ct = default) + public async Task InitializeAsync(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); @@ -89,6 +89,7 @@ public async Task InitializeAsync(Session session, NodeIdCollection nodeIds, Nod m_session = session; m_nodeIds = nodeIds; m_nodeClassMask = (nodeClassMask == 0) ? (NodeClass)Byte.MaxValue : nodeClassMask; + Telemetry = telemetry; if (nodeIds == null) { @@ -230,12 +231,12 @@ private async void ViewMI_ClickAsync(object sender, EventArgs e) if (nodes == null || nodes.Length == 1) { - await new NodeAttributesDlg().ShowDialogAsync(m_session, nodes[0].NodeId); + await new NodeAttributesDlg().ShowDialogAsync(m_session, nodes[0].NodeId, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -272,7 +273,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -294,7 +295,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs b/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs index b6b2cef38..c002bc2e9 100644 --- a/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs +++ b/Samples/Controls.Net4/Common/PerformanceResultsListCtrl.cs @@ -159,7 +159,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -171,7 +171,7 @@ private void ClearAllMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/PerformanceTestDlg.cs b/Samples/Controls.Net4/Common/PerformanceTestDlg.cs index 64cfda812..f44da1e28 100644 --- a/Samples/Controls.Net4/Common/PerformanceTestDlg.cs +++ b/Samples/Controls.Net4/Common/PerformanceTestDlg.cs @@ -65,6 +65,7 @@ public PerformanceTestDlg() private ServiceMessageContext m_messageContext; private X509Certificate2 m_clientCertificate; private string m_filePath; + private ITelemetryContext m_telemetry; /// /// Displays the dialog. @@ -72,16 +73,18 @@ public PerformanceTestDlg() public EndpointDescription ShowDialog( ApplicationConfiguration configuration, ConfiguredEndpointCollection endpoints, - X509Certificate2 clientCertificate) + X509Certificate2 clientCertificate, + ITelemetryContext telemetry) { m_configuration = configuration; m_endpoints = endpoints; m_messageContext = configuration.CreateMessageContext(); m_clientCertificate = clientCertificate; + m_telemetry = telemetry; m_running = false; m_filePath = @".\perftest.csv"; - EndpointSelectorCTRL.Initialize(m_endpoints, configuration); + EndpointSelectorCTRL.Initialize(m_endpoints, configuration, m_telemetry); lock (m_lock) { @@ -187,7 +190,7 @@ public void TestComplete(object state) } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), e); } } @@ -208,7 +211,7 @@ private void TestProgress(object state) } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), e); } } @@ -226,24 +229,24 @@ private void TestException(object state) try { OkBTN.Enabled = m_running = false; - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), (Exception)state); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), (Exception)state); } catch (Exception e) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), e); } } /// /// Runs all tests in a background thread. /// - private async Task DoAllTestsAsync(CancellationToken ct = default) + private async Task DoAllTestsAsync(ITelemetryContext telemetry, CancellationToken ct = default) { for (int ii = 0; ii < m_endpoints.Count; ii++) { try { - await DoTestAsync(m_endpoints[ii], ct); + await DoTestAsync(m_endpoints[ii], telemetry, ct); } catch { @@ -257,7 +260,7 @@ private async Task DoAllTestsAsync(CancellationToken ct = default) /// /// Runs the test in a background thread. /// - private async Task DoTestAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) + private async Task DoTestAsync(ConfiguredEndpoint endpoint, ITelemetryContext telemetry, CancellationToken ct = default) { PerformanceTestResult result = new PerformanceTestResult(endpoint, 100); @@ -273,19 +276,20 @@ private async Task DoTestAsync(ConfiguredEndpoint endpoint, CancellationToken ct // update the endpoint. if (endpoint.UpdateBeforeConnect) { - await endpoint.UpdateFromServerAsync(ct); + await endpoint.UpdateFromServerAsync(telemetry, ct); } SessionClient client = null; Uri url = new Uri(endpoint.Description.EndpointUrl); - ITransportChannel channel = SessionChannel.Create( + ITransportChannel channel = await UaChannelBase.CreateUaBinaryChannelAsync( m_configuration, endpoint.Description, endpoint.Configuration, m_clientCertificate, - m_messageContext); + m_messageContext, + ct); client = new SessionClient(channel); @@ -389,11 +393,11 @@ private void EndpointSelectorCTRL_ConnectEndpoint(object sender, ConnectEndpoint // start processing. OkBTN.Enabled = m_running = true; - Task.Run(() => DoTestAsync(endpoint)); + Task.Run(() => DoTestAsync(endpoint, m_telemetry)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); e.UpdateControl = false; } } @@ -409,7 +413,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -440,7 +444,7 @@ private void SaveBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -472,7 +476,7 @@ private void LoadBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -487,11 +491,11 @@ private void TestAllBTN_Click(object sender, EventArgs e) ResultsCTRL.Clear(); OkBTN.Enabled = m_running = true; - Task.Run(() => DoAllTestsAsync()); + Task.Run(() => DoAllTestsAsync(m_telemetry)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/PropertyListCtrl.cs b/Samples/Controls.Net4/Common/PropertyListCtrl.cs index dde321b9a..2cd6f8f89 100644 --- a/Samples/Controls.Net4/Common/PropertyListCtrl.cs +++ b/Samples/Controls.Net4/Common/PropertyListCtrl.cs @@ -91,6 +91,7 @@ public void Clear() public async Task UpdateAsync(Session session, ReferenceDescription reference, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); + Telemetry = session?.MessageContext?.Telemetry; Clear(); @@ -255,7 +256,7 @@ private void SelectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Common/SelectNodesDlg.cs b/Samples/Controls.Net4/Common/SelectNodesDlg.cs index ed4369e2a..99012ffb4 100644 --- a/Samples/Controls.Net4/Common/SelectNodesDlg.cs +++ b/Samples/Controls.Net4/Common/SelectNodesDlg.cs @@ -66,14 +66,15 @@ public async Task ShowDialogAsync( BrowseViewType browseView, NodeIdCollection nodesIds, NodeClass nodeClassMask, + ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; - await BrowseCTRL.SetViewAsync(session, browseView, null, ct); - await NodeListCTRL.InitializeAsync(session, nodesIds, nodeClassMask, ct); + await BrowseCTRL.SetViewAsync(session, browseView, null, telemetry, ct); + await NodeListCTRL.InitializeAsync(session, nodesIds, nodeClassMask, telemetry, ct); if (ShowDialog() != DialogResult.OK) { @@ -99,7 +100,7 @@ private async void BrowseCTRL_NodesSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/ServerForm.cs b/Samples/Controls.Net4/ServerForm.cs index 1e32aac94..6a79cc071 100644 --- a/Samples/Controls.Net4/ServerForm.cs +++ b/Samples/Controls.Net4/ServerForm.cs @@ -50,6 +50,7 @@ public ServerForm(StandardServer server, ApplicationConfiguration configuration) this.Icon = this.TrayIcon.Icon = ClientUtils.GetAppIcon(); GuiUtils.DisplayUaTcpImplementation(this, configuration); + m_telemetry = configuration.CreateMessageContext().Telemetry; m_server = server; @@ -62,6 +63,7 @@ public ServerForm(StandardServer server, ApplicationConfiguration configuration) #region Private Fields private bool m_exit; + private readonly ITelemetryContext m_telemetry; private StandardServer m_server; #endregion @@ -111,7 +113,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - Opc.Ua.Client.Controls.GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + Opc.Ua.Client.Controls.GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs b/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs index 38c963360..6b8bdb904 100644 --- a/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs +++ b/Samples/Controls.Net4/Sessions/AddressSpaceDlg.cs @@ -61,7 +61,7 @@ public AddressSpaceDlg() /// /// Displays the address space with the specified view /// - public void Show(Session session, BrowseViewType viewType, NodeId viewId) + public void Show(Session session, BrowseViewType viewType, NodeId viewId, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); @@ -73,7 +73,7 @@ public void Show(Session session, BrowseViewType viewType, NodeId viewId) m_session = session; m_session.SessionClosing += m_SessionClosing; - BrowseCTRL.SetViewAsync(session, viewType, viewId); + BrowseCTRL.SetViewAsync(session, viewType, viewId, telemetry); Show(); BringToFront(); } diff --git a/Samples/Controls.Net4/Sessions/BrowseDlg.cs b/Samples/Controls.Net4/Sessions/BrowseDlg.cs index 8ef105354..617a49ab1 100644 --- a/Samples/Controls.Net4/Sessions/BrowseDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseDlg.cs @@ -153,7 +153,7 @@ private async void BackBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -165,7 +165,7 @@ private async void ForwardBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -177,7 +177,7 @@ private async void NodeCTRL_SelectedIndexChangedAsync(object sender, EventArgs e } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -196,7 +196,7 @@ private void BrowseCTRL_PositionChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -208,7 +208,7 @@ private async void BrowseCTRL_PositionAddedAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs b/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs index d8a600b6b..44597917c 100644 --- a/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs +++ b/Samples/Controls.Net4/Sessions/BrowseListCtrl.cs @@ -158,6 +158,7 @@ public async Task InitializeAsync(Browser browser, NodeId startId, CancellationT m_browser = browser; m_session = browser.Session as Session; + Telemetry = m_session?.MessageContext?.Telemetry; m_startId = startId; m_position = -1; @@ -215,10 +216,7 @@ public async Task SetPositionAsync(int position, CancellationToken ct = default) await BrowseAsync(m_stack[m_position].Target.NodeId, ct); } - if (m_PositionChanged != null) - { - m_PositionChanged(this, null); - } + m_PositionChanged?.Invoke(this, null); } /// @@ -404,16 +402,13 @@ protected override async void PickItems() m_position++; m_stack.Add(itemData); - if (m_PositionAdded != null) - { - m_PositionAdded(this, null); - } + m_PositionAdded?.Invoke(this, null); await BrowseAsync(itemData.Target.NodeId); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs index e8ce9b04c..43f304ceb 100644 --- a/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseOptionsDlg.cs @@ -62,17 +62,21 @@ public BrowseOptionsDlg() #region Private Fields private Browser m_browser; + private ISession m_session; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Prompts the user to specify the browse options. /// - public async Task ShowDialogAsync(Browser browser, CancellationToken ct = default) + public async Task ShowDialogAsync(Browser browser, ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { if (browser == null) throw new ArgumentNullException(nameof(browser)); m_browser = browser; + m_session = session; + m_telemetry = telemetry; await ReferenceTypeCTRL.InitializeAsync(m_browser.Session as Session, null, ct); ViewIdTB.Text = null; @@ -152,7 +156,7 @@ private async void BrowseBTN_ClickAsync(object sender, EventArgs e) browser.ReferenceTypeId = ReferenceTypeIds.Organizes; browser.IncludeSubtypes = true; - ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(browser, Objects.ViewsFolder); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(browser, Objects.ViewsFolder, m_session, m_telemetry); if (reference != null) { @@ -167,7 +171,7 @@ private async void BrowseBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -215,11 +219,11 @@ private void OkBTN_Click(object sender, EventArgs e) m_browser.IncludeSubtypes = IncludeSubtypesCK.Checked; m_browser.NodeClassMask = 0; - int nodeClassMask = 0; + uint nodeClassMask = 0; foreach (NodeClass nodeClass in NodeClassList.CheckedItems) { - nodeClassMask |= (int)nodeClass; + nodeClassMask |= (uint)nodeClass; } m_browser.NodeClassMask = nodeClassMask; @@ -228,7 +232,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs index a67db1246..a764486ca 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTreeCtrl.cs @@ -40,6 +40,7 @@ using Opc.Ua.Client.Controls; using System.Threading.Tasks; using System.Threading; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Sample.Controls { @@ -56,6 +57,8 @@ public BrowseTreeCtrl() #region Private Fields private Browser m_browser; + private ISession m_session; + private ILogger m_logger; private NodeId m_rootId; private AttributeListCtrl m_AttributesCtrl; private bool m_allowPick; @@ -163,7 +166,7 @@ public void Clear() /// /// Sets the root node for the control. /// - public async Task SetRootAsync(Browser browser, NodeId rootId, CancellationToken ct = default) + public async Task SetRootAsync(Browser browser, NodeId rootId, ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { Clear(); @@ -171,6 +174,9 @@ public async Task SetRootAsync(Browser browser, NodeId rootId, CancellationToken m_rootId = rootId; m_browser = browser; + m_session = session; + Telemetry = telemetry; + m_logger = telemetry.CreateLogger(); if (m_browser != null) { @@ -190,7 +196,7 @@ public async Task SetRootAsync(Browser browser, NodeId rootId, CancellationToken if (m_browser != null) { - INode node = await m_browser.Session.NodeCache.FindAsync(m_rootId, ct); + INode node = await m_session.NodeCache.FindAsync(m_rootId, ct); if (node == null) { @@ -219,15 +225,15 @@ public async Task SetRootAsync(Browser browser, NodeId rootId, CancellationToken /// /// Sets the root node for the control. /// - public Task SetRootAsync(Session session, NodeId rootId, CancellationToken ct = default) + public Task SetRootAsync(Session session, NodeId rootId, ITelemetryContext telemetry, CancellationToken ct = default) { - return SetRootAsync(new Browser(session), rootId, ct); + return SetRootAsync(new Browser(session), rootId, session, telemetry, ct); } /// /// Sets the view for the control. /// - public Task SetViewAsync(Session session, BrowseViewType viewType, NodeId viewId, CancellationToken ct = default) + public Task SetViewAsync(Session session, BrowseViewType viewType, NodeId viewId, ITelemetryContext telemetry, CancellationToken ct = default) { Clear(); @@ -308,7 +314,7 @@ public Task SetViewAsync(Session session, BrowseViewType viewType, NodeId viewId } } - return SetRootAsync(browser, rootId, ct); + return SetRootAsync(browser, rootId, session, telemetry, ct); } /// @@ -331,7 +337,7 @@ protected override Task BeforeExpandAsync(TreeNode clickedNode, Cancellati clickedNode.Nodes.Clear(); // do nothing if an error is detected. - if (m_browser.Session.KeepAliveStopped) + if (m_session.KeepAliveStopped) { return Task.FromResult(false); } @@ -357,7 +363,7 @@ protected override async void EnableMenuItems(TreeNode clickedNode) if (clickedNode != null) { // do nothing if an error is detected. - if (m_browser.Session.KeepAliveStopped) + if (m_session.KeepAliveStopped) { return; } @@ -374,7 +380,7 @@ protected override async void EnableMenuItems(TreeNode clickedNode) BrowseMI.Enabled = (reference.NodeId != null && !reference.NodeId.IsAbsolute); ViewAttributesMI.Enabled = true; - NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris); + NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_session.NamespaceUris); INode node = await m_browser.Session.ReadNodeAsync(nodeId); @@ -481,7 +487,7 @@ protected override async void EnableMenuItems(TreeNode clickedNode) SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1); } - foreach (Subscription subscription in m_browser.Session.Subscriptions) + foreach (Subscription subscription in m_session.Subscriptions) { if (subscription.Created) { @@ -496,7 +502,7 @@ protected override async void EnableMenuItems(TreeNode clickedNode) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -522,7 +528,7 @@ protected override async void SelectNode() { if (reference != null) { - await m_AttributesCtrl.InitializeAsync(m_browser.Session as Session, reference.NodeId); + await m_AttributesCtrl.InitializeAsync(m_browser.Session as Session, reference.NodeId, Telemetry); } else { @@ -557,7 +563,7 @@ protected override async void SelectNode() } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -656,39 +662,39 @@ private async Task AddReferencesAsync(TreeNode parent, ReferenceDescriptionColle { if (reference.ReferenceTypeId.IsNullNodeId) { - Utils.Trace("Reference {0} has null reference type id", reference.DisplayName); + m_logger.LogDebug("Reference {0} has null reference type id", reference.DisplayName); continue; } - ReferenceTypeNode typeNode = await m_browser.Session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; + ReferenceTypeNode typeNode = await m_session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; if (typeNode == null) { - Utils.Trace("Reference {0} has invalid reference type id.", reference.DisplayName); + m_logger.LogDebug("Reference {0} has invalid reference type id.", reference.DisplayName); continue; } if (m_browser.BrowseDirection == BrowseDirection.Forward && !reference.IsForward || m_browser.BrowseDirection == BrowseDirection.Inverse && reference.IsForward) { - Utils.Trace("Reference's IsForward value is: {0}, but the browse direction is: {1}; for reference {2}", reference.IsForward, m_browser.BrowseDirection, reference.DisplayName); + m_logger.LogDebug("Reference's IsForward value is: {0}, but the browse direction is: {1}; for reference {2}", reference.IsForward, m_browser.BrowseDirection, reference.DisplayName); continue; } if (reference.NodeId == null || reference.NodeId.IsNull) { - Utils.Trace("The node id of the reference {0} is NULL.", reference.DisplayName); + m_logger.LogDebug("The node id of the reference {0} is NULL.", reference.DisplayName); continue; } if (reference.BrowseName == null || reference.BrowseName.Name == null) { - Utils.Trace("Browse name is empty for reference {0}", reference.DisplayName); + m_logger.LogDebug("Browse name is empty for reference {0}", reference.DisplayName); continue; } if (!Enum.IsDefined(typeof(Opc.Ua.NodeClass), reference.NodeClass) || reference.NodeClass == NodeClass.Unspecified) { - Utils.Trace("Node class is an unknown or unspecified value, for reference {0}", reference.DisplayName); + m_logger.LogDebug("Node class is an unknown or unspecified value, for reference {0}", reference.DisplayName); continue; } @@ -696,7 +702,7 @@ private async Task AddReferencesAsync(TreeNode parent, ReferenceDescriptionColle { if (reference.TypeDefinition == null || reference.TypeDefinition.IsNull) { - Utils.Trace("Type definition is null for reference {0}", reference.DisplayName); + m_logger.LogDebug("Type definition is null for reference {0}", reference.DisplayName); continue; } } @@ -756,11 +762,11 @@ private async Task FindReferenceTypeContainerAsync(TreeNode parent, Re if (reference.ReferenceTypeId.IsNullNodeId) { - Utils.Trace("NULL reference type id, for reference: {0}", reference.DisplayName); + m_logger.LogDebug("NULL reference type id, for reference: {0}", reference.DisplayName); return null; } - ReferenceTypeNode typeNode = await m_browser.Session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; + ReferenceTypeNode typeNode = await m_session.NodeCache.FindAsync(reference.ReferenceTypeId, ct) as ReferenceTypeNode; foreach (TreeNode child in parent.Nodes) { @@ -803,7 +809,7 @@ private async Task FindReferenceTypeContainerAsync(TreeNode parent, Re return AddNode(parent, typeNode.NodeId, text, icon); } - Utils.Trace("Reference type id not found for: {0}", reference.ReferenceTypeId); + m_logger.LogDebug("Reference type id not found for: {0}", reference.ReferenceTypeId); return null; } @@ -834,7 +840,7 @@ private async void BrowseOptionsMI_ClickAsync(object sender, EventArgs e) { try { - if (await new BrowseOptionsDlg().ShowDialogAsync(m_browser)) + if (await new BrowseOptionsDlg().ShowDialogAsync(m_browser, m_session, Telemetry)) { if (NodesTV.SelectedNode != null) { @@ -845,7 +851,7 @@ private async void BrowseOptionsMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -861,7 +867,7 @@ private async void BrowseRefreshMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -879,7 +885,7 @@ private async void Browser_MoreReferencesAsync(Browser sender, BrowserEventArgs } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -899,7 +905,7 @@ private void SelectItemMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -932,7 +938,7 @@ private void SelectChildrenMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -941,11 +947,11 @@ private async void ShowReferencesMI_CheckedChangedAsync(object sender, EventArgs m_showReferences = ShowReferencesMI.Checked; try { - await SetRootAsync(m_browser, m_rootId); + await SetRootAsync(m_browser, m_rootId, m_session, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -965,11 +971,11 @@ private async void ViewAttributesMI_ClickAsync(object sender, EventArgs e) return; } - await new NodeAttributesDlg().ShowDialogAsync(m_browser.Session as Session, reference.NodeId); + await new NodeAttributesDlg().ShowDialogAsync(m_browser.Session as Session, reference.NodeId, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1018,11 +1024,11 @@ private async void CallMI_ClickAsync(object sender, EventArgs e) } } - await new CallMethodDlg().ShowAsync(m_browser.Session as Session, objectId, methodId); + await new CallMethodDlg().ShowAsync(m_browser.Session as Session, objectId, methodId, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1057,11 +1063,11 @@ private async void ReadMI_ClickAsync(object sender, EventArgs e) valueIds.Add(valueId); // show form. - await new ReadDlg().ShowAsync(session, valueIds); + await new ReadDlg().ShowAsync(session, valueIds, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1096,11 +1102,11 @@ private async void WriteMI_ClickAsync(object sender, EventArgs e) values.Add(value); // show form. - await new WriteDlg().ShowAsync(session, values); + await new WriteDlg().ShowAsync(session, values, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1132,7 +1138,7 @@ private async void SubscribeNewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1161,7 +1167,7 @@ private async void Subscription_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1185,7 +1191,7 @@ private async void HistoryReadMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1209,7 +1215,7 @@ private async void BrowseMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs index 1fe09bc3d..e8a6cc218 100644 --- a/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs +++ b/Samples/Controls.Net4/Sessions/BrowseTypesDlg.cs @@ -100,7 +100,7 @@ private async void TypeNavigatorCTRL_TypeSelectedAsync(object sender, TypeNaviga } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs index d59982f39..d9eb9c631 100644 --- a/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs +++ b/Samples/Controls.Net4/Sessions/CreateSecureChannelDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -63,6 +63,7 @@ public CreateSecureChannelDlg() private ApplicationConfiguration m_configuration; private EndpointDescriptionCollection m_endpoints; private ServiceMessageContext m_messageContext; + private ITelemetryContext m_telemetry; /// /// Displays the dialog. @@ -77,6 +78,7 @@ public ITransportChannel ShowDialog( m_endpoints = endpoints; m_configuration = configuration; m_messageContext = configuration.CreateMessageContext(); + m_telemetry = m_messageContext.Telemetry; EndpointCB.Items.Clear(); @@ -118,14 +120,14 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) configuration.MaxStringLength = (int)MaxStringLengthNC.Value; configuration.MaxByteStringLength = (int)MaxByteStringLengthNC.Value; - ITransportChannel channel = SessionChannel.Create( + ITransportChannel channel = await UaChannelBase.CreateUaBinaryChannelAsync( m_configuration, m_endpoints[EndpointCB.SelectedIndex], configuration, await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(true), m_messageContext); - // create the channel. + // create the channel. // open the channel. Cursor = Cursors.WaitCursor; @@ -137,7 +139,7 @@ await m_configuration.SecurityConfiguration.ApplicationCertificate.FindAsync(tru } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } finally { @@ -184,7 +186,7 @@ private void EndpointCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -203,7 +205,7 @@ private void DetailsBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs b/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs index 7a750e99e..525cef513 100644 --- a/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs +++ b/Samples/Controls.Net4/Sessions/EndpointViewDlg.cs @@ -68,7 +68,7 @@ public bool ShowDialog(EndpointDescription endpoint) try { - X509Certificate2 certificate = CertificateFactory.Create(endpoint.ServerCertificate, true); + X509Certificate2 certificate = CertificateFactory.Create(endpoint.ServerCertificate); ServerCertificateTB.Text = String.Format("{0}", certificate.Subject); } catch diff --git a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs index c4d13212f..ec820b4e0 100644 --- a/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs +++ b/Samples/Controls.Net4/Sessions/NodeAttributesDlg.cs @@ -57,21 +57,23 @@ public NodeAttributesDlg() #region Private Fields private Session m_session; private ExpandedNodeId m_nodeId; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public async Task ShowDialogAsync(Session session, ExpandedNodeId nodeId, CancellationToken ct = default) + public async Task ShowDialogAsync(Session session, ExpandedNodeId nodeId, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); if (nodeId == null) throw new ArgumentNullException(nameof(nodeId)); m_session = session; m_nodeId = nodeId; + m_telemetry = telemetry; - await AttributesCTRL.InitializeAsync(session, nodeId, ct); + await AttributesCTRL.InitializeAsync(session, nodeId, telemetry, ct); if (ShowDialog() != DialogResult.OK) { @@ -84,11 +86,11 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) { try { - await AttributesCTRL.InitializeAsync(m_session, m_nodeId); + await AttributesCTRL.InitializeAsync(m_session, m_nodeId, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs index 64a1169af..367537d5d 100644 --- a/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs +++ b/Samples/Controls.Net4/Sessions/ReadHistoryDlg.cs @@ -444,7 +444,7 @@ private void GoBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -456,7 +456,7 @@ private void NextBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -468,7 +468,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs b/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs index 8d4bd6651..b04f68f3c 100644 --- a/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs +++ b/Samples/Controls.Net4/Sessions/SecuritySettingsDlg.cs @@ -67,8 +67,9 @@ public SecuritySettingsDlg() /// /// Displays the dialog. /// - public bool ShowDialog(ref MessageSecurityMode securityMode, ref string securityPolicyUri, ref bool useNativeStack) + public bool ShowDialog(ITelemetryContext telemetry, ref MessageSecurityMode securityMode, ref string securityPolicyUri, ref bool useNativeStack) { + m_telemetry = telemetry; // set security mode. SecurityModeCB.SelectedItem = securityMode; @@ -105,8 +106,10 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } + + private ITelemetryContext m_telemetry; } } diff --git a/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs b/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs index 356490049..fc64972a6 100644 --- a/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs +++ b/Samples/Controls.Net4/Sessions/SelectNodeDlg.cs @@ -66,20 +66,22 @@ public SelectNodeDlg() #region Private Fields private ReferenceDescription m_reference; + private ITelemetryContext m_telemetry; #endregion #region Public Interface /// /// Displays the dialog. /// - public async Task ShowDialogAsync(Browser browser, NodeId rootId, CancellationToken ct = default) + public async Task ShowDialogAsync(Browser browser, NodeId rootId, ISession session, ITelemetryContext telemetry, CancellationToken ct = default) { if (browser == null) throw new ArgumentNullException(nameof(browser)); - await BrowseCTRL.SetRootAsync(browser, rootId, ct); + m_telemetry = telemetry; + await BrowseCTRL.SetRootAsync(browser, rootId, session, telemetry, ct); NamespaceUriCB.Items.Clear(); - NamespaceUriCB.Items.AddRange(browser.Session.NamespaceUris.ToArray()); + NamespaceUriCB.Items.AddRange(session.NamespaceUris.ToArray()); OkBTN.Enabled = false; @@ -100,7 +102,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -195,7 +197,7 @@ private void BrowseCTRL_NodeSelected(object sender, TreeNodeActionEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs b/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs index d4d88b23d..c92d17acd 100644 --- a/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs +++ b/Samples/Controls.Net4/Sessions/SessionOpenDlg.cs @@ -53,7 +53,7 @@ public SessionOpenDlg() #region Private Fields private Session m_session; private const string m_BrowseCertificates = ""; - private static long m_Counter = 0; + private static uint m_Counter = 0; private IList m_preferredLocales; private bool m_checkDomain = true; #endregion @@ -133,7 +133,7 @@ private void UserIdentityTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -155,7 +155,7 @@ private void OkBTN_Click(object sender, EventArgs e) if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(PasswordTB.Text)) { - identity = new UserIdentity(username, PasswordTB.Text); + identity = new UserIdentity(username, Encoding.UTF8.GetBytes(PasswordTB.Text)); } } @@ -168,7 +168,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -223,7 +223,7 @@ private void OpenComplete(object e) if (e != null) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), (Exception)e); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), (Exception)e); } if (m_session.Connected && m_session.SessionTimeout < 1000) diff --git a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs index 4aa6a48db..e69804fb0 100644 --- a/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs +++ b/Samples/Controls.Net4/Sessions/SessionTreeCtrl.cs @@ -170,10 +170,12 @@ public ToolStripStatusLabel ServerStatusCtrl /// /// Creates a session with the endpoint. /// - public async Task ConnectAsync(ConfiguredEndpoint endpoint, CancellationToken ct = default) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITelemetryContext telemetry, CancellationToken ct = default) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); + Telemetry = telemetry; + EndpointDescriptionCollection availableEndpoints = null; // check if the endpoint needs to be updated. @@ -215,7 +217,7 @@ public async Task ConnectAsync(ConfiguredEndpoint endpoint, Cancellatio // load certificate chain clientCertificateChain = new X509Certificate2Collection(clientCertificate); List issuers = new List(); - await m_configuration.CertificateValidator.GetIssuersAsync(clientCertificate, issuers); + await m_configuration.CertificateValidator.GetIssuersAsync(clientCertificate, issuers, ct); for (int i = 0; i < issuers.Count; i++) { clientCertificateChain.Add(issuers[i].Certificate); @@ -223,25 +225,28 @@ public async Task ConnectAsync(ConfiguredEndpoint endpoint, Cancellatio } // create the channel. - ITransportChannel channel = SessionChannel.Create( + ITransportChannel channel = await UaChannelBase.CreateUaBinaryChannelAsync( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, m_configuration.SecurityConfiguration.SendCertificateChain ? clientCertificateChain : null, - m_messageContext); + m_messageContext, + ct); // create the session. - return await ConnectAsync(endpoint, channel, availableEndpoints, ct); + return await ConnectAsync(endpoint, channel, availableEndpoints, telemetry, ct); } /// /// Opens a new session. /// - public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITransportChannel channel, EndpointDescriptionCollection availableEndpoints, CancellationToken ct = default) + public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITransportChannel channel, EndpointDescriptionCollection availableEndpoints, ITelemetryContext telemetry, CancellationToken ct = default) { if (channel == null) throw new ArgumentNullException(nameof(channel)); + Telemetry = telemetry; + try { // create the session. @@ -270,7 +275,7 @@ public async Task ConnectAsync(ConfiguredEndpoint endpoint, ITransportC // ensure the channel is closed on error. if (channel != null) { - channel.Close(); + await channel.CloseAsync(ct); } } } @@ -361,7 +366,7 @@ public async Task CreateSubscriptionAsync(Session session, Cancell dialog.FormClosing += new FormClosingEventHandler(Subscription_FormClosing); // create subscription. - Subscription subscription = await dialog.NewAsync(session, ct); + Subscription subscription = await dialog.NewAsync(session, Telemetry, ct); if (subscription != null) { @@ -481,7 +486,7 @@ protected override void SelectNode() // update address space control. if (m_AddressSpaceCtrl != null) { - m_AddressSpaceCtrl.SetViewAsync(session, BrowseViewType.Objects, null); + m_AddressSpaceCtrl.SetViewAsync(session, BrowseViewType.Objects, null, Telemetry); } // update notification messages control. @@ -692,12 +697,12 @@ private void BrowseAllMI_Click(object sender, EventArgs e) if (session != null) { - new AddressSpaceDlg().Show(session, BrowseViewType.All, null); + new AddressSpaceDlg().Show(session, BrowseViewType.All, null, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -718,12 +723,12 @@ private void BrowseObjectsMI_Click(object sender, EventArgs e) if (session != null) { - new AddressSpaceDlg().Show(session, BrowseViewType.Objects, null); + new AddressSpaceDlg().Show(session, BrowseViewType.Objects, null, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -749,7 +754,7 @@ private async void BrowseObjectTypesMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -775,7 +780,7 @@ private async void BrowseVariableTypesMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -796,12 +801,12 @@ private void BrowseDataTypesMI_Click(object sender, EventArgs e) if (session != null) { - new AddressSpaceDlg().Show(session, BrowseViewType.DataTypes, null); + new AddressSpaceDlg().Show(session, BrowseViewType.DataTypes, null, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -822,12 +827,12 @@ private void BrowseReferenceTypesMI_Click(object sender, EventArgs e) if (session != null) { - new AddressSpaceDlg().Show(session, BrowseViewType.ReferenceTypes, null); + new AddressSpaceDlg().Show(session, BrowseViewType.ReferenceTypes, null, Telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -853,7 +858,7 @@ private async void BrowseEventTypesMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -896,7 +901,7 @@ private async void BrowseServerViewsMI_DropDownOpeningAsync(object sender, Event } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -926,13 +931,14 @@ void BrowseServerViewsMI_Click(object sender, EventArgs e) new AddressSpaceDlg().Show( session, BrowseViewType.ServerDefinedView, - (NodeId)reference.NodeId); + (NodeId)reference.NodeId, + Telemetry); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -961,7 +967,7 @@ private async void SubscriptionCreateMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -981,11 +987,11 @@ private async void NewSessionMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectAsync(m_endpoint); + await ConnectAsync(m_endpoint, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1027,7 +1033,7 @@ private async void DeleteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1080,11 +1086,11 @@ private async void ReadMI_ClickAsync(object sender, EventArgs e) } // show form. - await new ReadDlg().ShowAsync(session, valueIds); + await new ReadDlg().ShowAsync(session, valueIds, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1149,11 +1155,11 @@ private async void WriteMI_ClickAsync(object sender, EventArgs e) } // show form. - await new WriteDlg().ShowAsync(session, values); + await new WriteDlg().ShowAsync(session, values, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1179,7 +1185,7 @@ private async void SubscriptionEnabledPublishingMI_ClickAsync(object sender, Eve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1210,7 +1216,7 @@ private void SubscriptionMonitorMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1265,7 +1271,7 @@ private void SessionSaveMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1329,7 +1335,7 @@ private async void SessionLoadMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -1346,7 +1352,7 @@ private void NewWindowMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs b/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs index c1badc6bc..ae5adc9f8 100644 --- a/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs +++ b/Samples/Controls.Net4/Sessions/TypeHierarchyListCtrl.cs @@ -95,6 +95,7 @@ public async Task InitializeAsync(Session session, NodeId typeId, CancellationTo } m_session = session; + Telemetry = m_session?.MessageContext?.Telemetry; SortedDictionary instances = new SortedDictionary(); diff --git a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs index 9058f0e4f..43f30c4e1 100644 --- a/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs +++ b/Samples/Controls.Net4/Sessions/TypeNavigatorCtrl.cs @@ -131,7 +131,7 @@ private void RootBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -180,14 +180,11 @@ private async void RootBTN_DropDownOpeningAsync(object sender, EventArgs e) button.ShowDropDownArrow = (button.DropDownItems.Count == 0); - if (m_TypeSelected != null) - { - m_TypeSelected(this, new TypeNavigatorEventArgs(node)); - } + m_TypeSelected?.Invoke(this, new TypeNavigatorEventArgs(node)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -244,14 +241,11 @@ private void ChildBTN_Click(object sender, EventArgs e) TypePathCTRL.Items.Add(button); - if (m_TypeSelected != null) - { - m_TypeSelected(this, new TypeNavigatorEventArgs(node)); - } + m_TypeSelected?.Invoke(this, new TypeNavigatorEventArgs(node)); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs index 9eeb0f63f..528bffb72 100644 --- a/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/ContentFilterElementListCtrl.cs @@ -32,14 +32,14 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.Reflection; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Windows.Forms; -using System.Reflection; - using Opc.Ua.Client; using Opc.Ua.Client.Controls; -using System.Threading; -using System.Threading.Tasks; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip; namespace Opc.Ua.Sample.Controls { @@ -79,7 +79,7 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, ContentFilter filter) + public void Initialize(Session session, ContentFilter filter, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); @@ -88,6 +88,7 @@ public void Initialize(Session session, ContentFilter filter) m_session = session; m_browser = new Browser(session); m_filter = filter; + Telemetry = telemetry; if (m_filter == null) { @@ -219,7 +220,7 @@ private void SetOperatorMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -232,7 +233,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -240,7 +241,7 @@ private async void SelectNodeMI_ClickAsync(object sender, EventArgs e) { try { - ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser, ObjectTypes.BaseEventType); + ReferenceDescription reference = await new SelectNodeDlg().ShowDialogAsync(m_browser, ObjectTypes.BaseEventType, m_session, Telemetry); if (reference != null) { @@ -254,8 +255,8 @@ private async void SelectNodeMI_ClickAsync(object sender, EventArgs e) ContentFilterElement element = null; // build the relative path. - QualifiedNameCollection browsePath = new QualifiedNameCollection(); - NodeId typeId = m_session.NodeCache.BuildBrowsePath(node, browsePath); + QualifiedNameCollection browsePath = [node.BrowseName]; + NodeId typeId = null; switch (node.NodeClass) { @@ -319,7 +320,7 @@ private async void SelectNodeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -342,7 +343,7 @@ private void CreateElementAndMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -365,7 +366,7 @@ private void CreateElementOrMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -387,7 +388,7 @@ private void CreateElementNotMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -425,7 +426,7 @@ private void EditValueMI_Click(object sender, EventArgs e) } // edit the value. - object value = new SimpleValueEditDlg().ShowDialog(currentValue, currentValue.GetType()); + object value = new SimpleValueEditDlg().ShowDialog(currentValue, currentValue.GetType(), Telemetry); if (value == null) { @@ -439,7 +440,7 @@ private void EditValueMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs index 0d5db1e3b..c704f4857 100644 --- a/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/CreateMonitoredItemsDlg.cs @@ -54,6 +54,7 @@ public CreateMonitoredItemsDlg() #region Private Fields private Subscription m_subscription; + private ITelemetryContext m_telemetry; private SubscriptionStateChangedEventHandler m_SubscriptionStateChanged; #endregion @@ -61,7 +62,7 @@ public CreateMonitoredItemsDlg() /// /// Displays the dialog. /// - public void Show(Subscription subscription, bool useTypeModel) + public void Show(Subscription subscription, bool useTypeModel, ITelemetryContext telemetry) { if (subscription == null) throw new ArgumentNullException(nameof(subscription)); @@ -76,6 +77,7 @@ public void Show(Subscription subscription, bool useTypeModel) // start receiving notifications from the new subscription. m_subscription = subscription; + m_telemetry = telemetry; if (subscription != null) { @@ -85,9 +87,9 @@ public void Show(Subscription subscription, bool useTypeModel) m_subscription = subscription; BrowseCTRL.AllowPick = true; - BrowseCTRL.SetViewAsync(subscription.Session as Session, (useTypeModel) ? BrowseViewType.ObjectTypes : BrowseViewType.Objects, null); + BrowseCTRL.SetViewAsync(subscription.Session as Session, (useTypeModel) ? BrowseViewType.ObjectTypes : BrowseViewType.Objects, null, telemetry); - MonitoredItemsCTRL.Initialize(subscription); + MonitoredItemsCTRL.Initialize(subscription, telemetry); } #endregion @@ -120,7 +122,7 @@ void Subscription_StateChanged(Subscription subscription, SubscriptionStateChang } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -138,7 +140,7 @@ private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -150,7 +152,7 @@ private async void ApplyBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -162,7 +164,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs b/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs index 677a9966c..38d187e01 100644 --- a/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/DataChangeNotificationListCtrl.cs @@ -112,6 +112,7 @@ public async void InitializeAsync(Subscription subscription, MonitoredItem monit // start receiving notifications from the new subscription. m_subscription = subscription; m_monitoredItem = monitoredItem; + Telemetry = m_subscription?.Session?.MessageContext?.Telemetry; // get the events. List changes = new List(); @@ -498,11 +499,11 @@ private void ViewMI_Click(object sender, EventArgs e) return; } - new ComplexValueEditDlg().ShowDialog(change); + new ComplexValueEditDlg().ShowDialog(change, Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs index 6af6d7e67..67d97e689 100644 --- a/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/EventFilterDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,6 +53,7 @@ public EventFilterDlg() #region Private Fields private Session m_session; + private ITelemetryContext m_telemetry; private EventFilter m_filter; #endregion @@ -60,18 +61,19 @@ public EventFilterDlg() /// /// Displays the dialog. /// - public EventFilter ShowDialog(Session session, EventFilter filter, bool editWhereClause) + public EventFilter ShowDialog(Session session, ITelemetryContext telemetry, EventFilter filter, bool editWhereClause) { if (session == null) throw new ArgumentNullException(nameof(session)); if (filter == null) throw new ArgumentNullException(nameof(filter)); m_session = session; + m_telemetry = telemetry; m_filter = filter; - BrowseCTRL.SetViewAsync(m_session, BrowseViewType.EventTypes, null); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.EventTypes, null, telemetry); SelectClauseCTRL.Initialize(session, filter.SelectClauses); - ContentFilterCTRL.Initialize(session, filter.WhereClause); - FilterOperandsCTRL.Initialize(session, null, -1); + ContentFilterCTRL.Initialize(session, filter.WhereClause, telemetry); + FilterOperandsCTRL.Initialize(session, null, -1, telemetry); MoveBTN_Click((editWhereClause) ? NextBTN : BackBTN, null); @@ -99,7 +101,7 @@ private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -117,7 +119,7 @@ private void ContentFilterCTRL_ItemsSelected(object sender, ListItemActionEventA { if (Object.ReferenceEquals(elements[ii], item)) { - FilterOperandsCTRL.Initialize(m_session, elements, ii); + FilterOperandsCTRL.Initialize(m_session, elements, ii, m_telemetry); } } @@ -126,12 +128,12 @@ private void ContentFilterCTRL_ItemsSelected(object sender, ListItemActionEventA } else { - FilterOperandsCTRL.Initialize(m_session, null, -1); + FilterOperandsCTRL.Initialize(m_session, null, -1, m_telemetry); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -163,7 +165,7 @@ private void MoveBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -176,7 +178,7 @@ private void OkBTN_Click(object sender, EventArgs e) filter.SelectClauses.AddRange(SelectClauseCTRL.GetSelectClauses()); filter.WhereClause = ContentFilterCTRL.GetFilter(); - EventFilter.Result result = filter.Validate(new FilterContext(m_session.NamespaceUris, m_session.TypeTree)); + EventFilter.Result result = filter.Validate(new FilterContext(m_session.NamespaceUris, m_session.TypeTree, m_telemetry)); if (ServiceResult.IsBad(result.Status)) { @@ -189,7 +191,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } diff --git a/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs b/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs index cde08bca8..80540757b 100644 --- a/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/EventNotificationListCtrl.cs @@ -101,6 +101,7 @@ public void Initialize(Subscription subscription, MonitoredItem monitoredItem) // start receiving notifications from the new subscription. m_subscription = subscription; m_monitoredItem = monitoredItem; + Telemetry = m_subscription?.Session?.MessageContext?.Telemetry; // get the events. List events = new List(); @@ -432,11 +433,11 @@ private void ViewMI_Click(object sender, EventArgs e) return; } - new ComplexValueEditDlg().ShowDialog(fieldList, m_subscription.FindItemByClientHandle(fieldList.ClientHandle)); + new ComplexValueEditDlg().ShowDialog(fieldList, m_subscription.FindItemByClientHandle(fieldList.ClientHandle), Telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs b/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs index 8a5231e65..98b3efd35 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperandEditDlg.cs @@ -76,13 +76,16 @@ public FilterOperand ShowDialog( Session session, IList elements, int index, - FilterOperand operand) + FilterOperand operand, + ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); if (elements == null) throw new ArgumentNullException(nameof(elements)); m_session = session; + + TypeDefinitionIdCTRL.Telemetry = telemetry; TypeDefinitionIdCTRL.Browser = new Browser(session); TypeDefinitionIdCTRL.RootId = ObjectTypes.BaseEventType; @@ -192,7 +195,7 @@ private void OperandTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs index 103c58f06..8f72a5109 100644 --- a/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/FilterOperandListCtrl.cs @@ -78,7 +78,7 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, IList elements, int index) + public void Initialize(Session session, IList elements, int index, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); @@ -87,6 +87,7 @@ public void Initialize(Session session, IList elements, in m_session = session; m_elements = elements; m_index = index; + Telemetry = telemetry; if (elements == null || index < 0 || index >= elements.Count) { @@ -154,7 +155,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) { try { - FilterOperand operand = new FilterOperandEditDlg().ShowDialog(m_session, m_elements, m_index, null); + FilterOperand operand = new FilterOperandEditDlg().ShowDialog(m_session, m_elements, m_index, null, Telemetry); if (operand == null) { @@ -184,7 +185,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -195,7 +196,7 @@ private void EditMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -206,7 +207,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs index 92c236e0a..02d252771 100644 --- a/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/HistoryReadDlg.cs @@ -61,14 +61,14 @@ public HistoryReadDlg() /// /// Displays the dialog. /// - public void Show(Session session, ReadValueIdCollection valueIds) + public void Show(Session session, ReadValueIdCollection valueIds, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; - BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null); - ReadValuesCTRL.Initialize(session, valueIds); + BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, telemetry); + ReadValuesCTRL.Initialize(session, valueIds, telemetry); MoveBTN_ClickAsync(BackBTN, null); @@ -98,6 +98,7 @@ private async Task ReadAsync(CancellationToken ct = default) ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); + ReadResultsCTRL.Telemetry = m_session?.MessageContext?.Telemetry; await ReadResultsCTRL.ShowValueAsync(values, true, ct); } #endregion @@ -117,7 +118,7 @@ private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -149,7 +150,7 @@ private async void MoveBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -161,7 +162,7 @@ private async void ReadMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -173,7 +174,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs index 37e6ba888..f44f37d90 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemConfigCtrl.cs @@ -107,7 +107,7 @@ public void Clear() /// /// Displays the items for the specified subscription in the control. /// - public void Initialize(Subscription subscription) + public void Initialize(Subscription subscription, ITelemetryContext telemetry) { // do nothing if same subscription provided. if (Object.ReferenceEquals(m_subscription, subscription)) @@ -116,6 +116,7 @@ public void Initialize(Subscription subscription) } m_subscription = subscription; + Telemetry = telemetry; Clear(); UpdateItems(); @@ -152,14 +153,14 @@ public void SubscriptionChanged(SubscriptionStateChangedEventArgs e) /// /// Creates a new group item. /// - public MonitoredItem CreateItem(Subscription subscription) + public MonitoredItem CreateItem(Subscription subscription, ITelemetryContext telemetry) { if (subscription == null) throw new ArgumentNullException(nameof(subscription)); MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem); monitoredItem.QueueSize = 1; - if (!new MonitoredItemEditDlg().ShowDialog(subscription.Session as Session, monitoredItem)) + if (!new MonitoredItemEditDlg().ShowDialog(subscription.Session as Session, monitoredItem, telemetry)) { return null; } @@ -456,7 +457,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -471,12 +472,12 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) return; } - CreateItem(m_subscription); + CreateItem(m_subscription, Telemetry); await ApplyChangesAsync(false); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -496,7 +497,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - if (!new MonitoredItemEditDlg().ShowDialog(m_subscription.Session as Session, monitoredItem, true)) + if (!new MonitoredItemEditDlg().ShowDialog(m_subscription.Session as Session, monitoredItem, true, Telemetry)) { return; } @@ -505,7 +506,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -551,7 +552,7 @@ private async void DeleteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -592,7 +593,7 @@ private async void SetMonitoringModeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -618,7 +619,7 @@ private async void SetFilterMI_ClickAsync(object sender, EventArgs e) } else { - EventFilter filter = new EventFilterDlg().ShowDialog(m_subscription.Session as Session, monitoredItems[0].Filter as EventFilter, false); + EventFilter filter = new EventFilterDlg().ShowDialog(m_subscription.Session as Session, Telemetry, monitoredItems[0].Filter as EventFilter, false); if (filter == null) { @@ -634,7 +635,7 @@ private async void SetFilterMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -666,7 +667,7 @@ private void MonitorMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -685,7 +686,7 @@ void MonitoredItemDlg_FormClosing(object sender, FormClosingEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs index ded84287c..22ded8675 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemDlg.cs @@ -61,6 +61,7 @@ public MonitoredItemDlg() private SubscriptionStateChangedEventHandler m_SubscriptionStateChanged; private MonitoredItemNotificationEventHandler m_MonitoredItemNotification; private PublishStateChangedEventHandler m_PublishStatusChanged; + private ITelemetryContext m_telemetry; #endregion #region Public Interface @@ -94,13 +95,16 @@ public void Show(MonitoredItem monitoredItem) m_monitoredItem.Notification += m_MonitoredItemNotification; } + m_telemetry = m_subscription?.Session?.MessageContext?.Telemetry; + WindowMI_Click(WindowStatusMI, null); WindowMI_Click(WindowLatestValueMI, null); MonitoredItemsCTRL.Initialize(m_monitoredItem); EventsCTRL.Initialize(m_subscription, m_monitoredItem); DataChangesCTRL.InitializeAsync(m_subscription, m_monitoredItem); - LatestValueCTRL.ShowValueAsync(m_monitoredItem, false); + LatestValueCTRL.Telemetry = m_telemetry; + LatestValueCTRL.ShowValueAsync(m_monitoredItem, false).GetAwaiter().GetResult(); } #endregion @@ -174,6 +178,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, if (e != null) { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; + LatestValueCTRL.Telemetry = m_telemetry; await LatestValueCTRL.ShowValueAsync(notification, true); } // update item status. @@ -181,7 +186,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -218,7 +223,7 @@ private void Subscription_StateChanged(Subscription subscription, SubscriptionSt } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -250,7 +255,7 @@ private void Subscription_PublishStatusChanged(object subscription, PublishState } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -292,7 +297,7 @@ private void WindowMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -321,7 +326,7 @@ private async void MonitoringModeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -342,7 +347,7 @@ private void MonitoringModeMI_DropDownOpening(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs index f860efd8a..c267e81ea 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemEditDlg.cs @@ -67,20 +67,21 @@ public MonitoredItemEditDlg() /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Session session, MonitoredItem monitoredItem) + public bool ShowDialog(Session session, MonitoredItem monitoredItem, ITelemetryContext telemetry) { - return ShowDialog(session, monitoredItem, false); + return ShowDialog(session, monitoredItem, false, telemetry); } /// /// Prompts the user to specify the browse options. /// - public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool editMonitoredItem) + public bool ShowDialog(Session session, MonitoredItem monitoredItem, bool editMonitoredItem, ITelemetryContext telemetry) { if (monitoredItem == null) throw new ArgumentNullException(nameof(monitoredItem)); m_session = session; + NodeIdCTRL.Telemetry = telemetry; NodeIdCTRL.Browser = new Browser(session); if (editMonitoredItem) diff --git a/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs b/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs index 396720fb9..6fe8c6d01 100644 --- a/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/MonitoredItemStatusCtrl.cs @@ -98,6 +98,7 @@ public void Initialize(MonitoredItem monitoredItem) m_monitoredItem = monitoredItem; m_subscription = null; + Telemetry = m_subscription?.Session?.MessageContext?.Telemetry; Clear(); diff --git a/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs b/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs index 36e30e99f..d57d3c61a 100644 --- a/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/NotificationMessageListCtrl.cs @@ -128,6 +128,7 @@ public void Initialize(Session session, Subscription subscription) m_session = session; m_subscription = subscription; + Telemetry = m_subscription?.Session?.MessageContext?.Telemetry; // nothing to do if no session provided. if (m_session == null) @@ -307,7 +308,7 @@ private void Session_Notification(ISession sender, NotificationEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -318,7 +319,7 @@ private void ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -333,7 +334,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -345,7 +346,7 @@ private void ClearMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -368,7 +369,7 @@ private void RepublishMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } } diff --git a/Samples/Controls.Net4/Subscriptions/ReadDlg.cs b/Samples/Controls.Net4/Subscriptions/ReadDlg.cs index ce2d3b0e6..18b05aeca 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadDlg.cs @@ -61,14 +61,14 @@ public ReadDlg() /// /// Displays the dialog. /// - public async Task ShowAsync(Session session, ReadValueIdCollection valueIds, CancellationToken ct = default) + public async Task ShowAsync(Session session, ReadValueIdCollection valueIds, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; - await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); - ReadValuesCTRL.Initialize(session, valueIds); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, telemetry, ct); + ReadValuesCTRL.Initialize(session, valueIds, telemetry); MoveBTN_ClickAsync(BackBTN, null); @@ -98,6 +98,7 @@ private async Task ReadAsync(CancellationToken ct = default) ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); + ReadResultsCTRL.Telemetry = m_session?.MessageContext?.Telemetry; await ReadResultsCTRL.ShowValueAsync(values, true, ct); } #endregion @@ -117,7 +118,7 @@ private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -153,7 +154,7 @@ private async void MoveBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -165,7 +166,7 @@ private async void ReadMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -177,7 +178,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs b/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs index 1c3cc96fa..ded71263d 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadValueEditDlg.cs @@ -56,11 +56,12 @@ public ReadValueEditDlg() /// /// Prompts the user to specify the browse options. /// - public async Task ShowDialogAsync(Session session, ReadValueId valueId, CancellationToken ct = default) + public async Task ShowDialogAsync(Session session, ReadValueId valueId, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); if (valueId == null) throw new ArgumentNullException(nameof(valueId)); + NodeIdCTRL.Telemetry = telemetry; NodeIdCTRL.Browser = new Browser(session); INode node = await session.NodeCache.FindAsync(valueId.NodeId, ct); diff --git a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs index cd1523774..e0f2ce087 100644 --- a/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/ReadValueListCtrl.cs @@ -79,13 +79,14 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, ReadValueIdCollection valueIds) + public void Initialize(Session session, ReadValueIdCollection valueIds, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); Clear(); m_session = session; + Telemetry = telemetry; foreach (ReadValueId valueId in valueIds) { @@ -212,7 +213,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -224,7 +225,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) { ReadValueId valueId = new ReadValueId(); - if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId)) + if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId, Telemetry)) { AddItem(valueId); } @@ -233,7 +234,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -248,14 +249,14 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId)) + if (await new ReadValueEditDlg().ShowDialogAsync(m_session, valueId, Telemetry)) { await UpdateItemAsync(ItemsLV.SelectedItems[0], valueId); } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -267,7 +268,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs index 18a149821..3ddba753f 100644 --- a/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/RepublishNotificationMessageDlg.cs @@ -53,6 +53,7 @@ public RepublishNotificationMessageDlg() #region Private Fields private Subscription m_subscription; + private ITelemetryContext m_telemetry; private NotificationMessage m_message; #endregion @@ -65,6 +66,7 @@ public NotificationMessage ShowDialog(Subscription subscription) if (subscription == null) throw new ArgumentNullException(nameof(subscription)); m_subscription = subscription; + m_telemetry = subscription.Session?.MessageContext?.Telemetry; SequenceNumberNC.Value = 0; @@ -95,7 +97,7 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs b/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs index 2a4532244..bbf1c30e4 100644 --- a/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/SelectClauseListCtrl.cs @@ -86,6 +86,7 @@ public void Initialize(Session session, SimpleAttributeOperandCollection selectC m_session = session; m_selectClauses = selectClauses; + Telemetry = m_session?.MessageContext?.Telemetry; if (selectClauses == null) { @@ -122,7 +123,8 @@ public async Task AddSelectClauseAsync(ReferenceDescription reference, Cancellat SimpleAttributeOperand clause = new SimpleAttributeOperand(); - clause.TypeDefinitionId = m_session.NodeCache.BuildBrowsePath(node, clause.BrowsePath); + clause.BrowsePath.Add(node.BrowseName); + clause.TypeDefinitionId = null; clause.AttributeId = Attributes.Value; AddItem(clause, "Property", -1); @@ -205,7 +207,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -224,7 +226,7 @@ private void ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -246,7 +248,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs index fc7fc434e..6e4d885ca 100644 --- a/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/SubscriptionDlg.cs @@ -38,6 +38,7 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Client; using Opc.Ua.Client.Controls; @@ -58,6 +59,8 @@ public SubscriptionDlg() #endregion #region Private Fields + private ITelemetryContext m_telemetry; + private ILogger m_logger; private Subscription m_subscription; private NotificationEventHandler m_SessionNotification; private SubscriptionStateChangedEventHandler m_SubscriptionStateChanged; @@ -69,10 +72,13 @@ public SubscriptionDlg() /// /// Creates a new subscription. /// - public async Task NewAsync(Session session, CancellationToken ct = default) + public async Task NewAsync(Session session, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + Subscription subscription = new Subscription(session.DefaultSubscription); if (!await new SubscriptionEditDlg().ShowDialogAsync(subscription, ct)) @@ -86,7 +92,7 @@ public async Task NewAsync(Session session, CancellationToken ct = Subscription duplicateSubscription = session.Subscriptions.FirstOrDefault(s => s.Id != 0 && s.Id.Equals(subscription.Id) && s != subscription); if (duplicateSubscription != null) { - Utils.Trace("Duplicate subscription was created with the id: {0}", duplicateSubscription.Id); + m_logger.LogWarning("Duplicate subscription was created with the id: {0}", duplicateSubscription.Id); DialogResult result = MessageBox.Show("Duplicate subscription was created with the id: " + duplicateSubscription.Id + ". Do you want to keep it?", "Warning", MessageBoxButtons.YesNo); if (result == System.Windows.Forms.DialogResult.No) @@ -131,7 +137,7 @@ public void Show(Subscription subscription) m_subscription.Session.Notification += m_SessionNotification; } - MonitoredItemsCTRL.Initialize(subscription); + MonitoredItemsCTRL.Initialize(subscription, m_telemetry); EventsCTRL.Initialize(subscription, null); DataChangesCTRL.InitializeAsync(subscription, null); @@ -243,7 +249,7 @@ private async void Session_NotificationAsync(ISession session, NotificationEvent } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -280,7 +286,7 @@ private void Subscription_StateChanged(Subscription subscription, SubscriptionSt } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -312,7 +318,7 @@ private async void Subscription_PublishStatusChangedAsync(object subscription, E } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -324,7 +330,7 @@ private void SubscriptionMI_DropDownOpening(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -364,7 +370,7 @@ private void WindowMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -376,7 +382,7 @@ private async void SubscriptionEnablePublishingMI_ClickAsync(object sender, Even } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -393,7 +399,7 @@ private void SubscriptionDlg_FormClosing(object sender, FormClosingEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -410,7 +416,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -424,11 +430,11 @@ private void SubscriptionCreateItemMI_Click(object sender, EventArgs e) m_createDialog.FormClosing += new FormClosingEventHandler(CreateDialog_FormClosing); } - m_createDialog.Show(m_subscription, false); + m_createDialog.Show(m_subscription, false, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -443,7 +449,7 @@ void CreateDialog_FormClosing(object sender, FormClosingEventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -457,11 +463,11 @@ private void SubscriptionCreateItemFromTypeMI_Click(object sender, EventArgs e) m_createDialog.FormClosing += new FormClosingEventHandler(CreateDialog_FormClosing); } - m_createDialog.Show(m_subscription, true); + m_createDialog.Show(m_subscription, true, m_telemetry); } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -473,7 +479,7 @@ private async void ConditionRefreshMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/WriteDlg.cs b/Samples/Controls.Net4/Subscriptions/WriteDlg.cs index 17f2e9ff0..1dcc7aa95 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteDlg.cs @@ -61,14 +61,14 @@ public WriteDlg() /// /// Displays the dialog. /// - public async Task ShowAsync(Session session, WriteValueCollection values, CancellationToken ct = default) + public async Task ShowAsync(Session session, WriteValueCollection values, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); m_session = session; - await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, ct); - WriteValuesCTRL.Initialize(session, values); + await BrowseCTRL.SetViewAsync(m_session, BrowseViewType.Objects, null, telemetry, ct); + WriteValuesCTRL.Initialize(session, values, telemetry); MoveBTN_ClickAsync(BackBTN, null); @@ -118,6 +118,7 @@ private async Task WriteAsync(CancellationToken ct = default) ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); + WriteResultsCTRL.Telemetry = m_session?.MessageContext?.Telemetry; await WriteResultsCTRL.ShowValueAsync(results, true, ct); } #endregion @@ -137,7 +138,7 @@ private async void BrowseCTRL_ItemsSelectedAsync(object sender, NodesSelectedEve } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -173,7 +174,7 @@ private async void MoveBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -185,7 +186,7 @@ private async void WriteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -197,7 +198,7 @@ private void CancelBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs b/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs index deb5d7f27..282c2de73 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteValueEditDlg.cs @@ -55,12 +55,12 @@ public WriteValueEditDlg() /// /// Prompts the user to specify the browse options. /// - public async Task ShowDialogAsync(Session session, WriteValue value, CancellationToken ct = default) + public async Task ShowDialogAsync(Session session, WriteValue value, ITelemetryContext telemetry, CancellationToken ct = default) { if (session == null) throw new ArgumentNullException(nameof(session)); if (value == null) throw new ArgumentNullException(nameof(value)); - + NodeIdCTRL.Telemetry = telemetry; NodeIdCTRL.Browser = new Browser(session); INode node = await session.NodeCache.FindAsync(value.NodeId, ct); diff --git a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs index 47475f5b3..c26005b7d 100644 --- a/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs +++ b/Samples/Controls.Net4/Subscriptions/WriteValueListCtrl.cs @@ -82,13 +82,14 @@ public void Clear() /// /// Sets the nodes in the control. /// - public void Initialize(Session session, WriteValueCollection values) + public void Initialize(Session session, WriteValueCollection values, ITelemetryContext telemetry) { if (session == null) throw new ArgumentNullException(nameof(session)); Clear(); m_session = session; + Telemetry = telemetry; if (values != null) { @@ -279,7 +280,7 @@ protected override async Task OnDragDropAsync(object sender, DragEventArgs e, Ca } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion @@ -291,7 +292,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) { WriteValue value = new WriteValue(); - if (await new WriteValueEditDlg().ShowDialogAsync(m_session, value)) + if (await new WriteValueEditDlg().ShowDialogAsync(m_session, value, Telemetry)) { AddItem(value); } @@ -300,7 +301,7 @@ private async void NewMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -315,7 +316,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) return; } - if (await new WriteValueEditDlg().ShowDialogAsync(m_session, values[0])) + if (await new WriteValueEditDlg().ShowDialogAsync(m_session, values[0], Telemetry)) { Node node = await m_session.NodeCache.FindAsync(values[0].NodeId) as Node; @@ -336,7 +337,7 @@ private async void EditMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -382,7 +383,7 @@ private async void EditValueMI_ClickAsync(object sender, EventArgs e) if (useIndexRange) { - value = new ComplexValueEditDlg().ShowDialog(values[0]); + value = new ComplexValueEditDlg().ShowDialog(values[0], Telemetry); WriteValue writeValue = value as WriteValue; @@ -393,7 +394,7 @@ private async void EditValueMI_ClickAsync(object sender, EventArgs e) } else { - value = GuiUtils.EditValue(m_session, values[0].Value.Value, datatypeId, valueRank); + value = GuiUtils.EditValue(m_session, values[0].Value.Value, datatypeId, valueRank, Telemetry); } if (value != null) @@ -408,7 +409,7 @@ private async void EditValueMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -432,7 +433,7 @@ private void DeleteMI_Click(object sender, EventArgs e) } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(Telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } #endregion diff --git a/Samples/Controls.Net4/UA Sample Controls.csproj b/Samples/Controls.Net4/UA Sample Controls.csproj index e0fe6c38b..fbbc0ee11 100644 --- a/Samples/Controls.Net4/UA Sample Controls.csproj +++ b/Samples/Controls.Net4/UA Sample Controls.csproj @@ -700,10 +700,10 @@ - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs b/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs index 523f8e065..6a92f7f3a 100644 --- a/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs +++ b/Samples/GDS/Client/Controls/ApplicationCertificateControl.cs @@ -31,6 +31,7 @@ using System; using System.Drawing; using System.IO; +using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; @@ -45,6 +46,7 @@ public ApplicationCertificateControl() InitializeComponent(); } + private ITelemetryContext m_telemetry; private GlobalDiscoveryClientConfiguration m_configuration; private GlobalDiscoveryServerClient m_gds; private ServerPushConfigurationClient m_server; @@ -59,8 +61,10 @@ public async Task InitializeAsync( ServerPushConfigurationClient server, RegisteredApplication application, bool isHttps, + ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; m_configuration = configuration; m_gds = gds; m_server = server; @@ -221,7 +225,7 @@ private async Task RequestNewCertificatePushModeAsync(object sender, EventArgs e } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -248,13 +252,13 @@ private async Task RequestNewCertificatePullModeAsync(object sender, EventArgs e //this line fails with a CryptographicException if export of private key is not allowed _ = m_certificate.GetRSAPrivateKey().ExportParameters(true); //proceed with a CSR using the exportable private key - m_certificate = await id.LoadPrivateKeyAsync(m_certificatePassword); + m_certificate = await id.LoadPrivateKeyAsync(m_certificatePassword.ToCharArray()); } catch { //create temporary cert to generate csr from m_certificate = CertificateFactory.CreateCertificate( - X509Utils.GetApplicationUriFromCertificate(m_certificate), + X509Utils.GetApplicationUrisFromCertificate(m_certificate)[0], m_application.ApplicationName, Utils.ReplaceDCLocalhost(m_application.CertificateSubjectName), m_application.GetDomainNames(m_certificate)) @@ -285,7 +289,7 @@ private async Task RequestNewCertificatePullModeAsync(object sender, EventArgs e Utils.ReplaceDCLocalhost(m_application.CertificateSubjectName), domainNames, "PFX", - m_certificatePassword); + m_certificatePassword?.ToCharArray()); } else { @@ -300,11 +304,11 @@ private async Task RequestNewCertificatePullModeAsync(object sender, EventArgs e byte[] pkcsData = File.ReadAllBytes(absoluteCertificatePrivateKeyPath); if (m_application.GetPrivateKeyFormat(await m_server?.GetSupportedKeyFormatsAsync()) == "PFX") { - csrCertificate = X509PfxUtils.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword); + csrCertificate = X509PfxUtils.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword.AsSpan()); } else { - csrCertificate = CertificateFactory.CreateCertificateWithPEMPrivateKey(m_certificate, pkcsData, m_certificatePassword); + csrCertificate = CertificateFactory.CreateCertificateWithPEMPrivateKey(m_certificate, pkcsData, m_certificatePassword.AsSpan()); } } byte[] certificateRequest = CertificateFactory.CreateSigningRequest(csrCertificate, domainNames); @@ -318,7 +322,7 @@ private async Task RequestNewCertificatePullModeAsync(object sender, EventArgs e } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -356,7 +360,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) // update store var certificateStoreIdentifier = new CertificateStoreIdentifier(m_application.CertificateStorePath, false); - using (ICertificateStore store = certificateStoreIdentifier.OpenStore()) + using (ICertificateStore store = certificateStoreIdentifier.OpenStore(m_telemetry)) { // if we used a CSR, we already have a private key and therefore didn't request one from the GDS // in this case, privateKey is null @@ -365,7 +369,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) X509Certificate2 oldCertificate = await cid.FindAsync(true); if (oldCertificate != null && oldCertificate.HasPrivateKey) { - oldCertificate = await cid.LoadPrivateKeyAsync(string.Empty); + oldCertificate = await cid.LoadPrivateKeyAsync([]); newCert = CertificateFactory.CreateCertificateWithPrivateKey(newCert, m_temporaryCertificateCreated ? m_certificate : oldCertificate); await store.DeleteAsync(oldCertificate.Thumbprint); } @@ -377,7 +381,6 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) else { newCert = new X509Certificate2(privateKeyPFX, string.Empty, X509KeyStorageFlags.Exportable); - newCert = CertificateFactory.Load(newCert, true); } await store.AddAsync(newCert); if (m_temporaryCertificateCreated) @@ -441,7 +444,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) if (file.Exists) { byte[] pkcsData = File.ReadAllBytes(absoluteCertificatePrivateKeyPath); - X509Certificate2 oldCertificate = X509PfxUtils.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword); + X509Certificate2 oldCertificate = X509PfxUtils.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword.AsSpan()); newCert = CertificateFactory.CreateCertificateWithPrivateKey(newCert, oldCertificate); pkcsData = newCert.Export(X509ContentType.Pfx, m_certificatePassword); File.WriteAllBytes(absoluteCertificatePrivateKeyPath, pkcsData); @@ -463,7 +466,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) if (!String.IsNullOrEmpty(m_application.TrustListStorePath)) { var certificateStoreIdentifier = new CertificateStoreIdentifier(m_application.TrustListStorePath); - using (ICertificateStore store = certificateStoreIdentifier.OpenStore()) + using (ICertificateStore store = certificateStoreIdentifier.OpenStore(m_telemetry)) { foreach (byte[] issuerCertificate in issuerCertificates) { @@ -521,7 +524,7 @@ private async void CertificateRequestTimer_Tick(object sender, EventArgs e) RequestProgressLabel.Visible = false; CertificateRequestTimer.Enabled = false; - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, exception); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, exception); } } @@ -538,7 +541,7 @@ private async void ApplyChangesButton_Click(object sender, EventArgs e) if (se == null || se.StatusCode != StatusCodes.BadServerHalted) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Parent.Text, exception); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Parent.Text, exception); } } diff --git a/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs b/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs index beb658b60..c26f925ca 100644 --- a/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs +++ b/Samples/GDS/Client/Controls/ApplicationTrustListControl.cs @@ -53,19 +53,21 @@ public ApplicationTrustListControl() private RegisteredApplication m_application; private string m_trustListStorePath; private string m_issuerListStorePath; + private ITelemetryContext m_telemetry; - public async Task Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient server, RegisteredApplication application, bool isHttps, CancellationToken ct = default) + public async Task Initialize(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient server, RegisteredApplication application, bool isHttps, ITelemetryContext telemetry, CancellationToken ct = default) { m_gds = gds; m_server = server; m_application = application; + m_telemetry = telemetry; // display local trust list. if (application != null) { m_trustListStorePath = (isHttps) ? m_application.HttpsTrustListStorePath : m_application.TrustListStorePath; m_issuerListStorePath = (isHttps) ? m_application.HttpsIssuerListStorePath : m_application.IssuerListStorePath; - await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null, ct); + await CertificateStoreControl.Initialize(telemetry, m_trustListStorePath, m_issuerListStorePath, null, ct); MergeWithGdsButton.Enabled = !String.IsNullOrEmpty(m_trustListStorePath) || m_application.RegistrationType == RegistrationType.ServerPush; } @@ -90,17 +92,17 @@ private async void ReloadTrustListButton_ClickAsync(object sender, EventArgs e) } else { - await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); + await CertificateStoreControl.Initialize(m_telemetry, m_trustListStorePath, m_issuerListStorePath, null); } } else { - await CertificateStoreControl.Initialize(null, null, null); + await CertificateStoreControl.Initialize(m_telemetry, null, null, null); } } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -112,7 +114,7 @@ private async void MergeWithGdsButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -124,7 +126,7 @@ private async void PullFromGdsButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -136,7 +138,7 @@ private async Task DeleteExistingFromStoreAsync(string storePath, CancellationTo } var certificateStoreIdentifier = new CertificateStoreIdentifier(storePath); - using (var store = certificateStoreIdentifier.OpenStore()) + using (var store = certificateStoreIdentifier.OpenStore(m_telemetry)) { X509Certificate2Collection certificates = await store.EnumerateAsync(ct); foreach (var certificate in certificates) @@ -190,7 +192,7 @@ private async Task PullFromGdsAsync(bool deleteBeforeAdd, CancellationToken ct = if (trustListId == null) { - await CertificateStoreControl.Initialize(null, null, null, ct); + await CertificateStoreControl.Initialize(m_telemetry, null, null, null, ct); return; } @@ -222,7 +224,7 @@ private async Task PullFromGdsAsync(bool deleteBeforeAdd, CancellationToken ct = if (!String.IsNullOrEmpty(m_trustListStorePath)) { var certificateStoreIdentifier = new CertificateStoreIdentifier(m_trustListStorePath); - using (ICertificateStore store = certificateStoreIdentifier.OpenStore()) + using (ICertificateStore store = certificateStoreIdentifier.OpenStore(m_telemetry)) { if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.TrustedCertificates) != 0) { @@ -251,7 +253,7 @@ private async Task PullFromGdsAsync(bool deleteBeforeAdd, CancellationToken ct = if (!String.IsNullOrEmpty(m_application.IssuerListStorePath)) { var certificateStoreIdentifier = new CertificateStoreIdentifier(m_application.IssuerListStorePath); - using (ICertificateStore store = certificateStoreIdentifier.OpenStore()) + using (ICertificateStore store = certificateStoreIdentifier.OpenStore(m_telemetry)) { if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.IssuerCertificates) != 0) { @@ -277,7 +279,7 @@ private async Task PullFromGdsAsync(bool deleteBeforeAdd, CancellationToken ct = } } - await CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null, ct); + await CertificateStoreControl.Initialize(m_telemetry, m_trustListStorePath, m_issuerListStorePath, null, ct); MessageBox.Show( Parent, @@ -320,7 +322,7 @@ private async void PushToServerButton_Click(object sender, EventArgs e) } catch (Exception exception) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Parent.Text, exception); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Parent.Text, exception); } } @@ -346,7 +348,7 @@ private async void ApplyChangesButton_Click(object sender, EventArgs e) if (se == null || se.StatusCode != StatusCodes.BadServerHalted) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Parent.Text, exception); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Parent.Text, exception); } } diff --git a/Samples/GDS/Client/Controls/RegisterApplicationControl.cs b/Samples/GDS/Client/Controls/RegisterApplicationControl.cs index 3c187de5f..63b6d0416 100644 --- a/Samples/GDS/Client/Controls/RegisterApplicationControl.cs +++ b/Samples/GDS/Client/Controls/RegisterApplicationControl.cs @@ -38,6 +38,7 @@ using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; +using Microsoft.Extensions.Logging; using Opc.Ua.Gds.Client.Controls; namespace Opc.Ua.Gds.Client @@ -74,6 +75,8 @@ public RegisterApplicationControl() private RegisteredApplication m_application; private bool m_promptOnRegistrationTypeChange; private string m_externalEditor; + private ITelemetryContext m_telemetry; + private ILogger m_logger; private const int ClientPullManagement = (int)RegistrationType.ClientPull; private const int ServerPullManagement = (int)RegistrationType.ServerPull; @@ -96,12 +99,15 @@ public RegisteredApplication RegisteredApplication } } - public async Task InitializeAsync(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient pushClient, EndpointDescription endpoint, GlobalDiscoveryClientConfiguration configuration) + public async Task InitializeAsync(GlobalDiscoveryServerClient gds, ServerPushConfigurationClient pushClient, EndpointDescription endpoint, GlobalDiscoveryClientConfiguration configuration, ITelemetryContext telemetry) { m_gds = gds; m_pushClient = pushClient; m_application.ServerUrl = null; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); + if (configuration != null) { m_externalEditor = configuration.ExternalEditor; @@ -455,7 +461,7 @@ private void RaiseRegisteredApplicationChangedEvent(RegisteredApplication applic } catch (Exception e) { - Utils.Trace(e, "Unexpected error raising RegisteredApplicationChanged event."); + m_logger.LogError(e, "Unexpected error raising RegisteredApplicationChanged event."); } } } @@ -578,7 +584,7 @@ private async void InitializePullConfiguration(string configurationFilePath) try { - var configuration = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(path); + var configuration = new Opc.Ua.Security.SecurityConfigurationManager(m_telemetry).ReadConfiguration(path); if (configuration.ApplicationType == Security.ApplicationType.Client_1) { @@ -633,7 +639,7 @@ private void InitializePushConfiguration() } catch (Exception e) { - Utils.Trace(e, "Unexpected error raising SelectServer event."); + m_logger.LogError(e, "Unexpected error raising SelectServer event."); } } } @@ -686,7 +692,7 @@ private void ConfigurationFileButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -703,7 +709,7 @@ private void ServerCapabilitiesButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -711,7 +717,7 @@ private void DiscoveryUrlsButton_Click(object sender, EventArgs e) { try { - var discoveryUrls = new DiscoveryUrlsDialog().ShowDialog(Parent, DiscoveryUrlsTextBox.Tag as IList); + var discoveryUrls = new DiscoveryUrlsDialog().ShowDialog(m_logger, Parent, DiscoveryUrlsTextBox.Tag as IList); if (discoveryUrls != null) { @@ -733,7 +739,7 @@ private void DiscoveryUrlsButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -777,7 +783,7 @@ private void CertificateStorePathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -803,7 +809,7 @@ private void SetCertificatePublicKey(string path) if (String.IsNullOrWhiteSpace(ApplicationUriTextBox.Text)) { - ApplicationUriTextBox.Text = X509Utils.GetApplicationUriFromCertificate(certificate); + ApplicationUriTextBox.Text = X509Utils.GetApplicationUrisFromCertificate(certificate)[0]; } if (String.IsNullOrWhiteSpace(DiscoveryUrlsTextBox.Text) && RegistrationTypeComboBox.SelectedIndex != ClientPullManagement) @@ -898,7 +904,7 @@ private void CertificatePublicKeyPathButton_Click(object sender, EventArgs e) if (String.IsNullOrWhiteSpace(ApplicationUriTextBox.Text)) { - ApplicationUriTextBox.Text = X509Utils.GetApplicationUriFromCertificate(certificate); + ApplicationUriTextBox.Text = X509Utils.GetApplicationUrisFromCertificate(certificate)[0]; } } catch (Exception) @@ -913,7 +919,7 @@ private void CertificatePublicKeyPathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -960,7 +966,7 @@ private void CertificatePrivateKeyPathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1029,7 +1035,7 @@ private void HttpsCertificatePublicKeyPathButton_Click(object sender, EventArgs } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1076,7 +1082,7 @@ private void HttpsCertificatePrivateKeyPathButton_Click(object sender, EventArgs } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1126,7 +1132,7 @@ private void TrustListStorePathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1170,7 +1176,7 @@ private void IssuerListStorePathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1214,7 +1220,7 @@ private void HttpsTrustListStorePathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1258,7 +1264,7 @@ private void HttpsIssuerListStorePathButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1339,7 +1345,7 @@ private async void RegisterApplicationButton_Click(object sender, EventArgs e) { if (records.Length > 1) { - recordToReplace = new ViewApplicationRecordsDialog(m_gds).ShowDialog(Parent, records, recordToReplace?.ApplicationId); + recordToReplace = new ViewApplicationRecordsDialog(m_gds).ShowDialog(m_logger, Parent, records, recordToReplace?.ApplicationId); } else if (records.Length > 0) { @@ -1406,7 +1412,7 @@ private async void RegisterApplicationButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1446,7 +1452,7 @@ private async Task ReadRegistrationAsync(bool silent) { if (records.Length > 1) { - existingRecord = new ViewApplicationRecordsDialog(m_gds).ShowDialog(Parent, records, null); + existingRecord = new ViewApplicationRecordsDialog(m_gds).ShowDialog(m_logger, Parent, records, null); } else if (records.Length > 0) { @@ -1540,7 +1546,7 @@ private async void UnregisterApplicationButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1619,7 +1625,7 @@ private void RegistrationTypeComboBox_SelectedIndexChanged(object sender, EventA } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1717,7 +1723,7 @@ private void SaveButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1775,7 +1781,7 @@ private void LoadButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1788,7 +1794,7 @@ private void OpenConfigurationButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1841,7 +1847,7 @@ private void ClearButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1849,7 +1855,7 @@ private async void PickServerButton_Click(object sender, EventArgs e) { try { - string uri = new SelectPushServerDialog().ShowDialog(null, m_pushClient, await m_gds.GetDefaultServerUrlsAsync(null)); + string uri = new SelectPushServerDialog().ShowDialog(null, m_pushClient, await m_gds.GetDefaultServerUrlsAsync(null), m_telemetry); if (uri != null && m_pushClient.IsConnected) { EndpointDescription endpoint = m_pushClient.Endpoint.Description; @@ -1858,7 +1864,7 @@ private async void PickServerButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } } diff --git a/Samples/GDS/Client/GlobalDiscoveryClient.csproj b/Samples/GDS/Client/GlobalDiscoveryClient.csproj index bb45b5ae3..9cec66e51 100644 --- a/Samples/GDS/Client/GlobalDiscoveryClient.csproj +++ b/Samples/GDS/Client/GlobalDiscoveryClient.csproj @@ -141,10 +141,10 @@ - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/GDS/Client/MainForm.cs b/Samples/GDS/Client/MainForm.cs index 1fbfd82f5..c78250cf5 100644 --- a/Samples/GDS/Client/MainForm.cs +++ b/Samples/GDS/Client/MainForm.cs @@ -43,12 +43,13 @@ namespace Opc.Ua.Gds.Client { public partial class MainForm : Form { - public MainForm(ApplicationInstance application) + public MainForm(ApplicationInstance application, ITelemetryContext telemetry) { InitializeComponent(); Icon = ClientUtils.GetAppIcon(); m_application = application; + m_telemetry = telemetry; // get the configuration. m_configuration = m_application.ApplicationConfiguration.ParseExtension(); @@ -64,7 +65,7 @@ public MainForm(ApplicationInstance application) m_filters = new QueryServersFilter(); m_identity = new UserIdentity(); - m_gds = new GlobalDiscoveryServerClient(m_application.ApplicationConfiguration, m_configuration.GlobalDiscoveryServerUrl); + m_gds = new GlobalDiscoveryServerClient(m_application.ApplicationConfiguration); m_gds.KeepAlive += GdsServer_KeepAlive; m_gds.ServerStatusChanged += GdsServer_StatusNotification; m_lds = new LocalDiscoveryServerClient(m_application.ApplicationConfiguration); @@ -74,7 +75,7 @@ public MainForm(ApplicationInstance application) m_server.ServerStatusChanged += Server_StatusNotification; m_server.ConnectionStatusChanged += Server_ConnectionStatusChangedAsync; - RegistrationPanel.InitializeAsync(m_gds, m_server, null, m_configuration).GetAwaiter().GetResult(); + RegistrationPanel.InitializeAsync(m_gds, m_server, null, m_configuration, m_telemetry).GetAwaiter().GetResult(); m_application.ApplicationConfiguration.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; UpdateStatus(true, DateTime.MinValue, "---"); @@ -93,6 +94,7 @@ public MainForm(ApplicationInstance application) } private ApplicationInstance m_application; + private ITelemetryContext m_telemetry; private ConfiguredEndpointCollection m_endpoints = null; private QueryServersFilter m_filters; private UserIdentity m_identity; @@ -130,17 +132,17 @@ private async void Server_ConnectionStatusChangedAsync(object sender, EventArgs { if (m_server.IsConnected) { - await ServerStatusPanel.InitializeAsync(m_server); + await ServerStatusPanel.InitializeAsync(m_server, m_telemetry); } else { - await ServerStatusPanel.InitializeAsync(null); + await ServerStatusPanel.InitializeAsync(null, m_telemetry); } } } catch (Exception exception) { - GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -230,19 +232,19 @@ private async void SelectServerButton_Click(object sender, EventArgs e) { try { - var endpoint = new SelectServerDialog().ShowDialog(this, m_endpoints, m_lds, m_gds, m_filters); + var endpoint = new SelectServerDialog().ShowDialog(this, m_endpoints, m_lds, m_gds, m_filters, m_telemetry); if (endpoint != null) { SetServer(endpoint); - await RegistrationPanel.InitializeAsync(m_gds, m_server, endpoint, m_configuration); + await RegistrationPanel.InitializeAsync(m_gds, m_server, endpoint, m_configuration, m_telemetry); SelectGdsButton.Visible = true; return; } } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -259,12 +261,12 @@ private async void ConnectButton_ClickAsync(object sender, EventArgs e) await m_server.ConnectAsync(endpoint.Description.EndpointUrl); - await ServerStatusPanel.InitializeAsync(m_server); - await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false); + await ServerStatusPanel.InitializeAsync(m_server, m_telemetry); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false, m_telemetry); } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -283,7 +285,7 @@ private void GdsServer_StatusNotification(MonitoredItem monitoredItem, Monitored } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -302,7 +304,7 @@ private void Server_StatusNotification(MonitoredItem monitoredItem, MonitoredIte } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -325,7 +327,7 @@ private void CertificateValidator_CertificateValidation(CertificateValidator sen } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -363,7 +365,7 @@ private void GdsServer_KeepAlive(ISession session, KeepAliveEventArgs e) } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -401,7 +403,7 @@ private void Server_KeepAlive(ISession session, KeepAliveEventArgs e) } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -446,12 +448,12 @@ private async void DisconnectButton_Click(object sender, EventArgs e) { m_server.DisconnectAsync().GetAwaiter().GetResult(); UpdateStatus(true, DateTime.UtcNow, "Disconnected {0}", m_server.Endpoint); - await ServerStatusPanel.InitializeAsync(null); + await ServerStatusPanel.InitializeAsync(null, m_telemetry); } } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } @@ -461,7 +463,7 @@ private void RegistrationButton_Click(object sender, EventArgs e) { if (!m_gdsConfigured) { - string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult()); + string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult(), m_telemetry); if (uri != null) { m_configuration.GlobalDiscoveryServerUrl = m_gds.EndpointUrl; @@ -474,7 +476,7 @@ private void RegistrationButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -486,7 +488,7 @@ private void ServerStatusButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -494,12 +496,12 @@ private async void CertificateButton_ClickAsync(object sender, EventArgs e) { try { - await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, false, m_telemetry); ShowPanel(Panel.Certificate); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -507,12 +509,12 @@ private async void HttpsCertificateButton_ClickAsync(object sender, EventArgs e) { try { - await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, true); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, m_registeredApplication, true, m_telemetry); ShowPanel(Panel.HttpsCertificate); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -520,12 +522,12 @@ private async void TrustListButton_Click(object sender, EventArgs e) { try { - await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, false); + await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, false, m_telemetry); ShowPanel(Panel.TrustList); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -533,12 +535,12 @@ private async void HttpsTrustListButton_Click(object sender, EventArgs e) { try { - await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, true); + await TrustListPanel.Initialize(m_gds, m_server, m_registeredApplication, true, m_telemetry); ShowPanel(Panel.HttpsTrustList); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -546,12 +548,12 @@ private void DiscoveryButton_Click(object sender, EventArgs e) { try { - DiscoveryPanel.Initialize(m_endpoints, m_lds, m_gds, m_filters); + DiscoveryPanel.Initialize(m_endpoints, m_lds, m_gds, m_filters, m_telemetry); ShowPanel(Panel.Discovery); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -563,7 +565,7 @@ private void RegistrationPanel_ServerRequired(object sender, SelectServerEventAr } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -599,13 +601,13 @@ private async void RegistrationPanel_RegisteredApplicationChangedAsync(object se HttpsCertificateButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.GetHttpsDomainName())); HttpsTrustListButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.HttpsTrustListStorePath)); #endif - await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, e.Application, false); - await TrustListPanel.Initialize(m_gds, m_server, e.Application, false); + await CertificatePanel.InitializeAsync(m_configuration, m_gds, m_server, e.Application, false, m_telemetry); + await TrustListPanel.Initialize(m_gds, m_server, e.Application, false, m_telemetry); UpdateMainFormHeader(); } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -621,7 +623,7 @@ private void SelectGdsButton_Click(object sender, EventArgs e) m_gdsConfigured = false; UpdateGdsStatus(true, DateTime.UtcNow, "Disconnected"); - string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult()); + string uri = new SelectGdsDialog().ShowDialog(null, m_gds, m_gds.GetDefaultGdsUrlsAsync(m_lds).GetAwaiter().GetResult(), m_telemetry); if (uri != null) { m_configuration.GlobalDiscoveryServerUrl = m_gds.EndpointUrl; @@ -644,7 +646,7 @@ private void Server_AdminCredentialsRequired(object sender, AdminCredentialsRequ } catch (Exception exception) { - ExceptionDlg.Show(this.Text, exception); + ExceptionDlg.Show(m_telemetry, this.Text, exception); } } diff --git a/Samples/GDS/Client/Program.cs b/Samples/GDS/Client/Program.cs index a339b70ec..83366f119 100644 --- a/Samples/GDS/Client/Program.cs +++ b/Samples/GDS/Client/Program.cs @@ -29,13 +29,29 @@ using System; using System.Windows.Forms; -using Opc.Ua.Configuration; +using Microsoft.Extensions.Logging; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Opc.Ua.Gds.Client { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -47,7 +63,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Opc.Ua.GdsClient"; @@ -60,11 +76,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().GetAwaiter().GetResult(); // run the application interactively. - Application.Run(new MainForm(application)); + Application.Run(new MainForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs b/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs index 653bfdde5..a06cb63ce 100644 --- a/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs +++ b/Samples/GDS/ClientControls/Controls/DiscoveryControl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -72,6 +72,7 @@ public DiscoveryControl() private ConfiguredEndpointCollection m_endpoints; private QueryServersFilter m_filters; private DataSet m_dataset; + private ITelemetryContext m_telemetry; private DataTable ServersTable { get { return m_dataset.Tables[0]; } } private DataTable EndpointsTable { get { return m_dataset.Tables[1]; } } @@ -251,15 +252,17 @@ private EndpointDescription GetSelectedEndpoint() } public void Initialize( - ConfiguredEndpointCollection endpoints, - LocalDiscoveryServerClient lds, - GlobalDiscoveryServerClient gds, - QueryServersFilter filters) + ConfiguredEndpointCollection endpoints, + LocalDiscoveryServerClient lds, + GlobalDiscoveryServerClient gds, + QueryServersFilter filters, + ITelemetryContext telemetry) { m_lds = lds; m_gds = gds; m_filters = filters; - + m_telemetry = telemetry; + DiscoveryTreeView.Nodes.Clear(); TreeNode node = new TreeNode("Local Machine"); @@ -371,7 +374,7 @@ private async void DiscoveryTreeView_BeforeExpand(object sender, TreeViewCancelE if (RootFolders.GlobalDiscovery.Equals(e.Node.Tag)) { - var servers = new ViewServersOnNetworkDialog(m_gds).ShowDialog(this, ref m_filters); + var servers = new ViewServersOnNetworkDialog(m_gds, m_telemetry).ShowDialog(this, ref m_filters); if (servers != null) { @@ -437,7 +440,7 @@ private async Task PopulateServersOnNetworkNodeAsync(TreeNode parent, uint start } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -476,10 +479,10 @@ private async Task PopulateServersNodeAsync(TreeNode parent, string discoveryUrl } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } - + private void ShowApplicationDescriptions(TreeNodeCollection nodes) { ServersTable.Rows.Clear(); @@ -718,7 +721,7 @@ private void DiscoveryTreeView_DoubleClick(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -840,7 +843,7 @@ private async void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArg { e.Node.Nodes.Clear(); - var servers = new ViewServersOnNetworkDialog(m_gds).ShowDialog(this, ref m_filters); + var servers = new ViewServersOnNetworkDialog(m_gds, m_telemetry).ShowDialog(this, ref m_filters); if (servers != null) { @@ -854,7 +857,7 @@ private async void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArg } } } - + ShowServerOnNetworks(e.Node.Nodes); return; @@ -878,15 +881,15 @@ private async void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArg ApplicationTypeTextBox.Text = application.ApplicationType.ToString(); ApplicationUriTextBox.Text = application.ApplicationUri; ProductUriTextBox.Text = application.ProductUri; - + string discoveryUrl = SelectDiscoveryUrl(application); - + if (discoveryUrl != null) { await LoadEndpointsAndShowAsync(e.Node, discoveryUrl); } } - + if (e.Node.Tag is ServerOnNetwork) { EndpointsTable.Rows.Clear(); @@ -928,7 +931,7 @@ private async void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArg } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -945,7 +948,7 @@ private async Task LoadEndpointsAndShowAsync(TreeNode parent, string discoveryUr } catch (Exception e) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, e); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, e); } } @@ -966,7 +969,7 @@ private void FilterTextBox_TextChanged(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -994,7 +997,7 @@ private void EndpointsGridView_DoubleClick(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -1011,7 +1014,7 @@ private void ServersGridView_DoubleClick(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } } diff --git a/Samples/GDS/ClientControls/Controls/DiscoveryUrlsDialog.cs b/Samples/GDS/ClientControls/Controls/DiscoveryUrlsDialog.cs index 7b822f6cf..da31bdd61 100644 --- a/Samples/GDS/ClientControls/Controls/DiscoveryUrlsDialog.cs +++ b/Samples/GDS/ClientControls/Controls/DiscoveryUrlsDialog.cs @@ -1,8 +1,8 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { @@ -43,9 +44,11 @@ public DiscoveryUrlsDialog() } private List m_discoveryUrls; + private ILogger m_logger = LoggerUtils.Null.Logger; - public List ShowDialog(IWin32Window owner, IList discoveryUrls) + public List ShowDialog(ILogger logger, IWin32Window owner, IList discoveryUrls) { + m_logger = logger; StringBuilder builder = new StringBuilder(); if (discoveryUrls != null) @@ -102,7 +105,7 @@ private void OkButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } diff --git a/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs b/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs index 433ce6733..81a3910a9 100644 --- a/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs +++ b/Samples/GDS/ClientControls/Controls/EditValueCtrl.cs @@ -40,6 +40,7 @@ using System.Reflection; using System.IO; using System.Runtime.Serialization; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { @@ -73,6 +74,7 @@ public EditValueCtrl() #endregion #region Private Fields + private ILogger m_logger = LoggerUtils.Null.Logger; private DataSet m_dataset; private AccessInfo m_value; private bool m_readOnly; @@ -294,7 +296,7 @@ public void SetArraySize() array = matrix.ToArray(); } - SetTypeDlg.SetTypeResult result = new SetTypeDlg().ShowDialog(currentType, dimensions); + SetTypeDlg.SetTypeResult result = new SetTypeDlg().ShowDialog(m_logger, currentType, dimensions); if (result == null) { @@ -621,10 +623,7 @@ private void ShowValue(AccessInfo parent) ShowValueNoNotify(parent); ValuesDV.ClearSelection(); - if (m_ValueChanged != null) - { - m_ValueChanged(this, null); - } + m_ValueChanged?.Invoke(this, null); } /// @@ -1581,7 +1580,7 @@ private void NavigationMenu_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -1599,7 +1598,7 @@ private void ValuesDV_DoubleClick(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -1627,7 +1626,7 @@ private void ValuesDV_CellValidating(object sender, DataGridViewCellValidatingEv } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); e.Cancel = true; } } @@ -1661,7 +1660,7 @@ private void ValuesDV_CellValueChanged(object sender, DataGridViewCellEventArgs } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } diff --git a/Samples/GDS/ClientControls/Controls/EditValueDlg.cs b/Samples/GDS/ClientControls/Controls/EditValueDlg.cs index 37dcd7e46..8bdc0a960 100644 --- a/Samples/GDS/ClientControls/Controls/EditValueDlg.cs +++ b/Samples/GDS/ClientControls/Controls/EditValueDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,7 @@ using System; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { @@ -53,8 +54,9 @@ public EditValueDlg() SetTypeCB.SelectedItem = BuiltInType.String; } #endregion - + #region Private Fields + private ILogger m_logger = LoggerUtils.Null.Logger; #endregion #region Public Interface @@ -62,12 +64,14 @@ public EditValueDlg() /// Prompts the user to edit the value. /// public object ShowDialog( + ILogger logger, TypeInfo expectedType, string name, object value, bool readOnly, string caption) { + m_logger = logger; if (!String.IsNullOrEmpty(caption)) { this.Text = caption; @@ -98,7 +102,7 @@ private void ValueCTRL_ValueChanged(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -110,7 +114,7 @@ private void BackBTN_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -123,7 +127,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -135,7 +139,7 @@ private void SetTypeBTN_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -147,7 +151,7 @@ private void SetTypeCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } #endregion diff --git a/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs b/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs index c70188302..51b8792da 100644 --- a/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs +++ b/Samples/GDS/ClientControls/Controls/SelectGdsDialog.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -43,10 +43,12 @@ public SelectGdsDialog() } private GlobalDiscoveryServerClient m_gds; + private ITelemetryContext m_telemetry; - public string ShowDialog(IWin32Window owner, GlobalDiscoveryServerClient gds, IList serverUrls) + public string ShowDialog(IWin32Window owner, GlobalDiscoveryServerClient gds, IList serverUrls, ITelemetryContext telemetry) { m_gds = gds; + m_telemetry = telemetry; ServersListBox.Items.Clear(); @@ -92,7 +94,7 @@ private async void OkButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; - var endpoint = await CoreClientUtils.SelectEndpointAsync(m_gds.Configuration, url, true, 5000); + var endpoint = await CoreClientUtils.SelectEndpointAsync(m_gds.Configuration, url, true, 5000, m_telemetry); if (UserNameCredentialsRB.Checked) { @@ -120,7 +122,7 @@ private async void OkButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } } diff --git a/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs b/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs index f36dfad2d..8bdf5a3ef 100644 --- a/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs +++ b/Samples/GDS/ClientControls/Controls/SelectPushServerDialog.cs @@ -43,10 +43,12 @@ public SelectPushServerDialog() } private ServerPushConfigurationClient m_pushServer; + private ITelemetryContext m_telemetry; - public string ShowDialog(IWin32Window owner, ServerPushConfigurationClient pushServer, IList serverUrls) + public string ShowDialog(IWin32Window owner, ServerPushConfigurationClient pushServer, IList serverUrls, ITelemetryContext telemetry) { m_pushServer = pushServer; + m_telemetry = telemetry; ServersListBox.Items.Clear(); @@ -92,7 +94,7 @@ private async void OkButton_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; - var endpoint = await CoreClientUtils.SelectEndpointAsync(m_pushServer.Configuration, url, false, 5000); + var endpoint = await CoreClientUtils.SelectEndpointAsync(m_pushServer.Configuration, url, false, 5000, m_telemetry); if (UserNameCredentialsRB.Checked) { @@ -120,7 +122,7 @@ private async void OkButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } diff --git a/Samples/GDS/ClientControls/Controls/SelectServerDialog.cs b/Samples/GDS/ClientControls/Controls/SelectServerDialog.cs index 4c2967fcc..93dee593f 100644 --- a/Samples/GDS/ClientControls/Controls/SelectServerDialog.cs +++ b/Samples/GDS/ClientControls/Controls/SelectServerDialog.cs @@ -1,4 +1,4 @@ -/* ======================================================================== +/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 @@ -45,9 +45,10 @@ public EndpointDescription ShowDialog( ConfiguredEndpointCollection endpoints, LocalDiscoveryServerClient lds, GlobalDiscoveryServerClient gds, - QueryServersFilter filters) + QueryServersFilter filters, + ITelemetryContext telemetry) { - this.DiscoveryControl.Initialize(endpoints, lds, gds, filters); + this.DiscoveryControl.Initialize(endpoints, lds, gds, filters, telemetry); if (base.ShowDialog(owner) != System.Windows.Forms.DialogResult.OK) { diff --git a/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs b/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs index 301dfce37..e4721fde0 100644 --- a/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs +++ b/Samples/GDS/ClientControls/Controls/ServerStatusControl.cs @@ -44,11 +44,13 @@ public ServerStatusControl() } private ServerPushConfigurationClient m_server; + private ITelemetryContext m_telemetry; - public Task InitializeAsync(ServerPushConfigurationClient server, CancellationToken ct = default) + public Task InitializeAsync(ServerPushConfigurationClient server, ITelemetryContext telemetry, CancellationToken ct = default) { m_server = server; - return ServerBrowseControl.InitializeAsync((server != null) ? server.Session as Session : null, Opc.Ua.ObjectIds.ObjectsFolder, ct, ReferenceTypeIds.HierarchicalReferences); + m_telemetry = telemetry; + return ServerBrowseControl.InitializeAsync((server != null) ? server.Session as Session : null, Opc.Ua.ObjectIds.ObjectsFolder, telemetry, ct, ReferenceTypeIds.HierarchicalReferences); } public void SetServerStatus(ServerStatusDataType status) @@ -102,7 +104,7 @@ private async void ApplyChangesButton_Click(object sender, EventArgs e) if (se == null || se.StatusCode != StatusCodes.BadServerHalted) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Parent.Text, exception); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Parent.Text, exception); } } diff --git a/Samples/GDS/ClientControls/Controls/SetTypeDlg.cs b/Samples/GDS/ClientControls/Controls/SetTypeDlg.cs index 5736ac26d..06c7f19f7 100644 --- a/Samples/GDS/ClientControls/Controls/SetTypeDlg.cs +++ b/Samples/GDS/ClientControls/Controls/SetTypeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { @@ -51,10 +52,11 @@ public SetTypeDlg() ErrorHandlingCB.Items.Add("Throw Exception"); } #endregion - + #region Private Fields private SetTypeResult m_result; private TypeInfo m_typeInfo; + private ILogger m_logger = LoggerUtils.Null.Logger; #endregion #region SetTypeResult Class @@ -89,17 +91,17 @@ public class SetTypeResult /// /// Displays the available areas in a tree view. /// - public SetTypeResult ShowDialog(TypeInfo typeInfo, int[] dimensions) + public SetTypeResult ShowDialog(ILogger logger, TypeInfo typeInfo, int[] dimensions) { m_typeInfo = typeInfo; - + m_logger = logger; StructureTypeLB.Visible = false; StructureTypeTB.Visible = false; ArrayDimensionsLB.Visible = dimensions != null; ArrayDimensionsTB.Visible = dimensions != null; ErrorHandlingCB.SelectedIndex = 0; - + StringBuilder builder = new StringBuilder(); // display the current dimensions. @@ -127,7 +129,7 @@ public SetTypeResult ShowDialog(TypeInfo typeInfo, int[] dimensions) return m_result; } #endregion - + #region Private Methods #endregion @@ -170,7 +172,7 @@ private void OkBTN_Click(object sender, EventArgs e) dimensions.Add(dimension); } - + // save the result. int valueRank = (dimensions.Count < 1) ? ValueRanks.Scalar : dimensions.Count; @@ -183,7 +185,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } #endregion diff --git a/Samples/GDS/ClientControls/Controls/TrustListControl.cs b/Samples/GDS/ClientControls/Controls/TrustListControl.cs index acc2ec25f..a462ff37b 100644 --- a/Samples/GDS/ClientControls/Controls/TrustListControl.cs +++ b/Samples/GDS/ClientControls/Controls/TrustListControl.cs @@ -37,6 +37,7 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Security.Certificates; namespace Opc.Ua.Gds.Client.Controls @@ -67,6 +68,8 @@ public CertificateStoreControl() CertificateListGridView.DataSource = m_dataset.Tables[0]; } + private ITelemetryContext m_telemetry; + private ILogger m_logger = LoggerUtils.Null.Logger; private DataSet m_dataset; private FileInfo m_certificateFile; private string m_trustedStorePath; @@ -85,12 +88,14 @@ private enum Status private ICertificateStore CreateStore(string storePath) { CertificateStoreIdentifier certificateStoreIdentifier = new CertificateStoreIdentifier(storePath); - ICertificateStore store = certificateStoreIdentifier.OpenStore(); - return store; + return certificateStoreIdentifier.OpenStore(m_telemetry); } - public async Task Initialize(string trustedStorePath, string issuerStorePath, string rejectedStorePath, CancellationToken ct = default) + public async Task Initialize(ITelemetryContext telemetry, string trustedStorePath, string issuerStorePath, string rejectedStorePath, CancellationToken ct = default) { + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(nameof(CertificateStoreControl)); + CertificatesTable.Rows.Clear(); m_trustedStorePath = trustedStorePath; @@ -412,13 +417,13 @@ private void ViewMenuItem_Click(object sender, EventArgs e) { Size = new Size(800, 400) }; - dialog.ShowDialog(null, "", new CertificateWrapper() { Certificate = (X509Certificate2)source.Row[7] }, true, this.Text); + dialog.ShowDialog(m_logger, null, "", new CertificateWrapper() { Certificate = (X509Certificate2)source.Row[7] }, true, this.Text); break; } } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -445,7 +450,7 @@ private void DeleteMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -464,7 +469,7 @@ private void TrustMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -483,7 +488,7 @@ private void Reject_MenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -502,7 +507,7 @@ private void UntrustMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -538,7 +543,7 @@ private void ImportMenuItem_Click(object sender, EventArgs e) m_certificateFile = new FileInfo(dialog.FileName); - X509Certificate2 certificate = CertificateFactory.Load(new X509Certificate2(File.ReadAllBytes(dialog.FileName)), false); + X509Certificate2 certificate = new X509Certificate2(File.ReadAllBytes(dialog.FileName)); if (certificate != null) { @@ -556,7 +561,7 @@ private void ImportMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -607,7 +612,7 @@ private void ExportMenuItem_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } diff --git a/Samples/GDS/ClientControls/Controls/TrustListDialog.cs b/Samples/GDS/ClientControls/Controls/TrustListDialog.cs index 9e8e30cc4..cfc8a945b 100644 --- a/Samples/GDS/ClientControls/Controls/TrustListDialog.cs +++ b/Samples/GDS/ClientControls/Controls/TrustListDialog.cs @@ -41,9 +41,10 @@ public CertificatesStoreDialog() Icon = ImageListControl.AppIcon; } - public async Task ShowDialogAsync(ApplicationConfiguration configuration, CancellationToken ct = default) + public async Task ShowDialogAsync(ApplicationConfiguration configuration, ITelemetryContext telemetry, CancellationToken ct = default) { await CertificatesControl.Initialize( + telemetry, configuration.SecurityConfiguration.TrustedPeerCertificates.StorePath, configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath, configuration.SecurityConfiguration.RejectedCertificateStore.StorePath, diff --git a/Samples/GDS/ClientControls/Controls/UserIdentityDialog.cs b/Samples/GDS/ClientControls/Controls/UserIdentityDialog.cs index c97804933..0c036e593 100644 --- a/Samples/GDS/ClientControls/Controls/UserIdentityDialog.cs +++ b/Samples/GDS/ClientControls/Controls/UserIdentityDialog.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -28,7 +28,9 @@ * ======================================================================*/ using System; +using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { @@ -46,13 +48,15 @@ public UserIdentityDialog() InitializeComponent(); } #endregion - + #region Private Fields + private ILogger m_logger = LoggerUtils.Null.Logger; #endregion #region Public Interface - public UserIdentity ShowDialog(IWin32Window owner, string caption, UserIdentity identity) + public UserIdentity ShowDialog(ILogger logger, IWin32Window owner, string caption, UserIdentity identity) { + m_logger = logger; if (!String.IsNullOrEmpty(caption)) { InstructuctionsLabel.Text = caption; @@ -69,7 +73,7 @@ public UserIdentity ShowDialog(IWin32Window owner, string caption, UserIdentity if (token != null) { UserNameTextBox.Text = token.UserName; - PasswordTextBox.Text = token.DecryptedPassword; + PasswordTextBox.Text = Encoding.UTF8.GetString(token.DecryptedPassword); } } @@ -78,10 +82,10 @@ public UserIdentity ShowDialog(IWin32Window owner, string caption, UserIdentity return null; } - return new UserIdentity(UserNameTextBox.Text.Trim(), PasswordTextBox.Text.Trim()); + return new UserIdentity(UserNameTextBox.Text.Trim(), Encoding.UTF8.GetBytes(PasswordTextBox.Text.Trim())); } #endregion - + #region Private Methods #endregion @@ -101,7 +105,7 @@ private void OkButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } #endregion diff --git a/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs b/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs index 1bfe9ca88..bde9c7663 100644 --- a/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs +++ b/Samples/GDS/ClientControls/Controls/ViewApplicationRecordsDialog.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -32,6 +32,7 @@ using System.Data; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua.Client.Controls; namespace Opc.Ua.Gds.Client.Controls @@ -62,10 +63,12 @@ public ViewApplicationRecordsDialog(GlobalDiscoveryServerClient gds) private DataTable ApplicationsTable { get { return m_dataset.Tables[0]; } } private DataSet m_dataset; + private ILogger m_logger = LoggerUtils.Null.Logger; private GlobalDiscoveryServerClient m_gds; - public ApplicationRecordDataType ShowDialog(IWin32Window owner, IList records, NodeId defaultRecord) + public ApplicationRecordDataType ShowDialog(ILogger logger, IWin32Window owner, IList records, NodeId defaultRecord) { + m_logger = logger; ApplicationsTable.Rows.Clear(); DataRow selectedRow = null; @@ -186,7 +189,7 @@ private async void UnregisterButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } @@ -199,7 +202,7 @@ private void ApplicationRecordDataGridView_SelectionChanged(object sender, Event } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_logger, Text, ex); } } } diff --git a/Samples/GDS/ClientControls/Controls/ViewServersOnNetworkDialog.cs b/Samples/GDS/ClientControls/Controls/ViewServersOnNetworkDialog.cs index c13849c10..4f0434493 100644 --- a/Samples/GDS/ClientControls/Controls/ViewServersOnNetworkDialog.cs +++ b/Samples/GDS/ClientControls/Controls/ViewServersOnNetworkDialog.cs @@ -34,18 +34,21 @@ using System.Windows.Forms; using Opc.Ua.Client.Controls; using System.Linq; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Gds.Client.Controls { public partial class ViewServersOnNetworkDialog : Form { - public ViewServersOnNetworkDialog(GlobalDiscoveryServerClient gds) + public ViewServersOnNetworkDialog(GlobalDiscoveryServerClient gds, ITelemetryContext telemetry) { InitializeComponent(); Icon = ClientUtils.GetAppIcon(); ServersDataGridView.AutoGenerateColumns = false; m_gds = gds; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); m_dataset = new DataSet(); m_dataset.Tables.Add("Servers"); @@ -61,7 +64,9 @@ public ViewServersOnNetworkDialog(GlobalDiscoveryServerClient gds) private DataTable ServersTable { get { return m_dataset.Tables[0]; } } private DataSet m_dataset; + private ILogger m_logger; private GlobalDiscoveryServerClient m_gds; + private ITelemetryContext m_telemetry; public List ShowDialog(IWin32Window owner, ref QueryServersFilter filters) { @@ -99,7 +104,7 @@ private void ApplicationRecordDataGridView_SelectionChanged(object sender, Event } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -111,7 +116,7 @@ private async void SearchButton_Click(object sender, EventArgs e) if (!m_gds.IsConnected) { - new SelectGdsDialog().ShowDialog(null, m_gds, await m_gds.GetDefaultGdsUrlsAsync(null)); + new SelectGdsDialog().ShowDialog(null, m_gds, await m_gds.GetDefaultGdsUrlsAsync(null), m_telemetry); } uint maxNoOfRecords = (uint)NumberOfRecordsUpDown.Value; @@ -185,7 +190,7 @@ private async void SearchButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -255,7 +260,7 @@ private void NextButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -271,7 +276,7 @@ private void StopButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -288,7 +293,7 @@ private void SearchButton_Reset(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } @@ -322,7 +327,7 @@ private void ServerCapabilitiesButton_Click(object sender, EventArgs e) } catch (Exception ex) { - Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); + Opc.Ua.Client.Controls.ExceptionDlg.Show(m_telemetry, Text, ex); } } diff --git a/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj b/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj index 7d8e5f44b..ef0267f27 100644 --- a/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj +++ b/Samples/GDS/ClientControls/GlobalDiscoveryClientControls.csproj @@ -219,10 +219,10 @@ - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj b/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj index 463bc7522..af7f463d8 100644 --- a/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj +++ b/Samples/GDS/ConsoleServer/NetCoreGlobalDiscoveryServer.csproj @@ -12,10 +12,11 @@ + - - + + diff --git a/Samples/GDS/ConsoleServer/Program.cs b/Samples/GDS/ConsoleServer/Program.cs index 02eb7d7df..81c9214e2 100644 --- a/Samples/GDS/ConsoleServer/Program.cs +++ b/Samples/GDS/ConsoleServer/Program.cs @@ -35,6 +35,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Mono.Options; using Opc.Ua.Configuration; using Opc.Ua.Gds.Server.Database.Linq; @@ -137,9 +138,24 @@ public static async Task Main(string[] args) } } + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } + public class NetCoreGlobalDiscoveryServer { private GlobalDiscoverySampleServer server; + private readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); private Task status; private DateTime lastEventTime; public static ExitCode exitCode; @@ -150,17 +166,17 @@ public NetCoreGlobalDiscoveryServer() public async Task RunAsync() { - try { exitCode = ExitCode.ErrorServerNotStarted; - await ConsoleGlobalDiscoveryServerAsync().ConfigureAwait(false); + await ConsoleGlobalDiscoveryServerAsync(m_telemetry).ConfigureAwait(false); Console.WriteLine("Server started. Press Ctrl-C to exit..."); exitCode = ExitCode.ErrorServerRunning; } catch (Exception ex) { - Utils.Trace("ServiceResultException:" + ex.Message); + m_telemetry.CreateLogger() + .LogError("ServiceResultException:" + ex.Message); Console.WriteLine("Exception: {0}", ex.Message); exitCode = ExitCode.ErrorServerException; return; @@ -170,7 +186,8 @@ public async Task RunAsync() { try { - Console.CancelKeyPress += (sender, eArgs) => { + Console.CancelKeyPress += (sender, eArgs) => + { quitEvent.Set(); eArgs.Cancel = true; }; @@ -193,7 +210,7 @@ public async Task RunAsync() server = null; await status.ConfigureAwait(false); // Stop server and dispose - _server.Stop(); + await _server.StopAsync(); } } @@ -212,10 +229,11 @@ private static void CertificateValidator_CertificateValidation(CertificateValida } } - private async Task ConsoleGlobalDiscoveryServerAsync() + private async Task ConsoleGlobalDiscoveryServerAsync(ITelemetryContext telemetry) { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - var application = new ApplicationInstance { + var application = new ApplicationInstance(telemetry) + { ApplicationName = "Global Discovery Server", ApplicationType = ApplicationType.Server, ConfigSectionName = "Opc.Ua.GlobalDiscoveryServer" @@ -242,7 +260,7 @@ private async Task ConsoleGlobalDiscoveryServerAsync() string userdatabaseStorePath = Utils.ReplaceSpecialFolderNames(gdsConfiguration.UsersDatabaseStorePath); var database = JsonApplicationsDatabase.Load(databaseStorePath); - var userDatabase = JsonUserDatabase.Load(userdatabaseStorePath); + var userDatabase = JsonUserDatabase.Load(userdatabaseStorePath, telemetry); bool createStandardUsers = ConfigureUsers(userDatabase); @@ -250,10 +268,9 @@ private async Task ConsoleGlobalDiscoveryServerAsync() server = new GlobalDiscoverySampleServer( database, database, - new CertificateGroup(), + new CertificateGroup(telemetry), userDatabase, - true, - createStandardUsers); + true); await application.StartAsync(server).ConfigureAwait(false); // print endpoint info @@ -273,7 +290,7 @@ private async Task ConsoleGlobalDiscoveryServerAsync() } - private bool ConfigureUsers(JsonUserDatabase userDatabase) + private bool ConfigureUsers(IUserDatabase userDatabase) { ApplicationInstance.MessageDlg.Message("Use default users?", true); bool createStandardUsers = ApplicationInstance.MessageDlg.ShowAsync().GetAwaiter().GetResult(); @@ -299,10 +316,10 @@ private bool ConfigureUsers(JsonUserDatabase userDatabase) _ = password ?? throw new ArgumentNullException("Password is not allowed to be empty"); //create User, if User exists delete & recreate - if (!userDatabase.CreateUser(username, password, new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin })) + if (!userDatabase.CreateUser(username, Encoding.UTF8.GetBytes(password), new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin })) { userDatabase.DeleteUser(username); - userDatabase.CreateUser(username, password, new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin }); + userDatabase.CreateUser(username, Encoding.UTF8.GetBytes(password), new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin }); } } return createStandardUsers; diff --git a/Samples/GDS/Server/GlobalDiscoveryServer.csproj b/Samples/GDS/Server/GlobalDiscoveryServer.csproj index 017dae0fe..fad3bc000 100644 --- a/Samples/GDS/Server/GlobalDiscoveryServer.csproj +++ b/Samples/GDS/Server/GlobalDiscoveryServer.csproj @@ -7,7 +7,7 @@ 2.0 PackageReference true - {2E23571F-9987-4EBD-A9FD-5D5DD639E071} + {7148B244-B5A3-8F10-C50F-41B165904823} WinExe Properties Opc.Ua.Gds.Server @@ -234,11 +234,14 @@ 6.5.1 + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/GDS/Server/Program.cs b/Samples/GDS/Server/Program.cs index f782a8a34..3c14c3319 100644 --- a/Samples/GDS/Server/Program.cs +++ b/Samples/GDS/Server/Program.cs @@ -36,11 +36,27 @@ using System; using System.Collections.Generic; using System.Data.Entity; +using System.Text; namespace Opc.Ua.Gds.Server { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -52,7 +68,7 @@ static void Main() System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance + ApplicationInstance application = new ApplicationInstance(m_telemetry) { ApplicationType = ApplicationType.Server, ConfigSectionName = "Opc.Ua.GlobalDiscoveryServer" @@ -70,11 +86,11 @@ static void Main() throw new Exception("Application instance certificate invalid!"); } - + ILogger logger = m_telemetry.CreateLogger(); // load the user database. var userDatabase = new SqlUsersDatabase(); //initialize users Database - userDatabase.Initialize(); + userDatabase.Initialize(logger); bool createStandardUsers = ConfigureUsers(userDatabase); @@ -84,18 +100,17 @@ static void Main() var server = new GlobalDiscoverySampleServer( database, database, - new CertificateGroup(), + new CertificateGroup(m_telemetry), userDatabase, - true, - createStandardUsers); + true); application.StartAsync(server).Wait(); // run the application interactively. - System.Windows.Forms.Application.Run(new ServerForm(server, application.ApplicationConfiguration)); + System.Windows.Forms.Application.Run(new ServerForm(server, application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } @@ -122,10 +137,10 @@ private static bool ConfigureUsers(SqlUsersDatabase userDatabase) _ = password ?? throw new ArgumentNullException("Password is not allowed to be empty"); //create User, if User exists delete & recreate - if (!userDatabase.CreateUser(username, password, new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin })) + if (!userDatabase.CreateUser(username, Encoding.UTF8.GetBytes(password), new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin })) { userDatabase.DeleteUser(username); - userDatabase.CreateUser(username, password, new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin }); + userDatabase.CreateUser(username, Encoding.UTF8.GetBytes(password), new List() { Role.AuthenticatedUser, GdsRole.CertificateAuthorityAdmin, GdsRole.DiscoveryAdmin }); } } return createStandardUsers; diff --git a/Samples/GDS/Server/SqlApplicationsDatabase.cs b/Samples/GDS/Server/SqlApplicationsDatabase.cs index 050ddedfd..82c1a40b3 100644 --- a/Samples/GDS/Server/SqlApplicationsDatabase.cs +++ b/Samples/GDS/Server/SqlApplicationsDatabase.cs @@ -561,7 +561,7 @@ public override bool SetApplicationCertificate( { Guid id = GetNodeIdGuid(applicationId); - if (certificateTypeId.Equals(nameof(Ua.ObjectTypeIds.UserCredentialCertificateType), StringComparison.OrdinalIgnoreCase)) + if (certificateTypeId.Equals(nameof(Ua.ObjectTypeIds.UserCertificateType), StringComparison.OrdinalIgnoreCase)) { return false; } @@ -605,7 +605,7 @@ public override bool GetApplicationCertificate( List certificates = new List(); - if (certificateTypeId.Equals(nameof(Ua.ObjectTypeIds.UserCredentialCertificateType), StringComparison.OrdinalIgnoreCase)) + if (certificateTypeId.Equals(nameof(Ua.ObjectTypeIds.UserCertificateType), StringComparison.OrdinalIgnoreCase)) { return false; } @@ -754,7 +754,7 @@ public NodeId StartNewKeyPairRequest( string subjectName, string[] domainNames, string privateKeyFormat, - string privateKeyPassword, + ReadOnlySpan privateKeyPassword, string authorityId) { Guid id = GetNodeIdGuid(applicationId); @@ -784,7 +784,7 @@ public NodeId StartNewKeyPairRequest( request.SubjectName = subjectName; request.DomainNames = JsonConvert.SerializeObject(domainNames); request.PrivateKeyFormat = privateKeyFormat; - request.PrivateKeyPassword = privateKeyPassword; + request.PrivateKeyPassword = privateKeyPassword.ToString(); request.CertificateSigningRequest = null; if (isNew) @@ -909,7 +909,7 @@ public CertificateRequestState ReadRequest( out string subjectName, out string[] domainNames, out string privateKeyFormat, - out string privateKeyPassword) + out ReadOnlySpan privateKeyPassword) { certificateGroupId = null; certificateTypeId = null; @@ -950,7 +950,7 @@ public CertificateRequestState ReadRequest( subjectName = request.SubjectName; domainNames = request.DomainNames != null ? JsonConvert.DeserializeObject(request.DomainNames) : null; privateKeyFormat = request.PrivateKeyFormat; - privateKeyPassword = request.PrivateKeyPassword; + privateKeyPassword = request.PrivateKeyPassword.AsSpan(); entities.SaveChanges(); return CertificateRequestState.Approved; diff --git a/Samples/GDS/Server/SqlUsersDatabase.cs b/Samples/GDS/Server/SqlUsersDatabase.cs index 97c8f6c1d..d9f3a26cf 100644 --- a/Samples/GDS/Server/SqlUsersDatabase.cs +++ b/Samples/GDS/Server/SqlUsersDatabase.cs @@ -5,6 +5,8 @@ using System.Linq; using System.Reflection; using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua.Gds.Server.Database.Sql; using Opc.Ua.Gds.Server.DB; using Opc.Ua.Server; @@ -12,52 +14,54 @@ namespace Opc.Ua.Gds.Server { - public class SqlUsersDatabase: IUserDatabase + public class SqlUsersDatabase : IUserDatabase { #region IUsersDatabase - public void Initialize() + public void Initialize(ILogger logger) { using (usersdbEntities entities = new usersdbEntities()) { //only run initizailation logic if the database does not work -> throwS an exception try { - CheckCredentials("Test", "Test"); + CheckCredentials("Test", Encoding.UTF8.GetBytes("Test")); } catch (Exception e) { - Utils.LogError(e, "Could not connect to the Database!"); + logger.LogError(e, "Could not connect to the Database!"); var ie = e.InnerException; while (ie != null) { - Utils.LogInfo(ie, ""); + logger.LogInformation(ie, ""); ie = ie.InnerException; } - Utils.LogInfo("Initialize Database tables!"); + logger.LogInformation("Initialize Database tables!"); Assembly assembly = typeof(SqlApplicationsDatabase).GetTypeInfo().Assembly; StreamReader istrm = new StreamReader(assembly.GetManifestResourceStream("Opc.Ua.Gds.Server.DB.usersdb.edmx.sql")); string tables = istrm.ReadToEnd(); entities.Database.Initialize(true); entities.Database.CreateIfNotExists(); var parts = tables.Split(new string[] { "GO" }, System.StringSplitOptions.None); - foreach (var part in parts) { entities.Database.ExecuteSqlCommand(part); } + foreach (var part in parts) + { entities.Database.ExecuteSqlCommand(part); } entities.SaveChanges(); - Utils.LogInfo("Database Initialized!"); + logger.LogInformation("Database Initialized!"); } - + } } - public bool CreateUser(string userName, string password, IEnumerable roles) + public bool CreateUser(string userName, ReadOnlySpan password, ICollection roles) { + string passwordString = password.ToString(); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("UserName cannot be empty.", nameof(userName)); } - if (string.IsNullOrEmpty(password)) + if (string.IsNullOrEmpty(passwordString)) { throw new ArgumentException("Password cannot be empty.", nameof(password)); } @@ -69,7 +73,7 @@ public bool CreateUser(string userName, string password, IEnumerable roles return false; } - string hash = Hash(password); + string hash = Hash(passwordString); var sqlRoles = new List(); foreach (var role in roles) @@ -84,7 +88,7 @@ public bool CreateUser(string userName, string password, IEnumerable roles entities.SaveChanges(); return true; - } + } } public bool DeleteUser(string userName) @@ -107,13 +111,15 @@ public bool DeleteUser(string userName) } } - public bool CheckCredentials(string userName, string password) + public bool CheckCredentials(string userName, ReadOnlySpan password) { + string passwordString = password.ToString(); + if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("UserName cannot be empty.", nameof(userName)); } - if (string.IsNullOrEmpty(password)) + if (string.IsNullOrEmpty(passwordString)) { throw new ArgumentException("Password cannot be empty.", nameof(password)); } @@ -126,11 +132,11 @@ public bool CheckCredentials(string userName, string password) return false; } - return Check(user.Hash, password); + return Check(user.Hash, passwordString); } } - public IEnumerable GetUserRoles(string userName) + public ICollection GetUserRoles(string userName) { if (string.IsNullOrEmpty(userName)) { @@ -155,17 +161,20 @@ public IEnumerable GetUserRoles(string userName) } } - public bool ChangePassword(string userName, string oldPassword, string newPassword) + public bool ChangePassword(string userName, ReadOnlySpan oldPassword, ReadOnlySpan newPassword) { + string oldPasswordString = oldPassword.ToString(); + string newPasswordString = newPassword.ToString(); + if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("UserName cannot be empty.", nameof(userName)); } - if (string.IsNullOrEmpty(oldPassword)) + if (string.IsNullOrEmpty(oldPasswordString)) { throw new ArgumentException("Current Password cannot be empty.", nameof(oldPassword)); } - if (string.IsNullOrEmpty(newPassword)) + if (string.IsNullOrEmpty(newPasswordString)) { throw new ArgumentException("New Password cannot be empty.", nameof(newPassword)); } @@ -179,9 +188,9 @@ public bool ChangePassword(string userName, string oldPassword, string newPasswo return false; } - if (Check(user.Hash, oldPassword)) + if (Check(user.Hash, oldPasswordString)) { - var newHash = Hash(newPassword); + var newHash = Hash(newPasswordString); user.Hash = newHash; entities.SaveChanges(); return true; @@ -258,7 +267,7 @@ private bool Check(string hash, string password) #endregion #region Internal Members - + #endregion #region Internal Fields diff --git a/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs b/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs index 9f6acc759..9536ee4ca 100644 --- a/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs +++ b/Samples/Opc.Ua.Sample/Base/CustomNodeManager.cs @@ -36,6 +36,7 @@ using System.Threading; using System.Reflection; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Sample { @@ -52,6 +53,7 @@ public CustomNodeManager2(IServerInternal server) { // save a reference to the server that owns the node manager. m_server = server; + m_logger = server.Telemetry.CreateLogger(); // create the default context. m_systemContext = m_server.DefaultSystemContext.Copy(); @@ -1941,7 +1943,7 @@ protected virtual ServiceResult Call( if (ServiceResult.IsBad(argumentError)) { argumentsValid = false; - result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable)); + result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable, Server.Telemetry.CreateLogger())); } else { @@ -2205,7 +2207,7 @@ public virtual void CreateMonitoredItems( IList filterErrors, IList monitoredItems, bool createDurable, - ref long globalIdCounter) + MonitoredItemIdFactory globalIdCounter) { ServerSystemContext systemContext = m_systemContext.Copy(context); IDictionary operationCache = new NodeIdDictionary(); @@ -2263,7 +2265,7 @@ public virtual void CreateMonitoredItems( context.DiagnosticsMask, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterError, out monitoredItem); @@ -2309,7 +2311,7 @@ public virtual void CreateMonitoredItems( context.DiagnosticsMask, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterError, out monitoredItem); @@ -2421,7 +2423,7 @@ protected virtual ServiceResult CreateMonitoredItem( DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, - ref long globalIdCounter, + MonitoredItemIdFactory globalIdCounter, out MonitoringFilterResult filterError, out IMonitoredItem monitoredItem) { @@ -2481,7 +2483,7 @@ protected virtual ServiceResult CreateMonitoredItem( } // create a globally unique identifier. - uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter); + uint monitoredItemId = globalIdCounter.GetNextId(); // determine the sampling interval. double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval; @@ -2649,7 +2651,7 @@ private void DoSample(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error during diagnostics scan."); + m_logger.LogError(e, "Unexpected error during diagnostics scan."); } } @@ -3097,6 +3099,7 @@ public void RestoreMonitoredItems(IList itemsToRestore, IL #region Private Fields private object m_lock = new object(); private IServerInternal m_server; + private readonly ILogger m_logger; private ServerSystemContext m_systemContext; private IList m_namespaceUris; private ushort[] m_namespaceIndexes; diff --git a/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs b/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs index 1a70ec592..f4d98a60e 100644 --- a/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs +++ b/Samples/Opc.Ua.Sample/Base/DataChangeMonitoredItem.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,6 +30,8 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua.Server; namespace Opc.Ua.Sample @@ -94,6 +96,7 @@ public DataChangeMonitoredItem( bool alwaysReportUpdates) { m_source = source; + m_logger = source.Server.Telemetry.CreateLogger(); m_id = id; m_attributeId = attributeId; m_indexRange = indexRange; @@ -252,7 +255,7 @@ public ServiceResult Modify( m_samplingInterval = samplingInterval; - // calculate the next sampling interval. + // calculate the next sampling interval. long newSamplingInterval = (long)(m_samplingInterval * TimeSpan.TicksPerMillisecond); if (m_samplingInterval > 0) @@ -784,9 +787,9 @@ private void Publish( if (error != null) { error = new ServiceResult( - error.StatusCode.SetSemanticsChanged(true), - error.SymbolicId, error.NamespaceUri, + new StatusCode(error.StatusCode.SetSemanticsChanged(true).Code, + error.SymbolicId), error.LocalizedText, error.AdditionalInfo, error.InnerResult); @@ -806,9 +809,10 @@ private void Publish( if (error != null) { error = new ServiceResult( - error.StatusCode.SetStructureChanged(true), - error.SymbolicId, error.NamespaceUri, + new StatusCode( + error.StatusCode.SetStructureChanged(true).Code, + error.SymbolicId), error.LocalizedText, error.AdditionalInfo, error.InnerResult); @@ -843,14 +847,19 @@ private void Publish( { if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0) { - diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError); + diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError, m_logger); } } diagnostics.Enqueue(diagnosticInfo); } - public bool Publish(OperationContext context, Queue notifications, Queue diagnostics, uint maxNotificationsPerPublish) + public bool Publish( + OperationContext context, + Queue notifications, + Queue diagnostics, + uint maxNotificationsPerPublish, + ILogger logger) { return Publish(context, notifications, diagnostics); } @@ -869,6 +878,7 @@ public void Dispose() #region Private Fields private object m_lock = new object(); private MonitoredNode m_source; + private readonly ILogger m_logger; private ISubscription m_subscription; private uint m_id; private DataValue m_lastValue; diff --git a/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs b/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs index 5804eec82..33f8e99c0 100644 --- a/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs +++ b/Samples/Opc.Ua.Sample/Base/MonitoredItemQueue.cs @@ -381,9 +381,10 @@ private void SetOverflowBit(ref DataValue value, ref ServiceResult error) // have to copy before updating because the ServiceResult is invariant. ServiceResult copy = new ServiceResult( - status, - error.SymbolicId, error.NamespaceUri, + new StatusCode( + status.Code, + error.SymbolicId), error.LocalizedText, error.AdditionalInfo, error.InnerResult); diff --git a/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs b/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs index 5ad6bef8a..a83126d68 100644 --- a/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs +++ b/Samples/Opc.Ua.Sample/Base/SampleNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2022 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,7 @@ using System.Reflection; using Opc.Ua.Server; using System.Linq; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Sample { @@ -49,6 +50,7 @@ public SampleNodeManager(IServerInternal server) { // save a reference to the server that owns the node manager. m_server = server; + m_logger = server.Telemetry.CreateLogger(); // create the default context. m_systemContext = m_server.DefaultSystemContext.Copy(); @@ -56,7 +58,7 @@ public SampleNodeManager(IServerInternal server) m_systemContext.SystemHandle = null; m_systemContext.NodeIdFactory = this; - // create the table of nodes. + // create the table of nodes. m_predefinedNodes = new NodeIdDictionary(); m_rootNotifiers = new List(); m_sampledItems = new List(); @@ -340,7 +342,7 @@ protected set /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public virtual void CreateAddressSpace(IDictionary> externalReferences) { @@ -518,7 +520,7 @@ protected virtual void RemovePredefinedNode( /// protected virtual void OnNodeRemoved(NodeState node) { - // overridden by the sub-class. + // overridden by the sub-class. } /// @@ -722,7 +724,7 @@ protected void AddTypesToTypeTree(NodeId typeId) } /// - /// Finds the specified and checks if it is of the expected type. + /// Finds the specified and checks if it is of the expected type. /// /// Returns null if not found or not of the correct type. public NodeState FindPredefinedNode(NodeId nodeId, Type expectedType) @@ -766,7 +768,7 @@ public virtual void DeleteAddressSpace() /// Returns a unique handle for the node. /// /// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -782,7 +784,7 @@ public virtual object GetManagerHandle(NodeId nodeId) /// Returns a unique handle for the node. /// /// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -1031,7 +1033,7 @@ public virtual void Browse( // apply filters to references. for (IReference reference = browser.Next(); reference != null; reference = browser.Next()) { - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = GetReferenceDescription(context, reference, continuationPoint); if (description == null) @@ -1065,7 +1067,7 @@ private ReferenceDescription GetReferenceDescription( IReference reference, ContinuationPoint continuationPoint) { - // create the type definition reference. + // create the type definition reference. ReferenceDescription description = new ReferenceDescription(); description.NodeId = reference.TargetId; @@ -1147,9 +1149,9 @@ private ReferenceDescription GetReferenceDescription( /// Returns the target of the specified browse path fragment(s). /// /// - /// If reference exists but the node manager does not know the browse name it must + /// If reference exists but the node manager does not know the browse name it must /// return the NodeId as an unresolvedTargetIds. The caller will try to check the - /// browse name. + /// browse name. /// public virtual void TranslateBrowsePath( OperationContext context, @@ -1946,7 +1948,7 @@ protected virtual ServiceResult Call( if (ServiceResult.IsBad(argumentError)) { argumentsValid = false; - result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable)); + result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable, Server.Telemetry.CreateLogger())); } else { @@ -1975,8 +1977,8 @@ protected virtual ServiceResult Call( /// Subscribes or unsubscribes to events produced by the specified source. /// /// - /// This method is called when a event subscription is created or deletes. The node manager - /// must start/stop reporting events for the specified object and all objects below it in + /// This method is called when a event subscription is created or deletes. The node manager + /// must start/stop reporting events for the specified object and all objects below it in /// the notifier hierarchy. /// public virtual ServiceResult SubscribeToEvents( @@ -2041,7 +2043,7 @@ public virtual ServiceResult SubscribeToEvents( /// Subscribes or unsubscribes to events produced by all event sources. /// /// - /// This method is called when a event subscription is created or deleted. The node + /// This method is called when a event subscription is created or deleted. The node /// manager must start/stop reporting events for all objects that it manages. /// public virtual ServiceResult SubscribeToAllEvents( @@ -2208,7 +2210,7 @@ public virtual void CreateMonitoredItems( IList filterErrors, IList monitoredItems, bool createDurable, - ref long globalIdCounter) + MonitoredItemIdFactory globalIdCounter) { ServerSystemContext systemContext = m_systemContext.Copy(context); IDictionary operationCache = new NodeIdDictionary(); @@ -2266,7 +2268,7 @@ public virtual void CreateMonitoredItems( context.DiagnosticsMask, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterError, out monitoredItem); @@ -2312,7 +2314,7 @@ public virtual void CreateMonitoredItems( context.DiagnosticsMask, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterError, out monitoredItem); @@ -2459,7 +2461,7 @@ protected virtual ServiceResult CreateMonitoredItem( DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, - ref long globalIdCounter, + MonitoredItemIdFactory globalIdCounter, out MonitoringFilterResult filterError, out IMonitoredItem monitoredItem) { @@ -2527,7 +2529,7 @@ protected virtual ServiceResult CreateMonitoredItem( } // create a globally unique identifier. - uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter); + uint monitoredItemId = globalIdCounter.GetNextId(); // determine the sampling interval. double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval; @@ -2644,7 +2646,7 @@ private void DeleteSampledItem(DataChangeMonitoredItem monitoredItem) } /// - /// Polls each monitored item which requires sample. + /// Polls each monitored item which requires sample. /// private void DoSample(object state) { @@ -2665,7 +2667,7 @@ private void DoSample(object state) } catch (Exception e) { - Utils.LogError(e, "Unexpected error during diagnostics scan."); + m_logger.LogError(e, "Unexpected error during diagnostics scan."); } } @@ -3096,6 +3098,7 @@ public void RestoreMonitoredItems(IList itemsToRestore, IL #region Private Fields private object m_lock = new object(); private IServerInternal m_server; + protected readonly ILogger m_logger; private ServerSystemContext m_systemContext; private IList m_namespaceUris; private ushort[] m_namespaceIndexes; diff --git a/Samples/Opc.Ua.Sample/Boiler/Boiler.Classes.cs b/Samples/Opc.Ua.Sample/Boiler/Boiler.Classes.cs index e06338dd1..93b0afb1c 100644 --- a/Samples/Opc.Ua.Sample/Boiler/Boiler.Classes.cs +++ b/Samples/Opc.Ua.Sample/Boiler/Boiler.Classes.cs @@ -33,6 +33,7 @@ using System.Xml; using System.Runtime.Serialization; using Opc.Ua; +using Microsoft.Extensions.Logging; namespace Boiler { @@ -2272,8 +2273,9 @@ public partial class BoilerState : BaseObjectState /// /// Initializes the type with its default attribute values. /// - public BoilerState(NodeState parent) : base(parent) + public BoilerState(NodeState parent, ILogger logger) : base(parent) { + m_logger = logger; } /// @@ -2739,8 +2741,9 @@ protected override BaseInstanceState FindChild( private LevelControllerState m_levelController; private CustomControllerState m_customController; private BoilerStateMachineState m_simulation; + private readonly ILogger m_logger; #endregion } #endif #endregion -} \ No newline at end of file +} diff --git a/Samples/Opc.Ua.Sample/Boiler/BoilerNodeManager.cs b/Samples/Opc.Ua.Sample/Boiler/BoilerNodeManager.cs index 4525f1d28..7562bca22 100644 --- a/Samples/Opc.Ua.Sample/Boiler/BoilerNodeManager.cs +++ b/Samples/Opc.Ua.Sample/Boiler/BoilerNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -109,7 +109,7 @@ public override NodeId New(ISystemContext context, NodeState node) /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -125,9 +125,9 @@ public override void CreateAddressSpace(IDictionary> e /// /// The context to use. /// The unit number for the boiler. - private void CreateBoiler(SystemContext context, int unitNumber) + private void CreateBoiler(ServerSystemContext context, int unitNumber) { - BoilerState boiler = new BoilerState(null); + BoilerState boiler = new BoilerState(null, m_logger); string name = Utils.Format("Boiler #{0}", unitNumber); @@ -229,7 +229,7 @@ protected override NodeState AddBehaviourToPredefinedNode(ISystemContext context break; } - BoilerState activeNode = new BoilerState(passiveNode.Parent); + BoilerState activeNode = new BoilerState(passiveNode.Parent, m_logger); activeNode.Create(context, passiveNode); // replace the node in the parent. @@ -305,7 +305,7 @@ protected override void OnSetMonitoringMode( #region Private Fields private ushort m_namespaceIndex; private ushort m_typeNamespaceIndex; - private long m_lastUsedId; + private uint m_lastUsedId; private List m_boilers; #endregion } diff --git a/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs b/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs index f831a2c99..c3d45b706 100644 --- a/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs +++ b/Samples/Opc.Ua.Sample/Boiler/BoilerState.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Threading; +using Microsoft.Extensions.Logging; using Opc.Ua; namespace Boiler @@ -279,7 +280,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.LogError(e, "Unexpected error during boiler simulation."); + m_logger.LogError(e, "Unexpected error during boiler simulation."); } } #endregion diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs index 592f15ff6..466a9cfc1 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -103,7 +103,7 @@ public MemoryBufferNodeManager(IServerInternal server, ApplicationConfiguration /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -176,7 +176,7 @@ public override void DeleteAddressSpace() /// Returns a unique handle for the node. /// /// - /// This must efficiently determine whether the node belongs to the node manager. If it does belong to + /// This must efficiently determine whether the node belongs to the node manager. If it does belong to /// NodeManager it should return a handle that does not require the NodeId to be validated again when /// the handle is passed into other methods such as 'Read' or 'Write'. /// @@ -245,7 +245,7 @@ protected override object GetManagerHandle(ISystemContext context, NodeId nodeId // operations and pointers to functions in the buffer object that // allow the value to be accessed. These tags are ephemeral and are // discarded after the operation completes. This design pattern allows - // the server to expose potentially millions of UA nodes without + // the server to expose potentially millions of UA nodes without // creating millions of objects that reside in memory. return new MemoryTagState(buffer, offset); } @@ -268,7 +268,7 @@ protected override ServiceResult CreateMonitoredItem( DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, - ref long globalIdCounter, + MonitoredItemIdFactory globalIdCounter, out MonitoringFilterResult filterError, out IMonitoredItem monitoredItem) { @@ -288,7 +288,7 @@ protected override ServiceResult CreateMonitoredItem( diagnosticsMasks, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterError, out monitoredItem); } @@ -345,7 +345,7 @@ protected override ServiceResult CreateMonitoredItem( } // create a globally unique identifier. - uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter); + uint monitoredItemId = globalIdCounter.GetNextId(); // determine the sampling interval. double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval; diff --git a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs index 93c33a430..8a4085f72 100644 --- a/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs +++ b/Samples/Opc.Ua.Sample/MemoryBuffer/MemoryBufferState.cs @@ -36,6 +36,7 @@ using Opc.Ua; using Opc.Ua.Server; using System.Diagnostics; +using Microsoft.Extensions.Logging; namespace MemoryBuffer { @@ -428,6 +429,7 @@ public void InitializeMonitoring( lock (m_dataLock) { m_server = server; + m_logger = server.Telemetry.CreateLogger(); m_nodeManager = nodeManager; m_nonValueMonitoredItems = new Dictionary(); } @@ -556,7 +558,7 @@ void DoScan(object state) if (delta1 > 100) { - Utils.LogWarning("{0} SAMPLING DELAY ({1}ms)", nameof(MemoryBufferState), delta1); + m_logger.LogWarning("{0} SAMPLING DELAY ({1}ms)", nameof(MemoryBufferState), delta1); } } @@ -660,7 +662,7 @@ void PublishTimer_Tick(object sender, EventArgs e) { if (m_itemCount > 0 && m_updateCount < m_itemCount) { - Utils.LogInfo("{0:HH:mm:ss.fff} MEMORYBUFFER Reported {1}/{2} items ***.", DateTime.Now, m_updateCount, m_itemCount); + m_logger.LogInformation("{0:HH:mm:ss.fff} MEMORYBUFFER Reported {1}/{2} items ***.", DateTime.Now, m_updateCount, m_itemCount); } m_updateCount = 0; @@ -672,7 +674,7 @@ void PublishTimer_Tick(object sender, EventArgs e) if (delta1 > 100) { - Utils.LogInfo("{0} ****** PUBLISH DELAY ({1}ms) ******", nameof(MemoryBufferState), delta1); + m_logger.LogInformation("{0} ****** PUBLISH DELAY ({1}ms) ******", nameof(MemoryBufferState), delta1); } } #endregion @@ -680,6 +682,7 @@ void PublishTimer_Tick(object sender, EventArgs e) #region Private Fields private object m_dataLock = new object(); private IServerInternal m_server; + private ILogger m_logger; private INodeManager m_nodeManager; private MemoryBufferMonitoredItem[][] m_monitoringTable; private Dictionary m_nonValueMonitoredItems; diff --git a/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj b/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj index 80351b593..37ee8ee39 100644 --- a/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj +++ b/Samples/Opc.Ua.Sample/Opc.Ua.Sample.csproj @@ -18,8 +18,9 @@ - - + + + diff --git a/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs b/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs index f7673cd3f..0c68b9778 100644 --- a/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs +++ b/Samples/Opc.Ua.Sample/SampleServer.UserAuthentication.cs @@ -29,6 +29,8 @@ using System; using System.Security.Cryptography.X509Certificates; +using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua.Server; namespace Opc.Ua.Sample @@ -52,7 +54,7 @@ private void CreateUserIdentityValidators(ApplicationConfiguration configuration if (configuration.SecurityConfiguration.TrustedUserCertificates != null && configuration.SecurityConfiguration.UserIssuerCertificates != null) { - var certificateValidator = new CertificateValidator(); + var certificateValidator = new CertificateValidator(ServerInternal.Telemetry); certificateValidator.UpdateAsync(configuration.SecurityConfiguration, configuration.ApplicationUri).Wait(); certificateValidator.Update(configuration.SecurityConfiguration.UserIssuerCertificates, configuration.SecurityConfiguration.TrustedUserCertificates, @@ -78,9 +80,9 @@ private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventAr if (userNameToken != null) { - VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); + VerifyPassword(userNameToken.UserName, Encoding.UTF8.GetString(userNameToken.DecryptedPassword)); args.Identity = new UserIdentity(userNameToken); - Utils.Trace("UserName Token Accepted: {0}", args.Identity.DisplayName); + m_logger.LogInformation("UserName Token Accepted: {0}", args.Identity.DisplayName); return; } @@ -91,7 +93,7 @@ private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventAr { VerifyCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); - Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); + m_logger.LogInformation("X509 Token Accepted: {0}", args.Identity.DisplayName); return; } } @@ -112,9 +114,10 @@ private void VerifyPassword(string userName, string password) // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( - StatusCodes.BadIdentityTokenRejected, - "InvalidPassword", "http://opcfoundation.org/UA/Sample/", + new StatusCode( + StatusCodes.BadIdentityTokenRejected, + "InvalidPassword"), new LocalizedText(info))); } } @@ -128,11 +131,11 @@ private void VerifyCertificate(X509Certificate2 certificate) { if (m_certificateValidator != null) { - m_certificateValidator.Validate(certificate); + m_certificateValidator.ValidateAsync(certificate, System.Threading.CancellationToken.None).GetAwaiter().GetResult(); } else { - CertificateValidator.Validate(certificate); + CertificateValidator.ValidateAsync(certificate, System.Threading.CancellationToken.None).GetAwaiter().GetResult(); } } catch (Exception e) @@ -162,9 +165,8 @@ private void VerifyCertificate(X509Certificate2 certificate) // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( - result, - info.Key, "http://opcfoundation.org/UA/Sample/", + result, new LocalizedText(info))); } } diff --git a/Samples/Opc.Ua.Sample/SampleServer.cs b/Samples/Opc.Ua.Sample/SampleServer.cs index eecebea8c..34961e42a 100644 --- a/Samples/Opc.Ua.Sample/SampleServer.cs +++ b/Samples/Opc.Ua.Sample/SampleServer.cs @@ -29,9 +29,11 @@ #define CUSTOM_NODE_MANAGER -using Opc.Ua.Server; using System.Collections.Generic; using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Opc.Ua.Server; namespace Opc.Ua.Sample { @@ -50,7 +52,7 @@ public partial class SampleServer : ReverseConnectServer /// protected override void OnServerStarting(ApplicationConfiguration configuration) { - Utils.Trace("The server is starting."); + Debug.WriteLine("The server is starting."); base.OnServerStarting(configuration); @@ -76,11 +78,11 @@ protected override void OnServerStarted(IServerInternal server) /// /// This method is called before any shutdown processing occurs. /// - protected override void OnServerStopping() + protected override async ValueTask OnServerStoppingAsync(CancellationToken cancellationToken = default) { Debug.WriteLine("The Server is stopping."); - base.OnServerStopping(); + await base.OnServerStoppingAsync(cancellationToken); #if INCLUDE_Sample CleanSampleModel(); diff --git a/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs b/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs index f91fbf7f0..59427d5f2 100644 --- a/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs +++ b/Samples/Opc.Ua.Sample/TestData/HistoryArchive.cs @@ -34,6 +34,7 @@ using System.Xml; using System.IO; using Opc.Ua; +using Microsoft.Extensions.Logging; namespace TestData { @@ -42,6 +43,11 @@ namespace TestData /// internal class HistoryArchive : IDisposable { + public HistoryArchive(ITelemetryContext telemetryContext) + { + m_logger = telemetryContext.CreateLogger(); + } + #region IDisposable Members /// /// Frees any unmanaged resources. @@ -184,13 +190,14 @@ private void OnUpdate(object state) } catch (Exception e) { - Utils.LogError(e, "Unexpected error updating history."); + m_logger.LogError(e, "Unexpected error updating history."); } } #endregion #region Private Fields private object m_lock = new object(); + private readonly ILogger m_logger; private Timer m_updateTimer; private Dictionary m_records; #endregion diff --git a/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs b/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs index 4d1ffbc89..972fd8afe 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestDataNodeManager.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -91,7 +91,7 @@ public TestDataNodeManager(Opc.Ua.Server.IServerInternal server, ApplicationConf m_lastUsedId = m_configuration.NextUnusedId - 1; // create the object used to access the test system. - m_system = new TestDataSystem(this, server.NamespaceUris, server.ServerUris); + m_system = new TestDataSystem(this, server.NamespaceUris, server.ServerUris, server.Telemetry); // update the default context. SystemContext.SystemHandle = m_system; @@ -137,7 +137,7 @@ public override NodeId New(ISystemContext context, NodeState node) /// /// The externalReferences is an out parameter that allows the node manager to link to nodes /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and - /// should have a reference to the root folder node(s) exposed by this node manager. + /// should have a reference to the root folder node(s) exposed by this node manager. /// public override void CreateAddressSpace(IDictionary> externalReferences) { @@ -152,7 +152,7 @@ public override void CreateAddressSpace(IDictionary> e #if CONDITION_SAMPLES // start monitoring the system status. m_systemStatusCondition = (TestSystemConditionState)FindPredefinedNode( - new NodeId(Objects.Data_Conditions_SystemStatus, m_typeNamespaceIndex), + new NodeId(Objects.Data_Conditions_SystemStatus, m_typeNamespaceIndex), typeof(TestSystemConditionState)); if (m_systemStatusCondition != null) @@ -641,7 +641,7 @@ private void OnCheckSystemStatus(object state) lock (Lock) { try - { + { // create the dialog. if (m_dialog == null) { @@ -656,7 +656,7 @@ private void OnCheckSystemStatus(object state) m_dialog.OnAfterResponse = OnDialogComplete; } - + StatusCode systemStatus = m_system.SystemStatus; m_systemStatusCondition.UpdateStatus(systemStatus); @@ -681,12 +681,12 @@ private void OnCheckSystemStatus(object state) if (StatusCode.IsBad(systemStatus)) { m_dialog.RequestResponse( - SystemContext, - "Reset the test system?", + SystemContext, + "Reset the test system?", (uint)(int)(DialogConditionChoice.Ok | DialogConditionChoice.Cancel), (ushort)EventSeverity.MediumHigh); } - + // report the event. TranslationInfo info = new TranslationInfo( "TestSystemStatusChange", @@ -705,14 +705,14 @@ private void OnCheckSystemStatus(object state) Utils.LogError(e, "Unexpected error monitoring system status."); } } - } - + } + /// /// Handles a user response to a dialog. /// private ServiceResult OnDialogComplete( - ISystemContext context, - DialogConditionState dialog, + ISystemContext context, + DialogConditionState dialog, DialogConditionChoice response) { if (m_dialog != null) @@ -730,7 +730,7 @@ private ServiceResult OnDialogComplete( private ushort m_namespaceIndex; private ushort m_typeNamespaceIndex; private TestDataSystem m_system; - private long m_lastUsedId; + private uint m_lastUsedId; #if CONDITION_SAMPLES private Timer m_systemStatusTimer; private TestSystemConditionState m_systemStatusCondition; diff --git a/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs b/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs index 26138c965..3f4e90b74 100644 --- a/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs +++ b/Samples/Opc.Ua.Sample/TestData/TestDataSystem.cs @@ -35,6 +35,7 @@ using System.IO; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace TestData { @@ -49,15 +50,19 @@ void OnDataChange( public class TestDataSystem { - public TestDataSystem(ITestDataSystemCallback callback, NamespaceTable namespaceUris, StringTable serverUris) + public TestDataSystem(ITestDataSystemCallback callback, + NamespaceTable namespaceUris, + StringTable serverUris, + ITelemetryContext telemetry) { m_callback = callback; + m_logger = telemetry.CreateLogger(); m_minimumSamplingInterval = Int32.MaxValue; m_monitoredNodes = new Dictionary(); - m_generator = new Opc.Ua.Test.DataGenerator(null); + m_generator = new Opc.Ua.Test.DataGenerator(null, telemetry); m_generator.NamespaceUris = namespaceUris; m_generator.ServerUris = serverUris; - m_historyArchive = new HistoryArchive(); + m_historyArchive = new HistoryArchive(telemetry); } /// @@ -767,7 +772,7 @@ public void SetSamplingInterval(double samplingInterval) void DoSample(object state) { - Utils.LogTrace("DoSample HiRes={0:ss.ffff} Now={1:ss.ffff}", HiResClock.UtcNow, DateTime.UtcNow); + m_logger.LogTrace("DoSample HiRes={0:ss.ffff} Now={1:ss.ffff}", HiResClock.UtcNow, DateTime.UtcNow); Queue samples = new Queue(); @@ -832,6 +837,7 @@ private class Sample #region Private Fields private object m_lock = new object(); private ITestDataSystemCallback m_callback; + private readonly ILogger m_logger; private Opc.Ua.Test.DataGenerator m_generator; private int m_minimumSamplingInterval; private Dictionary m_monitoredNodes; diff --git a/Samples/ReferenceClient/MainForm.cs b/Samples/ReferenceClient/MainForm.cs index 3de02159a..c687e7f70 100644 --- a/Samples/ReferenceClient/MainForm.cs +++ b/Samples/ReferenceClient/MainForm.cs @@ -57,12 +57,13 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62541/Quickstarts/ReferenceServer"; this.Text = m_configuration.ApplicationName; + m_telemetry = telemetry; } #endregion @@ -70,6 +71,7 @@ public MainForm(ApplicationConfiguration configuration) private ApplicationConfiguration m_configuration; private ISession m_session; private bool m_connectedOnce; + private ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -83,11 +85,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -102,7 +104,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -117,7 +119,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -137,11 +139,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } // browse the instances in the server. - await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, m_telemetry, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -156,7 +158,7 @@ private async void Server_ReconnectStartingAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -172,7 +174,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Samples/ReferenceClient/Program.cs b/Samples/ReferenceClient/Program.cs index 006e84591..eebedc35d 100644 --- a/Samples/ReferenceClient/Program.cs +++ b/Samples/ReferenceClient/Program.cs @@ -29,14 +29,30 @@ using System; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; namespace Quickstarts.ReferenceClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -48,7 +64,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationName = "UA Reference Client"; application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.ReferenceClient"; @@ -67,11 +83,11 @@ static void Main() } // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Samples/ReferenceClient/Reference Client.csproj b/Samples/ReferenceClient/Reference Client.csproj index 06bb60c94..c3256a21b 100644 --- a/Samples/ReferenceClient/Reference Client.csproj +++ b/Samples/ReferenceClient/Reference Client.csproj @@ -129,16 +129,16 @@ - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/ReferenceServer/Program.cs b/Samples/ReferenceServer/Program.cs index 06737b9a2..876e49258 100644 --- a/Samples/ReferenceServer/Program.cs +++ b/Samples/ReferenceServer/Program.cs @@ -28,17 +28,33 @@ * ======================================================================*/ using System; +using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Configuration; using Opc.Ua.Server.Controls; -using System.Threading.Tasks; using Serilog; namespace Quickstarts.ReferenceServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,7 +66,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.ReferenceServer"; @@ -65,7 +81,6 @@ static void Main() loggerConfiguration.WriteTo.Debug(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning); #pragma warning restore CA1305 // Specify IFormatProvider #endif - SerilogTraceLogger.Create(loggerConfiguration, config); // check the application certificate. bool certOk = application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Result; @@ -91,11 +106,11 @@ static void Main() } // run the application interactively. - Application.Run(new ServerForm(application, showCertificateValidationDialog)); + Application.Run(new ServerForm(application, m_telemetry, showCertificateValidationDialog)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Samples/ReferenceServer/Reference Server.csproj b/Samples/ReferenceServer/Reference Server.csproj index 8d3ec8fb3..daedcdd6f 100644 --- a/Samples/ReferenceServer/Reference Server.csproj +++ b/Samples/ReferenceServer/Reference Server.csproj @@ -84,7 +84,6 @@ - @@ -141,13 +140,13 @@ - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.2-preview 4.3.0 diff --git a/Samples/ReferenceServer/ReferenceServerUtils.cs b/Samples/ReferenceServer/ReferenceServerUtils.cs index cd353481d..07be84dc5 100644 --- a/Samples/ReferenceServer/ReferenceServerUtils.cs +++ b/Samples/ReferenceServer/ReferenceServerUtils.cs @@ -27,6 +27,7 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; using System; @@ -363,13 +364,14 @@ public static uint CreateError( uint code, OperationContext context, DiagnosticInfoCollection diagnosticInfos, - int index) + int index, + ILogger logger) { ServiceResult error = new ServiceResult(code); if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { - diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable); + diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable, logger); } return error.Code; @@ -382,14 +384,15 @@ public static bool CreateError( uint code, StatusCodeCollection results, DiagnosticInfoCollection diagnosticInfos, - OperationContext context) + OperationContext context, + ILogger logger) { ServiceResult error = new ServiceResult(code); results.Add(error.Code); if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { - diagnosticInfos.Add(new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable)); + diagnosticInfos.Add(new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable, logger)); return true; } @@ -404,14 +407,15 @@ public static bool CreateError( StatusCodeCollection results, DiagnosticInfoCollection diagnosticInfos, int index, - OperationContext context) + OperationContext context, + ILogger logger) { ServiceResult error = new ServiceResult(code); results[index] = error.Code; if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { - diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable); + diagnosticInfos[index] = new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable, logger); return true; } @@ -439,7 +443,8 @@ public static void CreateSuccess( /// public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( OperationContext context, - IList errors) + IList errors, + ILogger logger) { // all done if no diagnostics requested. if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) == 0) @@ -454,7 +459,7 @@ public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( { if (ServiceResult.IsBad(error)) { - results.Add(new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable)); + results.Add(new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable, logger)); } else { @@ -471,6 +476,7 @@ public static DiagnosticInfoCollection CreateDiagnosticInfoCollection( public static StatusCodeCollection CreateStatusCodeCollection( OperationContext context, IList errors, + ILogger logger, out DiagnosticInfoCollection diagnosticInfos) { diagnosticInfos = null; @@ -494,7 +500,7 @@ public static StatusCodeCollection CreateStatusCodeCollection( // only generate diagnostics if errors exist. if (noErrors) { - diagnosticInfos = CreateDiagnosticInfoCollection(context, errors); + diagnosticInfos = CreateDiagnosticInfoCollection(context, errors, logger); } return results; @@ -510,7 +516,8 @@ public static StatusCodeCollection CreateStatusCodeCollection( public static DiagnosticInfo CreateDiagnosticInfo( IServerInternal server, OperationContext context, - ServiceResult error) + ServiceResult error, + ILogger logger) { if (error == null) { @@ -528,7 +535,8 @@ public static DiagnosticInfo CreateDiagnosticInfo( translatedError, context.DiagnosticsMask, false, - context.StringTable); + context.StringTable, + logger); return diagnosticInfo; } diff --git a/Samples/ReferenceServer/SerilogTraceLogger.cs b/Samples/ReferenceServer/SerilogTraceLogger.cs deleted file mode 100644 index 829bfc7d7..000000000 --- a/Samples/ReferenceServer/SerilogTraceLogger.cs +++ /dev/null @@ -1,135 +0,0 @@ -/* ======================================================================== - * Copyright (c) 2005-2021 The OPC Foundation, Inc. All rights reserved. - * - * OPC Foundation MIT License 1.00 - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * The complete license agreement can be found here: - * http://opcfoundation.org/License/MIT/1.00/ - * ======================================================================*/ - -using System; -using Opc.Ua; -using Serilog; -using Serilog.Events; - -namespace Quickstarts.ReferenceServer -{ - /// - /// A sample serilog trace logger replacement. - /// - public class SerilogTraceLogger - { - private int m_traceMask; - private ILogger m_logger; - - /// - /// Create a serilog trace logger which replaces the default logging. - /// - /// The application configuration. - /// The min log level for file output. - public static SerilogTraceLogger Create( - ApplicationConfiguration config, - LogEventLevel fileMinimumLevel = LogEventLevel.Information) - { - return Create(null, config, fileMinimumLevel); - } - - /// - /// Create a serilog trace logger which replaces the default logging. - /// - /// The logger configuration. - /// The application configuration. - /// The min log level for file output. - public static SerilogTraceLogger Create( - LoggerConfiguration loggerConfiguration, - ApplicationConfiguration config, - LogEventLevel fileMinimumLevel = LogEventLevel.Verbose) - { - if (loggerConfiguration == null) - { - loggerConfiguration = new LoggerConfiguration(); - } - // add file logging - if (!string.IsNullOrWhiteSpace(config.TraceConfiguration.OutputFilePath)) - { - loggerConfiguration.WriteTo.File( - Utils.ReplaceSpecialFolderNames(config.TraceConfiguration.OutputFilePath), - rollingInterval: RollingInterval.Infinite, - rollOnFileSizeLimit: true, - restrictedToMinimumLevel: fileMinimumLevel, - retainedFileCountLimit: 10, - flushToDiskInterval: TimeSpan.FromSeconds(13)); - } - - ILogger logger = loggerConfiguration - .MinimumLevel.Verbose() - .CreateLogger(); - - SerilogTraceLogger traceLogger = new SerilogTraceLogger(logger, config.TraceConfiguration.TraceMasks); - - // disable the built in tracing, use serilog - Utils.SetTraceMask(Utils.TraceMask & Utils.TraceMasks.StackTrace); - Utils.SetTraceOutput(Utils.TraceOutput.Off); - Utils.Tracing.TraceEventHandler += traceLogger.TraceEventHandler; - - return traceLogger; - } - - /// - /// Ctor of trace logger. - /// - /// The logger - /// The trace mask - public SerilogTraceLogger(ILogger logger, int traceMask) - { - m_logger = logger; - m_traceMask = traceMask; - } - - /// - /// Callback for logging OPC UA stack trace output - /// - /// Sender object - /// The trace event args. - public void TraceEventHandler(object sender, TraceEventArgs e) - { - if ((e.TraceMask & m_traceMask) != 0) - { - if (e.Exception != null) - { - m_logger.Error(e.Exception, e.Format, e.Arguments); - return; - } - switch (e.TraceMask) - { - case Utils.TraceMasks.StartStop: - case Utils.TraceMasks.Information: m_logger.Information(e.Format, e.Arguments); break; - case Utils.TraceMasks.Error: m_logger.Error(e.Format, e.Arguments); break; - case Utils.TraceMasks.StackTrace: - case Utils.TraceMasks.Security: m_logger.Warning(e.Format, e.Arguments); break; - default: m_logger.Verbose(e.Format, e.Arguments); break; - } - } - } - } -} diff --git a/Samples/Server.Net4/Program.cs b/Samples/Server.Net4/Program.cs index 99c889c34..80b5ee93e 100644 --- a/Samples/Server.Net4/Program.cs +++ b/Samples/Server.Net4/Program.cs @@ -28,15 +28,31 @@ * ======================================================================*/ using System; +using System.Threading.Tasks; using System.Windows.Forms; -using Opc.Ua.Configuration; +using Microsoft.Extensions.Logging; using Opc.Ua.Client.Controls; -using System.Threading.Tasks; +using Opc.Ua.Configuration; namespace Opc.Ua.Sample { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -47,7 +63,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationName = "UA Sample Server"; application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Opc.Ua.SampleServer"; @@ -67,11 +83,11 @@ static void Main() application.StartAsync(new SampleServer()).Wait(); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Samples/Server.Net4/ServerForm.cs b/Samples/Server.Net4/ServerForm.cs index 597c869be..f3fc90ea2 100644 --- a/Samples/Server.Net4/ServerForm.cs +++ b/Samples/Server.Net4/ServerForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,6 +27,7 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using Microsoft.Extensions.Logging; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; using Opc.Ua.Server; @@ -54,11 +55,13 @@ public ServerForm() /// /// Creates a form which displays the status for a UA server. /// - public ServerForm(ApplicationInstance application) + public ServerForm(ApplicationInstance application, ITelemetryContext telemetry) { InitializeComponent(); m_application = application; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); if (application.Server is StandardServer) { @@ -77,6 +80,8 @@ public ServerForm(ApplicationInstance application) #region Private Fields private ApplicationInstance m_application; + private readonly ITelemetryContext m_telemetry; + private readonly ILogger m_logger; #endregion #region Event Handlers @@ -91,7 +96,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - Opc.Ua.Client.Controls.GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + Opc.Ua.Client.Controls.GuiUtils.HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -114,15 +119,15 @@ private void Server_ExitMI_Click(object sender, EventArgs e) Close(); } - private void ServerForm_FormClosed(object sender, FormClosedEventArgs e) + private async void ServerForm_FormClosed(object sender, FormClosedEventArgs e) { try { - m_application.Stop(); + await m_application.StopAsync(); } catch (Exception exception) { - Utils.Trace(exception, "Error stopping server."); + m_logger.LogTrace(exception, "Error stopping server."); } } @@ -143,7 +148,7 @@ private void TrayIcon_MouseMove(object sender, MouseEventArgs e) } catch (Exception exception) { - Utils.Trace(exception, "Error getting server status."); + m_logger.LogTrace(exception, "Error getting server status."); } } #endregion diff --git a/Samples/Server.Net4/UA Sample Server.csproj b/Samples/Server.Net4/UA Sample Server.csproj index 7d30f7f6c..4010bf390 100644 --- a/Samples/Server.Net4/UA Sample Server.csproj +++ b/Samples/Server.Net4/UA Sample Server.csproj @@ -145,10 +145,13 @@ - 9.0.8 + 10.0.0 + + + 10.0.0 - 1.5.377.21 + 1.5.378.11-preview diff --git a/Samples/ServerControls.Net4/ExceptionDlg.cs b/Samples/ServerControls.Net4/ExceptionDlg.cs index 72ec00038..886c53e46 100644 --- a/Samples/ServerControls.Net4/ExceptionDlg.cs +++ b/Samples/ServerControls.Net4/ExceptionDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -33,6 +33,7 @@ using System.Data; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Server.Controls { @@ -175,12 +176,22 @@ private void Show(bool showStackTrace) /// /// Displays the exception in a dialog. /// - public static void Show(string caption, Exception e) + public static void Show(ITelemetryContext telemetry, string caption, Exception e) + { + // check if running as a service. + ILogger logger = telemetry.CreateLogger(); + Show(logger, caption, e); + } + + /// + /// Displays the exception in a dialog. + /// + public static void Show(ILogger logger, string caption, Exception e) { // check if running as a service. if (!Environment.UserInteractive) { - Utils.LogError(e, "Unexpected error in '{0}'.", caption); + logger.LogError(e, "Unexpected error in '{Caption}'.", caption); return; } diff --git a/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs b/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs index bb5ce9ea5..f395c45e6 100644 --- a/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs +++ b/Samples/ServerControls.Net4/ServerDiagnosticsCtrl.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -122,7 +122,7 @@ private void UpdateSessions() } } - // adjust + // adjust for (int ii = 0; ii < SessionsLV.Columns.Count; ii++) { SessionsLV.Columns[ii].Width = -2; @@ -185,7 +185,7 @@ private void UpdateTimerCTRL_Tick(object sender, EventArgs e) } catch (Exception exception) { - ServerUtils.HandleException(this.Text, exception); + ServerUtils.HandleException(m_server.MessageContext.Telemetry, this.Text, exception); } } #endregion diff --git a/Samples/ServerControls.Net4/ServerForm.cs b/Samples/ServerControls.Net4/ServerForm.cs index 04ba5b59a..95c6c8426 100644 --- a/Samples/ServerControls.Net4/ServerForm.cs +++ b/Samples/ServerControls.Net4/ServerForm.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -39,6 +39,7 @@ using Opc.Ua.Configuration; using System.IO; using System.Linq; +using Microsoft.Extensions.Logging; namespace Opc.Ua.Server.Controls { @@ -59,12 +60,14 @@ public ServerForm() /// /// Creates a form which displays the status for a UA server. /// - public ServerForm(StandardServer server, ApplicationConfiguration configuration, bool showCertificateValidationDialog = true) + public ServerForm(StandardServer server, ApplicationConfiguration configuration, ITelemetryContext telemetry, bool showCertificateValidationDialog = true) { InitializeComponent(); m_server = server; m_configuration = configuration; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); this.ServerDiagnosticsCTRL.Initialize(m_server, m_configuration); if (showCertificateValidationDialog && @@ -82,12 +85,14 @@ public ServerForm(StandardServer server, ApplicationConfiguration configuration, /// /// Creates a form which displays the status for a UA server. /// - public ServerForm(ApplicationInstance application, bool showCertificateValidationDialog = false) + public ServerForm(ApplicationInstance application, ITelemetryContext telemetry, bool showCertificateValidationDialog = false) { InitializeComponent(); m_application = application; m_server = application.Server as StandardServer; + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); m_configuration = application.ApplicationConfiguration; this.ServerDiagnosticsCTRL.Initialize(m_server, m_configuration); @@ -105,6 +110,8 @@ public ServerForm(ApplicationInstance application, bool showCertificateValidatio #region Private Fields private ApplicationInstance m_application; private StandardServer m_server; + private readonly ITelemetryContext m_telemetry; + private readonly ILogger m_logger; private ApplicationConfiguration m_configuration; #endregion @@ -120,7 +127,7 @@ void CertificateValidator_CertificateValidation(CertificateValidator validator, } catch (Exception exception) { - HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); + HandleException(m_telemetry, this.Text, MethodBase.GetCurrentMethod(), exception); } } @@ -143,15 +150,15 @@ private void Server_ExitMI_Click(object sender, EventArgs e) Close(); } - private void ServerForm_FormClosed(object sender, FormClosedEventArgs e) + private async void ServerForm_FormClosed(object sender, FormClosedEventArgs e) { try { - m_server.Stop(); + await m_server.StopAsync(); } catch (Exception exception) { - Utils.LogError(exception, "Error stopping server."); + m_logger.LogError(exception, "Error stopping server."); } } @@ -167,7 +174,7 @@ private void TrayIcon_MouseMove(object sender, MouseEventArgs e) } catch (Exception exception) { - Utils.LogError(exception, "Error getting server status."); + m_logger.LogError(exception, "Error getting server status."); } } #endregion @@ -195,13 +202,13 @@ private void ContentsToolStripMenuItem_Click(object sender, EventArgs e) /// /// Displays the details of an exception. /// - public static void HandleException(string caption, MethodBase method, Exception e) + public static void HandleException(ITelemetryContext telemetry, string caption, MethodBase method, Exception e) { if (String.IsNullOrEmpty(caption)) { caption = method.Name; } - ExceptionDlg.Show(caption, e); + ExceptionDlg.Show(telemetry, caption, e); } /// diff --git a/Samples/ServerControls.Net4/ServerUtils.cs b/Samples/ServerControls.Net4/ServerUtils.cs index 578189924..a27d01bd2 100644 --- a/Samples/ServerControls.Net4/ServerUtils.cs +++ b/Samples/ServerControls.Net4/ServerUtils.cs @@ -40,9 +40,9 @@ public partial class ServerUtils /// /// Handles an exception. /// - public static void HandleException(string caption, Exception e) + public static void HandleException(ITelemetryContext telemetry, string caption, Exception e) { - ExceptionDlg.Show(caption, e); + ExceptionDlg.Show(telemetry, caption, e); } /// diff --git a/Samples/ServerControls.Net4/UA Server Controls.csproj b/Samples/ServerControls.Net4/UA Server Controls.csproj index 768d5ed38..97fb1eb39 100644 --- a/Samples/ServerControls.Net4/UA Server Controls.csproj +++ b/Samples/ServerControls.Net4/UA Server Controls.csproj @@ -149,14 +149,17 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/UA Samples.slnx b/UA Samples.slnx new file mode 100644 index 000000000..6c536e112 --- /dev/null +++ b/UA Samples.slnx @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Workshop/Aggregation/Client/Aggregation Client.csproj b/Workshop/Aggregation/Client/Aggregation Client.csproj index 4afb247e0..6295a5d21 100644 --- a/Workshop/Aggregation/Client/Aggregation Client.csproj +++ b/Workshop/Aggregation/Client/Aggregation Client.csproj @@ -135,8 +135,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Aggregation/Client/MainForm.cs b/Workshop/Aggregation/Client/MainForm.cs index 1fe94fa31..e169e6723 100644 --- a/Workshop/Aggregation/Client/MainForm.cs +++ b/Workshop/Aggregation/Client/MainForm.cs @@ -58,10 +58,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62541/AggregationServer"; @@ -72,6 +73,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -85,11 +87,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -104,7 +106,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -119,7 +121,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -133,11 +135,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) m_session = ConnectServerCTRL.Session; // browse the instances in the server. - await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, m_telemetry, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -152,7 +154,7 @@ private async void Server_ReconnectStartingAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -168,7 +170,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -187,7 +189,7 @@ private void ShowReferencesMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -198,7 +200,7 @@ private void WriteValueMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -209,7 +211,7 @@ private void SubscribeMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -220,7 +222,7 @@ private void CallMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -231,7 +233,7 @@ private void Server_ChangeUserOrLocaleMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Aggregation/Client/Program.cs b/Workshop/Aggregation/Client/Program.cs index 07a94251b..3d72dc07c 100644 --- a/Workshop/Aggregation/Client/Program.cs +++ b/Workshop/Aggregation/Client/Program.cs @@ -27,16 +27,32 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; -using System; -using System.Windows.Forms; namespace AggregationClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -48,7 +64,7 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.AggregationClient"; @@ -61,11 +77,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().GetAwaiter().GetResult(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs b/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs index 386e23419..709456cfe 100644 --- a/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs +++ b/Workshop/Aggregation/Client/SetUserAndLocaleDlg.cs @@ -100,7 +100,7 @@ private void UpdateUserIdentity(ISession session) if (token != null) { UserNameTB.Text = token.UserName; - PasswordTB.Text = token.DecryptedPassword; + PasswordTB.Text = Encoding.UTF8.GetString(token.DecryptedPassword); } } } @@ -171,7 +171,7 @@ private void OkBTN_Click(object sender, EventArgs e) // could add check for domain name in user name and use a kerberos token instead. else { - identity = new UserIdentity(UserNameTB.Text, PasswordTB.Text); + identity = new UserIdentity(UserNameTB.Text, Encoding.UTF8.GetBytes(PasswordTB.Text)); } // can specify multiple locales but just use one here to keep the UI simple. @@ -197,7 +197,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Aggregation/Client/ShowReferencesDlg.cs b/Workshop/Aggregation/Client/ShowReferencesDlg.cs index 6592fe8e7..51f715843 100644 --- a/Workshop/Aggregation/Client/ShowReferencesDlg.cs +++ b/Workshop/Aggregation/Client/ShowReferencesDlg.cs @@ -243,7 +243,7 @@ private void OkBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Aggregation/Client/SubscribeDlg.cs b/Workshop/Aggregation/Client/SubscribeDlg.cs index 5ff01d27b..37f12feee 100644 --- a/Workshop/Aggregation/Client/SubscribeDlg.cs +++ b/Workshop/Aggregation/Client/SubscribeDlg.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -53,14 +53,14 @@ public SubscribeDlg() CreateDataSet(); } #endregion - + #region Private Fields private Session m_session; private NodeId m_nodeId; private DataSet m_dataset; private int m_nextId; #endregion - + #region Public Interface public void Show(Session session, NodeId nodeId) { @@ -70,7 +70,7 @@ public void Show(Session session, NodeId nodeId) Show(); } #endregion - + #region Private Methods /// /// Creates the dataset and initializes the view. @@ -137,7 +137,7 @@ private void SubscribeDlg_FormClosing(object sender, FormClosingEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj b/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj index 8f31ecd88..35bd22c0d 100644 --- a/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj +++ b/Workshop/Aggregation/ConsoleAggregationServer/ConsoleAggregationServer.csproj @@ -41,21 +41,22 @@ - - - + + + - - - + + + + diff --git a/Workshop/Aggregation/ConsoleAggregationServer/Program.cs b/Workshop/Aggregation/ConsoleAggregationServer/Program.cs index 1878e3877..ecac6321e 100644 --- a/Workshop/Aggregation/ConsoleAggregationServer/Program.cs +++ b/Workshop/Aggregation/ConsoleAggregationServer/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,6 +27,7 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Configuration; using Opc.Ua.Server; @@ -86,11 +87,26 @@ public static void Main(string[] args) } } + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } + public class MyServer { AggregationServer server; Task status; DateTime lastEventTime; + private readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); public void Start() { @@ -103,7 +119,8 @@ public void Start() } catch (Exception ex) { - Utils.Trace("ServiceResultException:" + ex.Message); + m_telemetry.CreateLogger() + .LogError(ex, "ServiceResultException:"); Console.WriteLine("Exception: {0}", ex.Message); } @@ -140,7 +157,7 @@ private static void CertificateValidator_CertificateValidation(CertificateValida private async Task ConsoleAggregationServerAsync() { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationName = "Quickstart Aggregation Server"; application.ApplicationType = ApplicationType.Server; diff --git a/Workshop/Aggregation/Server/AggregatedTypeCache.cs b/Workshop/Aggregation/Server/AggregatedTypeCache.cs index e49811329..b405e0553 100644 --- a/Workshop/Aggregation/Server/AggregatedTypeCache.cs +++ b/Workshop/Aggregation/Server/AggregatedTypeCache.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -72,7 +73,8 @@ private async Task LoadTypesAsync(Opc.Ua.Client.ISession client, IServerInternal } catch (Exception e) { - Utils.Trace("Could not browse subtypes of {0}. {1}", parentId, e.Message); + server.Telemetry.CreateLogger() + .LogError("Could not browse subtypes of {0}. {1}", parentId, e.Message); return; } diff --git a/Workshop/Aggregation/Server/Aggregation Server.csproj b/Workshop/Aggregation/Server/Aggregation Server.csproj index 7d2beb24c..8fa57dfed 100644 --- a/Workshop/Aggregation/Server/Aggregation Server.csproj +++ b/Workshop/Aggregation/Server/Aggregation Server.csproj @@ -130,17 +130,20 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Aggregation/Server/AggregationNodeManager.cs b/Workshop/Aggregation/Server/AggregationNodeManager.cs index 651a5b588..b8aecd895 100644 --- a/Workshop/Aggregation/Server/AggregationNodeManager.cs +++ b/Workshop/Aggregation/Server/AggregationNodeManager.cs @@ -34,6 +34,7 @@ using Opc.Ua; using Opc.Ua.Server; using System.Linq; +using Microsoft.Extensions.Logging; namespace AggregationServer { @@ -647,7 +648,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte } // create a request. - Opc.Ua.Client.MonitoredItem request = new Opc.Ua.Client.MonitoredItem(monitoredItem.Id); + Opc.Ua.Client.MonitoredItem request = new Opc.Ua.Client.MonitoredItem(monitoredItem.Id, Server.Telemetry); request.StartNodeId = m_mapper.ToRemoteId(monitoredItem.NodeId); request.MonitoringMode = monitoredItem.MonitoringMode; @@ -669,7 +670,7 @@ protected override void OnCreateMonitoredItemsComplete(ServerSystemContext conte // create subscription. if (client.SubscriptionCount == 0) { - Opc.Ua.Client.Subscription subscription = new Opc.Ua.Client.Subscription(); + Opc.Ua.Client.Subscription subscription = new Opc.Ua.Client.Subscription(Server.Telemetry); subscription.PublishingInterval = 250; subscription.KeepAliveCount = 100; @@ -871,7 +872,7 @@ protected override void OnDeleteMonitoredItemsComplete(ServerSystemContext conte } catch (Exception e) { - Utils.Trace(e, "Could not access external system."); + m_logger.LogError(e, "Could not access external system."); } } } @@ -1032,7 +1033,7 @@ public override ServiceResult SubscribeToEvents( } // create a request. - Opc.Ua.Client.MonitoredItem request = new Opc.Ua.Client.MonitoredItem(localItem.Id); + Opc.Ua.Client.MonitoredItem request = new Opc.Ua.Client.MonitoredItem(localItem.Id, Server.Telemetry); if (localItem.NodeId == ObjectIds.Server || localItem.NodeId == m_root.NodeId) { @@ -1056,7 +1057,7 @@ public override ServiceResult SubscribeToEvents( // create subscription. if (client.SubscriptionCount == 0) { - Opc.Ua.Client.Subscription subscription = new Opc.Ua.Client.Subscription(); + Opc.Ua.Client.Subscription subscription = new Opc.Ua.Client.Subscription(Server.Telemetry); subscription.PublishingInterval = 250; subscription.KeepAliveCount = 100; @@ -1092,13 +1093,13 @@ public override ServiceResult SubscribeToEvents( if (ServiceResult.IsBad(request.Status.Error)) { - Utils.Trace((int)Utils.TraceMasks.Error, "Could not create event item. {0}", request.Status.Error.ToLongString()); + m_logger.LogError("Could not create event item. {0}", request.Status.Error.ToLongString()); } } } catch (Exception e) { - Utils.Trace(e, "Could not access external system."); + m_logger.LogError(e, "Could not access external system."); } return ServiceResult.Good; @@ -1261,8 +1262,8 @@ Opc.Ua.Client.ISession GetClientSession(ServerSystemContext context) try { - Utils.Trace($"Create Connect Session: {m_endpoint} for {sessionName}"); - var session = Opc.Ua.Client.Session.CreateAsync( + m_logger.LogInformation($"Create Connect Session: {m_endpoint} for {sessionName}"); + Opc.Ua.Client.ISession session = new Opc.Ua.Client.DefaultSessionFactory(Server.Telemetry).CreateAsync( m_configuration, m_reverseConnectManager, m_endpoint, @@ -1298,7 +1299,7 @@ Opc.Ua.Client.ISession GetClientSession(ServerSystemContext context) } catch (Exception e) { - Utils.Trace(e, "Could not connect to server."); + m_logger.LogError(e, "Could not connect to server."); lock (m_clientsLock) { @@ -1440,7 +1441,7 @@ private async void DoMetadataUpdateAsync(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error updating event type cache."); + m_logger.LogError(e, "Unexpected error updating event type cache."); } finally { @@ -1487,7 +1488,7 @@ protected override NodeState ValidateNode( // get remote node. NodeId targetId = m_mapper.ToRemoteId(handle.NodeId); - ILocalNode node = client.ReadNodeAsync(targetId).GetAwaiter().GetResult(); + ILocalNode node = Opc.Ua.Client.SessionClientExtensions.ReadNodeAsync(client, targetId).GetAwaiter().GetResult(); if (node == null) { @@ -1654,7 +1655,7 @@ private void Client_KeepAlive(Opc.Ua.Client.ISession session, Opc.Ua.Client.Keep { if (e.Status != null && ServiceResult.IsNotGood(e.Status)) { - Utils.Trace("{0} {1}/{2}", e.Status, session.OutstandingRequestCount, session.DefunctRequestCount); + m_logger.LogDebug("{ 0} {1}/{2}", e.Status, session.OutstandingRequestCount, session.DefunctRequestCount); var totalBadRequestCount = session.OutstandingRequestCount + session.DefunctRequestCount; Opc.Ua.Client.SessionReconnectHandler reconnectHandler; if (totalBadRequestCount >= 3 && @@ -1665,15 +1666,15 @@ private void Client_KeepAlive(Opc.Ua.Client.ISession session, Opc.Ua.Client.Keep AggregationClientSession clientSession = m_clients.Where(c => c.Value?.SessionSessionId == session.SessionId).FirstOrDefault().Value; if (clientSession != null && clientSession.ReconnectHandler == null) { - Utils.Trace($"--- RECONNECTING --- SessionId: {clientSession.ClientSessionId}"); - reconnectHandler = new Opc.Ua.Client.SessionReconnectHandler(true); + m_logger.LogInformation($"--- RECONNECTING --- SessionId: {clientSession.ClientSessionId}"); + reconnectHandler = new Opc.Ua.Client.SessionReconnectHandler(Server.Telemetry, true); reconnectHandler.BeginReconnect(session, m_reverseConnectManager, DefaultReconnectPeriod, Client_ReconnectComplete); clientSession.ReconnectHandler = reconnectHandler; e.CancelKeepAlive = true; } else if (clientSession == null) { - Utils.Trace($"--- KEEP ALIVE for stale session --- SessionId: {session.SessionId}"); + m_logger.LogWarning($"--- KEEP ALIVE for stale session --- SessionId: {session.SessionId}"); } } } @@ -1695,7 +1696,7 @@ private void Client_ReconnectComplete(object sender, EventArgs e) AggregationClientSession clientSession = m_clients.Where(c => Object.ReferenceEquals(reconnectHandler, c.Value?.ReconnectHandler)).FirstOrDefault().Value; if (clientSession == null) { - Utils.Trace($"--- RECONNECTED --- SessionId: {clientSession.ClientSessionId} but client session was not found."); + m_logger.LogInformation($"--- RECONNECTED --- SessionId: {clientSession.ClientSessionId} but client session was not found."); return; } @@ -1710,7 +1711,7 @@ private void Client_ReconnectComplete(object sender, EventArgs e) Utils.SilentDispose(oldSession); } reconnectHandler.Dispose(); - Utils.Trace($"--- RECONNECTED --- SessionId: {clientSession.ClientSessionId}"); + m_logger.LogInformation($"--- RECONNECTED --- SessionId: {clientSession.ClientSessionId}"); } } diff --git a/Workshop/Aggregation/Server/AggregationServer.cs b/Workshop/Aggregation/Server/AggregationServer.cs index 21c968ab7..4951895f5 100644 --- a/Workshop/Aggregation/Server/AggregationServer.cs +++ b/Workshop/Aggregation/Server/AggregationServer.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Server; @@ -43,7 +44,7 @@ namespace AggregationServer /// Each server instance must have one instance of a StandardServer object which is /// responsible for reading the configuration file, creating the endpoints and dispatching /// incoming requests to the appropriate handler. - /// + /// /// This sub-class specifies non-configurable metadata such as Product Name and initializes /// the AggregationNodeManager which provides access to the data exposed by the Server. /// @@ -60,7 +61,7 @@ public partial class AggregationServer : ReverseConnectServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + m_logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); @@ -73,7 +74,7 @@ protected override MasterNodeManager CreateMasterNodeManager(IServerInternal ser { var reverseConnect = configuration.ClientConfiguration.ReverseConnect; // start the reverse connection manager - reverseConnectManager = new Opc.Ua.Client.ReverseConnectManager(); + reverseConnectManager = new Opc.Ua.Client.ReverseConnectManager(server.Telemetry); foreach (var endpoint in reverseConnect.ClientEndpoints) { reverseConnectManager.AddEndpoint(new Uri(endpoint.EndpointUrl)); diff --git a/Workshop/Aggregation/Server/Program.cs b/Workshop/Aggregation/Server/Program.cs index eb075ac4d..966260a42 100644 --- a/Workshop/Aggregation/Server/Program.cs +++ b/Workshop/Aggregation/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,17 +27,33 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ -using Opc.Ua; -using Opc.Ua.Configuration; -using Opc.Ua.Server.Controls; using System; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using Opc.Ua; +using Opc.Ua.Configuration; +using Opc.Ua.Server.Controls; namespace AggregationServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -53,7 +69,7 @@ static async Task MyMainAsync() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.AggregationServer"; @@ -69,11 +85,11 @@ static async Task MyMainAsync() await application.StartAsync(new AggregationServer()); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); } } } diff --git a/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj b/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj index d318a4c04..822483671 100644 --- a/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj +++ b/Workshop/AlarmCondition/Client/AlarmCondition Client.csproj @@ -216,8 +216,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/AlarmCondition/Client/AuditEventForm.cs b/Workshop/AlarmCondition/Client/AuditEventForm.cs index 3619da710..e4d95d411 100644 --- a/Workshop/AlarmCondition/Client/AuditEventForm.cs +++ b/Workshop/AlarmCondition/Client/AuditEventForm.cs @@ -58,7 +58,7 @@ public AuditEventForm() /// The session. /// The subscription. /// The cancellation token. - public async Task InitializeAsync(ISession session, Subscription subscription, CancellationToken ct = default) + public async Task InitializeAsync(ISession session, Subscription subscription, ITelemetryContext telemetry, CancellationToken ct = default) { InitializeComponent(); @@ -83,7 +83,7 @@ public async Task InitializeAsync(ISession session, Subscription subscription, C m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); // create a monitored item based on the current filter settings. - m_monitoredItem = m_filter.CreateMonitoredItem(m_session); + m_monitoredItem = m_filter.CreateMonitoredItem(m_session, telemetry); // set up callback for notifications. m_monitoredItem.Notification += m_MonitoredItem_Notification; @@ -266,7 +266,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -289,7 +289,7 @@ private void Events_ViewMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -306,7 +306,7 @@ private void Events_ClearMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -324,7 +324,7 @@ private void AuditEventForm_FormClosing(object sender, FormClosingEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/AlarmCondition/Client/FilterDefinition.cs b/Workshop/AlarmCondition/Client/FilterDefinition.cs index 9d2248c2f..fb3ef5bf2 100644 --- a/Workshop/AlarmCondition/Client/FilterDefinition.cs +++ b/Workshop/AlarmCondition/Client/FilterDefinition.cs @@ -72,7 +72,7 @@ public class FilterDefinition /// /// The session. /// The monitored item. - public MonitoredItem CreateMonitoredItem(ISession session) + public MonitoredItem CreateMonitoredItem(ISession session, ITelemetryContext telemetry) { // choose the server object by default. if (AreaId == null) @@ -81,7 +81,7 @@ public MonitoredItem CreateMonitoredItem(ISession session) } // create the item with the filter. - MonitoredItem monitoredItem = new MonitoredItem(); + MonitoredItem monitoredItem = new MonitoredItem(telemetry); monitoredItem.DisplayName = null; monitoredItem.StartNodeId = AreaId; diff --git a/Workshop/AlarmCondition/Client/FormUtils.cs b/Workshop/AlarmCondition/Client/FormUtils.cs index 4c75780ed..c750eeda6 100644 --- a/Workshop/AlarmCondition/Client/FormUtils.cs +++ b/Workshop/AlarmCondition/Client/FormUtils.cs @@ -62,7 +62,7 @@ public static class FormUtils /// The discovery URL. /// if set to true select an endpoint that uses security. /// The best available endpoint. - public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, CancellationToken ct = default) + public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, ITelemetryContext telemetry, CancellationToken ct = default) { // needs to add the '/discovery' back onto non-UA TCP URLs. if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp)) @@ -83,7 +83,7 @@ public static async Task SelectEndpointAsync(string discove EndpointDescription selectedEndpoint = null; // Connect to the server's discovery endpoint and find the available configuration. - using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration)) + using (DiscoveryClient client = await DiscoveryClient.CreateAsync(uri, configuration, telemetry, DiagnosticsMasks.None, ct)) { EndpointDescriptionCollection endpoints = await client.GetEndpointsAsync(null, ct); @@ -271,13 +271,20 @@ public static async Task ConstructEventAsync( switch (id.Value) { - case ObjectTypes.ConditionType: { e = new ConditionState(null); break; } - case ObjectTypes.DialogConditionType: { e = new DialogConditionState(null); break; } - case ObjectTypes.AlarmConditionType: { e = new AlarmConditionState(null); break; } - case ObjectTypes.ExclusiveLimitAlarmType: { e = new ExclusiveLimitAlarmState(null); break; } - case ObjectTypes.NonExclusiveLimitAlarmType: { e = new NonExclusiveLimitAlarmState(null); break; } - case ObjectTypes.AuditEventType: { e = new AuditEventState(null); break; } - case ObjectTypes.AuditUpdateMethodEventType: { e = new AuditUpdateMethodEventState(null); break; } + case ObjectTypes.ConditionType: + { e = new ConditionState(null); break; } + case ObjectTypes.DialogConditionType: + { e = new DialogConditionState(null); break; } + case ObjectTypes.AlarmConditionType: + { e = new AlarmConditionState(null); break; } + case ObjectTypes.ExclusiveLimitAlarmType: + { e = new ExclusiveLimitAlarmState(null); break; } + case ObjectTypes.NonExclusiveLimitAlarmType: + { e = new NonExclusiveLimitAlarmState(null); break; } + case ObjectTypes.AuditEventType: + { e = new AuditEventState(null); break; } + case ObjectTypes.AuditUpdateMethodEventType: + { e = new AuditUpdateMethodEventState(null); break; } default: { diff --git a/Workshop/AlarmCondition/Client/MainForm.cs b/Workshop/AlarmCondition/Client/MainForm.cs index cb4272cb7..bc7b0be3e 100644 --- a/Workshop/AlarmCondition/Client/MainForm.cs +++ b/Workshop/AlarmCondition/Client/MainForm.cs @@ -60,7 +60,7 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); @@ -74,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) // the filter to use. m_filter = new FilterDefinition(); + m_telemetry = telemetry; m_filter.AreaId = ObjectIds.Server; m_filter.Severity = EventSeverity.Min; @@ -108,6 +109,7 @@ public MainForm(ApplicationConfiguration configuration) private MonitoredItemNotificationEventHandler m_MonitoredItem_Notification; private AuditEventForm m_auditEventForm; private bool m_connectedOnce; + private readonly ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -121,11 +123,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -140,7 +142,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -155,7 +157,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -187,7 +189,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } // create the default subscription. - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.DisplayName = null; m_subscription.PublishingInterval = 1000; @@ -211,7 +213,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) ObjectTypeIds.NonExclusiveLimitAlarmType); // create a monitored item based on the current filter settings. - m_monitoredItem = m_filter.CreateMonitoredItem(m_session); + m_monitoredItem = m_filter.CreateMonitoredItem(m_session, m_telemetry); // set up callback for notifications. m_monitoredItem.Notification += m_MonitoredItem_Notification; @@ -227,7 +229,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -243,7 +245,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -286,7 +288,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -310,7 +312,7 @@ private async Task UpdateFilterAsync(CancellationToken ct = default) // changing the filter changes the fields requested. this makes it // impossible to process notifications sent before the change. // to avoid this problem we create a new item and remove the old one. - MonitoredItem monitoredItem = m_filter.CreateMonitoredItem(m_session); + MonitoredItem monitoredItem = m_filter.CreateMonitoredItem(m_session, m_telemetry); // set up callback for notifications. monitoredItem.Notification += m_MonitoredItem_Notification; @@ -786,7 +788,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -826,7 +828,7 @@ private async void Conditions_RefreshMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -843,7 +845,7 @@ private async void Conditions_EnableMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -860,7 +862,7 @@ private async void Conditions_DisableMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -908,7 +910,7 @@ private void ConditionsMI_DropDownOpening(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -925,7 +927,7 @@ private async void Conditions_AddCommentMI_ClickAsync(object sender, EventArgs e } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -942,7 +944,7 @@ private async void Conditions_AcknowledgeMI_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -959,7 +961,7 @@ private async void Conditions_ConfirmMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -976,7 +978,7 @@ private async void Conditions_UnshelveMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -993,7 +995,7 @@ private async void Conditions_ManualShelveMI_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1010,7 +1012,7 @@ private async void Conditions_OneShotShelveMI_ClickAsync(object sender, EventArg } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1027,7 +1029,7 @@ private async void Conditions_TimedShelveMI_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1050,7 +1052,7 @@ private void Conditions_MonitorMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1074,7 +1076,7 @@ private async void Conditions_SeverityMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1127,7 +1129,7 @@ private async void Conditions_TypeMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1153,7 +1155,7 @@ private async void Conditions_SetAreaFilterMI_ClickAsync(object sender, EventArg } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1169,7 +1171,7 @@ private async void View_AuditEventsMI_ClickAsync(object sender, EventArgs e) if (m_auditEventForm == null) { m_auditEventForm = new AuditEventForm(); - await m_auditEventForm.InitializeAsync(m_session, m_subscription); + await m_auditEventForm.InitializeAsync(m_session, m_subscription, m_telemetry); m_auditEventForm.FormClosing += new FormClosingEventHandler(AuditEventForm_FormClosing); } @@ -1179,7 +1181,7 @@ private async void View_AuditEventsMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1226,7 +1228,7 @@ private async void Conditions_RespondMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Workshop/AlarmCondition/Client/Program.cs b/Workshop/AlarmCondition/Client/Program.cs index 51d607db2..b382c5ab0 100644 --- a/Workshop/AlarmCondition/Client/Program.cs +++ b/Workshop/AlarmCondition/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -31,14 +31,30 @@ using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; namespace Quickstarts.AlarmConditionClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "AlarmConditionClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs index 7777992e9..733f92bb8 100644 --- a/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs +++ b/Workshop/AlarmCondition/Client/SetAreaFilterDlg.cs @@ -120,7 +120,7 @@ private void BrowseTV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -151,7 +151,7 @@ private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -204,7 +204,7 @@ private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEvent } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj b/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj index 771cd21ba..2c5cf7488 100644 --- a/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj +++ b/Workshop/AlarmCondition/Server/AlarmCondition Server.csproj @@ -179,8 +179,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs b/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs index 32623e1f8..ec5075100 100644 --- a/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs +++ b/Workshop/AlarmCondition/Server/AlarmConditionNodeManager.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Threading; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -55,12 +56,14 @@ public AlarmConditionServerNodeManager(IServerInternal server, ApplicationConfig : base(server, configuration, Namespaces.AlarmCondition) { - SystemContext.SystemHandle = m_system = new UnderlyingSystem(); + SystemContext.SystemHandle = m_system = new UnderlyingSystem(server.Telemetry); SystemContext.NodeIdFactory = this; // get the configuration for the node manager. m_configuration = configuration.ParseExtension(); + m_logger = server.Telemetry.CreateLogger(); + // use suitable defaults if no configuration exists. if (m_configuration == null) { @@ -189,7 +192,7 @@ private void OnRaiseSystemEvents(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error in OnRaiseSystemEvents"); + m_logger.LogError(e, "Unexpected error in OnRaiseSystemEvents"); } } @@ -428,6 +431,7 @@ protected override NodeState ValidateNode( #region Private Fields private UnderlyingSystem m_system; private AlarmConditionServerConfiguration m_configuration; + private ILogger m_logger; private Dictionary m_areas; private Dictionary m_sources; private Timer m_simulationTimer; diff --git a/Workshop/AlarmCondition/Server/AlarmConditionServer.cs b/Workshop/AlarmCondition/Server/AlarmConditionServer.cs index cf50b2eea..a957c58d8 100644 --- a/Workshop/AlarmCondition/Server/AlarmConditionServer.cs +++ b/Workshop/AlarmCondition/Server/AlarmConditionServer.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -68,7 +69,8 @@ public IServerInternal ServerInstance /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/AlarmCondition/Server/Model/SourceState.cs b/Workshop/AlarmCondition/Server/Model/SourceState.cs index 484950a8e..d43fbfcb8 100644 --- a/Workshop/AlarmCondition/Server/Model/SourceState.cs +++ b/Workshop/AlarmCondition/Server/Model/SourceState.cs @@ -726,12 +726,7 @@ private uint GetRecordNumber(AlarmConditionState alarm) /// private string GetUserName(ISystemContext context) { - if (context.UserIdentity != null) - { - return context.UserIdentity.DisplayName; - } - - return null; + return (context as ISessionSystemContext)?.UserIdentity?.DisplayName; } #endregion diff --git a/Workshop/AlarmCondition/Server/Program.cs b/Workshop/AlarmCondition/Server/Program.cs index 6bd59a7e6..3b1e26b03 100644 --- a/Workshop/AlarmCondition/Server/Program.cs +++ b/Workshop/AlarmCondition/Server/Program.cs @@ -31,14 +31,30 @@ using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Configuration; using Opc.Ua.Server.Controls; namespace Quickstarts.AlarmConditionServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,25 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "AlarmConditionServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new AlarmConditionServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -79,11 +82,11 @@ static void Main() application.StartAsync(new AlarmConditionServer()).Wait(); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs index c2b5e1f94..19a2de390 100644 --- a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs +++ b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystem.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Threading; +using Microsoft.Extensions.Logging; using Opc.Ua; namespace Quickstarts.AlarmConditionServer @@ -43,9 +44,10 @@ public class UnderlyingSystem : IDisposable /// /// Initializes a new instance of the class. /// - public UnderlyingSystem() + public UnderlyingSystem(ITelemetryContext telemetry) { m_sources = new Dictionary(); + m_logger = telemetry.CreateLogger(); } #endregion @@ -97,7 +99,7 @@ public UnderlyingSystemSource CreateSource(string sourcePath, AlarmChangedEventH lock (m_lock) { // create a new source. - source = new UnderlyingSystemSource(); + source = new UnderlyingSystemSource(m_logger); // extract the name from the path. string name = sourcePath; @@ -219,7 +221,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error running simulation for system"); + m_logger.LogError(e, "Unexpected error running simulation for system"); } } #endregion @@ -229,6 +231,7 @@ private void DoSimulation(object state) private Dictionary m_sources; private Timer m_simulationTimer; private long m_simulationCounter; + private ILogger m_logger; #endregion } } diff --git a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs index 4da2a08a2..24587c8f9 100644 --- a/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs +++ b/Workshop/AlarmCondition/Server/UnderlyingSystem/UnderlyingSystemSource.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Opc.Ua; namespace Quickstarts.AlarmConditionServer @@ -42,10 +43,11 @@ public class UnderlyingSystemSource /// /// Initializes a new instance of the class. /// - public UnderlyingSystemSource() + public UnderlyingSystemSource(ILogger logger) { m_alarms = new List(); m_archive = new Dictionary(); + m_logger = logger; } #endregion @@ -402,7 +404,7 @@ public void DoSimulation(long counter, int index) } catch (Exception e) { - Utils.Trace(e, "Unexpected error running simulation for source {0}", m_sourcePath); + m_logger.LogError(e, "Unexpected error running simulation for source {0}", m_sourcePath); } } #endregion @@ -460,7 +462,7 @@ private void ReportAlarmChange(UnderlyingSystemAlarm alarm) } catch (Exception e) { - Utils.Trace(e, "Unexpected error reporting change to an Alarm for Source {0}.", m_sourcePath); + m_logger.LogError(e, "Unexpected error reporting change to an Alarm for Source {0}.", m_sourcePath); } } } @@ -600,6 +602,7 @@ private void UpdateAlarm(UnderlyingSystemAlarm alarm, long counter, int index, L private string m_sourceType; private List m_alarms; private Dictionary m_archive; + private ILogger m_logger; private bool m_isOffline; private uint m_nextRecordNumber; #endregion diff --git a/Workshop/Boiler/Client/Boiler Client.csproj b/Workshop/Boiler/Client/Boiler Client.csproj index aeff3dae4..f9c5fbe6a 100644 --- a/Workshop/Boiler/Client/Boiler Client.csproj +++ b/Workshop/Boiler/Client/Boiler Client.csproj @@ -142,8 +142,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Boiler/Client/MainForm.cs b/Workshop/Boiler/Client/MainForm.cs index 5c41668a2..964365456 100644 --- a/Workshop/Boiler/Client/MainForm.cs +++ b/Workshop/Boiler/Client/MainForm.cs @@ -60,7 +60,7 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); @@ -68,6 +68,7 @@ public MainForm(ApplicationConfiguration configuration) ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62567/Quickstarts/BoilerServer"; this.Text = m_configuration.ApplicationName; + m_telemetry = telemetry; } #endregion @@ -76,6 +77,7 @@ public MainForm(ApplicationConfiguration configuration) private ISession m_session; private Subscription m_subscription; private bool m_connectedOnce; + private readonly ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -89,11 +91,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -110,7 +112,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -125,7 +127,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -158,7 +160,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -173,7 +175,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -196,7 +198,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -275,7 +277,7 @@ private async void BoilerCB_SelectedIndexChangedAsync(object sender, EventArgs e return; } - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.PublishingEnabled = true; m_subscription.PublishingInterval = 1000; @@ -319,7 +321,7 @@ private async void BoilerCB_SelectedIndexChangedAsync(object sender, EventArgs e if (nodes[ii] != null) { - MonitoredItem monitoredItem = new MonitoredItem(); + MonitoredItem monitoredItem = new MonitoredItem(m_telemetry); monitoredItem.StartNodeId = nodes[ii]; monitoredItem.AttributeId = Attributes.Value; monitoredItem.Handle = controls[ii]; @@ -332,7 +334,7 @@ private async void BoilerCB_SelectedIndexChangedAsync(object sender, EventArgs e } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -364,7 +366,7 @@ void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotifi } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Boiler/Client/Program.cs b/Workshop/Boiler/Client/Program.cs index 86e41f196..623d30aca 100644 --- a/Workshop/Boiler/Client/Program.cs +++ b/Workshop/Boiler/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.Boiler.Client { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "BoilerClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Boiler/Server/Boiler Server.csproj b/Workshop/Boiler/Server/Boiler Server.csproj index ae4fb5e6b..ace8f71a5 100644 --- a/Workshop/Boiler/Server/Boiler Server.csproj +++ b/Workshop/Boiler/Server/Boiler Server.csproj @@ -140,8 +140,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Boiler/Server/BoilerNodeManager.cs b/Workshop/Boiler/Server/BoilerNodeManager.cs index d209dc92e..2c20ec552 100644 --- a/Workshop/Boiler/Server/BoilerNodeManager.cs +++ b/Workshop/Boiler/Server/BoilerNodeManager.cs @@ -37,6 +37,7 @@ using System.Reflection; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.Boiler.Server { @@ -261,7 +262,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error during simulation."); + m_logger.LogError(e, "Unexpected error during simulation."); } } #endregion diff --git a/Workshop/Boiler/Server/BoilerServer.cs b/Workshop/Boiler/Server/BoilerServer.cs index fb70c8c14..50cd3fa12 100644 --- a/Workshop/Boiler/Server/BoilerServer.cs +++ b/Workshop/Boiler/Server/BoilerServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class BoilerServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/Boiler/Server/Program.cs b/Workshop/Boiler/Server/Program.cs index b89335df4..7842eaec6 100644 --- a/Workshop/Boiler/Server/Program.cs +++ b/Workshop/Boiler/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.Boiler.Server { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "BoilerServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new BoilerServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new BoilerServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Common/BackwardCompatibility.cs b/Workshop/Common/BackwardCompatibility.cs index 6301d7162..b70dfa94b 100644 --- a/Workshop/Common/BackwardCompatibility.cs +++ b/Workshop/Common/BackwardCompatibility.cs @@ -84,14 +84,14 @@ public ServerForm() : base() /// /// Creates a form which displays the status for a UA server. /// - public ServerForm(StandardServer server, ApplicationConfiguration configuration) : base(server, configuration) + public ServerForm(StandardServer server, ApplicationConfiguration configuration, ITelemetryContext telemetry) : base(server, configuration, telemetry) { } /// /// Creates a form which displays the status for a UA server. /// - public ServerForm(ApplicationInstance application) : base(application) + public ServerForm(ApplicationInstance application, ITelemetryContext telemetry) : base(application, telemetry) { } } diff --git a/Workshop/Common/FilterDefinition.cs b/Workshop/Common/FilterDefinition.cs index 5ed4c1a77..e5ae19341 100644 --- a/Workshop/Common/FilterDefinition.cs +++ b/Workshop/Common/FilterDefinition.cs @@ -67,7 +67,7 @@ public class FilterDefinition /// /// The session. /// The monitored item. - public MonitoredItem CreateMonitoredItem(Session session) + public MonitoredItem CreateMonitoredItem(ISession session, ITelemetryContext telemetry) { // choose the server object by default. if (AreaId == null) @@ -76,7 +76,7 @@ public MonitoredItem CreateMonitoredItem(Session session) } // create the item with the filter. - MonitoredItem monitoredItem = new MonitoredItem(); + MonitoredItem monitoredItem = new MonitoredItem(telemetry); monitoredItem.DisplayName = null; monitoredItem.StartNodeId = AreaId; @@ -151,7 +151,7 @@ public async Task ConstructSelectClausesAsync( /// Constructs the event filter for the subscription. /// /// The event filter. - public EventFilter ConstructFilter(Session session) + public EventFilter ConstructFilter(ISession session) { EventFilter filter = new EventFilter(); diff --git a/Workshop/Common/FormUtils.cs b/Workshop/Common/FormUtils.cs index 6c09c6f54..7de25ccf2 100644 --- a/Workshop/Common/FormUtils.cs +++ b/Workshop/Common/FormUtils.cs @@ -265,7 +265,7 @@ public static async Task GetAttributeDisplayTextAsync(Session session, u /// /// The configuration. /// A list of server urls. - public static async Task> DiscoverServersAsync(ApplicationConfiguration configuration, CancellationToken ct = default) + public static async Task> DiscoverServersAsync(ApplicationConfiguration configuration, ITelemetryContext telemetry, CancellationToken ct = default) { List serverUrls = new List(); @@ -274,7 +274,7 @@ public static async Task> DiscoverServersAsync(ApplicationConfigur endpointConfiguration.OperationTimeout = 5000; // Connect to the local discovery server and find the available servers. - using (DiscoveryClient client = DiscoveryClient.Create(new Uri("opc.tcp://localhost:4840"), endpointConfiguration)) + using (DiscoveryClient client = await DiscoveryClient.CreateAsync(new Uri("opc.tcp://localhost:4840"), endpointConfiguration, telemetry, DiagnosticsMasks.None, ct)) { ApplicationDescriptionCollection servers = await client.FindServersAsync(null, ct); @@ -316,7 +316,7 @@ public static async Task> DiscoverServersAsync(ApplicationConfigur /// if set to true select an endpoint that uses security. /// The token to cancel the operation with /// The best available endpoint. - public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, CancellationToken ct = default) + public static async Task SelectEndpointAsync(string discoveryUrl, bool useSecurity, ITelemetryContext telemetry, CancellationToken ct = default) { // needs to add the '/discovery' back onto non-UA TCP URLs. if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp)) @@ -337,7 +337,7 @@ public static async Task SelectEndpointAsync(string discove EndpointDescription selectedEndpoint = null; // Connect to the server's discovery endpoint and find the available configuration. - using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration)) + using (DiscoveryClient client = await DiscoveryClient.CreateAsync(uri, configuration, telemetry, DiagnosticsMasks.None, ct)) { EndpointDescriptionCollection endpoints = await client.GetEndpointsAsync(null, ct); diff --git a/Workshop/Common/Quickstart Library.csproj b/Workshop/Common/Quickstart Library.csproj index 1b34baea4..8a1b7e857 100644 --- a/Workshop/Common/Quickstart Library.csproj +++ b/Workshop/Common/Quickstart Library.csproj @@ -133,7 +133,7 @@ - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Common/QuickstartNodeManager.cs b/Workshop/Common/QuickstartNodeManager.cs index ef86b1519..a43bf07c8 100644 --- a/Workshop/Common/QuickstartNodeManager.cs +++ b/Workshop/Common/QuickstartNodeManager.cs @@ -33,6 +33,7 @@ using System.Reflection; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts { @@ -81,6 +82,8 @@ protected QuickstartNodeManager( // save a reference to the UA server instance that owns the node manager. m_server = server; + m_logger = server.Telemetry.CreateLogger(); + // all operations require information about the system m_systemContext = m_server.DefaultSystemContext.Copy(); @@ -2177,7 +2180,7 @@ protected virtual void HistoryRead( } // validate the event filter. - EventFilter.Result result = readEventDetails.Filter.Validate(new FilterContext(m_server.NamespaceUris, m_server.TypeTree, context)); + EventFilter.Result result = readEventDetails.Filter.Validate(new FilterContext(m_server.NamespaceUris, m_server.TypeTree, context, Server.Telemetry)); if (ServiceResult.IsBad(result.Status)) { @@ -2732,7 +2735,7 @@ protected virtual ServiceResult Call( if (ServiceResult.IsBad(argumentError)) { argumentsValid = false; - result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable)); + result.InputArgumentDiagnosticInfos.Add(new DiagnosticInfo(argumentError, systemContext.OperationContext.DiagnosticsMask, false, systemContext.OperationContext.StringTable, m_logger)); } else { @@ -3096,7 +3099,7 @@ public virtual void CreateMonitoredItems( IList filterResults, IList monitoredItems, bool createDurable, - ref long globalIdCounter) + MonitoredItemIdFactory globalIdCounter) { ServerSystemContext systemContext = m_systemContext.Copy(context); IDictionary operationCache = new NodeIdDictionary(); @@ -3171,7 +3174,7 @@ public virtual void CreateMonitoredItems( context.DiagnosticsMask, timestampsToReturn, itemToCreate, - ref globalIdCounter, + globalIdCounter, out filterResult, out monitoredItem); } @@ -3216,7 +3219,7 @@ protected virtual ServiceResult CreateMonitoredItem( DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, - ref long globalIdCounter, + MonitoredItemIdFactory globalIdCounter, out MonitoringFilterResult filterResult, out IMonitoredItem monitoredItem) { @@ -3245,7 +3248,7 @@ protected virtual ServiceResult CreateMonitoredItem( handle.MonitoredNode = monitoredNode; // create a globally unique identifier. - uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter); + uint monitoredItemId = globalIdCounter.GetNextId(); // determine the sampling interval. double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval; @@ -4189,6 +4192,7 @@ public void RestoreMonitoredItems(IList itemsToRestore, IL #region Private Fields private object m_lock = new object(); private IServerInternal m_server; + private readonly ILogger m_logger; private ServerSystemContext m_systemContext; private string[] m_namespaceUris; private ushort[] m_namespaceIndexes; diff --git a/Workshop/DataAccess/Client/DataAccess Client.csproj b/Workshop/DataAccess/Client/DataAccess Client.csproj index 486738dc4..8df214828 100644 --- a/Workshop/DataAccess/Client/DataAccess Client.csproj +++ b/Workshop/DataAccess/Client/DataAccess Client.csproj @@ -184,8 +184,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/DataAccess/Client/MainForm.cs b/Workshop/DataAccess/Client/MainForm.cs index 33db946f9..3b4b7ff0c 100644 --- a/Workshop/DataAccess/Client/MainForm.cs +++ b/Workshop/DataAccess/Client/MainForm.cs @@ -60,10 +60,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62548/Quickstarts/DataAccessServer"; @@ -77,6 +78,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private bool m_connectedOnce; private Subscription m_subscription; private MonitoredItemNotificationEventHandler m_monitoredItem_Notification; @@ -93,11 +95,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync().ConfigureAwait(false); + await ConnectServerCTRL.ConnectAsync(m_telemetry).ConfigureAwait(false); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -115,7 +117,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -130,7 +132,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -166,7 +168,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -183,7 +185,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -207,7 +209,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -276,7 +278,7 @@ private async Task PopulateBranchAsync(NodeId sourceId, TreeNodeCollection nodes } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -444,7 +446,7 @@ private async Task DisplayAttributesAsync(NodeId sourceId, CancellationToken ct } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -519,7 +521,7 @@ private async void BrowseNodesTV_BeforeExpandAsync(object sender, TreeViewCancel } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -543,7 +545,7 @@ private async void BrowseNodesTV_AfterSelectAsync(object sender, TreeViewEventAr } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -558,7 +560,7 @@ private void BrowseNodesTV_MouseDown(object sender, MouseEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -607,7 +609,7 @@ private async void Browse_MonitorMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -696,7 +698,7 @@ private async void Browse_WriteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -727,7 +729,7 @@ private async void Browse_ReadHistoryMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -764,7 +766,7 @@ private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredIt } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -830,7 +832,7 @@ private async void Monitoring_MonitoringMode_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -900,7 +902,7 @@ private async void Monitoring_SamplingInterval_ClickAsync(object sender, EventAr } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -994,7 +996,7 @@ private async void Monitoring_Deadband_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1062,7 +1064,7 @@ private async void Monitoring_DeleteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1110,7 +1112,7 @@ private async void Monitoring_WriteMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1124,7 +1126,7 @@ private void File_LoadMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1138,7 +1140,7 @@ private void File_SaveMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1167,7 +1169,7 @@ private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1178,7 +1180,7 @@ private void Server_SetUserMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/DataAccess/Client/Program.cs b/Workshop/DataAccess/Client/Program.cs index 9cf739b86..e39930dfb 100644 --- a/Workshop/DataAccess/Client/Program.cs +++ b/Workshop/DataAccess/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,14 +30,30 @@ using System; using System.Collections.Generic; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; namespace Quickstarts.DataAccessClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -49,18 +65,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "DataAccessClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -68,11 +78,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/DataAccess/Client/ReadHistoryDlg.cs b/Workshop/DataAccess/Client/ReadHistoryDlg.cs index b377b9e09..4d67bfc09 100644 --- a/Workshop/DataAccess/Client/ReadHistoryDlg.cs +++ b/Workshop/DataAccess/Client/ReadHistoryDlg.cs @@ -434,7 +434,7 @@ private void GoBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, "Error Reading History", exception); } } @@ -446,7 +446,7 @@ private void NextBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, "Error Reading History", exception); } } @@ -458,7 +458,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, "Error Reading History", exception); } } diff --git a/Workshop/DataAccess/Client/WriteValueDlg.cs b/Workshop/DataAccess/Client/WriteValueDlg.cs index cf0f3a125..d86e9de77 100644 --- a/Workshop/DataAccess/Client/WriteValueDlg.cs +++ b/Workshop/DataAccess/Client/WriteValueDlg.cs @@ -241,7 +241,7 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Writing Value", exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, "Error Writing Value", exception); } } #endregion diff --git a/Workshop/DataAccess/Server/DataAccess Server.csproj b/Workshop/DataAccess/Server/DataAccess Server.csproj index 31405e961..8016d6ead 100644 --- a/Workshop/DataAccess/Server/DataAccess Server.csproj +++ b/Workshop/DataAccess/Server/DataAccess Server.csproj @@ -167,8 +167,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/DataAccess/Server/DataAccessNodeManager.cs b/Workshop/DataAccess/Server/DataAccessNodeManager.cs index b2b2d61a7..b8eede7b5 100644 --- a/Workshop/DataAccess/Server/DataAccessNodeManager.cs +++ b/Workshop/DataAccess/Server/DataAccessNodeManager.cs @@ -55,7 +55,7 @@ public DataAccessServerNodeManager(IServerInternal server, ApplicationConfigurat { this.AliasRoot = "DA"; - SystemContext.SystemHandle = m_system = new UnderlyingSystem(); + SystemContext.SystemHandle = m_system = new UnderlyingSystem(server.Telemetry); SystemContext.NodeIdFactory = this; // get the configuration for the node manager. @@ -141,7 +141,7 @@ public override void CreateAddressSpace(IDictionary> e } // start the simulation. - m_system.StartSimulation(); + m_system.StartSimulation(Server.Telemetry); } } diff --git a/Workshop/DataAccess/Server/DataAccessServer.cs b/Workshop/DataAccess/Server/DataAccessServer.cs index 12115c8f6..a4ae730f9 100644 --- a/Workshop/DataAccess/Server/DataAccessServer.cs +++ b/Workshop/DataAccess/Server/DataAccessServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -69,7 +70,8 @@ public IServerInternal ServerInstance /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/DataAccess/Server/Program.cs b/Workshop/DataAccess/Server/Program.cs index 0a69f2713..11d7d6c8c 100644 --- a/Workshop/DataAccess/Server/Program.cs +++ b/Workshop/DataAccess/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.DataAccessServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "DataAccessServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new DataAccessServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new DataAccessServer()).Wait(); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs index 4c057caf3..3389f6d76 100644 --- a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs +++ b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystem.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Threading; +using Microsoft.Extensions.Logging; using Opc.Ua; namespace Quickstarts.DataAccessServer @@ -43,9 +44,11 @@ public class UnderlyingSystem : IDisposable /// /// Initializes a new instance of the class. /// - public UnderlyingSystem() + public UnderlyingSystem(ITelemetryContext telemetry) { m_blocks = new Dictionary(); + m_telemetry = telemetry; + m_logger = telemetry.CreateLogger(); } #endregion @@ -445,7 +448,7 @@ public UnderlyingSystemBlock FindBlock(string blockId) } // create a new block. - block = new UnderlyingSystemBlock(); + block = new UnderlyingSystemBlock(m_logger); // create the block. block.Id = blockId; @@ -566,7 +569,7 @@ public IList FindSegmentsForBlock(string blockId) /// Once an tag is confirmed it go to the inactive state. /// If the tag stays active the severity will be gradually increased. /// - public void StartSimulation() + public void StartSimulation(ITelemetryContext telemetry) { lock (m_lock) { @@ -576,7 +579,7 @@ public void StartSimulation() m_simulationTimer = null; } - m_generator = new Opc.Ua.Test.DataGenerator(null); + m_generator = new Opc.Ua.Test.DataGenerator(null, telemetry); m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000); } } @@ -622,7 +625,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error running simulation for system"); + m_logger.LogError(e, "Unexpected error running simulation for system"); } } #endregion @@ -630,6 +633,8 @@ private void DoSimulation(object state) #region Private Fields private object m_lock = new object(); private Dictionary m_blocks; + private ITelemetryContext m_telemetry; + private ILogger m_logger; private Timer m_simulationTimer; private long m_simulationCounter; private Opc.Ua.Test.DataGenerator m_generator; diff --git a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs index e0209f7a3..78c276aaa 100644 --- a/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs +++ b/Workshop/DataAccess/Server/UnderlyingSystem/UnderlyingSystemBlock.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Opc.Ua; namespace Quickstarts.DataAccessServer @@ -42,9 +43,10 @@ public class UnderlyingSystemBlock /// /// Initializes a new instance of the class. /// - public UnderlyingSystemBlock() + public UnderlyingSystemBlock(ILogger logger) { m_tags = new List(); + m_logger = logger; } #endregion @@ -332,14 +334,11 @@ public void DoSimulation(long counter, int index, Opc.Ua.Test.DataGenerator gene } // report any tag changes after releasing the lock. - if (onTagsChanged != null) - { - onTagsChanged(snapshots); - } + onTagsChanged?.Invoke(snapshots); } catch (Exception e) { - Utils.Trace(e, "Unexpected error running simulation for block {0}", m_name); + m_logger.LogError(e, "Unexpected error running simulation for block {0}", m_name); } } #endregion @@ -558,6 +557,7 @@ private bool UpdateTagMetadata( private DateTime m_timestamp; private List m_tags; private TagsChangedEventHandler OnTagsChanged; + private ILogger m_logger; #endregion } diff --git a/Workshop/DataTypes/Client/DataTypes Client.csproj b/Workshop/DataTypes/Client/DataTypes Client.csproj index f1b40b8b1..c60a0f2aa 100644 --- a/Workshop/DataTypes/Client/DataTypes Client.csproj +++ b/Workshop/DataTypes/Client/DataTypes Client.csproj @@ -124,8 +124,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/DataTypes/Client/MainForm.cs b/Workshop/DataTypes/Client/MainForm.cs index dc8e73f72..46a2ffc42 100644 --- a/Workshop/DataTypes/Client/MainForm.cs +++ b/Workshop/DataTypes/Client/MainForm.cs @@ -59,10 +59,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62555/DataTypesServer"; @@ -73,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -86,11 +88,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -105,7 +107,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -120,7 +122,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -136,6 +138,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) // browse the instances in the server. await BrowseCTRL.InitializeAsync(m_session, ObjectIds.RootFolder, + m_telemetry, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates, @@ -149,7 +152,7 @@ await BrowseCTRL.InitializeAsync(m_session, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -164,7 +167,7 @@ private async void Server_ReconnectStartingAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -180,7 +183,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -205,7 +208,7 @@ private async void Browse_ViewValueMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/DataTypes/Client/Program.cs b/Workshop/DataTypes/Client/Program.cs index 855ba19c8..ab200c6bf 100644 --- a/Workshop/DataTypes/Client/Program.cs +++ b/Workshop/DataTypes/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.DataTypes { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "DataTypesClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -72,11 +82,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/DataTypes/Common/DataTypes Library.csproj b/Workshop/DataTypes/Common/DataTypes Library.csproj index 4f3ae3762..6d200ef67 100644 --- a/Workshop/DataTypes/Common/DataTypes Library.csproj +++ b/Workshop/DataTypes/Common/DataTypes Library.csproj @@ -104,7 +104,7 @@ - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/DataTypes/Server/DataTypes Server.csproj b/Workshop/DataTypes/Server/DataTypes Server.csproj index 31453544d..0edbabd08 100644 --- a/Workshop/DataTypes/Server/DataTypes Server.csproj +++ b/Workshop/DataTypes/Server/DataTypes Server.csproj @@ -144,8 +144,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/DataTypes/Server/DataTypesServer.cs b/Workshop/DataTypes/Server/DataTypesServer.cs index 5702ff117..56ab7c734 100644 --- a/Workshop/DataTypes/Server/DataTypesServer.cs +++ b/Workshop/DataTypes/Server/DataTypesServer.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Xml; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -61,7 +62,8 @@ public partial class DataTypesServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); // add the types defined in the quickstart information model library to the factory. server.Factory.AddEncodeableTypes(typeof(Quickstarts.DataTypes.Types.VehicleType).Assembly); diff --git a/Workshop/DataTypes/Server/Program.cs b/Workshop/DataTypes/Server/Program.cs index 1fbc12191..19abc5cbd 100644 --- a/Workshop/DataTypes/Server/Program.cs +++ b/Workshop/DataTypes/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,18 +29,34 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; -using Quickstarts; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; +using Quickstarts; namespace Quickstarts.DataTypes { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -52,25 +68,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "DataTypesServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new DataTypesServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -81,11 +84,11 @@ static void Main() application.StartAsync(new DataTypesServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Empty/Client/Empty Client.csproj b/Workshop/Empty/Client/Empty Client.csproj index 4123d6d23..1d2a22c82 100644 --- a/Workshop/Empty/Client/Empty Client.csproj +++ b/Workshop/Empty/Client/Empty Client.csproj @@ -133,8 +133,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Empty/Client/MainForm.cs b/Workshop/Empty/Client/MainForm.cs index 24929d095..abe1e557e 100644 --- a/Workshop/Empty/Client/MainForm.cs +++ b/Workshop/Empty/Client/MainForm.cs @@ -58,10 +58,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62546/Quickstarts/EmptyServer"; @@ -72,6 +73,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private bool m_connectedOnce; #endregion @@ -86,11 +88,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -105,7 +107,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -120,7 +122,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -140,11 +142,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } // browse the instances in the server. - await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, m_telemetry, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -159,7 +161,7 @@ private async void Server_ReconnectStartingAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -175,7 +177,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Workshop/Empty/Client/Program.cs b/Workshop/Empty/Client/Program.cs index 66290ca7b..3e0e24f2f 100644 --- a/Workshop/Empty/Client/Program.cs +++ b/Workshop/Empty/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.EmptyClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.EmptyClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Empty/Server/Empty Server.csproj b/Workshop/Empty/Server/Empty Server.csproj index 302cea525..d5d2d994b 100644 --- a/Workshop/Empty/Server/Empty Server.csproj +++ b/Workshop/Empty/Server/Empty Server.csproj @@ -130,8 +130,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Empty/Server/EmptyServer.cs b/Workshop/Empty/Server/EmptyServer.cs index c63ac9308..bad957d45 100644 --- a/Workshop/Empty/Server/EmptyServer.cs +++ b/Workshop/Empty/Server/EmptyServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class EmptyServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/Empty/Server/Program.cs b/Workshop/Empty/Server/Program.cs index 8e29cd38a..13dd55568 100644 --- a/Workshop/Empty/Server/Program.cs +++ b/Workshop/Empty/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.EmptyServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.EmptyServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new EmptyServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new EmptyServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj b/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj index b2cadd427..1f66fe11b 100644 --- a/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj +++ b/Workshop/HistoricalAccess/Client/HistoricalAccess Client.csproj @@ -179,8 +179,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/HistoricalAccess/Client/MainForm.cs b/Workshop/HistoricalAccess/Client/MainForm.cs index 433df25d8..ad03607df 100644 --- a/Workshop/HistoricalAccess/Client/MainForm.cs +++ b/Workshop/HistoricalAccess/Client/MainForm.cs @@ -58,10 +58,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ReadCTRL.Reset(); ConnectServerCTRL.Configuration = m_configuration = configuration; @@ -73,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private bool m_connectedOnce; #endregion @@ -87,11 +89,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -106,7 +108,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -121,7 +123,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -140,11 +142,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) m_connectedOnce = true; } - await ReadCTRL.ChangeSessionAsync(m_session); + await ReadCTRL.ChangeSessionAsync(m_session, m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -160,7 +162,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -188,6 +190,7 @@ private async void Aggregates_SelectVariableMI_ClickAsync(object sender, EventAr m_session, Opc.Ua.ObjectIds.ObjectsFolder, "Select Variable to Monitor", + m_telemetry, default, ReferenceTypes.Organizes, ReferenceTypes.Aggregates); @@ -199,7 +202,7 @@ private async void Aggregates_SelectVariableMI_ClickAsync(object sender, EventAr } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -216,7 +219,7 @@ private async void ViewHistoricalConfigurationMI_ClickAsync(object sender, Event } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalAccess/Client/Program.cs b/Workshop/HistoricalAccess/Client/Program.cs index 5af2cb8a6..b0d06ed8a 100644 --- a/Workshop/HistoricalAccess/Client/Program.cs +++ b/Workshop/HistoricalAccess/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -30,14 +30,30 @@ using System; using System.Collections.Generic; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; namespace Quickstarts.HistoricalAccess.Client { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -49,18 +65,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "HistoricalAccessClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -68,11 +78,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs index 5cc4b504e..5a94cbcfb 100644 --- a/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs +++ b/Workshop/HistoricalAccess/Client/ReadHistoryDlg.cs @@ -82,6 +82,7 @@ private enum ReadType } private Session m_session; + private ITelemetryContext m_telemetry; private NodeId m_nodeId; private HistoryReadResult m_result; private int m_index; @@ -92,6 +93,7 @@ private enum ReadType public async Task ShowDialogAsync(Session session, NodeId nodeId, CancellationToken ct = default) { m_session = session; + m_telemetry = session?.MessageContext?.Telemetry; m_nodeId = nodeId; // update the title. @@ -440,7 +442,7 @@ private void GoBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } @@ -452,7 +454,7 @@ private void NextBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } @@ -464,7 +466,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } diff --git a/Workshop/HistoricalAccess/Client/WriteValueDlg.cs b/Workshop/HistoricalAccess/Client/WriteValueDlg.cs index 7e1d3302c..fc39c9eb6 100644 --- a/Workshop/HistoricalAccess/Client/WriteValueDlg.cs +++ b/Workshop/HistoricalAccess/Client/WriteValueDlg.cs @@ -58,6 +58,7 @@ public WriteValueDlg() #region Private Fields private Session m_session; + private ITelemetryContext m_telemetry; private NodeId m_nodeId; private uint m_attributeId; private DataValue m_value; @@ -75,6 +76,7 @@ public WriteValueDlg() public async Task ShowDialogAsync(Session session, NodeId nodeId, uint attributeId, CancellationToken ct = default) { m_session = session; + m_telemetry = session?.MessageContext?.Telemetry; m_nodeId = nodeId; m_attributeId = attributeId; @@ -242,7 +244,7 @@ private async void OkBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Writing Value", exception); + ClientUtils.HandleException(m_telemetry, "Error Writing Value", exception); } } #endregion diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj b/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj index 66bda8747..2c7138d52 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj +++ b/Workshop/HistoricalAccess/Server/HistoricalAccess Server.csproj @@ -193,8 +193,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs b/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs index cd5dc7c19..f7b24cdae 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs +++ b/Workshop/HistoricalAccess/Server/HistoricalAccessNodeManager.cs @@ -38,6 +38,7 @@ using System.Data; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.HistoricalAccessServer { @@ -172,7 +173,7 @@ private void CreateFolderFromResources(NodeState root, string folderName) ArchiveItem item = new ArchiveItem(resourcePath, Assembly.GetExecutingAssembly(), resourcePath); ArchiveItemState node = new ArchiveItemState(SystemContext, item, NamespaceIndex); - node.ReloadFromSource(SystemContext); + node.ReloadFromSource(SystemContext, Server.Telemetry); dataFolder.AddReference(ReferenceTypeIds.Organizes, false, node.NodeId); node.AddReference(ReferenceTypeIds.Organizes, true, dataFolder.NodeId); @@ -284,7 +285,7 @@ protected override NodeState ValidateNode( case NodeTypes.Item: { ArchiveItemState item = m_system.GetItemState(SystemContext, pnd); - item.LoadConfiguration(context); + item.LoadConfiguration(context, Server.Telemetry); target = item; break; } @@ -353,7 +354,7 @@ protected override void Read( if (item != null && item.ArchiveItem.LastLoadTime.AddMinutes(10) < DateTime.UtcNow) { - item.LoadConfiguration(context); + item.LoadConfiguration(context, Server.Telemetry); } ReadValueId nodeToRead = nodesToRead[handle.Index]; @@ -958,7 +959,7 @@ protected override void HistoryUpdateData( continue; } - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); // process each item. for (int jj = 0; jj < nodeToUpdate.UpdateValues.Count; jj++) @@ -1081,7 +1082,7 @@ protected override void HistoryDeleteRawModified( continue; } - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); // delete the history. item.DeleteHistory(context, nodeToUpdate.StartTime, nodeToUpdate.EndTime, nodeToUpdate.IsDeleteModified); @@ -1129,7 +1130,7 @@ protected override void HistoryDeleteAtTime( continue; } - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); // process each item. for (int jj = 0; jj < nodeToUpdate.ReqTimes.Count; jj++) @@ -1167,7 +1168,7 @@ private ArchiveItemState Reload(ISystemContext context, NodeHandle handle) if (item != null) { - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); } return item; @@ -1385,7 +1386,7 @@ private HistoryReadRequest CreateHistoryReadRequest( throw new ServiceResultException(StatusCodes.BadNotSupported); } - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); LinkedList values = new LinkedList(); @@ -1472,7 +1473,7 @@ private HistoryReadRequest CreateHistoryReadRequest( throw new ServiceResultException(StatusCodes.BadNotSupported); } - item.ReloadFromSource(context); + item.ReloadFromSource(context, Server.Telemetry); // find the start and end times. DateTime startTime = DateTime.MaxValue; @@ -1737,7 +1738,7 @@ private void DoSimulation(object state) { if (item.ArchiveItem.LastLoadTime.AddSeconds(10) < DateTime.UtcNow) { - item.LoadConfiguration(SystemContext); + item.LoadConfiguration(SystemContext, Server.Telemetry); } foreach (DataValue value in item.NewSamples(SystemContext)) @@ -1752,7 +1753,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace("Unexpected error during simulation: {0}", e.Message); + m_logger.LogError("Unexpected error during simulation: {0}", e.Message); } } #endregion diff --git a/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs b/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs index bbe63aa12..5423f9848 100644 --- a/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs +++ b/Workshop/HistoricalAccess/Server/HistoricalAccessServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -69,7 +70,8 @@ public IServerInternal ServerInstance /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/HistoricalAccess/Server/Program.cs b/Workshop/HistoricalAccess/Server/Program.cs index f475508c9..eb8f49098 100644 --- a/Workshop/HistoricalAccess/Server/Program.cs +++ b/Workshop/HistoricalAccess/Server/Program.cs @@ -29,22 +29,39 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; -using System.Security.Cryptography.X509Certificates; -using System.Reflection; using System.Data; -using System.Text; -using System.IO; using System.Globalization; +using System.IO; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.HistoricalAccessServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + private static ILogger m_logger; + /// /// The main entry point for the application. /// @@ -56,29 +73,18 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "HistoricalAccessServer"; + m_logger = m_telemetry.CreateLogger(nameof(Program)); + try { // DoTests(false, false, "Quickstarts.HistoricalAccessServer.Data.Historian1.txt", "..\\..\\Data\\Historian1ExpectedData.csv"); // DoTests(false, true, "Quickstarts.HistoricalAccessServer.Data.Historian2.txt", "..\\..\\Data\\Historian2ExpectedData.csv"); // DoTests(true, true, "Quickstarts.HistoricalAccessServer.Data.Historian3.txt", "..\\..\\Data\\Historian3ExpectedData.csv"); - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new HistoricalAccessServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -89,11 +95,11 @@ static void Main() application.StartAsync(new HistoricalAccessServer()).Wait(); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } @@ -292,7 +298,7 @@ static void DoTest(TestCase test, string filePath) ArchiveItem item = new ArchiveItem(test.DataPath, Assembly.GetExecutingAssembly(), test.DataPath); DataFileReader reader = new DataFileReader(); - reader.LoadConfiguration(null, item); + reader.LoadConfiguration(null, item, m_telemetry); reader.LoadHistoryData(null, item); AggregateConfiguration configuration = new AggregateConfiguration(); @@ -311,7 +317,8 @@ static void DoTest(TestCase test, string filePath) startTime.AddSeconds(100), 5000, test.Stepped, - configuration); + configuration, + m_telemetry); StringBuilder buffer = new StringBuilder(); List values = new List(); @@ -322,7 +329,7 @@ static void DoTest(TestCase test, string filePath) if (!calculator.QueueRawValue(rawValue)) { - Utils.Trace("Oops!"); + m_logger.LogTrace("Oops!"); continue; } @@ -343,13 +350,13 @@ static void DoTest(TestCase test, string filePath) { if (values[ii].SourceTimestamp != expectedValues[ii].SourceTimestamp) { - Utils.Trace("Wrong Status Timestamp"); + m_logger.LogTrace("Wrong Status Timestamp"); continue; } if (values[ii].StatusCode != expectedValues[ii].StatusCode) { - Utils.Trace("Wrong Status Code"); + m_logger.LogTrace("Wrong Status Code"); continue; } @@ -360,7 +367,7 @@ static void DoTest(TestCase test, string filePath) if (value1 != value2) { - Utils.Trace("Wrong Value"); + m_logger.LogTrace("Wrong Value"); continue; } } diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs index 1cd65d775..b6115ef06 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/ArchiveItemState.cs @@ -107,11 +107,11 @@ public ArchiveItemState(ISystemContext context, ArchiveItem item, ushort namespa /// /// Loads the configuration. /// - public void LoadConfiguration(ISystemContext context) + public void LoadConfiguration(ISystemContext context, ITelemetryContext telemetry) { DataFileReader reader = new DataFileReader(); - if (reader.LoadConfiguration(context, m_archiveItem)) + if (reader.LoadConfiguration(context, m_archiveItem, telemetry)) { this.DataType = (uint)m_archiveItem.DataType; this.ValueRank = m_archiveItem.ValueRank; @@ -132,9 +132,9 @@ public void LoadConfiguration(ISystemContext context) /// /// Loads the data. /// - public void ReloadFromSource(ISystemContext context) + public void ReloadFromSource(ISystemContext context, ITelemetryContext telemetry) { - LoadConfiguration(context); + LoadConfiguration(context, telemetry); if (m_archiveItem.LastLoadTime == DateTime.MinValue || (m_archiveItem.Persistent && m_archiveItem.LastLoadTime.AddSeconds(10) < DateTime.UtcNow)) { @@ -205,7 +205,7 @@ public List NewSamples(ISystemContext context) /// /// Updates the history. /// - public uint UpdateHistory(SystemContext context, DataValue value, PerformUpdateType performUpdateType) + public uint UpdateHistory(ServerSystemContext context, DataValue value, PerformUpdateType performUpdateType) { bool replaced = false; @@ -327,7 +327,7 @@ public uint UpdateHistory(SystemContext context, DataValue value, PerformUpdateT /// /// Updates the history. /// - public uint UpdateAnnotations(SystemContext context, Annotation annotation, DataValue value, PerformUpdateType performUpdateType) + public uint UpdateAnnotations(ServerSystemContext context, Annotation annotation, DataValue value, PerformUpdateType performUpdateType) { bool replaced = false; @@ -425,7 +425,7 @@ private DataTable SelectTable(QualifiedName propertyName) /// /// Deletes a value from the history. /// - public uint DeleteHistory(SystemContext context, DateTime sourceTimestamp) + public uint DeleteHistory(ServerSystemContext context, DateTime sourceTimestamp) { bool deleted = false; @@ -488,7 +488,7 @@ public uint DeleteAnnotationHistory(SystemContext context, QualifiedName propert /// /// Deletes a value from the history. /// - public uint DeleteHistory(SystemContext context, DateTime startTime, DateTime endTime, bool isModified) + public uint DeleteHistory(ServerSystemContext context, DateTime startTime, DateTime endTime, bool isModified) { // ensure time goes up. if (endTime < startTime) @@ -556,16 +556,13 @@ public uint DeleteHistory(SystemContext context, DateTime startTime, DateTime en /// /// Creates a modification info record. /// - private ModificationInfo GetModificationInfo(SystemContext context, HistoryUpdateType updateType) + private ModificationInfo GetModificationInfo(ServerSystemContext context, HistoryUpdateType updateType) { ModificationInfo info = new ModificationInfo(); info.UpdateType = updateType; info.ModificationTime = DateTime.UtcNow; - if (context.OperationContext != null && context.OperationContext.UserIdentity != null) - { - info.UserName = context.OperationContext.UserIdentity.DisplayName; - } + info.UserName = (context.OperationContext as ISessionOperationContext)?.UserIdentity?.DisplayName; return info; } diff --git a/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs b/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs index aa29e7226..de7a27dd5 100644 --- a/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs +++ b/Workshop/HistoricalAccess/Server/UnderlyingSystem/DataFileReader.cs @@ -35,6 +35,7 @@ using System.Data; using System.Reflection; using Opc.Ua; +using Microsoft.Extensions.Logging; namespace Quickstarts.HistoricalAccessServer { @@ -89,8 +90,10 @@ private DataSet CreateDataSet() /// /// Loads the item configuaration. /// - public bool LoadConfiguration(ISystemContext context, ArchiveItem item) + public bool LoadConfiguration(ISystemContext context, ArchiveItem item, ITelemetryContext telemetry) { + m_logger = telemetry.CreateLogger(); + m_telemetry = telemetry; using (StreamReader reader = item.OpenArchive()) { while (!reader.EndOfStream) @@ -250,7 +253,7 @@ public void CreateData(ArchiveItem item) } DateTime currentTime = startTime; - Opc.Ua.Test.DataGenerator generator = new Opc.Ua.Test.DataGenerator(null); + Opc.Ua.Test.DataGenerator generator = new Opc.Ua.Test.DataGenerator(null, m_telemetry); while (currentTime < DateTime.UtcNow) { @@ -321,7 +324,7 @@ private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader { DataSet dataset = CreateDataSet(); - ServiceMessageContext messageContext = new ServiceMessageContext(); + ServiceMessageContext messageContext = new ServiceMessageContext(m_telemetry); if (context != null) { @@ -329,12 +332,6 @@ private DataSet LoadData(ISystemContext context, DateTime baseline, StreamReader messageContext.ServerUris = context.ServerUris; messageContext.Factory = context.EncodeableFactory; } - else - { - messageContext.NamespaceUris = ServiceMessageContext.GlobalContext.NamespaceUris; - messageContext.ServerUris = ServiceMessageContext.GlobalContext.ServerUris; - messageContext.Factory = ServiceMessageContext.GlobalContext.Factory; - } int sourceTimeOffset = 0; int serverTimeOffset = 0; @@ -574,7 +571,7 @@ private bool ExtractField(int lineCount, ref string line, out int value) } catch (Exception e) { - Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); + m_logger.LogError("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return false; } @@ -606,7 +603,7 @@ private bool ExtractField(int lineCount, ref string line, out StatusCode value) } catch (Exception e) { - Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); + m_logger.LogError("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return false; } @@ -632,7 +629,7 @@ private bool ExtractField(int lineCount, ref string line, out BuiltInType value) } catch (Exception e) { - Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); + m_logger.LogError("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return false; } @@ -676,12 +673,15 @@ private bool ExtractField(int lineCount, ref string line, ServiceMessageContext } catch (Exception e) { - Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); + m_logger.LogError("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return false; } return true; } #endregion + + private ILogger m_logger; + private ITelemetryContext m_telemetry; } } diff --git a/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj b/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj index 7e7d987c5..28b056b2d 100644 --- a/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj +++ b/Workshop/HistoricalAccess/Tester/Aggregate Tester.csproj @@ -143,11 +143,14 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/HistoricalAccess/Tester/MainForm.cs b/Workshop/HistoricalAccess/Tester/MainForm.cs index fb21e3b15..161cc000e 100644 --- a/Workshop/HistoricalAccess/Tester/MainForm.cs +++ b/Workshop/HistoricalAccess/Tester/MainForm.cs @@ -45,11 +45,12 @@ namespace Quickstarts { public partial class MainForm : Form { - public MainForm() + public MainForm(ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; m_dataset = new DataSet(); m_dataset.Tables.Add("TestData"); @@ -126,6 +127,7 @@ private enum RowState private ProcessedDataSetType m_currentDataSet; private TestData m_testData; private bool m_loading; + private readonly ITelemetryContext m_telemetry; /// /// Adds a raw value to the grid. @@ -449,7 +451,7 @@ private void DeleteValuesBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -460,7 +462,7 @@ private void DeleteValuesBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -712,7 +714,8 @@ private void GenerateData(string historianName, string aggregateName, double pro startTime.AddSeconds(100), processingInterval, stepped, - configuration); + configuration, + m_telemetry); SortedDictionary rawValues = m_testData.GetRawValues(historianName); List processedValues = new List(); @@ -779,7 +782,8 @@ private void DoTest() (this.TimeFlowsBackwardsCK.Checked) ? startTime : startTime.AddSeconds(100), (double)ProcessingIntervalNP.Value, SteppedCK.Checked, - configuration); + configuration, + m_telemetry); SortedDictionary rawValues = m_testData.GetRawValues(HistorianCB.SelectedItem as string); List processedValues = new List(); @@ -939,7 +943,7 @@ private void File_LoadDefaultsMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -978,7 +982,7 @@ private void TestDataDV_CellEndEdit(object sender, DataGridViewCellEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1077,7 +1081,7 @@ private void RunTestBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1118,7 +1122,7 @@ private void HistorianCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1134,7 +1138,7 @@ private void File_LoadMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1152,7 +1156,7 @@ private void File_SaveMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1170,7 +1174,7 @@ private void DeleteTestBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1203,7 +1207,7 @@ private void TestNameCB_SelectedIndexChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -1220,7 +1224,7 @@ private void SaveTestBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1238,7 +1242,7 @@ private void CopyTestBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1262,7 +1266,7 @@ private void CopyActualValuesBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1368,7 +1372,7 @@ private void CopyToClipboardBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -1380,7 +1384,7 @@ private void GenerateReportBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } diff --git a/Workshop/HistoricalAccess/Tester/Program.cs b/Workshop/HistoricalAccess/Tester/Program.cs index dd83697f1..4e0d32deb 100644 --- a/Workshop/HistoricalAccess/Tester/Program.cs +++ b/Workshop/HistoricalAccess/Tester/Program.cs @@ -31,11 +31,28 @@ using System.Collections.Generic; using System.Linq; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using Opc.Ua; namespace Quickstarts { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -44,7 +61,7 @@ static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new MainForm()); + Application.Run(new MainForm(m_telemetry)); } } } diff --git a/Workshop/HistoricalEvents/Client/EventListView.cs b/Workshop/HistoricalEvents/Client/EventListView.cs index cfabeac07..38bdfc851 100644 --- a/Workshop/HistoricalEvents/Client/EventListView.cs +++ b/Workshop/HistoricalEvents/Client/EventListView.cs @@ -51,6 +51,7 @@ public EventListView() #region Private Methods private ISession m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private FilterDeclaration m_filter; @@ -103,8 +104,10 @@ public FilterDeclaration Filter /// /// Changes the session. /// - public async Task ChangeSessionAsync(ISession session, bool fetchRecent, CancellationToken ct = default) + public async Task ChangeSessionAsync(ISession session, bool fetchRecent, ITelemetryContext telemetry, CancellationToken ct = default) { + m_telemetry = telemetry; + if (Object.ReferenceEquals(session, m_session)) { return; @@ -276,7 +279,7 @@ public async Task AddEventHistoryAsync(HistoryEvent events, CancellationToken ct /// private async Task CreateSubscriptionAsync(CancellationToken ct = default) { - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.Handle = this; m_subscription.DisplayName = null; m_subscription.PublishingInterval = 1000; @@ -289,7 +292,7 @@ private async Task CreateSubscriptionAsync(CancellationToken ct = default) m_session.AddSubscription(m_subscription); await m_subscription.CreateAsync(ct); - m_monitoredItem = new MonitoredItem(); + m_monitoredItem = new MonitoredItem(m_telemetry); m_monitoredItem.StartNodeId = m_areaId; m_monitoredItem.AttributeId = Attributes.EventNotifier; m_monitoredItem.SamplingInterval = 0; @@ -433,7 +436,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -616,7 +619,7 @@ private void ViewDetailsMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -658,7 +661,7 @@ private async void DeleteHistoryMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj b/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj index ef5989b37..dac5580d6 100644 --- a/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj +++ b/Workshop/HistoricalEvents/Client/HistoricalEvents Client.csproj @@ -188,8 +188,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/HistoricalEvents/Client/MainForm.cs b/Workshop/HistoricalEvents/Client/MainForm.cs index bb9b72269..cd7b6da64 100644 --- a/Workshop/HistoricalEvents/Client/MainForm.cs +++ b/Workshop/HistoricalEvents/Client/MainForm.cs @@ -59,10 +59,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62553/Quickstarts/HistoricalEventsServer"; @@ -73,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private bool m_connectedOnce; #endregion @@ -87,11 +89,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -106,7 +108,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -121,7 +123,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -149,11 +151,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } await EventsLV.SetSubscribedAsync(Events_EnableSubscriptionMI.Checked); - await EventsLV.ChangeSessionAsync(m_session, true); + await EventsLV.ChangeSessionAsync(m_session, true, m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -169,7 +171,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -201,7 +203,7 @@ private async void Events_SelectEventTypeMI_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -214,7 +216,7 @@ private async void Events_ModifyEventFilterMI_ClickAsync(object sender, EventArg return; } - if (!new ModifyFilterDlg().ShowDialog(EventsLV.Filter)) + if (!new ModifyFilterDlg().ShowDialog(EventsLV.Filter, m_telemetry)) { return; } @@ -223,7 +225,7 @@ private async void Events_ModifyEventFilterMI_ClickAsync(object sender, EventArg } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -236,7 +238,7 @@ private async void Events_SelectEventAreaMI_ClickAsync(object sender, EventArgs return; } - NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", default, Opc.Ua.ReferenceTypeIds.HasEventSource); + NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", m_telemetry, default, Opc.Ua.ReferenceTypeIds.HasEventSource); if (areaId == null) { @@ -247,7 +249,7 @@ private async void Events_SelectEventAreaMI_ClickAsync(object sender, EventArgs } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -259,7 +261,7 @@ private async void Events_EnableSubscriptionMI_CheckedChangedAsync(object sender } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -272,11 +274,11 @@ private async void Events_EditEventHistoryMI_ClickAsync(object sender, EventArgs return; } - await new ReadEventHistoryDlg().ShowDialogAsync(m_session, EventsLV.AreaId, new FilterDeclaration(EventsLV.Filter)); + await new ReadEventHistoryDlg().ShowDialogAsync(m_session, EventsLV.AreaId, new FilterDeclaration(EventsLV.Filter), m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -304,7 +306,7 @@ private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs b/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs index b8517b635..f3782db9d 100644 --- a/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs +++ b/Workshop/HistoricalEvents/Client/ModifyFilterDlg.cs @@ -54,6 +54,7 @@ public ModifyFilterDlg() #region Private Fields private FilterDeclaration m_filter; + private ITelemetryContext m_telemetry; /// /// The supported filter operators. @@ -95,9 +96,10 @@ public FilterItem(FilterDeclarationField declaration) /// /// Displays the available areas in a tree view. /// - public bool ShowDialog(FilterDeclaration filter) + public bool ShowDialog(FilterDeclaration filter, ITelemetryContext telemetry) { m_filter = filter; + m_telemetry = telemetry; Populate(); @@ -239,7 +241,7 @@ private void DisplayInListViewMI_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -265,7 +267,7 @@ private void FilterEnabledMI_CheckedChanged(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -287,7 +289,7 @@ private void DeleteFieldMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -330,7 +332,7 @@ private void FilterOperandMI_DropDownOpening(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -364,7 +366,7 @@ private void SetFilterValueMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalEvents/Client/Program.cs b/Workshop/HistoricalEvents/Client/Program.cs index b1c28a901..6e4d770eb 100644 --- a/Workshop/HistoricalEvents/Client/Program.cs +++ b/Workshop/HistoricalEvents/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.HistoricalEvents.Client { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "HistoricalEventsClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs index b7c936aaf..5a2963a89 100644 --- a/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs +++ b/Workshop/HistoricalEvents/Client/ReadEventHistoryDlg.cs @@ -60,6 +60,7 @@ public ReadEventHistoryDlg() #region Private Fields private ISession m_session; + private ITelemetryContext m_telemetry; private NodeId m_areaId; private FilterDeclaration m_filter; private ReadEventDetails m_details; @@ -70,9 +71,10 @@ public ReadEventHistoryDlg() /// /// Displays the dialog. /// - public async Task ShowDialogAsync(ISession session, NodeId areaId, FilterDeclaration filter, CancellationToken ct = default) + public async Task ShowDialogAsync(ISession session, NodeId areaId, FilterDeclaration filter, ITelemetryContext telemetry, CancellationToken ct = default) { m_session = session; + m_telemetry = telemetry; m_areaId = areaId; m_filter = filter; @@ -81,7 +83,7 @@ public async Task ShowDialogAsync(ISession session, NodeId areaId, FilterD EventFilterTB.Text = GetFilterFields(m_filter); await ResultsLV.SetSubscribedAsync(false, ct); - await ResultsLV.ChangeSessionAsync(session, false, ct); + await ResultsLV.ChangeSessionAsync(session, false, telemetry, ct); await ResultsLV.ChangeAreaAsync(areaId, false, ct); await ResultsLV.ChangeFilterAsync(filter, false, ct); @@ -355,7 +357,7 @@ private async void GoBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } @@ -370,7 +372,7 @@ private async void NextBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } @@ -382,7 +384,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException("Error Reading History", exception); + ClientUtils.HandleException(m_telemetry, "Error Reading History", exception); } } @@ -422,7 +424,7 @@ private async void EventAreaBTN_ClickAsync(object sender, EventArgs e) return; } - NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", default, Opc.Ua.ReferenceTypeIds.HasEventSource); + NodeId areaId = await new SelectNodeDlg().ShowDialogAsync(m_session, Opc.Ua.ObjectIds.Server, "Select Event Area", m_telemetry, default, Opc.Ua.ReferenceTypeIds.HasEventSource); if (areaId == null) { @@ -435,7 +437,7 @@ private async void EventAreaBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -462,7 +464,7 @@ private async void EventTypeBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -475,7 +477,7 @@ private async void EventFilterBTN_ClickAsync(object sender, EventArgs e) return; } - if (!new ModifyFilterDlg().ShowDialog(m_filter)) + if (!new ModifyFilterDlg().ShowDialog(m_filter, m_telemetry)) { return; } @@ -485,7 +487,7 @@ private async void EventFilterBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs b/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs index c990fc912..3303bbf21 100644 --- a/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs +++ b/Workshop/HistoricalEvents/Client/SelectTypeDlg.cs @@ -156,7 +156,7 @@ private void BrowseTV_DoubleClick(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -212,7 +212,7 @@ private async void BrowseTV_AfterSelectAsync(object sender, TreeViewEventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } @@ -265,7 +265,7 @@ private async void BrowseTV_BeforeExpandAsync(object sender, TreeViewCancelEvent } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_session?.MessageContext?.Telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj b/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj index 025689be1..7d28d100b 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj +++ b/Workshop/HistoricalEvents/Server/HistoricalEvents Server.csproj @@ -143,8 +143,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs b/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs index 33f43b6ee..a2fc8cc11 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs +++ b/Workshop/HistoricalEvents/Server/HistoricalEventsNodeManager.cs @@ -38,6 +38,7 @@ using System.Data; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.HistoricalEvents.Server { @@ -64,6 +65,8 @@ public HistoricalEventsNodeManager(IServerInternal server, ApplicationConfigurat // get the configuration for the node manager. m_configuration = configuration.ParseExtension(); + m_logger = server.Telemetry.CreateLogger(); + // use suitable defaults if no configuration exists. if (m_configuration == null) { @@ -155,7 +158,7 @@ public override void CreateAddressSpace(IDictionary> e /// /// Creates a new area. /// - private BaseObjectState CreateArea(SystemContext context, BaseObjectState platforms, string areaName) + private BaseObjectState CreateArea(ServerSystemContext context, BaseObjectState platforms, string areaName) { FolderState area = new FolderState(null); @@ -176,7 +179,7 @@ private BaseObjectState CreateArea(SystemContext context, BaseObjectState platfo /// /// Creates a new well. /// - private void CreateWell(SystemContext context, BaseObjectState area, string wellId, string wellName) + private void CreateWell(ServerSystemContext context, BaseObjectState area, string wellId, string wellName) { WellState well = new WellState(null); @@ -374,7 +377,7 @@ protected override void HistoryUpdateEvents( HistoryUpdateResult result = results[handle.Index]; // validate the event filter. - FilterContext filterContext = new FilterContext(context.NamespaceUris, context.TypeTable, context); + FilterContext filterContext = new FilterContext(context.NamespaceUris, context.TypeTable, context, Server.Telemetry); EventFilter.Result filterResult = nodeToUpdate.Filter.Validate(filterContext); if (ServiceResult.IsBad(filterResult.Status)) @@ -439,7 +442,7 @@ protected override void HistoryDeleteEvents( { if (StatusCode.IsBad(result.OperationResults[jj])) { - result.DiagnosticInfos.Add(ServerUtils.CreateDiagnosticInfo(Server, context.OperationContext, result.OperationResults[jj])); + result.DiagnosticInfos.Add(ServerUtils.CreateDiagnosticInfo(Server, context.OperationContext, result.OperationResults[jj], m_logger)); } } } @@ -509,7 +512,7 @@ private HistoryReadRequest CreateHistoryReadRequest( NodeHandle handle, HistoryReadValueId nodeToRead) { - FilterContext filterContext = new FilterContext(context.NamespaceUris, context.TypeTable, context.PreferredLocales); + FilterContext filterContext = new FilterContext(context.NamespaceUris, context.TypeTable, context.PreferredLocales, Server.Telemetry); LinkedList events = new LinkedList(); for (ReportType ii = ReportType.FluidLevelTest; ii <= ReportType.InjectionTest; ii++) @@ -708,13 +711,14 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error during simulation."); + m_logger.LogError(e, "Unexpected error during simulation."); } } #endregion #region Private Fields private HistoricalEventsServerConfiguration m_configuration; + private ILogger m_logger; private Timer m_simulationTimer; private ReportGenerator m_generator; #endregion diff --git a/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs b/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs index 4d0ff8b8f..bbe2635f3 100644 --- a/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs +++ b/Workshop/HistoricalEvents/Server/HistoricalEventsServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class HistoricalEventsServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/HistoricalEvents/Server/Program.cs b/Workshop/HistoricalEvents/Server/Program.cs index 6a35c10d7..4dec7003a 100644 --- a/Workshop/HistoricalEvents/Server/Program.cs +++ b/Workshop/HistoricalEvents/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.HistoricalEvents.Server { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -57,25 +73,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "HistoricalEventsServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new HistoricalEventsServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -86,11 +89,11 @@ static void Main() application.StartAsync(new HistoricalEventsServer()).Wait(); // run the application interactively. - Application.Run(new ServerForm(application)); + Application.Run(new ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Methods/Client/MainForm.cs b/Workshop/Methods/Client/MainForm.cs index 7f845c4a9..ce62d01e1 100644 --- a/Workshop/Methods/Client/MainForm.cs +++ b/Workshop/Methods/Client/MainForm.cs @@ -58,10 +58,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62557/Quickstarts/MethodsServer"; @@ -76,6 +77,7 @@ public MainForm(ApplicationConfiguration configuration) private NodeId m_objectNode; private NodeId m_methodNode; private bool m_connectedOnce; + private readonly ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -89,11 +91,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -108,7 +110,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -123,7 +125,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -169,7 +171,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) // subscribe to the state if available. if (nodes.Count > 0 && !NodeId.IsNull(nodes[0])) { - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.PublishingEnabled = true; m_subscription.PublishingInterval = 1000; @@ -181,7 +183,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) m_session.AddSubscription(m_subscription); await m_subscription.CreateAsync(); - MonitoredItem monitoredItem = new MonitoredItem(); + MonitoredItem monitoredItem = new MonitoredItem(m_telemetry); monitoredItem.StartNodeId = nodes[0]; monitoredItem.AttributeId = Attributes.Value; monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); @@ -203,7 +205,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -218,7 +220,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -242,7 +244,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -286,7 +288,7 @@ private async void StartBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -311,7 +313,7 @@ void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotifi } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/Methods/Client/Methods Client.csproj b/Workshop/Methods/Client/Methods Client.csproj index 45a700a59..7a5cb633c 100644 --- a/Workshop/Methods/Client/Methods Client.csproj +++ b/Workshop/Methods/Client/Methods Client.csproj @@ -133,8 +133,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Methods/Client/Program.cs b/Workshop/Methods/Client/Program.cs index 7054a86b1..6f2e996d0 100644 --- a/Workshop/Methods/Client/Program.cs +++ b/Workshop/Methods/Client/Program.cs @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.MethodsClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.MethodsClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Methods/Server/Methods Server.csproj b/Workshop/Methods/Server/Methods Server.csproj index 879bbeb44..173746a58 100644 --- a/Workshop/Methods/Server/Methods Server.csproj +++ b/Workshop/Methods/Server/Methods Server.csproj @@ -132,8 +132,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Methods/Server/MethodsNodeManager.cs b/Workshop/Methods/Server/MethodsNodeManager.cs index 9d0047e54..bfde20b11 100644 --- a/Workshop/Methods/Server/MethodsNodeManager.cs +++ b/Workshop/Methods/Server/MethodsNodeManager.cs @@ -37,6 +37,7 @@ using System.Reflection; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.MethodsServer { @@ -309,7 +310,7 @@ private void OnUpdateProcess(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error updating process."); + m_logger.LogError(e, "Unexpected error updating process."); } } diff --git a/Workshop/Methods/Server/MethodsServer.cs b/Workshop/Methods/Server/MethodsServer.cs index ddd97a712..6e649fc4a 100644 --- a/Workshop/Methods/Server/MethodsServer.cs +++ b/Workshop/Methods/Server/MethodsServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class MethodsServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/Methods/Server/Program.cs b/Workshop/Methods/Server/Program.cs index bbdc1b2ee..a91c862dc 100644 --- a/Workshop/Methods/Server/Program.cs +++ b/Workshop/Methods/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.MethodsServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.MethodsServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new MethodsServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new MethodsServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/PerfTest/Client/MainForm.cs b/Workshop/PerfTest/Client/MainForm.cs index 70f097b16..8702ac9fd 100644 --- a/Workshop/PerfTest/Client/MainForm.cs +++ b/Workshop/PerfTest/Client/MainForm.cs @@ -59,12 +59,13 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62559/Quickstarts/PerfTestServer"; this.Text = m_configuration.ApplicationName; + m_telemetry = telemetry; } #endregion @@ -73,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) private ISession m_session; private bool m_connectedOnce; private Tester m_tester; + private readonly ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -86,11 +88,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -105,7 +107,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -120,7 +122,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -154,14 +156,14 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) m_tester = new Tester(); m_tester.SamplingRate = (int)UpdateRateCTRL.Value; m_tester.ItemCount = (int)ItemCountCTRL.Value; - await m_tester.StartAsync(m_session); + await m_tester.StartAsync(m_session, m_telemetry); UpdateTimer.Enabled = true; StopBTN.Visible = true; } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -176,7 +178,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -191,7 +193,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -280,7 +282,7 @@ private async void StopBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/PerfTest/Client/PerfTest Client.csproj b/Workshop/PerfTest/Client/PerfTest Client.csproj index 6bd632ff5..a01b42e59 100644 --- a/Workshop/PerfTest/Client/PerfTest Client.csproj +++ b/Workshop/PerfTest/Client/PerfTest Client.csproj @@ -131,8 +131,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/PerfTest/Client/Program.cs b/Workshop/PerfTest/Client/Program.cs index e21327d3c..61a15cd31 100644 --- a/Workshop/PerfTest/Client/Program.cs +++ b/Workshop/PerfTest/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.PerfTestClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "PerfTestClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/PerfTest/Client/Tester.cs b/Workshop/PerfTest/Client/Tester.cs index ec6a58f71..2cd06867c 100644 --- a/Workshop/PerfTest/Client/Tester.cs +++ b/Workshop/PerfTest/Client/Tester.cs @@ -144,12 +144,12 @@ public void GetStatistics( /// Starts the specified session. /// /// The session. - public async Task StartAsync(ISession session) + public async Task StartAsync(ISession session, ITelemetryContext telemetry) { m_NotificationEventHandler = new NotificationEventHandler(Session_Notification); session.Notification += m_NotificationEventHandler; - Subscription subscription = m_subscription = new Subscription(); + Subscription subscription = m_subscription = new Subscription(telemetry); subscription.PublishingInterval = m_samplingRate; subscription.KeepAliveCount = 10; @@ -167,7 +167,7 @@ public async Task StartAsync(ISession session) for (int ii = 0; ii < m_itemCount; ii++) { - MonitoredItem monitoredItem = new MonitoredItem((uint)ii); + MonitoredItem monitoredItem = new MonitoredItem((uint)ii, telemetry); monitoredItem.StartNodeId = new NodeId((uint)((1 << 24) + ii), 2); monitoredItem.AttributeId = Attributes.Value; diff --git a/Workshop/PerfTest/Server/PerfTest Server.csproj b/Workshop/PerfTest/Server/PerfTest Server.csproj index 1187346c3..5693ba856 100644 --- a/Workshop/PerfTest/Server/PerfTest Server.csproj +++ b/Workshop/PerfTest/Server/PerfTest Server.csproj @@ -134,8 +134,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/PerfTest/Server/PerfTestNodeManager.cs b/Workshop/PerfTest/Server/PerfTestNodeManager.cs index 29e065f93..8b96ae8f6 100644 --- a/Workshop/PerfTest/Server/PerfTestNodeManager.cs +++ b/Workshop/PerfTest/Server/PerfTestNodeManager.cs @@ -103,7 +103,7 @@ public override void CreateAddressSpace(IDictionary> e { lock (Lock) { - m_system.Initialize(); + m_system.Initialize(Server.Telemetry); IList registers = m_system.GetRegisters(); diff --git a/Workshop/PerfTest/Server/PerfTestServer.cs b/Workshop/PerfTest/Server/PerfTestServer.cs index 82afbbb51..c1ca4e067 100644 --- a/Workshop/PerfTest/Server/PerfTestServer.cs +++ b/Workshop/PerfTest/Server/PerfTestServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class PerfTestServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/PerfTest/Server/Program.cs b/Workshop/PerfTest/Server/Program.cs index 7b5efb757..370d64841 100644 --- a/Workshop/PerfTest/Server/Program.cs +++ b/Workshop/PerfTest/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.PerfTestServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -47,25 +63,12 @@ static class Program static void Main() { ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "PerfTestServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new PerfTestServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -76,11 +79,11 @@ static void Main() application.StartAsync(new PerfTestServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/PerfTest/Server/UnderlyingSystem.cs b/Workshop/PerfTest/Server/UnderlyingSystem.cs index d5a9dee5e..4659a9eb3 100644 --- a/Workshop/PerfTest/Server/UnderlyingSystem.cs +++ b/Workshop/PerfTest/Server/UnderlyingSystem.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using System.Text; using System.Threading; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -38,12 +39,13 @@ namespace Quickstarts.PerfTestServer { public class UnderlyingSystem { - public void Initialize() + public void Initialize(ITelemetryContext telemetry) { + m_logger = telemetry.CreateLogger(); m_registers = new List(); MemoryRegister register1 = new MemoryRegister(); - register1.Initialize(1, "R1", 50000); m_registers.Add(register1); + register1.Initialize(1, "R1", 50000, m_logger); } public IList GetRegisters() @@ -62,6 +64,7 @@ public MemoryRegister GetRegister(int id) } private List m_registers; + private ILogger m_logger; } public class MemoryRegister @@ -81,12 +84,13 @@ public int Size get { return m_values.Length; } } - public void Initialize(int id, string name, int size) + public void Initialize(int id, string name, int size, ILogger logger) { m_id = id; m_name = name; m_values = new int[size]; m_monitoredItems = new IDataChangeMonitoredItem2[size][]; + m_logger = logger; } public int Read(int index) @@ -210,13 +214,13 @@ private void OnUpdate(object state) if ((HiResClock.UtcNow - start).TotalMilliseconds > 50) { - Utils.Trace("Update took {0}ms.", (HiResClock.UtcNow - start).TotalMilliseconds); + m_logger.LogWarning("Update took {0}ms.", (HiResClock.UtcNow - start).TotalMilliseconds); } } } catch (Exception e) { - Utils.Trace(e, "Unexpected error updating items."); + m_logger.LogError(e, "Unexpected error updating items."); } } @@ -227,5 +231,6 @@ private void OnUpdate(object state) private int m_start; private Timer m_timer; private IDataChangeMonitoredItem2[][] m_monitoredItems; + private ILogger m_logger; } } diff --git a/Workshop/SimpleEvents/Client/MainForm.cs b/Workshop/SimpleEvents/Client/MainForm.cs index 6087e25b2..324172388 100644 --- a/Workshop/SimpleEvents/Client/MainForm.cs +++ b/Workshop/SimpleEvents/Client/MainForm.cs @@ -60,11 +60,12 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62563/Quickstarts/SimpleEventsServer"; this.Text = m_configuration.ApplicationName; @@ -81,6 +82,7 @@ public MainForm(ApplicationConfiguration configuration) private Dictionary m_eventTypeMappings; private MonitoredItemNotificationEventHandler m_MonitoredItem_Notification; private bool m_connectedOnce; + private readonly ITelemetryContext m_telemetry; #endregion #region Private Methods @@ -94,11 +96,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -113,7 +115,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -128,7 +130,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -156,7 +158,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -170,7 +172,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -197,7 +199,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -217,7 +219,7 @@ private void MainForm_FormClosing(object sender, FormClosingEventArgs e) private async Task CreateSubscriptionAsync(CancellationToken ct = default) { // create the default subscription. - m_subscription = new Subscription(); + m_subscription = new Subscription(m_telemetry); m_subscription.DisplayName = null; m_subscription.PublishingInterval = 1000; @@ -249,7 +251,7 @@ private async Task CreateSubscriptionAsync(CancellationToken ct = default) m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_NotificationAsync); // create a monitored item based on the current filter settings. - m_monitoredItem = new MonitoredItem(); + m_monitoredItem = new MonitoredItem(m_telemetry); m_monitoredItem.StartNodeId = Opc.Ua.ObjectIds.Server; m_monitoredItem.AttributeId = Attributes.EventNotifier; m_monitoredItem.SamplingInterval = 0; @@ -406,7 +408,7 @@ private async void MonitoredItem_NotificationAsync(MonitoredItem monitoredItem, } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -434,7 +436,7 @@ private async void Server_SetLocaleMI_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } #endregion diff --git a/Workshop/SimpleEvents/Client/Program.cs b/Workshop/SimpleEvents/Client/Program.cs index ced77af9d..0d7f9b314 100644 --- a/Workshop/SimpleEvents/Client/Program.cs +++ b/Workshop/SimpleEvents/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.SimpleEvents.Client { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "SimpleEventsClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj b/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj index c77593478..9a82bc29d 100644 --- a/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj +++ b/Workshop/SimpleEvents/Client/SimpleEvents Client.csproj @@ -120,8 +120,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/SimpleEvents/Server/Program.cs b/Workshop/SimpleEvents/Server/Program.cs index f4ffe9fbc..0f71efcec 100644 --- a/Workshop/SimpleEvents/Server/Program.cs +++ b/Workshop/SimpleEvents/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.SimpleEvents.Server { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "SimpleEventsServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new SimpleEventsServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new SimpleEventsServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj b/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj index a7b502cff..4bc4dea4d 100644 --- a/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj +++ b/Workshop/SimpleEvents/Server/SimpleEvents Server.csproj @@ -138,8 +138,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs b/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs index 40dc4ae02..a67cf534c 100644 --- a/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs +++ b/Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs @@ -37,6 +37,7 @@ using System.Reflection; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.SimpleEvents.Server { @@ -247,7 +248,7 @@ private void DoSimulation(object state) } catch (Exception e) { - Utils.Trace(e, "Unexpected error during simulation."); + m_logger.LogError(e, "Unexpected error during simulation."); } } #endregion diff --git a/Workshop/SimpleEvents/Server/SimpleEventsServer.cs b/Workshop/SimpleEvents/Server/SimpleEventsServer.cs index 2faaaae75..0f3856fb9 100644 --- a/Workshop/SimpleEvents/Server/SimpleEventsServer.cs +++ b/Workshop/SimpleEvents/Server/SimpleEventsServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class SimpleEventsServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/Workshop/UserAuthentication/Client/MainForm.cs b/Workshop/UserAuthentication/Client/MainForm.cs index 42ee2cc89..9c1879c66 100644 --- a/Workshop/UserAuthentication/Client/MainForm.cs +++ b/Workshop/UserAuthentication/Client/MainForm.cs @@ -43,6 +43,7 @@ using Opc.Ua.Client.Controls; using System.Threading; using System.Threading.Tasks; +using System.Text; namespace Quickstarts.UserAuthenticationClient { @@ -65,7 +66,7 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); @@ -73,6 +74,7 @@ public MainForm(ApplicationConfiguration configuration) ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62565/Quickstarts/UserAuthenticationServer"; this.Text = m_configuration.ApplicationName; + m_telemetry = telemetry; UserNameTB.Text = "Operator"; PreferredLocalesTB.Text = "de,es,en"; @@ -107,6 +109,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private Subscription m_subscription; private MonitoredItem m_monitoredItem; private bool m_connectedOnce; @@ -126,11 +129,11 @@ private async void Server_ConnectMI_ClickAsync(object sender, EventArgs e) { try { - await ConnectServerCTRL.ConnectAsync(); + await ConnectServerCTRL.ConnectAsync(m_telemetry); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -145,7 +148,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -160,7 +163,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -192,7 +195,7 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -206,7 +209,7 @@ private void Server_ReconnectStarting(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -233,7 +236,7 @@ private void Server_ReconnectComplete(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -439,7 +442,7 @@ private void UserNameImpersonateBTN_Click(object sender, EventArgs e) // want to get error text for this call. m_session.ReturnDiagnostics = DiagnosticsMasks.All; - UserIdentity identity = new UserIdentity(UserNameTB.Text, PasswordTB.Text); + UserIdentity identity = new UserIdentity(UserNameTB.Text, Encoding.UTF8.GetBytes(PasswordTB.Text)); string[] preferredLocales = PreferredLocalesTB.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); m_session.UpdateSession(identity, preferredLocales); @@ -447,7 +450,7 @@ private void UserNameImpersonateBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -474,14 +477,14 @@ private void CertificateImpersonateBTN_Click(object sender, EventArgs e) m_session.ReturnDiagnostics = DiagnosticsMasks.All; UserIdentity identity = new UserIdentity(certificate); - string[] preferredLocales = PreferredLocalesTB.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] preferredLocales = PreferredLocalesTB.Text.Split([','], StringSplitOptions.RemoveEmptyEntries); m_session.UpdateSession(identity, preferredLocales); MessageBox.Show("User identity changed.", "Impersonate User", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -508,7 +511,7 @@ private void AnonymousImpersonateBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -538,7 +541,7 @@ private void KerberosImpersonateBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -591,7 +594,7 @@ private async Task ReadLogFilePathAsync(CancellationToken ct = default) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { @@ -638,7 +641,7 @@ private async void ChangeLogFileBTN_ClickAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } finally { diff --git a/Workshop/UserAuthentication/Client/Program.cs b/Workshop/UserAuthentication/Client/Program.cs index 5ebfe4e9f..79e82d937 100644 --- a/Workshop/UserAuthentication/Client/Program.cs +++ b/Workshop/UserAuthentication/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,16 +29,32 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Configuration; using Opc.Ua.Client.Controls; +using Opc.Ua.Configuration; namespace Quickstarts.UserAuthenticationClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -50,18 +66,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.UserAuthenticationClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -69,11 +79,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj b/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj index 30c86a8e4..2329b4339 100644 --- a/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj +++ b/Workshop/UserAuthentication/Client/UserAuthentication Client.csproj @@ -126,8 +126,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/UserAuthentication/Server/Program.cs b/Workshop/UserAuthentication/Server/Program.cs index f8d191a25..0111a3dfc 100644 --- a/Workshop/UserAuthentication/Server/Program.cs +++ b/Workshop/UserAuthentication/Server/Program.cs @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.UserAuthenticationServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.UserAuthenticationServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new UserAuthenticationServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new UserAuthenticationServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj b/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj index 0e6bd9353..560e55d5a 100644 --- a/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj +++ b/Workshop/UserAuthentication/Server/UserAuthentication Server.csproj @@ -155,8 +155,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs b/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs index bbfa4b3b4..5747a5176 100644 --- a/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs +++ b/Workshop/UserAuthentication/Server/UserAuthenticationNodeManager.cs @@ -147,7 +147,9 @@ public override void CreateAddressSpace(IDictionary> e public ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref object value) { - if (context.UserIdentity == null || context.UserIdentity.TokenType == UserTokenType.Anonymous) + UserTokenType? tokenType = (context as ISessionSystemContext)?.UserIdentity?.TokenType; + + if (tokenType is null or UserTokenType.Anonymous) { TranslationInfo info = new TranslationInfo( "BadUserAccessDenied", @@ -195,7 +197,9 @@ public ServiceResult OnWriteValue(ISystemContext context, NodeState node, ref ob public ServiceResult OnReadUserAccessLevel(ISystemContext context, NodeState node, ref byte value) { - if (context.UserIdentity == null || context.UserIdentity.TokenType == UserTokenType.Anonymous) + UserTokenType? tokenType = (context as ISessionSystemContext)?.UserIdentity?.TokenType; + + if (tokenType is null or UserTokenType.Anonymous) { value = AccessLevels.CurrentRead; } diff --git a/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs b/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs index f1ad99935..bce1d4356 100644 --- a/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs +++ b/Workshop/UserAuthentication/Server/UserAuthenticationServer.cs @@ -40,6 +40,7 @@ using System.Runtime.InteropServices; using Opc.Ua; using Opc.Ua.Server; +using Microsoft.Extensions.Logging; namespace Quickstarts.UserAuthenticationServer { @@ -96,7 +97,7 @@ protected override void OnServerStarted(IServerInternal server) /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + m_logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); @@ -169,8 +170,7 @@ private void CreateUserIdentityValidators(ApplicationConfiguration configuration if (trustedIssuers == null) { - Utils.Trace( - (int)Utils.TraceMasks.Error, + m_logger.LogError( "Could not load CertificateTrustList for UserTokenPolicy {0}", policy.PolicyId); @@ -206,9 +206,9 @@ private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventAr if (userNameToken != null) { - VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); + VerifyPassword(userNameToken.UserName, Encoding.UTF8.GetString(userNameToken.DecryptedPassword)); args.Identity = new UserIdentity(userNameToken); - Utils.Trace("UserName Token Accepted: {0}", args.Identity.DisplayName); + m_logger.LogInformation("UserName Token Accepted: {0}", args.Identity.DisplayName); return; } @@ -219,7 +219,7 @@ private void SessionManager_ImpersonateUser(ISession session, ImpersonateEventAr { VerifyCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); - Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); + m_logger.LogInformation("X509 Token Accepted: {0}", args.Identity.DisplayName); return; } } @@ -306,11 +306,11 @@ private void VerifyCertificate(X509Certificate2 certificate) // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( - e, - StatusCodes.BadIdentityTokenRejected, - "InvalidCertificate", Namespaces.UserAuthentication, - new LocalizedText(info))); + new StatusCode(StatusCodes.BadIdentityTokenRejected, + "InvalidCertificate"), + new LocalizedText(info), + e)); } } @@ -353,11 +353,12 @@ private SecurityToken ParseAndVerifyKerberosToken(byte[] tokenData) // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( - e, - StatusCodes.BadIdentityTokenRejected, - "InvalidKerberosToken", Namespaces.UserAuthentication, - new LocalizedText(info))); + new StatusCode( + StatusCodes.BadIdentityTokenRejected, + "InvalidKerberosToken"), + new LocalizedText(info), + e)); } finally { @@ -458,9 +459,12 @@ private void LogonUser(OperationContext context, UserNameSecurityToken securityT /// /// This method is called at the being of the thread that processes a request. /// - protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) + protected override OperationContext ValidateRequest( + SecureChannelContext secureChannelContext, + RequestHeader requestHeader, + RequestType requestType) { - OperationContext context = base.ValidateRequest(requestHeader, requestType); + OperationContext context = base.ValidateRequest(secureChannelContext, requestHeader, requestType); if (requestType == RequestType.Write) { @@ -475,9 +479,9 @@ protected override OperationContext ValidateRequest(RequestHeader requestHeader, // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( - StatusCodes.BadUserAccessDenied, - "NoWriteAllowed", Namespaces.UserAuthentication, + new StatusCode(StatusCodes.BadUserAccessDenied, + "NoWriteAllowed"), new LocalizedText(info))); } #if TODO diff --git a/Workshop/Views/Client/MainForm.cs b/Workshop/Views/Client/MainForm.cs index ef9688236..60d1c9114 100644 --- a/Workshop/Views/Client/MainForm.cs +++ b/Workshop/Views/Client/MainForm.cs @@ -58,10 +58,11 @@ private MainForm() /// Creates a form which uses the specified client configuration. /// /// The configuration to use. - public MainForm(ApplicationConfiguration configuration) + public MainForm(ApplicationConfiguration configuration, ITelemetryContext telemetry) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); + m_telemetry = telemetry; ConnectServerCTRL.Configuration = m_configuration = configuration; ConnectServerCTRL.ServerUrl = "opc.tcp://localhost:62561/Quickstarts/ViewsServer"; @@ -72,6 +73,7 @@ public MainForm(ApplicationConfiguration configuration) #region Private Fields private ApplicationConfiguration m_configuration; private ISession m_session; + private ITelemetryContext m_telemetry; private bool m_connectedOnce; #endregion @@ -86,11 +88,11 @@ private void Server_ConnectMI_Click(object sender, EventArgs e) { try { - ConnectServerCTRL.ConnectAsync().Wait(); + ConnectServerCTRL.ConnectAsync(m_telemetry).Wait(); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -105,7 +107,7 @@ private void Server_DisconnectMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -120,7 +122,7 @@ private void Server_DiscoverMI_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -164,11 +166,11 @@ private async void Server_ConnectCompleteAsync(object sender, EventArgs e) } // browse the instances in the server. - await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); + await BrowseCTRL.InitializeAsync(m_session, ObjectIds.ObjectsFolder, m_telemetry, default, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates); } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -183,7 +185,7 @@ private async void Server_ReconnectStartingAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -199,7 +201,7 @@ private async void Server_ReconnectCompleteAsync(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } @@ -233,7 +235,7 @@ private void ChangeViewBTN_Click(object sender, EventArgs e) } catch (Exception exception) { - ClientUtils.HandleException(this.Text, exception); + ClientUtils.HandleException(m_telemetry, this.Text, exception); } } } diff --git a/Workshop/Views/Client/Program.cs b/Workshop/Views/Client/Program.cs index 9a6d65b75..ab1199942 100644 --- a/Workshop/Views/Client/Program.cs +++ b/Workshop/Views/Client/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -27,16 +27,33 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Client.Controls; using Opc.Ua.Configuration; -using System; -using System.Windows.Forms; namespace Quickstarts.ViewsClient { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } + static class Program { + private static ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -48,18 +65,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Client; application.ConfigSectionName = "Quickstarts.ViewsClient"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -67,11 +78,11 @@ static void Main() application.CheckApplicationInstanceCertificatesAsync(false).AsTask().Wait(); // run the application interactively. - Application.Run(new MainForm(application.ApplicationConfiguration)); + Application.Run(new MainForm(application.ApplicationConfiguration, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Views/Client/Views Client.csproj b/Workshop/Views/Client/Views Client.csproj index 4814279cd..a46ef4a29 100644 --- a/Workshop/Views/Client/Views Client.csproj +++ b/Workshop/Views/Client/Views Client.csproj @@ -132,8 +132,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Views/Server/Program.cs b/Workshop/Views/Server/Program.cs index 622c34d8e..37b30611a 100644 --- a/Workshop/Views/Server/Program.cs +++ b/Workshop/Views/Server/Program.cs @@ -2,7 +2,7 @@ * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,7 +11,7 @@ * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, @@ -29,17 +29,33 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; using Opc.Ua; -using Opc.Ua.Server; using Opc.Ua.Configuration; +using Opc.Ua.Server; using Opc.Ua.Server.Controls; namespace Quickstarts.ViewsServer { + public sealed class ConsoleTelemetry : TelemetryContextBase + { + public ConsoleTelemetry() + : base( + Microsoft.Extensions.Logging.LoggerFactory.Create(builder => + { + builder.SetMinimumLevel(LogLevel.Information); + builder.AddConsole(); + }) + ) + { + } + } static class Program { + private static readonly ITelemetryContext m_telemetry = new ConsoleTelemetry(); + /// /// The main entry point for the application. /// @@ -51,25 +67,12 @@ static void Main() Application.SetCompatibleTextRenderingDefault(false); ApplicationInstance.MessageDlg = new ApplicationMessageDlg(); - ApplicationInstance application = new ApplicationInstance(); + ApplicationInstance application = new ApplicationInstance(m_telemetry); application.ApplicationType = ApplicationType.Server; application.ConfigSectionName = "Quickstarts.ViewsServer"; try { - // process and command line arguments. - if (application.ProcessCommandLine()) - { - return; - } - - // check if running as a service. - if (!Environment.UserInteractive) - { - application.StartAsService(new ViewsServer()); - return; - } - // load the application configuration. application.LoadApplicationConfigurationAsync(false).AsTask().Wait(); @@ -80,11 +83,11 @@ static void Main() application.StartAsync(new ViewsServer()).Wait(); // run the application interactively. - Application.Run(new Opc.Ua.Server.Controls.ServerForm(application)); + Application.Run(new Opc.Ua.Server.Controls.ServerForm(application, m_telemetry)); } catch (Exception e) { - ExceptionDlg.Show(application.ApplicationName, e); + ExceptionDlg.Show(m_telemetry, application.ApplicationName, e); return; } } diff --git a/Workshop/Views/Server/Views Server.csproj b/Workshop/Views/Server/Views Server.csproj index e9d8e3f4e..828444b76 100644 --- a/Workshop/Views/Server/Views Server.csproj +++ b/Workshop/Views/Server/Views Server.csproj @@ -146,8 +146,11 @@ + + 10.0.0 + - 1.5.377.21 + 1.5.378.11-preview diff --git a/Workshop/Views/Server/ViewsServer.cs b/Workshop/Views/Server/ViewsServer.cs index ed53f28a2..0c3ccf603 100644 --- a/Workshop/Views/Server/ViewsServer.cs +++ b/Workshop/Views/Server/ViewsServer.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -59,7 +60,8 @@ public partial class ViewsServer : StandardServer /// protected override MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - Utils.Trace("Creating the Node Managers."); + ILogger logger = server.Telemetry.CreateLogger(); + logger.LogInformation("Creating the Node Managers."); List nodeManagers = new List(); diff --git a/targets.props b/targets.props index 71332ef16..029f75ac3 100644 --- a/targets.props +++ b/targets.props @@ -22,11 +22,11 @@ - $(DotNetTargetFramework)net8.0 - net8.0 - $(DotNetTargetFramework);net8.0 - $(DotNetTargetFramework)netstandard2.0;netstandard2.1;net8.0 - $(DotNetTargetFramework)netstandard2.1;net8.0 + $(DotNetTargetFramework)net8.0;net10.0 + net10.0 + $(DotNetTargetFramework)net8.0;net10.0 + $(DotNetTargetFramework)netstandard2.1;net8.0;net10.0 + $(DotNetTargetFramework)netstandard2.1;net8.0;net10.0 true