Quellcode durchsuchen

feat: 同步OPC UA升级至AOI-3分支 - 升级OPC Foundation SDK至1.5.378.152 - 引入OpcUaHelper本地项目替换NuGet包v2.2.1 - 修复后台轮询时序(Delay提前确保读取间隔) - 优化轮询间隔参数(25→50/100ms) - 新增异常日志记录 - 更新绑定重定向及依赖包版本

赵留洋 vor 4 Monaten
Ursprung
Commit
1e8e02634e
56 geänderte Dateien mit 9048 neuen und 55 gelöschten Zeilen
  1. 1267 0
      OpcUaHelper/ClientUtils.cs
  2. 223 0
      OpcUaHelper/ExceptionDlg.cs
  3. 151 0
      OpcUaHelper/ExceptionDlg.designer.cs
  4. 120 0
      OpcUaHelper/ExceptionDlg.resx
  5. 476 0
      OpcUaHelper/FilterDeclaration.cs
  6. 1022 0
      OpcUaHelper/FormUtils.cs
  7. 235 0
      OpcUaHelper/Forms/DiscoverServerDlg.cs
  8. 164 0
      OpcUaHelper/Forms/DiscoverServerDlg.designer.cs
  9. 120 0
      OpcUaHelper/Forms/DiscoverServerDlg.resx
  10. 1632 0
      OpcUaHelper/Forms/FormBrowseServer.cs
  11. 503 0
      OpcUaHelper/Forms/FormBrowseServer.designer.cs
  12. 231 0
      OpcUaHelper/Forms/FormBrowseServer.resx
  13. 252 0
      OpcUaHelper/Forms/FormConnectSelect.Designer.cs
  14. 96 0
      OpcUaHelper/Forms/FormConnectSelect.cs
  15. 120 0
      OpcUaHelper/Forms/FormConnectSelect.resx
  16. 49 0
      OpcUaHelper/Forms/TreeViewEx.cs
  17. 1462 0
      OpcUaHelper/OpcUaClient.cs
  18. 191 0
      OpcUaHelper/OpcUaHelper.csproj
  19. 61 0
      OpcUaHelper/OpcUaStatusEventArgs.cs
  20. 36 0
      OpcUaHelper/Properties/AssemblyInfo.cs
  21. 293 0
      OpcUaHelper/Properties/Resources.Designer.cs
  22. 190 0
      OpcUaHelper/Properties/Resources.resx
  23. 51 0
      OpcUaHelper/app.config
  24. BIN
      OpcUaHelper/img/Activity_16xLG.png
  25. BIN
      OpcUaHelper/img/ClassIcon.ico
  26. BIN
      OpcUaHelper/img/ClassIcon.png
  27. BIN
      OpcUaHelper/img/Class_489.png
  28. BIN
      OpcUaHelper/img/Cloud_16xLG.png
  29. BIN
      OpcUaHelper/img/Copy_6524.png
  30. BIN
      OpcUaHelper/img/Delegate_8339.png
  31. BIN
      OpcUaHelper/img/Enum_582.png
  32. BIN
      OpcUaHelper/img/Event_594.png
  33. BIN
      OpcUaHelper/img/Event_594_exp.png
  34. BIN
      OpcUaHelper/img/ListView_687.png
  35. BIN
      OpcUaHelper/img/Method_636.png
  36. BIN
      OpcUaHelper/img/Module_648.png
  37. BIN
      OpcUaHelper/img/RegistryEditor_5838.ico
  38. BIN
      OpcUaHelper/img/SingleMessage_5727.ico
  39. BIN
      OpcUaHelper/img/Structure_507.png
  40. BIN
      OpcUaHelper/img/Table_748.png
  41. BIN
      OpcUaHelper/img/Tag_7213.png
  42. BIN
      OpcUaHelper/img/UserInterfaceEditor_5845.ico
  43. BIN
      OpcUaHelper/img/VirtualMachine.png
  44. BIN
      OpcUaHelper/img/WindowsForm_817.ico
  45. BIN
      OpcUaHelper/img/brackets_Square_16xMD.png
  46. BIN
      OpcUaHelper/img/docview_xaml_on_16x16.png
  47. BIN
      OpcUaHelper/img/glasses_16xLG.png
  48. BIN
      OpcUaHelper/img/grid_Data_16xLG.png
  49. BIN
      OpcUaHelper/img/lightningBolt_16xLG.png
  50. BIN
      OpcUaHelper/img/loading.gif
  51. BIN
      OpcUaHelper/img/usbcontroller.png
  52. 7 1
      TeamAAS-VM.sln
  53. 21 5
      TeamAAS-VM/App.config
  54. 14 10
      TeamAAS-VM/Core/PLCs/OPCuaClientPLC.cs
  55. 40 24
      TeamAAS-VM/TeamAAS-VP.csproj
  56. 21 15
      TeamAAS-VM/packages.config

+ 1267 - 0
OpcUaHelper/ClientUtils.cs

@@ -0,0 +1,1267 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Opc.Ua;
+using Opc.Ua.Client;
+
+namespace OpcUaHelper
+{
+    /// <summary>
+    /// Defines numerous re-useable utility functions.
+    /// </summary>
+    public partial class ClientUtils
+    {
+        /// <summary>
+        /// Handles an exception.
+        /// </summary>
+        public static void HandleException( string caption, Exception e )
+        {
+            ExceptionDlg.Show( caption, e );
+        }
+
+        /// <summary>
+        /// Returns the application icon.
+        /// </summary>
+        public static System.Drawing.Icon GetAppIcon()
+        {
+            try
+            {
+                return new Icon( "App.ico" );
+            }
+            catch (Exception)
+            {
+                return null;
+            }
+        }
+
+        #region DisplayText Lookup
+        /// <summary>
+        /// Gets the display text for the access level attribute.
+        /// </summary>
+        /// <param name="accessLevel">The access level.</param>
+        /// <returns>The access level formatted as a string.</returns>
+        public static string GetAccessLevelDisplayText( byte accessLevel )
+        {
+            StringBuilder buffer = new StringBuilder( );
+
+            if (accessLevel == AccessLevels.None)
+            {
+                buffer.Append( "None" );
+            }
+
+            if ((accessLevel & AccessLevels.CurrentRead) == AccessLevels.CurrentRead)
+            {
+                buffer.Append( "Read" );
+            }
+
+            if ((accessLevel & AccessLevels.CurrentWrite) == AccessLevels.CurrentWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "Write" );
+            }
+
+            if ((accessLevel & AccessLevels.HistoryRead) == AccessLevels.HistoryRead)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryRead" );
+            }
+
+            if ((accessLevel & AccessLevels.HistoryWrite) == AccessLevels.HistoryWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryWrite" );
+            }
+
+            if ((accessLevel & AccessLevels.SemanticChange) == AccessLevels.SemanticChange)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "SemanticChange" );
+            }
+
+            return buffer.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the event notifier attribute.
+        /// </summary>
+        /// <param name="eventNotifier">The event notifier.</param>
+        /// <returns>The event notifier formatted as a string.</returns>
+        public static string GetEventNotifierDisplayText( byte eventNotifier )
+        {
+            StringBuilder buffer = new StringBuilder( );
+
+            if (eventNotifier == EventNotifiers.None)
+            {
+                buffer.Append( "None" );
+            }
+
+            if ((eventNotifier & EventNotifiers.SubscribeToEvents) == EventNotifiers.SubscribeToEvents)
+            {
+                buffer.Append( "Subscribe" );
+            }
+
+            if ((eventNotifier & EventNotifiers.HistoryRead) == EventNotifiers.HistoryRead)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryRead" );
+            }
+
+            if ((eventNotifier & EventNotifiers.HistoryWrite) == EventNotifiers.HistoryWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryWrite" );
+            }
+
+            return buffer.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the value rank attribute.
+        /// </summary>
+        /// <param name="valueRank">The value rank.</param>
+        /// <returns>The value rank formatted as a string.</returns>
+        public static string GetValueRankDisplayText( int valueRank )
+        {
+            switch (valueRank)
+            {
+                case ValueRanks.Any: return "Any";
+                case ValueRanks.Scalar: return "Scalar";
+                case ValueRanks.ScalarOrOneDimension: return "ScalarOrOneDimension";
+                case ValueRanks.OneOrMoreDimensions: return "OneOrMoreDimensions";
+                case ValueRanks.OneDimension: return "OneDimension";
+                case ValueRanks.TwoDimensions: return "TwoDimensions";
+            }
+
+            return valueRank.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the specified attribute.
+        /// </summary>
+        /// <param name="session">The currently active session.</param>
+        /// <param name="attributeId">The id of the attribute.</param>
+        /// <param name="value">The value of the attribute.</param>
+        /// <returns>The attribute formatted as a string.</returns>
+        public static string GetAttributeDisplayText( Session session, uint attributeId, Variant value )
+        {
+            if (value == Variant.Null)
+            {
+                return String.Empty;
+            }
+
+            switch (attributeId)
+            {
+                case Attributes.AccessLevel:
+                case Attributes.UserAccessLevel:
+                    {
+                        byte? field = value.Value as byte?;
+
+                        if (field != null)
+                        {
+                            return GetAccessLevelDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.EventNotifier:
+                    {
+                        byte? field = value.Value as byte?;
+
+                        if (field != null)
+                        {
+                            return GetEventNotifierDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.DataType:
+                    {
+                        return session.NodeCache.GetDisplayText( value.Value as NodeId );
+                    }
+
+                case Attributes.ValueRank:
+                    {
+                        int? field = value.Value as int?;
+
+                        if (field != null)
+                        {
+                            return GetValueRankDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.NodeClass:
+                    {
+                        int? field = value.Value as int?;
+
+                        if (field != null)
+                        {
+                            return ((NodeClass)field.Value).ToString( );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.NodeId:
+                    {
+                        NodeId field = value.Value as NodeId;
+
+                        if (!NodeId.IsNull( field ))
+                        {
+                            return field.ToString( );
+                        }
+
+                        return "Null";
+                    }
+            }
+
+            // check for byte strings.
+            if (value.Value is byte[])
+            {
+                return Utils.ToHexString( value.Value as byte[] );
+            }
+
+            // use default format.
+            return value.ToString( );
+        }
+        #endregion
+
+        #region Browse
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodesToBrowse">The set of browse operations to perform.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection Browse( Session session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError )
+        {
+            return Browse( session, null, nodesToBrowse, throwOnError );
+        }
+
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        public static ReferenceDescriptionCollection Browse( Session session, ViewDescription view, BrowseDescriptionCollection nodesToBrowse, bool throwOnError )
+        {
+            try
+            {
+                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
+
+                while (nodesToBrowse.Count > 0)
+                {
+                    // start the browse operation.
+                    BrowseResultCollection results = null;
+                    DiagnosticInfoCollection diagnosticInfos = null;
+
+                    session.Browse(
+                        null,
+                        view,
+                        0,
+                        nodesToBrowse,
+                        out results,
+                        out diagnosticInfos );
+
+                    ClientBase.ValidateResponse( results, nodesToBrowse );
+                    ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+
+                    ByteStringCollection continuationPoints = new ByteStringCollection( );
+                    BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection( );
+
+                    for (int ii = 0; ii < nodesToBrowse.Count; ii++)
+                    {
+                        // check for error.
+                        if (StatusCode.IsBad( results[ii].StatusCode ))
+                        {
+                            // this error indicates that the server does not have enough simultaneously active 
+                            // continuation points. This request will need to be resent after the other operations
+                            // have been completed and their continuation points released.
+                            if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints)
+                            {
+                                unprocessedOperations.Add( nodesToBrowse[ii] );
+                            }
+
+                            continue;
+                        }
+
+                        // check if all references have been fetched.
+                        if (results[ii].References.Count == 0)
+                        {
+                            continue;
+                        }
+
+                        // save results.
+                        references.AddRange( results[ii].References );
+
+                        // check for continuation point.
+                        if (results[ii].ContinuationPoint != null)
+                        {
+                            continuationPoints.Add( results[ii].ContinuationPoint );
+                        }
+                    }
+
+                    // process continuation points.
+                    while (continuationPoints.Count > 0)
+                    {
+                        // continue browse operation.
+                        session.BrowseNext(
+                            null,
+                            false,
+                            continuationPoints,
+                            out results,
+                            out diagnosticInfos );
+
+                        ClientBase.ValidateResponse( results, continuationPoints );
+                        ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
+
+                        ByteStringCollection revisedContinuationPoints = new ByteStringCollection( );
+                        for (int ii = 0; ii < continuationPoints.Count; ii++)
+                        {
+                            // check for error.
+                            if (StatusCode.IsBad( results[ii].StatusCode ))
+                            {
+                                continue;
+                            }
+
+                            // check if all references have been fetched.
+                            if (results[ii].References.Count == 0)
+                            {
+                                continue;
+                            }
+
+                            // save results.
+                            references.AddRange( results[ii].References );
+
+                            // check for continuation point.
+                            if (results[ii].ContinuationPoint != null)
+                            {
+                                revisedContinuationPoints.Add( results[ii].ContinuationPoint );
+                            }
+                        }
+
+                        // check if browsing must continue;
+                        continuationPoints = revisedContinuationPoints;
+                    }
+
+                    // check if unprocessed results exist.
+                    nodesToBrowse = unprocessedOperations;
+                }
+
+                // return complete list.
+                return references;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodeToBrowse">The NodeId for the starting node.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection Browse( Session session, BrowseDescription nodeToBrowse, bool throwOnError )
+        {
+            return Browse( session, null, nodeToBrowse, throwOnError );
+        }
+
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        public static ReferenceDescriptionCollection Browse( Session session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError )
+        {
+            try
+            {
+                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
+
+                // construct browse request.
+                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+                nodesToBrowse.Add( nodeToBrowse );
+
+                // start the browse operation.
+                BrowseResultCollection results = null;
+                DiagnosticInfoCollection diagnosticInfos = null;
+
+                session.Browse(
+                    null,
+                    view,
+                    0,
+                    nodesToBrowse,
+                    out results,
+                    out diagnosticInfos );
+
+                ClientBase.ValidateResponse( results, nodesToBrowse );
+                ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+
+                do
+                {
+                    // check for error.
+                    if (StatusCode.IsBad( results[0].StatusCode ))
+                    {
+                        throw new ServiceResultException( results[0].StatusCode );
+                    }
+
+                    // process results.
+                    for (int ii = 0; ii < results[0].References.Count; ii++)
+                    {
+                        references.Add( results[0].References[ii] );
+                    }
+
+                    // check if all references have been fetched.
+                    if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
+                    {
+                        break;
+                    }
+
+                    // continue browse operation.
+                    ByteStringCollection continuationPoints = new ByteStringCollection( );
+                    continuationPoints.Add( results[0].ContinuationPoint );
+
+                    session.BrowseNext(
+                        null,
+                        false,
+                        continuationPoints,
+                        out results,
+                        out diagnosticInfos );
+
+                    ClientBase.ValidateResponse( results, continuationPoints );
+                    ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
+                }
+                while (true);
+
+                //return complete list.
+                return references;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Browses the address space and returns all of the supertypes of the specified type node.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="typeId">The NodeId for a type node in the address space.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection BrowseSuperTypes( Session session, NodeId typeId, bool throwOnError )
+        {
+            ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection( );
+
+            try
+            {
+                // find all of the children of the field.
+                BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+                nodeToBrowse.NodeId = typeId;
+                nodeToBrowse.BrowseDirection = BrowseDirection.Inverse;
+                nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
+                nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible.
+                nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. 
+                nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+                ReferenceDescriptionCollection references = Browse( session, nodeToBrowse, throwOnError );
+
+                while (references != null && references.Count > 0)
+                {
+                    // should never be more than one supertype.
+                    supertypes.Add( references[0] );
+
+                    // only follow references within this server.
+                    if (references[0].NodeId.IsAbsolute)
+                    {
+                        break;
+                    }
+
+                    // get the references for the next level up.
+                    nodeToBrowse.NodeId = (NodeId)references[0].NodeId;
+                    references = Browse( session, nodeToBrowse, throwOnError );
+                }
+
+                // return complete list.
+                return supertypes;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Returns the node ids for a set of relative paths.
+        /// </summary>
+        /// <param name="session">An open session with the server to use.</param>
+        /// <param name="startNodeId">The starting node for the relative paths.</param>
+        /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param>
+        /// <param name="relativePaths">The relative paths.</param>
+        /// <returns>A collection of local nodes.</returns>
+        public static List<NodeId> TranslateBrowsePaths(
+            Session session,
+            NodeId startNodeId,
+            NamespaceTable namespacesUris,
+            params string[] relativePaths )
+        {
+            // build the list of browse paths to follow by parsing the relative paths.
+            BrowsePathCollection browsePaths = new BrowsePathCollection( );
+
+            if (relativePaths != null)
+            {
+                for (int ii = 0; ii < relativePaths.Length; ii++)
+                {
+                    BrowsePath browsePath = new BrowsePath( );
+
+                    // The relative paths used indexes in the namespacesUris table. These must be 
+                    // converted to indexes used by the server. An error occurs if the relative path
+                    // refers to a namespaceUri that the server does not recognize.
+
+                    // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object
+                    // allows the parser to look up the server's NodeId for the ReferenceType.
+
+                    browsePath.RelativePath = RelativePath.Parse(
+                        relativePaths[ii],
+                        session.TypeTree,
+                        namespacesUris,
+                        session.NamespaceUris );
+
+                    browsePath.StartingNode = startNodeId;
+
+                    browsePaths.Add( browsePath );
+                }
+            }
+
+            // make the call to the server.
+            BrowsePathResultCollection results;
+            DiagnosticInfoCollection diagnosticInfos;
+
+            ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds(
+                null,
+                browsePaths,
+                out results,
+                out diagnosticInfos );
+
+            // ensure that the server returned valid results.
+            Session.ValidateResponse( results, browsePaths );
+            Session.ValidateDiagnosticInfos( diagnosticInfos, browsePaths );
+
+            // collect the list of node ids found.
+            List<NodeId> nodes = new List<NodeId>( );
+
+            for (int ii = 0; ii < results.Count; ii++)
+            {
+                // check if the start node actually exists.
+                if (StatusCode.IsBad( results[ii].StatusCode ))
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // an empty list is returned if no node was found.
+                if (results[ii].Targets.Count == 0)
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // Multiple matches are possible, however, the node that matches the type model is the
+                // one we are interested in here. The rest can be ignored.
+                BrowsePathTarget target = results[ii].Targets[0];
+
+                if (target.RemainingPathIndex != UInt32.MaxValue)
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // The targetId is an ExpandedNodeId because it could be node in another server. 
+                // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId.
+                nodes.Add( ExpandedNodeId.ToNodeId( target.TargetId, session.NamespaceUris ) );
+            }
+
+            // return whatever was found.
+            return nodes;
+        }
+        #endregion
+
+        #region Events
+        /// <summary>
+        /// Finds the type of the event for the notification.
+        /// </summary>
+        /// <param name="monitoredItem">The monitored item.</param>
+        /// <param name="notification">The notification.</param>
+        /// <returns>The NodeId of the EventType.</returns>
+        public static NodeId FindEventType( MonitoredItem monitoredItem, EventFieldList notification )
+        {
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+
+            if (filter != null)
+            {
+                for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
+                {
+                    SimpleAttributeOperand clause = filter.SelectClauses[ii];
+
+                    if (clause.BrowsePath.Count == 1 && clause.BrowsePath[0] == BrowseNames.EventType)
+                    {
+                        return notification.EventFields[ii].Value as NodeId;
+                    }
+                }
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// Constructs an event object from a notification.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="monitoredItem">The monitored item that produced the notification.</param>
+        /// <param name="notification">The notification.</param>
+        /// <param name="knownEventTypes">The known event types.</param>
+        /// <param name="eventTypeMappings">Mapping between event types and known event types.</param>
+        /// <returns>
+        /// The event object. Null if the notification is not a valid event type.
+        /// </returns>
+        public static BaseEventState ConstructEvent(
+            Session session,
+            MonitoredItem monitoredItem,
+            EventFieldList notification,
+            Dictionary<NodeId, Type> knownEventTypes,
+            Dictionary<NodeId, NodeId> eventTypeMappings )
+        {
+            // find the event type.
+            NodeId eventTypeId = FindEventType( monitoredItem, notification );
+
+            if (eventTypeId == null)
+            {
+                return null;
+            }
+
+            // look up the known event type.
+            Type knownType = null;
+            NodeId knownTypeId = null;
+
+            if (eventTypeMappings.TryGetValue( eventTypeId, out knownTypeId ))
+            {
+                knownType = knownEventTypes[knownTypeId];
+            }
+
+            // try again.
+            if (knownType == null)
+            {
+                if (knownEventTypes.TryGetValue( eventTypeId, out knownType ))
+                {
+                    knownTypeId = eventTypeId;
+                    eventTypeMappings.Add( eventTypeId, eventTypeId );
+                }
+            }
+
+            // try mapping it to a known type.
+            if (knownType == null)
+            {
+                // browse for the supertypes of the event type.
+                ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes( session, eventTypeId, false );
+
+                // can't do anything with unknown types.
+                if (supertypes == null)
+                {
+                    return null;
+                }
+
+                // find the first supertype that matches a known event type.
+                for (int ii = 0; ii < supertypes.Count; ii++)
+                {
+                    NodeId superTypeId = (NodeId)supertypes[ii].NodeId;
+
+                    if (knownEventTypes.TryGetValue( superTypeId, out knownType ))
+                    {
+                        knownTypeId = superTypeId;
+                        eventTypeMappings.Add( eventTypeId, superTypeId );
+                    }
+
+                    if (knownTypeId != null)
+                    {
+                        break;
+                    }
+                }
+
+                // can't do anything with unknown types.
+                if (knownTypeId == null)
+                {
+                    return null;
+                }
+            }
+
+            // construct the event based on the known event type.
+            BaseEventState e = (BaseEventState)Activator.CreateInstance( knownType, new object[] { (NodeState)null } );
+
+            // get the filter which defines the contents of the notification.
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+
+            // initialize the event with the values in the notification.
+            e.Update( session.SystemContext, filter.SelectClauses, notification );
+
+            // save the orginal notification.
+            e.Handle = notification;
+
+            return e;
+        }
+        #endregion
+
+        #region Type Model Browsing
+        /// <summary>
+        /// Collects the instance declarations for a type.
+        /// </summary>
+        public static List<InstanceDeclaration> CollectInstanceDeclarationsForType( Session session, NodeId typeId )
+        {
+            return CollectInstanceDeclarationsForType( session, typeId, true );
+        }
+
+        /// <summary>
+        /// Collects the instance declarations for a type.
+        /// </summary>
+        public static List<InstanceDeclaration> CollectInstanceDeclarationsForType( Session session, NodeId typeId, bool includeSupertypes )
+        {
+            // process the types starting from the top of the tree.
+            List<InstanceDeclaration> instances = new List<InstanceDeclaration>( );
+            Dictionary<string, InstanceDeclaration> map = new Dictionary<string, InstanceDeclaration>( );
+
+            // get the supertypes.
+            if (includeSupertypes)
+            {
+                ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes( session, typeId, false );
+
+                if (supertypes != null)
+                {
+                    for (int ii = supertypes.Count - 1; ii >= 0; ii--)
+                    {
+                        CollectInstanceDeclarations( session, (NodeId)supertypes[ii].NodeId, null, instances, map );
+                    }
+                }
+            }
+
+            // collect the fields for the selected type.
+            CollectInstanceDeclarations( session, typeId, null, instances, map );
+
+            // return the complete list.
+            return instances;
+        }
+
+        /// <summary>
+        /// Collects the fields for the instance node.
+        /// </summary>
+        private static void CollectInstanceDeclarations(
+            Session session,
+            NodeId typeId,
+            InstanceDeclaration parent,
+            List<InstanceDeclaration> instances,
+            IDictionary<string, InstanceDeclaration> map )
+        {
+            // find the children.
+            BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+            if (parent == null)
+            {
+                nodeToBrowse.NodeId = typeId;
+            }
+            else
+            {
+                nodeToBrowse.NodeId = parent.NodeId;
+            }
+
+            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasChild;
+            nodeToBrowse.IncludeSubtypes = true;
+            nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method);
+            nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+            // ignore any browsing errors.
+            ReferenceDescriptionCollection references = ClientUtils.Browse( session, nodeToBrowse, false );
+
+            if (references == null)
+            {
+                return;
+            }
+
+            // process the children.
+            List<NodeId> nodeIds = new List<NodeId>( );
+            List<InstanceDeclaration> children = new List<InstanceDeclaration>( );
+
+            for (int ii = 0; ii < references.Count; ii++)
+            {
+                ReferenceDescription reference = references[ii];
+
+                if (reference.NodeId.IsAbsolute)
+                {
+                    continue;
+                }
+
+                // create a new declaration.
+                InstanceDeclaration child = new InstanceDeclaration( );
+
+                child.RootTypeId = typeId;
+                child.NodeId = (NodeId)reference.NodeId;
+                child.BrowseName = reference.BrowseName;
+                child.NodeClass = reference.NodeClass;
+
+                if (!LocalizedText.IsNullOrEmpty( reference.DisplayName ))
+                {
+                    child.DisplayName = reference.DisplayName.Text;
+                }
+                else
+                {
+                    child.DisplayName = reference.BrowseName.Name;
+                }
+
+                if (parent != null)
+                {
+                    child.BrowsePath = new QualifiedNameCollection( parent.BrowsePath );
+                    child.BrowsePathDisplayText = Utils.Format( "{0}/{1}", parent.BrowsePathDisplayText, reference.BrowseName );
+                    child.DisplayPath = Utils.Format( "{0}/{1}", parent.DisplayPath, reference.DisplayName );
+                }
+                else
+                {
+                    child.BrowsePath = new QualifiedNameCollection( );
+                    child.BrowsePathDisplayText = Utils.Format( "{0}", reference.BrowseName );
+                    child.DisplayPath = Utils.Format( "{0}", reference.DisplayName );
+                }
+
+                child.BrowsePath.Add( reference.BrowseName );
+
+                // check if reading an overridden declaration.
+                InstanceDeclaration overriden = null;
+
+                if (map.TryGetValue( child.BrowsePathDisplayText, out overriden ))
+                {
+                    child.OverriddenDeclaration = overriden;
+                }
+
+                map[child.BrowsePathDisplayText] = child;
+
+                // add to list.
+                children.Add( child );
+                nodeIds.Add( child.NodeId );
+            }
+
+            // check if nothing more to do.
+            if (children.Count == 0)
+            {
+                return;
+            }
+
+            // find the modelling rules.
+            List<NodeId> modellingRules = FindTargetOfReference( session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false );
+
+            if (modellingRules != null)
+            {
+                for (int ii = 0; ii < nodeIds.Count; ii++)
+                {
+                    children[ii].ModellingRule = modellingRules[ii];
+
+                    // if the modelling rule is null then the instance is not part of the type declaration.
+                    if (NodeId.IsNull( modellingRules[ii] ))
+                    {
+                        map.Remove( children[ii].BrowsePathDisplayText );
+                    }
+                }
+            }
+
+            // update the descriptions.
+            UpdateInstanceDescriptions( session, children, false );
+
+            // recusively collect instance declarations for the tree below.
+            for (int ii = 0; ii < children.Count; ii++)
+            {
+                if (!NodeId.IsNull( children[ii].ModellingRule ))
+                {
+                    instances.Add( children[ii] );
+                    CollectInstanceDeclarations( session, typeId, children[ii], instances, map );
+                }
+            }
+        }
+
+        /// <summary>
+        /// Finds the targets for the specified reference.
+        /// </summary>
+        private static List<NodeId> FindTargetOfReference( Session session, List<NodeId> nodeIds, NodeId referenceTypeId, bool throwOnError )
+        {
+            try
+            {
+                // construct browse request.
+                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+
+                for (int ii = 0; ii < nodeIds.Count; ii++)
+                {
+                    BrowseDescription nodeToBrowse = new BrowseDescription( );
+                    nodeToBrowse.NodeId = nodeIds[ii];
+                    nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+                    nodeToBrowse.ReferenceTypeId = referenceTypeId;
+                    nodeToBrowse.IncludeSubtypes = false;
+                    nodeToBrowse.NodeClassMask = 0;
+                    nodeToBrowse.ResultMask = (uint)BrowseResultMask.None;
+                    nodesToBrowse.Add( nodeToBrowse );
+                }
+
+                // start the browse operation.
+                BrowseResultCollection results = null;
+                DiagnosticInfoCollection diagnosticInfos = null;
+
+                session.Browse(
+                    null,
+                    null,
+                    1,
+                    nodesToBrowse,
+                    out results,
+                    out diagnosticInfos );
+
+                ClientBase.ValidateResponse( results, nodesToBrowse );
+                ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+
+                List<NodeId> targetIds = new List<NodeId>( );
+                ByteStringCollection continuationPoints = new ByteStringCollection( );
+
+                for (int ii = 0; ii < nodeIds.Count; ii++)
+                {
+                    targetIds.Add( null );
+
+                    // check for error.
+                    if (StatusCode.IsBad( results[ii].StatusCode ))
+                    {
+                        continue;
+                    }
+
+                    // check for continuation point.
+                    if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0)
+                    {
+                        continuationPoints.Add( results[ii].ContinuationPoint );
+                    }
+
+                    // get the node id.
+                    if (results[ii].References.Count > 0)
+                    {
+                        if (NodeId.IsNull( results[ii].References[0].NodeId ) || results[ii].References[0].NodeId.IsAbsolute)
+                        {
+                            continue;
+                        }
+
+                        targetIds[ii] = (NodeId)results[ii].References[0].NodeId;
+                    }
+                }
+
+                // release continuation points.
+                if (continuationPoints.Count > 0)
+                {
+                    session.BrowseNext(
+                        null,
+                        true,
+                        continuationPoints,
+                        out results,
+                        out diagnosticInfos );
+
+                    ClientBase.ValidateResponse( results, nodesToBrowse );
+                    ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+                }
+
+                //return complete list.
+                return targetIds;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Finds the targets for the specified reference.
+        /// </summary>
+        private static void UpdateInstanceDescriptions( Session session, List<InstanceDeclaration> instances, bool throwOnError )
+        {
+            try
+            {
+                ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+
+                for (int ii = 0; ii < instances.Count; ii++)
+                {
+                    ReadValueId nodeToRead = new ReadValueId( );
+                    nodeToRead.NodeId = instances[ii].NodeId;
+                    nodeToRead.AttributeId = Attributes.Description;
+                    nodesToRead.Add( nodeToRead );
+
+                    nodeToRead = new ReadValueId( );
+                    nodeToRead.NodeId = instances[ii].NodeId;
+                    nodeToRead.AttributeId = Attributes.DataType;
+                    nodesToRead.Add( nodeToRead );
+
+                    nodeToRead = new ReadValueId( );
+                    nodeToRead.NodeId = instances[ii].NodeId;
+                    nodeToRead.AttributeId = Attributes.ValueRank;
+                    nodesToRead.Add( nodeToRead );
+                }
+
+                // start the browse operation.
+                DataValueCollection results = null;
+                DiagnosticInfoCollection diagnosticInfos = null;
+
+                session.Read(
+                    null,
+                    0,
+                    TimestampsToReturn.Neither,
+                    nodesToRead,
+                    out results,
+                    out diagnosticInfos );
+
+                ClientBase.ValidateResponse( results, nodesToRead );
+                ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+                // update the instances.
+                for (int ii = 0; ii < nodesToRead.Count; ii += 3)
+                {
+                    InstanceDeclaration instance = instances[ii / 3];
+
+                    instance.Description = results[ii].GetValue<LocalizedText>( LocalizedText.Null ).Text;
+                    instance.DataType = results[ii + 1].GetValue<NodeId>( NodeId.Null );
+                    instance.ValueRank = results[ii + 2].GetValue<int>( ValueRanks.Any );
+
+                    if (!NodeId.IsNull( instance.DataType ))
+                    {
+                        instance.BuiltInType = DataTypes.GetBuiltInType( instance.DataType, session.TypeTree );
+                        instance.DataTypeDisplayText = session.NodeCache.GetDisplayText( instance.DataType );
+
+                        if (instance.ValueRank >= 0)
+                        {
+                            instance.DataTypeDisplayText += "[]";
+                        }
+                    }
+                }
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+            }
+        }
+        #endregion
+
+        #region Private Methods
+        /// <summary>
+        /// Collects the fields for the type.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="typeId">The type id.</param>
+        /// <param name="fields">The fields.</param>
+        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
+        private static void CollectFieldsForType( Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
+        {
+            // get the supertypes.
+            ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes( session, typeId, false );
+
+            if (supertypes == null)
+            {
+                return;
+            }
+
+            // process the types starting from the top of the tree.
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
+            QualifiedNameCollection parentPath = new QualifiedNameCollection( );
+
+            for (int ii = supertypes.Count - 1; ii >= 0; ii--)
+            {
+                CollectFields( session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes );
+            }
+
+            // collect the fields for the selected type.
+            CollectFields( session, typeId, parentPath, fields, fieldNodeIds, foundNodes );
+        }
+
+        /// <summary>
+        /// Collects the fields for the instance.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="instanceId">The instance id.</param>
+        /// <param name="fields">The fields.</param>
+        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
+        private static void CollectFieldsForInstance( Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
+        {
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
+            QualifiedNameCollection parentPath = new QualifiedNameCollection( );
+            CollectFields( session, instanceId, parentPath, fields, fieldNodeIds, foundNodes );
+        }
+
+        /// <summary>
+        /// Collects the fields for the instance node.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodeId">The node id.</param>
+        /// <param name="parentPath">The parent path.</param>
+        /// <param name="fields">The event fields.</param>
+        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
+        /// <param name="foundNodes">The table of found nodes.</param>
+        private static void CollectFields(
+            Session session,
+            NodeId nodeId,
+            QualifiedNameCollection parentPath,
+            SimpleAttributeOperandCollection fields,
+            List<NodeId> fieldNodeIds,
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes )
+        {
+            // find all of the children of the field.
+            BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+            nodeToBrowse.NodeId = nodeId;
+            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.Aggregates;
+            nodeToBrowse.IncludeSubtypes = true;
+            nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable);
+            nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+            ReferenceDescriptionCollection children = ClientUtils.Browse( session, nodeToBrowse, false );
+
+            if (children == null)
+            {
+                return;
+            }
+
+            // process the children.
+            for (int ii = 0; ii < children.Count; ii++)
+            {
+                ReferenceDescription child = children[ii];
+
+                if (child.NodeId.IsAbsolute)
+                {
+                    continue;
+                }
+
+                // construct browse path.
+                QualifiedNameCollection browsePath = new QualifiedNameCollection( parentPath );
+                browsePath.Add( child.BrowseName );
+
+                // check if the browse path is already in the list.
+                int index = ContainsPath( fields, browsePath );
+
+                if (index < 0)
+                {
+                    SimpleAttributeOperand field = new SimpleAttributeOperand( );
+
+                    field.TypeDefinitionId = ObjectTypeIds.BaseEventType;
+                    field.BrowsePath = browsePath;
+                    field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId;
+
+                    fields.Add( field );
+                    fieldNodeIds.Add( (NodeId)child.NodeId );
+                }
+
+                // recusively find all of the children.
+                NodeId targetId = (NodeId)child.NodeId;
+
+                // need to guard against loops.
+                if (!foundNodes.ContainsKey( targetId ))
+                {
+                    foundNodes.Add( targetId, browsePath );
+                    CollectFields( session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes );
+                }
+            }
+        }
+
+        /// <summary>
+        /// Determines whether the specified select clause contains the browse path.
+        /// </summary>
+        /// <param name="selectClause">The select clause.</param>
+        /// <param name="browsePath">The browse path.</param>
+        /// <returns>
+        /// 	<c>true</c> if the specified select clause contains path; otherwise, <c>false</c>.
+        /// </returns>
+        private static int ContainsPath( SimpleAttributeOperandCollection selectClause, QualifiedNameCollection browsePath )
+        {
+            for (int ii = 0; ii < selectClause.Count; ii++)
+            {
+                SimpleAttributeOperand field = selectClause[ii];
+
+                if (field.BrowsePath.Count != browsePath.Count)
+                {
+                    continue;
+                }
+
+                bool match = true;
+
+                for (int jj = 0; jj < field.BrowsePath.Count; jj++)
+                {
+                    if (field.BrowsePath[jj] != browsePath[jj])
+                    {
+                        match = false;
+                        break;
+                    }
+                }
+
+                if (match)
+                {
+                    return ii;
+                }
+            }
+
+            return -1;
+        }
+
+        #endregion
+
+    }
+}

+ 223 - 0
OpcUaHelper/ExceptionDlg.cs

@@ -0,0 +1,223 @@
+/* ========================================================================
+ * 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
+ * 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 Opc.Ua;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Text;
+using System.Windows.Forms;
+
+namespace OpcUaHelper
+{
+    /// <summary>
+    /// A dialog that displays an exception trace in an HTML page.
+    /// </summary>
+    public partial class ExceptionDlg : Form
+    {
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ExceptionDlg"/> class.
+        /// </summary>
+        public ExceptionDlg()
+        {
+            InitializeComponent();
+        }
+
+        private Exception m_exception;
+
+        /// <summary>
+        /// Replaces all special characters in the message.
+        /// </summary>
+        private string ReplaceSpecialCharacters(string message)
+        {
+            message = message.Replace("&", "&#38;");
+            message = message.Replace("<", "&lt;");
+            message = message.Replace(">", "&gt;");
+            message = message.Replace("\"", "&#34;");
+            message = message.Replace("'", "&#39;");
+            message = message.Replace("\r\n", "<br/>");
+
+            return message;
+        }
+
+        private void AddBlock(StringBuilder buffer, string text)
+        {
+            AddBlock(buffer, text, 0);
+        }
+
+        private void AddBlock(StringBuilder buffer, string text, int level)
+        {
+            if (!String.IsNullOrEmpty(text))
+            {
+                if (level > 0)
+                {
+                    if (level == 1)
+                    {
+                        buffer.Append("<tr style='background-color:#990000;");
+                    }
+                    else if (level == 2)
+                    {
+                        buffer.Append("<tr style='background-color:#CC6600;");
+                    }
+                    else
+                    {
+                        buffer.Append("<tr style='background-color:#999999;");
+                    }
+
+                    buffer.Append("color:#FFFFFF;font-weight:bold;font-size:10pt;font-family:Verdana'><td>");
+                    buffer.Append("<p>"); 
+                }
+                else
+                {
+                    buffer.Append("<tr style='font-size:10pt;font-family:Verdana'><td>");
+                    buffer.Append("<p>");
+                }
+
+                buffer.Append(ReplaceSpecialCharacters(text));
+                buffer.Append("</p>");
+                buffer.Append("</td></tr>");
+            }
+        }
+
+        private void Add(StringBuilder buffer, Exception e, bool showStackTrace)
+        {
+            AddBlock(buffer, "EXCEPTION (" + e.GetType().Name + ")", 1);
+            AddBlock(buffer, e.Message);
+
+            ServiceResultException sre = e as ServiceResultException;
+
+            if (sre != null)
+            {
+                ServiceResult sr = new ServiceResult(sre);
+
+                while (sr != null)
+                {
+                    AddBlock(buffer, "SERVICE RESULT (" + new StatusCode(sr.Code).ToString() + ")", 2);
+
+                    string text = (sr.LocalizedText != null) ? sr.LocalizedText.Text : null;
+
+                    if (text != e.Message)
+                    {
+                        AddBlock(buffer, text);
+                    }
+
+                    AddBlock(buffer, sr.SymbolicId);
+                    AddBlock(buffer, sr.NamespaceUri);
+
+                    if (showStackTrace)
+                    {
+                        if (!String.IsNullOrEmpty(sre.AdditionalInfo))
+                        {
+                            AddBlock(buffer, "ADDITIONAL INFO (" + new StatusCode(sr.Code).ToString() + ")", 3);
+                            AddBlock(buffer, sre.AdditionalInfo);
+                        }
+                    }
+
+                    sr = sr.InnerResult;
+                }
+            }
+
+            if (showStackTrace)
+            {
+                AddBlock(buffer, "STACK TRACE", 3);
+                AddBlock(buffer, e.StackTrace);
+            }
+        }
+
+        private void Show(bool showStackTrace)
+        {
+            StringBuilder buffer = new StringBuilder();
+            buffer.Append("<html><body style='margin:0;width:100%'>");
+            //buffer.Append(ExceptionBrowser.Parent.Width);
+            //buffer.Append("px'>");
+            buffer.Append("<table border='1' style='width:100%'>");
+
+            Exception e = m_exception;
+
+            while (e != null)
+            {
+                Add(buffer, e, showStackTrace);
+                e = e.InnerException;
+            }
+
+            buffer.Append("</table>");
+            buffer.Append("</body></html>");
+
+            ExceptionBrowser.DocumentText = buffer.ToString();
+        }
+
+        /// <summary>
+        /// Displays the exception in a dialog.
+        /// </summary>
+        public static void Show(string caption, Exception e)
+        {
+            // check if running as a service.
+            if (!Environment.UserInteractive)
+            {
+                Utils.Trace(e, "Unexpected error in '{0}'.", caption);
+                return;
+            }
+            
+            new ExceptionDlg().ShowDialog(caption, e);
+        }
+
+        /// <summary>
+        /// Display the exception in the dialog.
+        /// </summary>
+        public void ShowDialog(string caption, Exception e)
+        {
+            if (!String.IsNullOrEmpty(caption))
+            {
+                Text = caption;
+            }
+
+            m_exception = e;
+            
+            #if _DEBUG
+            ShowStackTracesCK.Checked = true;
+            #else
+            ShowStackTracesCK.Checked = false;
+            #endif
+
+            Show(ShowStackTracesCK.Checked);
+            ShowDialog();
+        }
+
+        private void OkButton_Click(object sender, EventArgs e)
+        {
+            Close();
+        }
+
+        private void ShowStackTracesCK_CheckedChanged(object sender, EventArgs e)
+        {
+            Show(ShowStackTracesCK.Checked);
+        }
+    }
+}

+ 151 - 0
OpcUaHelper/ExceptionDlg.designer.cs

@@ -0,0 +1,151 @@
+/* ========================================================================
+ * 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
+ * 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/
+ * ======================================================================*/
+
+namespace OpcUaHelper
+{
+    partial class ExceptionDlg
+    {
+        /// <summary>
+        /// Required designer variable.
+        /// </summary>
+        private System.ComponentModel.IContainer components = null;
+
+        /// <summary>
+        /// Clean up any resources being used.
+        /// </summary>
+        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+        protected override void Dispose(bool disposing)
+        {
+            if (disposing && (components != null))
+            {
+                components.Dispose();
+            }
+            base.Dispose(disposing);
+        }
+
+        #region Windows Form Designer generated code
+
+        /// <summary>
+        /// Required method for Designer support - do not modify
+        /// the contents of this method with the code editor.
+        /// </summary>
+        private void InitializeComponent()
+        {
+            this.BottomPN = new System.Windows.Forms.Panel();
+            this.ShowStackTracesCK = new System.Windows.Forms.CheckBox();
+            this.CloseBTN = new System.Windows.Forms.Button();
+            this.MainPN = new System.Windows.Forms.Panel();
+            this.ExceptionBrowser = new System.Windows.Forms.WebBrowser();
+            this.BottomPN.SuspendLayout();
+            this.MainPN.SuspendLayout();
+            this.SuspendLayout();
+            // 
+            // BottomPN
+            // 
+            this.BottomPN.Controls.Add(this.ShowStackTracesCK);
+            this.BottomPN.Controls.Add(this.CloseBTN);
+            this.BottomPN.Dock = System.Windows.Forms.DockStyle.Bottom;
+            this.BottomPN.Location = new System.Drawing.Point(0, 181);
+            this.BottomPN.Name = "BottomPN";
+            this.BottomPN.Size = new System.Drawing.Size(780, 29);
+            this.BottomPN.TabIndex = 1;
+            // 
+            // ShowStackTracesCK
+            // 
+            this.ShowStackTracesCK.AutoSize = true;
+            this.ShowStackTracesCK.Location = new System.Drawing.Point(3, 7);
+            this.ShowStackTracesCK.Name = "ShowStackTracesCK";
+            this.ShowStackTracesCK.Size = new System.Drawing.Size(138, 17);
+            this.ShowStackTracesCK.TabIndex = 1;
+            this.ShowStackTracesCK.Text = "Show Exception Details";
+            this.ShowStackTracesCK.UseVisualStyleBackColor = true;
+            this.ShowStackTracesCK.CheckedChanged += new System.EventHandler(this.ShowStackTracesCK_CheckedChanged);
+            // 
+            // CloseBTN
+            // 
+            this.CloseBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
+            this.CloseBTN.DialogResult = System.Windows.Forms.DialogResult.Cancel;
+            this.CloseBTN.Location = new System.Drawing.Point(353, 3);
+            this.CloseBTN.Name = "CloseBTN";
+            this.CloseBTN.Size = new System.Drawing.Size(75, 23);
+            this.CloseBTN.TabIndex = 0;
+            this.CloseBTN.Text = "Close";
+            this.CloseBTN.UseVisualStyleBackColor = true;
+            // 
+            // MainPN
+            // 
+            this.MainPN.AutoSize = true;
+            this.MainPN.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
+            this.MainPN.Controls.Add(this.ExceptionBrowser);
+            this.MainPN.Dock = System.Windows.Forms.DockStyle.Fill;
+            this.MainPN.Location = new System.Drawing.Point(0, 0);
+            this.MainPN.Name = "MainPN";
+            this.MainPN.Size = new System.Drawing.Size(780, 181);
+            this.MainPN.TabIndex = 1;
+            // 
+            // ExceptionBrowser
+            // 
+            this.ExceptionBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
+            this.ExceptionBrowser.Location = new System.Drawing.Point(0, 0);
+            this.ExceptionBrowser.MinimumSize = new System.Drawing.Size(20, 20);
+            this.ExceptionBrowser.Name = "ExceptionBrowser";
+            this.ExceptionBrowser.ScriptErrorsSuppressed = true;
+            this.ExceptionBrowser.Size = new System.Drawing.Size(780, 181);
+            this.ExceptionBrowser.TabIndex = 1;
+            // 
+            // ExceptionDlg
+            // 
+            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+            this.AutoSize = true;
+            this.ClientSize = new System.Drawing.Size(780, 210);
+            this.Controls.Add(this.MainPN);
+            this.Controls.Add(this.BottomPN);
+            this.MaximumSize = new System.Drawing.Size(4096, 4096);
+            this.Name = "ExceptionDlg";
+            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+            this.Text = "Exception";
+            this.BottomPN.ResumeLayout(false);
+            this.BottomPN.PerformLayout();
+            this.MainPN.ResumeLayout(false);
+            this.ResumeLayout(false);
+            this.PerformLayout();
+
+        }
+
+        #endregion
+
+        private System.Windows.Forms.Panel BottomPN;
+        private System.Windows.Forms.Button CloseBTN;
+        private System.Windows.Forms.Panel MainPN;
+        private System.Windows.Forms.WebBrowser ExceptionBrowser;
+        private System.Windows.Forms.CheckBox ShowStackTracesCK;
+
+    }
+}

+ 120 - 0
OpcUaHelper/ExceptionDlg.resx

@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+</root>

+ 476 - 0
OpcUaHelper/FilterDeclaration.cs

@@ -0,0 +1,476 @@
+/* ========================================================================
+ * 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
+ * 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 System.Text;
+using System.Collections.Generic;
+using Opc.Ua;
+using Opc.Ua.Client;
+
+namespace OpcUaHelper
+{
+    /// <summary>
+    /// Stores a type declaration retrieved from a server.
+    /// </summary>
+    public class TypeDeclaration
+    {
+        /// <summary>
+        /// The node if for the type.
+        /// </summary>
+        public NodeId NodeId;
+
+        /// <summary>
+        /// The fully inhierited list of instance declarations for the type.
+        /// </summary>
+        public List<InstanceDeclaration> Declarations;
+    }
+
+    /// <summary>
+    /// Stores an instance declaration fetched from the server.
+    /// </summary>
+    public class InstanceDeclaration
+    {
+        /// <summary>
+        /// The type that the declaration belongs to.
+        /// </summary>
+        public NodeId RootTypeId;
+
+        /// <summary>
+        /// The browse path to the instance declaration.
+        /// </summary>
+        public QualifiedNameCollection BrowsePath;
+
+        /// <summary>
+        /// The browse path to the instance declaration.
+        /// </summary>
+        public string BrowsePathDisplayText;
+
+        /// <summary>
+        /// A localized path to the instance declaration.
+        /// </summary>
+        public string DisplayPath;
+
+        /// <summary>
+        /// The node id for the instance declaration.
+        /// </summary>
+        public NodeId NodeId;
+
+        /// <summary>
+        /// The node class of the instance declaration.
+        /// </summary>
+        public NodeClass NodeClass;
+
+        /// <summary>
+        /// The browse name for the instance declaration.
+        /// </summary>
+        public QualifiedName BrowseName;
+
+        /// <summary>
+        /// The display name for the instance declaration.
+        /// </summary>
+        public string DisplayName;
+
+        /// <summary>
+        /// The description for the instance declaration.
+        /// </summary>
+        public string Description;
+
+        /// <summary>
+        /// The modelling rule for the instance declaration (i.e. Mandatory or Optional).
+        /// </summary>
+        public NodeId ModellingRule;
+
+        /// <summary>
+        /// The data type for the instance declaration.
+        /// </summary>
+        public NodeId DataType;
+
+        /// <summary>
+        /// The value rank for the instance declaration.
+        /// </summary>
+        public int ValueRank;
+
+        /// <summary>
+        /// The built-in type parent for the data type.
+        /// </summary>
+        public BuiltInType BuiltInType;
+
+        /// <summary>
+        /// A localized name for the data type.
+        /// </summary>
+        public string DataTypeDisplayText;
+
+        /// <summary>
+        /// An instance declaration that has been overridden by the current instance.
+        /// </summary>
+        public InstanceDeclaration OverriddenDeclaration;
+    }
+
+    /// <summary>
+    /// A field in a filter declaration.
+    /// </summary>
+    public class FilterDeclarationField
+    {
+        /// <summary>
+        /// Creates a new instance of a FilterDeclarationField.
+        /// </summary>
+        public FilterDeclarationField()
+        {
+            Selected = true;
+            DisplayInList = false;
+            FilterEnabled = false;
+            FilterOperator = FilterOperator.Equals;
+            FilterValue = Variant.Null;
+            InstanceDeclaration = null;
+        }
+
+        /// <summary>
+        /// Creates a new instance of a FilterDeclarationField.
+        /// </summary>
+        public FilterDeclarationField( InstanceDeclaration instanceDeclaration )
+        {
+            Selected = true;
+            DisplayInList = false;
+            FilterEnabled = false;
+            FilterOperator = FilterOperator.Equals;
+            FilterValue = Variant.Null;
+            InstanceDeclaration = instanceDeclaration;
+        }
+
+        /// <summary>
+        /// Creates a new instance of a FilterDeclarationField.
+        /// </summary>
+        public FilterDeclarationField( FilterDeclarationField field )
+        {
+            Selected = field.Selected;
+            DisplayInList = field.DisplayInList;
+            FilterEnabled = field.FilterEnabled;
+            FilterOperator = field.FilterOperator;
+            FilterValue = field.FilterValue;
+            InstanceDeclaration = field.InstanceDeclaration;
+        }
+
+        /// <summary>
+        /// Whether the field is returned as part of the event notification.
+        /// </summary>
+        public bool Selected;
+
+        /// <summary>
+        /// Whether the field is displayed in the list view.
+        /// </summary>
+        public bool DisplayInList;
+
+        /// <summary>
+        /// Whether the filter is enabled.
+        /// </summary>
+        public bool FilterEnabled;
+
+        /// <summary>
+        /// The filter operator to use in the where clause.
+        /// </summary>
+        public FilterOperator FilterOperator;
+
+        /// <summary>
+        /// The filter value to use in the where clause.
+        /// </summary>
+        public Variant FilterValue;
+
+        /// <summary>
+        /// The instance declaration associated with the field.
+        /// </summary>
+        public InstanceDeclaration InstanceDeclaration;
+    }
+
+    /// <summary>
+    /// A declararion of an event filter.
+    /// </summary>
+    public class FilterDeclaration
+    {
+        /// <summary>
+        /// Creates a new instance of a FilterDeclaration.
+        /// </summary>
+        public FilterDeclaration()
+        {
+            EventTypeId = Opc.Ua.ObjectTypeIds.BaseEventType;
+            Fields = new List<FilterDeclarationField>( );
+        }
+
+        /// <summary>
+        /// Creates a new instance of a FilterDeclaration.
+        /// </summary>
+        public FilterDeclaration( TypeDeclaration eventType, FilterDeclaration template )
+        {
+            EventTypeId = eventType.NodeId;
+            Fields = new List<FilterDeclarationField>( );
+
+            foreach (InstanceDeclaration instanceDeclaration in eventType.Declarations)
+            {
+                if (instanceDeclaration.NodeClass == NodeClass.Method)
+                {
+                    continue;
+                }
+
+                if (NodeId.IsNull( instanceDeclaration.ModellingRule ))
+                {
+                    continue;
+                }
+
+                FilterDeclarationField element = new FilterDeclarationField( instanceDeclaration );
+                Fields.Add( element );
+
+                // set reasonable defaults.
+                if (template == null)
+                {
+                    if (instanceDeclaration.RootTypeId == Opc.Ua.ObjectTypeIds.BaseEventType && instanceDeclaration.BrowseName != Opc.Ua.BrowseNames.EventId)
+                    {
+                        element.DisplayInList = true;
+                    }
+                }
+
+                // preserve filter settings.
+                else
+                {
+                    foreach (FilterDeclarationField field in template.Fields)
+                    {
+                        if (field.InstanceDeclaration.BrowsePathDisplayText == element.InstanceDeclaration.BrowsePathDisplayText)
+                        {
+                            element.DisplayInList = field.DisplayInList;
+                            element.FilterEnabled = field.FilterEnabled;
+                            element.FilterOperator = field.FilterOperator;
+                            element.FilterValue = field.FilterValue;
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+
+        /// <summary>
+        /// Creates a new instance of a FilterDeclaration.
+        /// </summary>
+        public FilterDeclaration( FilterDeclaration declaration )
+        {
+            EventTypeId = declaration.EventTypeId;
+            Fields = new List<FilterDeclarationField>( declaration.Fields.Count );
+
+            for (int ii = 0; ii < declaration.Fields.Count; ii++)
+            {
+                Fields.Add( new FilterDeclarationField( declaration.Fields[ii] ) );
+            }
+        }
+
+        /// <summary>
+        /// Returns the event filter defined by the filter declaration.
+        /// </summary>
+        public EventFilter GetFilter()
+        {
+            EventFilter filter = new EventFilter( );
+            filter.SelectClauses = GetSelectClause( );
+            filter.WhereClause = GetWhereClause( );
+            return filter;
+        }
+
+        /// <summary>
+        /// Adds a simple field to the declaration.
+        /// </summary>
+        public void AddSimpleField( QualifiedName browseName, BuiltInType dataType, bool displayInList )
+        {
+            AddSimpleField( new QualifiedName[] { browseName }, NodeClass.Variable, dataType, ValueRanks.Scalar, displayInList );
+        }
+
+        /// <summary>
+        /// Adds a simple field to the declaration.
+        /// </summary>
+        public void AddSimpleField( QualifiedName browseName, BuiltInType dataType, int valueRank, bool displayInList )
+        {
+            AddSimpleField( new QualifiedName[] { browseName }, NodeClass.Variable, dataType, valueRank, displayInList );
+        }
+
+        /// <summary>
+        /// Adds a simple field to the declaration.
+        /// </summary>
+        public void AddSimpleField( QualifiedName[] browseNames, BuiltInType dataType, int valueRank, bool displayInList )
+        {
+            AddSimpleField( browseNames, NodeClass.Variable, dataType, valueRank, displayInList );
+        }
+
+        /// <summary>
+        /// Adds a simple field to the declaration.
+        /// </summary>
+        public void AddSimpleField( QualifiedName[] browseNames, NodeClass nodeClass, BuiltInType dataType, int valueRank, bool displayInList )
+        {
+            FilterDeclarationField field = new FilterDeclarationField( );
+
+            field.DisplayInList = displayInList;
+            field.InstanceDeclaration = new InstanceDeclaration( );
+            field.InstanceDeclaration.NodeClass = nodeClass;
+
+            if (browseNames != null)
+            {
+                field.InstanceDeclaration.BrowseName = browseNames[browseNames.Length - 1];
+                field.InstanceDeclaration.BrowsePath = new QualifiedNameCollection( );
+
+                StringBuilder path = new StringBuilder( );
+
+                for (int ii = 0; ii < browseNames.Length; ii++)
+                {
+                    if (path.Length > 0)
+                    {
+                        path.Append( '/' );
+                    }
+
+                    path.Append( browseNames[ii] );
+                    field.InstanceDeclaration.BrowsePath.Add( browseNames[ii] );
+                }
+
+                field.InstanceDeclaration.BrowsePathDisplayText = path.ToString( );
+            }
+
+            field.InstanceDeclaration.BuiltInType = dataType;
+            field.InstanceDeclaration.DataType = (uint)dataType;
+            field.InstanceDeclaration.ValueRank = valueRank;
+            field.InstanceDeclaration.DataTypeDisplayText = dataType.ToString( );
+
+            if (valueRank >= 0)
+            {
+                field.InstanceDeclaration.DataTypeDisplayText += "[]";
+            }
+
+            field.InstanceDeclaration.DisplayName = field.InstanceDeclaration.BrowseName.Name;
+            field.InstanceDeclaration.DisplayPath = field.InstanceDeclaration.BrowsePathDisplayText;
+            field.InstanceDeclaration.RootTypeId = ObjectTypeIds.BaseEventType;
+            Fields.Add( field );
+        }
+
+        /// <summary>
+        /// Returns the select clause defined by the filter declaration.
+        /// </summary>
+        public SimpleAttributeOperandCollection GetSelectClause()
+        {
+            SimpleAttributeOperandCollection selectClause = new SimpleAttributeOperandCollection( );
+
+            SimpleAttributeOperand operand = new SimpleAttributeOperand( );
+            operand.TypeDefinitionId = Opc.Ua.ObjectTypeIds.BaseEventType;
+            operand.AttributeId = Attributes.NodeId;
+            selectClause.Add( operand );
+
+            foreach (FilterDeclarationField field in Fields)
+            {
+                if (field.Selected)
+                {
+                    operand = new SimpleAttributeOperand( );
+                    operand.TypeDefinitionId = field.InstanceDeclaration.RootTypeId;
+                    operand.AttributeId = (field.InstanceDeclaration.NodeClass == NodeClass.Object) ? Attributes.NodeId : Attributes.Value;
+                    operand.BrowsePath = field.InstanceDeclaration.BrowsePath;
+                    selectClause.Add( operand );
+                }
+            }
+
+            return selectClause;
+        }
+
+        /// <summary>
+        /// Returns the where clause defined by the filter declaration.
+        /// </summary>
+        public ContentFilter GetWhereClause()
+        {
+            ContentFilter whereClause = new ContentFilter( );
+            ContentFilterElement element1 = whereClause.Push( FilterOperator.OfType, EventTypeId );
+
+            EventFilter filter = new EventFilter( );
+
+            foreach (FilterDeclarationField field in Fields)
+            {
+                if (field.FilterEnabled)
+                {
+                    SimpleAttributeOperand operand1 = new SimpleAttributeOperand( );
+                    operand1.TypeDefinitionId = field.InstanceDeclaration.RootTypeId;
+                    operand1.AttributeId = (field.InstanceDeclaration.NodeClass == NodeClass.Object) ? Attributes.NodeId : Attributes.Value;
+                    operand1.BrowsePath = field.InstanceDeclaration.BrowsePath;
+
+                    LiteralOperand operand2 = new LiteralOperand( );
+                    operand2.Value = field.FilterValue;
+
+                    ContentFilterElement element2 = whereClause.Push( field.FilterOperator, operand1, operand2 );
+                    element1 = whereClause.Push( FilterOperator.And, element1, element2 );
+                }
+            }
+
+            return whereClause;
+        }
+
+        /// <summary>
+        /// Returns the value for the specified browse name.
+        /// </summary>
+        public T GetValue<T>( QualifiedName browseName, VariantCollection fields, T defaultValue )
+        {
+            if (fields == null || fields.Count == 0)
+            {
+                return defaultValue;
+            }
+
+            if (browseName == null)
+            {
+                browseName = QualifiedName.Null;
+            }
+
+            for (int ii = 0; ii < this.Fields.Count; ii++)
+            {
+                if (this.Fields[ii].InstanceDeclaration.BrowseName == browseName)
+                {
+                    if (ii >= fields.Count + 1)
+                    {
+                        return defaultValue;
+                    }
+
+                    object value = fields[ii + 1].Value;
+
+                    if (typeof( T ).IsInstanceOfType( value ))
+                    {
+                        return (T)value;
+                    }
+
+                    break;
+                }
+            }
+
+            return defaultValue;
+        }
+
+        /// <summary>
+        /// The type of event.
+        /// </summary>
+        public NodeId EventTypeId;
+
+        /// <summary>
+        /// The list of declarations for the fields.
+        /// </summary>
+        public List<FilterDeclarationField> Fields;
+    }
+}

+ 1022 - 0
OpcUaHelper/FormUtils.cs

@@ -0,0 +1,1022 @@
+using Opc.Ua;
+using Opc.Ua.Client;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OpcUaHelper
+{
+    /// <summary>
+    /// 辅助类
+    /// </summary>
+    public class FormUtils
+    {
+        /// <summary>
+        /// Gets the display text for the access level attribute.
+        /// </summary>
+        /// <param name="accessLevel">The access level.</param>
+        /// <returns>The access level formatted as a string.</returns>
+        private static string GetAccessLevelDisplayText( byte accessLevel )
+        {
+            StringBuilder buffer = new StringBuilder( );
+
+            if (accessLevel == AccessLevels.None)
+            {
+                buffer.Append( "None" );
+            }
+
+            if ((accessLevel & AccessLevels.CurrentRead) == AccessLevels.CurrentRead)
+            {
+                buffer.Append( "Read" );
+            }
+
+            if ((accessLevel & AccessLevels.CurrentWrite) == AccessLevels.CurrentWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "Write" );
+            }
+
+            if ((accessLevel & AccessLevels.HistoryRead) == AccessLevels.HistoryRead)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryRead" );
+            }
+
+            if ((accessLevel & AccessLevels.HistoryWrite) == AccessLevels.HistoryWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryWrite" );
+            }
+
+            if ((accessLevel & AccessLevels.SemanticChange) == AccessLevels.SemanticChange)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "SemanticChange" );
+            }
+
+            return buffer.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the event notifier attribute.
+        /// </summary>
+        /// <param name="eventNotifier">The event notifier.</param>
+        /// <returns>The event notifier formatted as a string.</returns>
+        private static string GetEventNotifierDisplayText( byte eventNotifier )
+        {
+            StringBuilder buffer = new StringBuilder( );
+
+            if (eventNotifier == EventNotifiers.None)
+            {
+                buffer.Append( "None" );
+            }
+
+            if ((eventNotifier & EventNotifiers.SubscribeToEvents) == EventNotifiers.SubscribeToEvents)
+            {
+                buffer.Append( "Subscribe" );
+            }
+
+            if ((eventNotifier & EventNotifiers.HistoryRead) == EventNotifiers.HistoryRead)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryRead" );
+            }
+
+            if ((eventNotifier & EventNotifiers.HistoryWrite) == EventNotifiers.HistoryWrite)
+            {
+                if (buffer.Length > 0)
+                {
+                    buffer.Append( " | " );
+                }
+
+                buffer.Append( "HistoryWrite" );
+            }
+
+            return buffer.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the value rank attribute.
+        /// </summary>
+        /// <param name="valueRank">The value rank.</param>
+        /// <returns>The value rank formatted as a string.</returns>
+        private static string GetValueRankDisplayText( int valueRank )
+        {
+            switch (valueRank)
+            {
+                case ValueRanks.Any: return "Any";
+                case ValueRanks.Scalar: return "Scalar";
+                case ValueRanks.ScalarOrOneDimension: return "ScalarOrOneDimension";
+                case ValueRanks.OneOrMoreDimensions: return "OneOrMoreDimensions";
+                case ValueRanks.OneDimension: return "OneDimension";
+                case ValueRanks.TwoDimensions: return "TwoDimensions";
+            }
+
+            return valueRank.ToString( );
+        }
+
+        /// <summary>
+        /// Gets the display text for the specified attribute.
+        /// </summary>
+        /// <param name="session">The currently active session.</param>
+        /// <param name="attributeId">The id of the attribute.</param>
+        /// <param name="value">The value of the attribute.</param>
+        /// <returns>The attribute formatted as a string.</returns>
+        public static string GetAttributeDisplayText( Session session, uint attributeId, Variant value )
+        {
+            if (value == Variant.Null)
+            {
+                return String.Empty;
+            }
+
+            switch (attributeId)
+            {
+                case Attributes.AccessLevel:
+                case Attributes.UserAccessLevel:
+                    {
+                        byte? field = value.Value as byte?;
+
+                        if (field != null)
+                        {
+                            return GetAccessLevelDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.EventNotifier:
+                    {
+                        byte? field = value.Value as byte?;
+
+                        if (field != null)
+                        {
+                            return GetEventNotifierDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.DataType:
+                    {
+                        return session.NodeCache.GetDisplayText( value.Value as NodeId );
+                    }
+
+                case Attributes.ValueRank:
+                    {
+                        int? field = value.Value as int?;
+
+                        if (field != null)
+                        {
+                            return GetValueRankDisplayText( field.Value );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.NodeClass:
+                    {
+                        int? field = value.Value as int?;
+
+                        if (field != null)
+                        {
+                            return ((NodeClass)field.Value).ToString( );
+                        }
+
+                        break;
+                    }
+
+                case Attributes.NodeId:
+                    {
+                        NodeId field = value.Value as NodeId;
+
+                        if (!NodeId.IsNull( field ))
+                        {
+                            return field.ToString( );
+                        }
+
+                        return "Null";
+                    }
+            }
+
+            // check for byte strings.
+            if (value.Value is byte[])
+            {
+                return Utils.ToHexString( value.Value as byte[] );
+            }
+
+            // use default format.
+            return value.ToString( );
+        }
+
+        /// <summary>
+        /// Discovers the servers on the local machine.
+        /// </summary>
+        /// <param name="configuration">The configuration.</param>
+        /// <returns>A list of server urls.</returns>
+        public static IList<string> DiscoverServers( ApplicationConfiguration configuration )
+        {
+            List<string> serverUrls = new List<string>( );
+
+            // set a short timeout because this is happening in the drop down event.
+            EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create( configuration );
+            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 ))
+            {
+                ApplicationDescriptionCollection servers = client.FindServers( null );
+
+                // populate the drop down list with the discovery URLs for the available servers.
+                for (int ii = 0; ii < servers.Count; ii++)
+                {
+                    if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
+                    {
+                        continue;
+                    }
+
+                    for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
+                    {
+                        string discoveryUrl = servers[ii].DiscoveryUrls[jj];
+
+                        // Many servers will use the '/discovery' suffix for the discovery endpoint.
+                        // The URL without this prefix should be the base URL for the server. 
+                        if (discoveryUrl.EndsWith( "/discovery" ))
+                        {
+                            discoveryUrl = discoveryUrl.Substring( 0, discoveryUrl.Length - "/discovery".Length );
+                        }
+
+                        // ensure duplicates do not get added.
+                        if (!serverUrls.Contains( discoveryUrl ))
+                        {
+                            serverUrls.Add( discoveryUrl );
+                        }
+                    }
+                }
+            }
+
+            return serverUrls;
+        }
+
+        /// <summary>
+        /// Finds the endpoint that best matches the current settings.
+        /// </summary>
+        /// <param name="discoveryUrl">The discovery URL.</param>
+        /// <param name="useSecurity">if set to <c>true</c> select an endpoint that uses security.</param>
+        /// <returns>The best available endpoint.</returns>
+        public static EndpointDescription SelectEndpoint( string discoveryUrl, bool useSecurity )
+        {
+            // needs to add the '/discovery' back onto non-UA TCP URLs.
+            if (!discoveryUrl.StartsWith( Utils.UriSchemeOpcTcp ))
+            {
+                if (!discoveryUrl.EndsWith( "/discovery" ))
+                {
+                    discoveryUrl += "/discovery";
+                }
+            }
+
+            // parse the selected URL.
+            Uri uri = new Uri( discoveryUrl );
+
+            // set a short timeout because this is happening in the drop down event.
+            EndpointConfiguration configuration = EndpointConfiguration.Create( );
+            configuration.OperationTimeout = 5000;
+
+            EndpointDescription selectedEndpoint = null;
+
+            // Connect to the server's discovery endpoint and find the available configuration.
+            using (DiscoveryClient client = DiscoveryClient.Create( uri, configuration ))
+            {
+                EndpointDescriptionCollection endpoints = client.GetEndpoints( null );
+
+                // select the best endpoint to use based on the selected URL and the UseSecurity checkbox. 
+                for (int ii = 0; ii < endpoints.Count; ii++)
+                {
+                    EndpointDescription endpoint = endpoints[ii];
+
+                    // check for a match on the URL scheme.
+                    if (endpoint.EndpointUrl.StartsWith( uri.Scheme ))
+                    {
+                        // check if security was requested.
+                        if (useSecurity)
+                        {
+                            if (endpoint.SecurityMode == MessageSecurityMode.None)
+                            {
+                                continue;
+                            }
+                        }
+                        else
+                        {
+                            if (endpoint.SecurityMode != MessageSecurityMode.None)
+                            {
+                                continue;
+                            }
+                        }
+
+                        // pick the first available endpoint by default.
+                        if (selectedEndpoint == null)
+                        {
+                            selectedEndpoint = endpoint;
+                        }
+
+                        // The security level is a relative measure assigned by the server to the 
+                        // endpoints that it returns. Clients should always pick the highest level
+                        // unless they have a reason not too.
+                        if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel)
+                        {
+                            selectedEndpoint = endpoint;
+                        }
+                    }
+                }
+
+                // pick the first available endpoint by default.
+                if (selectedEndpoint == null && endpoints.Count > 0)
+                {
+                    selectedEndpoint = endpoints[0];
+                }
+            }
+
+            // if a server is behind a firewall it may return URLs that are not accessible to the client.
+            // This problem can be avoided by assuming that the domain in the URL used to call 
+            // GetEndpoints can be used to access any of the endpoints. This code makes that conversion.
+            // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint.
+
+            Uri endpointUrl = Utils.ParseUri( selectedEndpoint.EndpointUrl );
+
+            if (endpointUrl != null && endpointUrl.Scheme == uri.Scheme)
+            {
+                UriBuilder builder = new UriBuilder( endpointUrl );
+                builder.Host = uri.DnsSafeHost;
+                builder.Port = uri.Port;
+                selectedEndpoint.EndpointUrl = builder.ToString( );
+            }
+
+            // return the selected endpoint.
+            return selectedEndpoint;
+        }
+
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodesToBrowse">The set of browse operations to perform.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection Browse( ISession session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError )
+        {
+            try
+            {
+                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
+                BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection( );
+
+                while (nodesToBrowse.Count > 0)
+                {
+                    // start the browse operation.
+                    BrowseResultCollection results = null;
+                    DiagnosticInfoCollection diagnosticInfos = null;
+
+                    session.Browse(
+                        null,
+                        null,
+                        0,
+                        nodesToBrowse,
+                        out results,
+                        out diagnosticInfos );
+
+                    ClientBase.ValidateResponse( results, nodesToBrowse );
+                    ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+
+                    ByteStringCollection continuationPoints = new ByteStringCollection( );
+
+                    for (int ii = 0; ii < nodesToBrowse.Count; ii++)
+                    {
+                        // check for error.
+                        if (StatusCode.IsBad( results[ii].StatusCode ))
+                        {
+                            // this error indicates that the server does not have enough simultaneously active 
+                            // continuation points. This request will need to be resent after the other operations
+                            // have been completed and their continuation points released.
+                            if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints)
+                            {
+                                unprocessedOperations.Add( nodesToBrowse[ii] );
+                            }
+
+                            continue;
+                        }
+
+                        // check if all references have been fetched.
+                        if (results[ii].References.Count == 0)
+                        {
+                            continue;
+                        }
+
+                        // save results.
+                        references.AddRange( results[ii].References );
+
+                        // check for continuation point.
+                        if (results[ii].ContinuationPoint != null)
+                        {
+                            continuationPoints.Add( results[ii].ContinuationPoint );
+                        }
+                    }
+
+                    // process continuation points.
+                    ByteStringCollection revisedContiuationPoints = new ByteStringCollection( );
+
+                    while (continuationPoints.Count > 0)
+                    {
+                        // continue browse operation.
+                        session.BrowseNext(
+                            null,
+                            true,
+                            continuationPoints,
+                            out results,
+                            out diagnosticInfos );
+
+                        ClientBase.ValidateResponse( results, continuationPoints );
+                        ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
+
+                        for (int ii = 0; ii < continuationPoints.Count; ii++)
+                        {
+                            // check for error.
+                            if (StatusCode.IsBad( results[ii].StatusCode ))
+                            {
+                                continue;
+                            }
+
+                            // check if all references have been fetched.
+                            if (results[ii].References.Count == 0)
+                            {
+                                continue;
+                            }
+
+                            // save results.
+                            references.AddRange( results[ii].References );
+
+                            // check for continuation point.
+                            if (results[ii].ContinuationPoint != null)
+                            {
+                                revisedContiuationPoints.Add( results[ii].ContinuationPoint );
+                            }
+                        }
+
+                        // check if browsing must continue;
+                        revisedContiuationPoints = continuationPoints;
+                    }
+
+                    // check if unprocessed results exist.
+                    nodesToBrowse = unprocessedOperations;
+                }
+
+                // return complete list.
+                return references;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Finds the type of the event for the notification.
+        /// </summary>
+        /// <param name="monitoredItem">The monitored item.</param>
+        /// <param name="notification">The notification.</param>
+        /// <returns>The NodeId of the EventType.</returns>
+        public static NodeId FindEventType( MonitoredItem monitoredItem, EventFieldList notification )
+        {
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+
+            if (filter != null)
+            {
+                for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
+                {
+                    SimpleAttributeOperand clause = filter.SelectClauses[ii];
+
+                    if (clause.BrowsePath.Count == 1 && clause.BrowsePath[0] == BrowseNames.EventType)
+                    {
+                        return notification.EventFields[ii].Value as NodeId;
+                    }
+                }
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// Browses the address space and returns the references found.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodeToBrowse">The NodeId for the starting node.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection Browse( Session session, BrowseDescription nodeToBrowse, bool throwOnError )
+        {
+            try
+            {
+                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection( );
+
+                // construct browse request.
+                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+                nodesToBrowse.Add( nodeToBrowse );
+
+                // start the browse operation.
+                BrowseResultCollection results = null;
+                DiagnosticInfoCollection diagnosticInfos = null;
+
+                session.Browse(
+                    null,
+                    null,
+                    0,
+                    nodesToBrowse,
+                    out results,
+                    out diagnosticInfos );
+
+                ClientBase.ValidateResponse( results, nodesToBrowse );
+                ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToBrowse );
+
+                do
+                {
+                    // check for error.
+                    if (StatusCode.IsBad( results[0].StatusCode ))
+                    {
+                        throw new ServiceResultException( results[0].StatusCode );
+                    }
+
+                    // process results.
+                    for (int ii = 0; ii < results[0].References.Count; ii++)
+                    {
+                        references.Add( results[0].References[ii] );
+                    }
+
+                    // check if all references have been fetched.
+                    if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
+                    {
+                        break;
+                    }
+
+                    // continue browse operation.
+                    ByteStringCollection continuationPoints = new ByteStringCollection( );
+                    continuationPoints.Add( results[0].ContinuationPoint );
+
+                    session.BrowseNext(
+                        null,
+                        false,
+                        continuationPoints,
+                        out results,
+                        out diagnosticInfos );
+
+                    ClientBase.ValidateResponse( results, continuationPoints );
+                    ClientBase.ValidateDiagnosticInfos( diagnosticInfos, continuationPoints );
+                }
+                while (true);
+
+                //return complete list.
+                return references;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Browses the address space and returns all of the supertypes of the specified type node.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="typeId">The NodeId for a type node in the address space.</param>
+        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
+        /// <returns>
+        /// The references found. Null if an error occurred.
+        /// </returns>
+        public static ReferenceDescriptionCollection BrowseSuperTypes( Session session, NodeId typeId, bool throwOnError )
+        {
+            ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection( );
+
+            try
+            {
+                // find all of the children of the field.
+                BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+                nodeToBrowse.NodeId = typeId;
+                nodeToBrowse.BrowseDirection = BrowseDirection.Inverse;
+                nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
+                nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible.
+                nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. 
+                nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+                ReferenceDescriptionCollection references = Browse( session, nodeToBrowse, throwOnError );
+
+                while (references != null && references.Count > 0)
+                {
+                    // should never be more than one supertype.
+                    supertypes.Add( references[0] );
+
+                    // only follow references within this server.
+                    if (references[0].NodeId.IsAbsolute)
+                    {
+                        break;
+                    }
+
+                    // get the references for the next level up.
+                    nodeToBrowse.NodeId = (NodeId)references[0].NodeId;
+                    references = Browse( session, nodeToBrowse, throwOnError );
+                }
+
+                // return complete list.
+                return supertypes;
+            }
+            catch (Exception exception)
+            {
+                if (throwOnError)
+                {
+                    throw new ServiceResultException( exception, StatusCodes.BadUnexpectedError );
+                }
+
+                return null;
+            }
+        }
+
+        /// <summary>
+        /// Constructs an event object from a notification.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="monitoredItem">The monitored item that produced the notification.</param>
+        /// <param name="notification">The notification.</param>
+        /// <param name="knownEventTypes">The known event types.</param>
+        /// <param name="eventTypeMappings">Mapping between event types and known event types.</param>
+        /// <returns>
+        /// The event object. Null if the notification is not a valid event type.
+        /// </returns>
+        public static BaseEventState ConstructEvent(
+            Session session,
+            MonitoredItem monitoredItem,
+            EventFieldList notification,
+            Dictionary<NodeId, Type> knownEventTypes,
+            Dictionary<NodeId, NodeId> eventTypeMappings )
+        {
+            // find the event type.
+            NodeId eventTypeId = FindEventType( monitoredItem, notification );
+
+            if (eventTypeId == null)
+            {
+                return null;
+            }
+
+            // look up the known event type.
+            Type knownType = null;
+            NodeId knownTypeId = null;
+
+            if (eventTypeMappings.TryGetValue( eventTypeId, out knownTypeId ))
+            {
+                knownType = knownEventTypes[knownTypeId];
+            }
+
+            // try again.
+            if (knownType == null)
+            {
+                if (knownEventTypes.TryGetValue( eventTypeId, out knownType ))
+                {
+                    knownTypeId = eventTypeId;
+                    eventTypeMappings.Add( eventTypeId, eventTypeId );
+                }
+            }
+
+            // try mapping it to a known type.
+            if (knownType == null)
+            {
+                // browse for the supertypes of the event type.
+                ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes( session, eventTypeId, false );
+
+                // can't do anything with unknown types.
+                if (supertypes == null)
+                {
+                    return null;
+                }
+
+                // find the first supertype that matches a known event type.
+                for (int ii = 0; ii < supertypes.Count; ii++)
+                {
+                    NodeId superTypeId = (NodeId)supertypes[ii].NodeId;
+
+                    if (knownEventTypes.TryGetValue( superTypeId, out knownType ))
+                    {
+                        knownTypeId = superTypeId;
+                        eventTypeMappings.Add( eventTypeId, superTypeId );
+                    }
+
+                    if (knownTypeId != null)
+                    {
+                        break;
+                    }
+                }
+
+                // can't do anything with unknown types.
+                if (knownTypeId == null)
+                {
+                    return null;
+                }
+            }
+
+            // construct the event based on the known event type.
+            BaseEventState e = (BaseEventState)Activator.CreateInstance( knownType, new object[] { (NodeState)null } );
+
+            // get the filter which defines the contents of the notification.
+            EventFilter filter = monitoredItem.Status.Filter as EventFilter;
+
+            // initialize the event with the values in the notification.
+            e.Update( session.SystemContext, filter.SelectClauses, notification );
+
+            // save the orginal notification.
+            e.Handle = notification;
+
+            return e;
+        }
+
+        /// <summary>
+        /// Returns the node ids for a set of relative paths.
+        /// </summary>
+        /// <param name="session">An open session with the server to use.</param>
+        /// <param name="startNodeId">The starting node for the relative paths.</param>
+        /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param>
+        /// <param name="relativePaths">The relative paths.</param>
+        /// <returns>A collection of local nodes.</returns>
+        public static List<NodeId> TranslateBrowsePaths(
+            Session session,
+            NodeId startNodeId,
+            NamespaceTable namespacesUris,
+            params string[] relativePaths )
+        {
+            // build the list of browse paths to follow by parsing the relative paths.
+            BrowsePathCollection browsePaths = new BrowsePathCollection( );
+
+            if (relativePaths != null)
+            {
+                for (int ii = 0; ii < relativePaths.Length; ii++)
+                {
+                    BrowsePath browsePath = new BrowsePath( );
+
+                    // The relative paths used indexes in the namespacesUris table. These must be 
+                    // converted to indexes used by the server. An error occurs if the relative path
+                    // refers to a namespaceUri that the server does not recognize.
+
+                    // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object
+                    // allows the parser to look up the server's NodeId for the ReferenceType.
+
+                    browsePath.RelativePath = RelativePath.Parse(
+                        relativePaths[ii],
+                        session.TypeTree,
+                        namespacesUris,
+                        session.NamespaceUris );
+
+                    browsePath.StartingNode = startNodeId;
+
+                    browsePaths.Add( browsePath );
+                }
+            }
+
+            // make the call to the server.
+            BrowsePathResultCollection results;
+            DiagnosticInfoCollection diagnosticInfos;
+
+            ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds(
+                null,
+                browsePaths,
+                out results,
+                out diagnosticInfos );
+
+            // ensure that the server returned valid results.
+            Session.ValidateResponse( results, browsePaths );
+            Session.ValidateDiagnosticInfos( diagnosticInfos, browsePaths );
+
+            // collect the list of node ids found.
+            List<NodeId> nodes = new List<NodeId>( );
+
+            for (int ii = 0; ii < results.Count; ii++)
+            {
+                // check if the start node actually exists.
+                if (StatusCode.IsBad( results[ii].StatusCode ))
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // an empty list is returned if no node was found.
+                if (results[ii].Targets.Count == 0)
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // Multiple matches are possible, however, the node that matches the type model is the
+                // one we are interested in here. The rest can be ignored.
+                BrowsePathTarget target = results[ii].Targets[0];
+
+                if (target.RemainingPathIndex != UInt32.MaxValue)
+                {
+                    nodes.Add( null );
+                    continue;
+                }
+
+                // The targetId is an ExpandedNodeId because it could be node in another server. 
+                // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId.
+                nodes.Add( ExpandedNodeId.ToNodeId( target.TargetId, session.NamespaceUris ) );
+            }
+
+            // return whatever was found.
+            return nodes;
+        }
+
+        /// <summary>
+        /// Collects the fields for the type.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="fields">The fields.</param>
+        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
+        public static void CollectFieldsForType( Session session, NodeId typeId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
+        {
+            // get the supertypes.
+            ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes( session, typeId, false );
+
+            if (supertypes == null)
+            {
+                return;
+            }
+
+            // process the types starting from the top of the tree.
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
+            QualifiedNameCollection parentPath = new QualifiedNameCollection( );
+
+            for (int ii = supertypes.Count - 1; ii >= 0; ii--)
+            {
+                CollectFields( session, (NodeId)supertypes[ii].NodeId, parentPath, fields, fieldNodeIds, foundNodes );
+            }
+
+            // collect the fields for the selected type.
+            CollectFields( session, typeId, parentPath, fields, fieldNodeIds, foundNodes );
+        }
+
+        /// <summary>
+        /// Collects the fields for the instance.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="fields">The fields.</param>
+        /// <param name="fieldNodeIds">字段</param>
+        /// <param name="instanceId">The node id for the declaration of the field.</param>
+        public static void CollectFieldsForInstance( Session session, NodeId instanceId, SimpleAttributeOperandCollection fields, List<NodeId> fieldNodeIds )
+        {
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes = new Dictionary<NodeId, QualifiedNameCollection>( );
+            QualifiedNameCollection parentPath = new QualifiedNameCollection( );
+            CollectFields( session, instanceId, parentPath, fields, fieldNodeIds, foundNodes );
+        }
+
+        /// <summary>
+        /// Collects the fields for the instance node.
+        /// </summary>
+        /// <param name="session">The session.</param>
+        /// <param name="nodeId">The node id.</param>
+        /// <param name="parentPath">The parent path.</param>
+        /// <param name="fields">The event fields.</param>
+        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
+        /// <param name="foundNodes">The table of found nodes.</param>
+        private static void CollectFields(
+            Session session,
+            NodeId nodeId,
+            QualifiedNameCollection parentPath,
+            SimpleAttributeOperandCollection fields,
+            List<NodeId> fieldNodeIds,
+            Dictionary<NodeId, QualifiedNameCollection> foundNodes )
+        {
+            // find all of the children of the field.
+            BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+            nodeToBrowse.NodeId = nodeId;
+            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.Aggregates;
+            nodeToBrowse.IncludeSubtypes = true;
+            nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable);
+            nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+            ReferenceDescriptionCollection children = FormUtils.Browse( session, nodeToBrowse, false );
+
+            if (children == null)
+            {
+                return;
+            }
+
+            // process the children.
+            for (int ii = 0; ii < children.Count; ii++)
+            {
+                ReferenceDescription child = children[ii];
+
+                if (child.NodeId.IsAbsolute)
+                {
+                    continue;
+                }
+
+                // construct browse path.
+                QualifiedNameCollection browsePath = new QualifiedNameCollection( parentPath );
+                browsePath.Add( child.BrowseName );
+
+                // check if the browse path is already in the list.
+                int index = ContainsPath( fields, browsePath );
+
+                if (index < 0)
+                {
+                    SimpleAttributeOperand field = new SimpleAttributeOperand( );
+
+                    field.TypeDefinitionId = ObjectTypeIds.BaseEventType;
+                    field.BrowsePath = browsePath;
+                    field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId;
+
+                    fields.Add( field );
+                    fieldNodeIds.Add( (NodeId)child.NodeId );
+                }
+
+                // recusively find all of the children.
+                NodeId targetId = (NodeId)child.NodeId;
+
+                // need to guard against loops.
+                if (!foundNodes.ContainsKey( targetId ))
+                {
+                    foundNodes.Add( targetId, browsePath );
+                    CollectFields( session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes );
+                }
+            }
+        }
+
+        /// <summary>
+        /// Determines whether the specified select clause contains the browse path.
+        /// </summary>
+        /// <param name="selectClause">The select clause.</param>
+        /// <param name="browsePath">The browse path.</param>
+        /// <returns>
+        /// 	<c>true</c> if the specified select clause contains path; otherwise, <c>false</c>.
+        /// </returns>
+        private static int ContainsPath( SimpleAttributeOperandCollection selectClause, QualifiedNameCollection browsePath )
+        {
+            for (int ii = 0; ii < selectClause.Count; ii++)
+            {
+                SimpleAttributeOperand field = selectClause[ii];
+
+                if (field.BrowsePath.Count != browsePath.Count)
+                {
+                    continue;
+                }
+
+                bool match = true;
+
+                for (int jj = 0; jj < field.BrowsePath.Count; jj++)
+                {
+                    if (field.BrowsePath[jj] != browsePath[jj])
+                    {
+                        match = false;
+                        break;
+                    }
+                }
+
+                if (match)
+                {
+                    return ii;
+                }
+            }
+
+            return -1;
+        }
+    }
+}

+ 235 - 0
OpcUaHelper/Forms/DiscoverServerDlg.cs

@@ -0,0 +1,235 @@
+/* ========================================================================
+ * 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
+ * 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 System.Collections.Generic;
+using System.ComponentModel;
+using System.Drawing;
+using System.Text;
+using System.Windows.Forms;
+using Opc.Ua;
+using Opc.Ua.Client;
+
+namespace OpcUaHelper.Forms
+{
+    /// <summary>
+    /// Prompts the user to specify a host name and discovers the servers.
+    /// </summary>
+    public partial class DiscoverServerDlg : Form
+    {
+        #region Constructors
+        /// <summary>
+        /// Creates an empty form.
+        /// </summary>
+        public DiscoverServerDlg()
+        {
+            InitializeComponent();
+            this.Icon = ClientUtils.GetAppIcon();
+        }
+        #endregion
+        
+        #region Private Fields
+        private ApplicationConfiguration m_configuration;
+        #endregion
+        
+        #region Public Interface
+        /// <summary>
+        /// Shows the dialog.
+        /// </summary>
+        /// <param name="configuration">The client applicatio configuration.</param>
+        /// <returns>The selected endpoint url</returns>
+        public string ShowDialog(ApplicationConfiguration configuration)
+        {
+            return ShowDialog(configuration, null);
+        }
+
+        /// <summary>
+        /// Shows the dialog.
+        /// </summary>
+        /// <param name="configuration">The client applicatio configuration.</param>
+        /// <param name="hostName">The default host name.</param>
+        /// <returns>The selected endpoint url</returns>
+        public string ShowDialog(ApplicationConfiguration configuration, string hostName)
+        {
+            m_configuration = configuration;
+
+            if (String.IsNullOrEmpty(hostName))
+            {
+                ValueTB.Text = System.Net.Dns.GetHostName();
+            }
+            else
+            {
+                ValueTB.Text = hostName;
+            }
+
+            // display the dialog.
+            if (ShowDialog() != DialogResult.OK)
+            {
+                return null;
+            }
+
+            return ServersLB.SelectedItem as string;
+        }
+        #endregion
+
+        #region Private Methods
+        /// <summary>
+        /// Gets the endpoints for the host.
+        /// </summary>
+        /// <param name="hostName">Name of the host.</param>
+        private string[] GetEndpoints(string hostName)
+        {
+            List<string> urls = new List<string>();
+
+            try
+            {
+                Cursor = Cursors.WaitCursor;
+
+                // set a short timeout because this is happening in the drop down event.
+                EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration);
+                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))
+                {
+                    ApplicationDescriptionCollection servers = client.FindServers(null);
+
+                    // populate the drop down list with the discovery URLs for the available servers.
+                    for (int ii = 0; ii < servers.Count; ii++)
+                    {
+                        // don't show discovery servers.
+                        if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
+                        {
+                            continue;
+                        }
+
+                        for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
+                        {
+                            string discoveryUrl = servers[ii].DiscoveryUrls[jj];
+
+                            // Many servers will use the '/discovery' suffix for the discovery endpoint.
+                            // The URL without this prefix should be the base URL for the server. 
+                            if (discoveryUrl.EndsWith("/discovery"))
+                            {
+                                discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
+                            }
+
+                            // remove duplicates.
+                            if (!urls.Contains(discoveryUrl))
+                            {
+                                urls.Add(discoveryUrl);
+                            }
+                        }
+                    }
+                }
+
+                return urls.ToArray();
+            }
+            catch (Exception)
+            {
+                return urls.ToArray();
+            }
+            finally
+            {
+                Cursor = Cursors.Default;
+            }
+        }
+        #endregion
+                
+        #region Event Handlers
+        private void OkBTN_Click(object sender, EventArgs e)
+        {
+            try
+            {
+                if (Utils.ParseUri(ServersLB.SelectedItem as string) != null)
+                {
+                    DialogResult = DialogResult.OK;
+                }
+            }
+            catch (Exception exception)
+            {
+                ClientUtils.HandleException(this.Text, exception);
+            }
+        }
+
+        private void ServersLB_SelectedIndexChanged(object sender, EventArgs e)
+        {
+            try
+            {
+                OkBTN.Enabled = Utils.ParseUri(ServersLB.SelectedItem as string) != null;
+            }
+            catch (Exception exception)
+            {
+                ClientUtils.HandleException(this.Text, exception);
+            }
+        }
+
+        private void FindBTN_Click(object sender, EventArgs e)
+        {
+            try
+            {
+                Cursor.Current = Cursors.WaitCursor;
+
+                ServersLB.Items.Clear();
+                ServersLB.Items.Add("No endpoints found.");
+
+                if (String.IsNullOrEmpty(ValueTB.Text))
+                {
+                    return;
+                }
+
+                ServersLB.Items.Clear();
+
+                foreach (string url in GetEndpoints(ValueTB.Text))
+                {
+                    ServersLB.Items.Add(url);
+                }
+
+                if (ServersLB.Items.Count == 0)
+                {
+                    ServersLB.Items.Add("No endpoints found.");
+                }
+            }
+            catch (Exception exception)
+            {
+                ClientUtils.HandleException(this.Text, exception);
+            }
+            finally
+            {
+                Cursor.Current = Cursors.Default;
+            }
+        }
+
+        private void ValueTB_TextChanged(object sender, EventArgs e)
+        {
+            ServersLB.Items.Clear();
+        }
+        #endregion
+    }
+}

+ 164 - 0
OpcUaHelper/Forms/DiscoverServerDlg.designer.cs

@@ -0,0 +1,164 @@
+/* ========================================================================
+ * 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
+ * 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/
+ * ======================================================================*/
+
+namespace OpcUaHelper.Forms
+{
+    partial class DiscoverServerDlg
+    {
+        /// <summary>
+        /// Required designer variable.
+        /// </summary>
+        private System.ComponentModel.IContainer components = null;
+
+        /// <summary>
+        /// Clean up any resources being used.
+        /// </summary>
+        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+        protected override void Dispose(bool disposing)
+        {
+            if (disposing && (components != null))
+            {
+                components.Dispose();
+            }
+            base.Dispose(disposing);
+        }
+
+        #region Windows Form Designer generated code
+
+        /// <summary>
+        /// Required method for Designer support - do not modify
+        /// the contents of this method with the code editor.
+        /// </summary>
+        private void InitializeComponent()
+        {
+            this.CancelBTN = new System.Windows.Forms.Button();
+            this.OkBTN = new System.Windows.Forms.Button();
+            this.ValueLB = new System.Windows.Forms.Label();
+            this.ValueTB = new System.Windows.Forms.TextBox();
+            this.ServersLB = new System.Windows.Forms.ListBox();
+            this.FindBTN = new System.Windows.Forms.Button();
+            this.SuspendLayout();
+            // 
+            // CancelBTN
+            // 
+            this.CancelBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+            this.CancelBTN.DialogResult = System.Windows.Forms.DialogResult.Cancel;
+            this.CancelBTN.Location = new System.Drawing.Point(313, 173);
+            this.CancelBTN.Name = "CancelBTN";
+            this.CancelBTN.Size = new System.Drawing.Size(75, 23);
+            this.CancelBTN.TabIndex = 0;
+            this.CancelBTN.Text = "Cancel";
+            this.CancelBTN.UseVisualStyleBackColor = true;
+            // 
+            // OkBTN
+            // 
+            this.OkBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
+            this.OkBTN.Location = new System.Drawing.Point(4, 173);
+            this.OkBTN.Name = "OkBTN";
+            this.OkBTN.Size = new System.Drawing.Size(75, 23);
+            this.OkBTN.TabIndex = 1;
+            this.OkBTN.Text = "OK";
+            this.OkBTN.UseVisualStyleBackColor = true;
+            this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click);
+            // 
+            // ValueLB
+            // 
+            this.ValueLB.AutoSize = true;
+            this.ValueLB.Location = new System.Drawing.Point(1, 9);
+            this.ValueLB.Name = "ValueLB";
+            this.ValueLB.Size = new System.Drawing.Size(29, 13);
+            this.ValueLB.TabIndex = 2;
+            this.ValueLB.Text = "Host";
+            // 
+            // ValueTB
+            // 
+            this.ValueTB.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.ValueTB.Location = new System.Drawing.Point(36, 6);
+            this.ValueTB.Name = "ValueTB";
+            this.ValueTB.Size = new System.Drawing.Size(306, 20);
+            this.ValueTB.TabIndex = 3;
+            this.ValueTB.TextChanged += new System.EventHandler(this.ValueTB_TextChanged);
+            // 
+            // ServersLB
+            // 
+            this.ServersLB.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
+            | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.ServersLB.FormattingEnabled = true;
+            this.ServersLB.Location = new System.Drawing.Point(4, 32);
+            this.ServersLB.Name = "ServersLB";
+            this.ServersLB.Size = new System.Drawing.Size(384, 134);
+            this.ServersLB.TabIndex = 5;
+            this.ServersLB.SelectedIndexChanged += new System.EventHandler(this.ServersLB_SelectedIndexChanged);
+            // 
+            // FindBTN
+            // 
+            this.FindBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
+            this.FindBTN.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
+            this.FindBTN.Location = new System.Drawing.Point(345, 4);
+            this.FindBTN.Margin = new System.Windows.Forms.Padding(0);
+            this.FindBTN.Name = "FindBTN";
+            this.FindBTN.Size = new System.Drawing.Size(43, 23);
+            this.FindBTN.TabIndex = 4;
+            this.FindBTN.Text = "Find";
+            this.FindBTN.UseVisualStyleBackColor = true;
+            this.FindBTN.Click += new System.EventHandler(this.FindBTN_Click);
+            // 
+            // DiscoverServerDlg
+            // 
+            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+            this.ClientSize = new System.Drawing.Size(392, 198);
+            this.Controls.Add(this.FindBTN);
+            this.Controls.Add(this.ServersLB);
+            this.Controls.Add(this.ValueTB);
+            this.Controls.Add(this.ValueLB);
+            this.Controls.Add(this.OkBTN);
+            this.Controls.Add(this.CancelBTN);
+            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
+            this.MaximizeBox = false;
+            this.Name = "DiscoverServerDlg";
+            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+            this.Text = "Discover Servers";
+            this.ResumeLayout(false);
+            this.PerformLayout();
+
+        }
+
+        #endregion
+
+        private System.Windows.Forms.Button CancelBTN;
+        private System.Windows.Forms.Button OkBTN;
+        private System.Windows.Forms.Label ValueLB;
+        private System.Windows.Forms.TextBox ValueTB;
+        private System.Windows.Forms.ListBox ServersLB;
+        private System.Windows.Forms.Button FindBTN;
+    }
+}

+ 120 - 0
OpcUaHelper/Forms/DiscoverServerDlg.resx

@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+</root>

+ 1632 - 0
OpcUaHelper/Forms/FormBrowseServer.cs

@@ -0,0 +1,1632 @@
+using Newtonsoft.Json.Linq;
+using Opc.Ua;
+using Opc.Ua.Client;
+using Opc.Ua.Export;
+using Org.BouncyCastle.Asn1.Ocsp;
+using Org.BouncyCastle.Asn1.X509;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement;
+
+namespace OpcUaHelper.Forms
+{
+
+	/// <summary>
+	/// 一个浏览OPC服务器节点的窗口类
+	/// </summary>
+	public partial class FormBrowseServer : Form
+	{
+		#region Constructor
+		/// <summary>
+		/// 允许自己输入服务器地址的实例化
+		/// </summary>
+		public FormBrowseServer()
+		{
+			InitializeComponent();
+			
+			Icon = ClientUtils.GetAppIcon();
+			m_typeImageMapping = new Dictionary<NodeId, string>( );
+		}
+
+		/// <summary>
+		/// 固定地址且不允许更改的实例化
+		/// </summary>
+		public FormBrowseServer(string server)
+		{
+			InitializeComponent();
+			
+			Icon = ClientUtils.GetAppIcon();
+			textBox1.Text = server;
+		}
+
+		#endregion
+
+		#region Load Show Close
+
+
+		private void FormBrowseServer_Load(object sender, EventArgs e)
+		{
+			BrowseNodesTV.Enabled = false;
+
+			BrowseNodesTV.ImageList = new ImageList();
+			BrowseNodesTV.ImageList.Images.Add("Class_489", Properties.Resources.Class_489);
+			BrowseNodesTV.ImageList.Images.Add("ClassIcon", Properties.Resources.ClassIcon);
+			BrowseNodesTV.ImageList.Images.Add("brackets", Properties.Resources.brackets_Square_16xMD);
+			BrowseNodesTV.ImageList.Images.Add("VirtualMachine", Properties.Resources.VirtualMachine);
+			BrowseNodesTV.ImageList.Images.Add("Enum_582", Properties.Resources.Enum_582);
+			BrowseNodesTV.ImageList.Images.Add("Method_636", Properties.Resources.Method_636);
+			BrowseNodesTV.ImageList.Images.Add("Module_648", Properties.Resources.Module_648);
+			BrowseNodesTV.ImageList.Images.Add("Loading", Properties.Resources.loading);
+
+			// 判断是否允许更改
+			if (!string.IsNullOrEmpty(textBox1.Text)) textBox1.ReadOnly = true;
+			// Opc Ua 服务的初始化
+			OpcUaClientInitialization();
+		}
+
+
+
+		private string GetImageKeyFromDescription(ReferenceDescription target, NodeId sourceId)
+		{
+			if (target.NodeClass == NodeClass.Variable)
+			{
+				DataValue dataValue = m_OpcUaClient.ReadNode((NodeId)target.NodeId);
+
+				if (dataValue.WrappedValue.TypeInfo != null)
+				{
+					if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.Scalar)
+					{
+						return "Enum_582";
+					}
+					else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.OneDimension)
+					{
+						return "brackets";
+					}
+					else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.TwoDimensions)
+					{
+						return "Module_648";
+					}
+					else
+					{
+						return "ClassIcon";
+					}
+				}
+				else
+				{
+					return "ClassIcon";
+				}
+			}
+			else if (target.NodeClass == NodeClass.Object)
+			{
+				if (sourceId == ObjectIds.ObjectsFolder)
+				{
+					return "VirtualMachine";
+				}
+				else
+				{
+					return "ClassIcon";
+				}
+			}
+			else if (target.NodeClass == NodeClass.Method)
+			{
+				return "Method_636";
+			}
+			else
+			{
+				return "ClassIcon";
+			}
+		}
+
+		private string GetImageIndex( DataValue dataValue )
+		{
+			if (dataValue == null) return "ClassIcon";
+			if (dataValue.WrappedValue.TypeInfo != null)
+			{
+				if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.Scalar)
+				{
+					return "Enum_582";
+				}
+				else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.OneDimension)
+				{
+					return "brackets";
+				}
+				else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.TwoDimensions)
+				{
+					return "Module_648";
+				}
+				else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.OneOrMoreDimensions)
+				{
+					return "Module_648";
+				}
+				else
+				{
+					return "ClassIcon";
+				}
+			}
+			return "ClassIcon";
+		}
+
+		/// <summary>
+		/// Returns an image index for the specified attribute.
+		/// </summary>
+		public string GetImageIndex( Session session, NodeClass nodeClass, ExpandedNodeId typeDefinitionId, bool selected, NodeId valueId = null )
+		{
+			if (nodeClass == NodeClass.Variable)
+			{
+				//if (session.NodeCache.IsTypeOf( typeDefinitionId, Opc.Ua.VariableTypeIds.PropertyType ))
+				//{
+				//	return "ClassIcon";
+				//}
+
+				if (valueId != null) return GetImageIndex( m_OpcUaClient.ReadNode( valueId ) );
+
+				return "ClassIcon";
+			}
+
+			if (nodeClass == NodeClass.Object)
+			{
+				if (typeDefinitionId == ObjectIds.ObjectsFolder)
+				{
+					return "VirtualMachine";
+				}
+				else if (session.NodeCache.IsTypeOf( typeDefinitionId, Opc.Ua.ObjectTypeIds.FolderType ))
+				{
+					if (selected)
+					{
+						return "ClassIcon";
+					}
+					else
+					{
+						return "ClassIcon";
+					}
+				}
+
+				return "ClassIcon";
+			}
+
+			if (nodeClass == NodeClass.Method)
+			{
+				return "Method_636";
+			}
+
+			if (nodeClass == NodeClass.View)
+			{
+				return "Method_636";
+			}
+
+			return "ClassIcon";
+		}
+
+
+		private void FormBrowseServer_FormClosing(object sender, FormClosingEventArgs e)
+		{
+			m_OpcUaClient.Disconnect();
+		}
+
+		#endregion
+
+		#region OPC UA client
+
+		/// <summary>
+		/// Opc客户端的核心类
+		/// </summary>
+		private OpcUaClient m_OpcUaClient = null;
+
+		/// <summary>
+		/// 初始化
+		/// </summary>
+		private void OpcUaClientInitialization()
+		{
+			m_OpcUaClient = new OpcUaClient();
+			m_OpcUaClient.OpcStatusChange += M_OpcUaClient_OpcStatusChange1; ;
+			m_OpcUaClient.ConnectComplete += M_OpcUaClient_ConnectComplete;
+		}
+		/// <summary>
+		/// 连接服务器结束后马上浏览根节点
+		/// </summary>
+		/// <param name="sender"></param>
+		/// <param name="e"></param>
+		private void M_OpcUaClient_ConnectComplete(object sender, EventArgs e)
+		{
+			//try
+			//{
+			//	OpcUaClient client = (OpcUaClient)sender;
+			//	if (client.Connected)
+			//	{
+			//		// populate the browse view.
+			//		PopulateBranch(ObjectIds.ObjectsFolder, BrowseNodesTV.Nodes);
+			//		BrowseNodesTV.Enabled = true;
+			//	}
+			//}
+			//catch (Exception exception)
+			//{
+			//	ClientUtils.HandleException(Text, exception);
+			//}
+
+			try
+			{
+				m_session = m_OpcUaClient.Session as Opc.Ua.Client.Session;
+
+				// set a suitable initial state.
+				if (m_session != null)
+				{
+
+					BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+					nodeToBrowse.NodeId = Opc.Ua.ObjectIds.ViewsFolder;
+					nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HierarchicalReferences;
+					nodeToBrowse.IncludeSubtypes = true;
+					nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+					nodeToBrowse.NodeClassMask = 0;
+					nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+					ReferenceDescriptionCollection references = ClientUtils.Browse( m_session, nodeToBrowse, false );
+				}
+
+				// browse the instances in the server.
+				Initialize( m_session, ObjectIds.ObjectsFolder, ReferenceTypeIds.Organizes, ReferenceTypeIds.Aggregates );
+				BrowseNodesTV.Enabled = true;
+			}
+			catch (Exception exception)
+			{
+				ClientUtils.HandleException( this.Text, exception );
+			}
+		}
+
+		/// <summary>
+		/// OPC 客户端的状态变化后的消息提醒
+		/// </summary>
+		/// <param name="sender"></param>
+		/// <param name="e"></param>
+		private void M_OpcUaClient_OpcStatusChange1(object sender, OpcUaStatusEventArgs e)
+		{
+			if (InvokeRequired)
+			{
+				BeginInvoke(new Action(() =>
+				{
+					M_OpcUaClient_OpcStatusChange1(sender, e);
+				}));
+				return;
+			}
+
+			if (e.Error)
+			{
+				toolStripStatusLabel1.BackColor = Color.Red;
+			}
+			else
+			{
+				toolStripStatusLabel1.BackColor = SystemColors.Control;
+			}
+
+			toolStripStatusLabel_opc.Text = e.ToString();
+		}
+
+
+		private ReferenceDescriptionCollection GetReferenceDescriptionCollection(NodeId sourceId)
+		{
+			TaskCompletionSource<ReferenceDescriptionCollection> task = new TaskCompletionSource<ReferenceDescriptionCollection>();
+
+			// find all of the components of the node.
+			BrowseDescription nodeToBrowse1 = new BrowseDescription();
+
+			nodeToBrowse1.NodeId = sourceId;
+			nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates;
+			nodeToBrowse1.IncludeSubtypes = true;
+			nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method | NodeClass.ReferenceType | NodeClass.ObjectType | NodeClass.View | NodeClass.VariableType | NodeClass.DataType);
+			nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
+
+			// find all nodes organized by the node.
+			BrowseDescription nodeToBrowse2 = new BrowseDescription();
+
+			nodeToBrowse2.NodeId = sourceId;
+			nodeToBrowse2.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse2.ReferenceTypeId = ReferenceTypeIds.Organizes;
+			nodeToBrowse2.IncludeSubtypes = true;
+			nodeToBrowse2.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method | NodeClass.View | NodeClass.ReferenceType | NodeClass.ObjectType | NodeClass.VariableType | NodeClass.DataType);
+			nodeToBrowse2.ResultMask = (uint)BrowseResultMask.All;
+
+			BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
+			nodesToBrowse.Add(nodeToBrowse1);
+			nodesToBrowse.Add(nodeToBrowse2);
+
+			// fetch references from the server.
+			ReferenceDescriptionCollection references = FormUtils.Browse(m_OpcUaClient.Session, nodesToBrowse, false);
+			return references;
+		}
+
+		/// <summary>
+		/// 0:NodeClass  1:Value  2:AccessLevel  3:DisplayName  4:Description
+		/// </summary>
+		/// <param name="nodeIds"></param>
+		/// <returns></returns>
+		private DataValue[] ReadOneNodeFiveAttributes(List<NodeId> nodeIds)
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
+			foreach (var nodeId in nodeIds)
+			{
+				NodeId sourceId = nodeId;
+				nodesToRead.Add(new ReadValueId()
+				{
+					NodeId = sourceId,
+					AttributeId = Attributes.NodeClass
+				});
+				nodesToRead.Add(new ReadValueId()
+				{
+					NodeId = sourceId,
+					AttributeId = Attributes.Value
+				});
+				nodesToRead.Add(new ReadValueId()
+				{
+					NodeId = sourceId,
+					AttributeId = Attributes.AccessLevel
+				});
+				nodesToRead.Add(new ReadValueId()
+				{
+					NodeId = sourceId,
+					AttributeId = Attributes.DisplayName
+				});
+				nodesToRead.Add(new ReadValueId()
+				{
+					NodeId = sourceId,
+					AttributeId = Attributes.Description
+				});
+			}
+
+			// read all values.
+			m_OpcUaClient.Session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out DataValueCollection results,
+				out DiagnosticInfoCollection diagnosticInfos);
+
+			ClientBase.ValidateResponse(results, nodesToRead);
+			ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
+
+			return results.ToArray();
+		}
+
+
+		/// <summary>
+		/// 读取一个节点的指定属性
+		/// </summary>
+		/// <param name="nodeId"></param>
+		/// <param name="attribute"></param>
+		/// <returns></returns>
+		private DataValue ReadNoteDataValueAttributes(NodeId nodeId, uint attribute)
+		{
+			NodeId sourceId = nodeId;
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
+
+
+			ReadValueId nodeToRead = new ReadValueId();
+			nodeToRead.NodeId = sourceId;
+			nodeToRead.AttributeId = attribute;
+			nodesToRead.Add(nodeToRead);
+
+			int startOfProperties = nodesToRead.Count;
+
+			// find all of the pror of the node.
+			BrowseDescription nodeToBrowse1 = new BrowseDescription();
+
+			nodeToBrowse1.NodeId = sourceId;
+			nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
+			nodeToBrowse1.IncludeSubtypes = true;
+			nodeToBrowse1.NodeClassMask = 0;
+			nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
+
+			BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
+			nodesToBrowse.Add(nodeToBrowse1);
+
+			// fetch property references from the server.
+			ReferenceDescriptionCollection references = FormUtils.Browse(m_OpcUaClient.Session, nodesToBrowse, false);
+
+			if (references == null)
+			{
+				return null;
+			}
+
+			for (int ii = 0; ii < references.Count; ii++)
+			{
+				// ignore external references.
+				if (references[ii].NodeId.IsAbsolute)
+				{
+					continue;
+				}
+
+				ReadValueId nodeToRead2 = new ReadValueId();
+				nodeToRead2.NodeId = (NodeId)references[ii].NodeId;
+				nodeToRead2.AttributeId = Attributes.Value;
+				nodesToRead.Add(nodeToRead2);
+			}
+
+			// read all values.
+			DataValueCollection results = null;
+			DiagnosticInfoCollection diagnosticInfos = null;
+
+			m_OpcUaClient.Session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out results,
+				out diagnosticInfos);
+
+			ClientBase.ValidateResponse(results, nodesToRead);
+			ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
+
+			return results[0];
+		}
+
+		#endregion
+
+		#region Menu Click Event
+
+		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
+		{
+			// press exit menu button
+			Close();
+		}
+
+		private void discoverToolStripMenuItem_Click(object sender, EventArgs e)
+		{
+			string endpointUrl = new DiscoverServerDlg().ShowDialog(m_OpcUaClient.AppConfig, null);
+
+			if (endpointUrl != null)
+			{
+				textBox1.Text = endpointUrl;
+			}
+		}
+
+
+
+		#endregion
+
+		#region Press Connect Click Button
+
+		private async void button1_Click( object sender, EventArgs e )
+		{
+			// connect to server
+			using (FormConnectSelect formConnectSelect = new FormConnectSelect( m_OpcUaClient ))
+			{
+				if (formConnectSelect.ShowDialog( ) == DialogResult.OK)
+				{
+					try
+					{
+						await m_OpcUaClient.ConnectServer( textBox1.Text );
+						button1.Enabled = false;
+						button3.Enabled = true;
+					}
+					catch (Exception ex)
+					{
+						ClientUtils.HandleException( Text, ex );
+					}
+				}
+			}
+		}
+
+		private void button3_Click( object sender, EventArgs e )
+		{
+			// 关闭连接
+			try
+			{
+				m_OpcUaClient?.Disconnect( );
+				button1.Enabled = true;
+				button3.Enabled = false;
+			}
+			catch (Exception ex)
+			{
+				ClientUtils.HandleException( Text, ex );
+			}
+		}
+
+		#endregion
+
+		#region 填入分支
+
+		/// <summary>
+		/// Populates the branch in the tree view.
+		/// </summary>
+		/// <param name="sourceId">The NodeId of the Node to browse.</param>
+		/// <param name="nodes">The node collect to populate.</param>
+		private async void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes)
+		{
+			nodes.Clear();
+			nodes.Add(new TreeNode("Browsering...", 7, 7));
+			// fetch references from the server.
+			TreeNode[] listNode = await Task.Run(() =>
+			 {
+				 ReferenceDescriptionCollection references = GetReferenceDescriptionCollection(sourceId);
+				 List<TreeNode> list = new List<TreeNode>();
+				 if (references != null)
+				 {
+					 // process results.
+					 for (int ii = 0; ii < references.Count; ii++)
+					 {
+						 ReferenceDescription target = references[ii];
+						 TreeNode child = new TreeNode(Utils.Format("{0}", target));
+
+						 child.Tag = target;
+						 string key = GetImageKeyFromDescription(target, sourceId);
+						 child.ImageKey = key;
+						 child.SelectedImageKey = key;
+
+						 // if (target.NodeClass == NodeClass.Object || target.NodeClass == NodeClass.Unspecified || expanded)
+						 // {
+						 //     child.Nodes.Add(new TreeNode());
+						 // }
+
+						 if (!checkBox1.Checked)
+						 {
+							 if (GetReferenceDescriptionCollection( (NodeId)target.NodeId ).Count > 0)
+							 {
+								child.Nodes.Add( new TreeNode( ) );
+							 }
+						 }
+						 else
+						 {
+							 child.Nodes.Add( new TreeNode( ) );
+						 }
+						 
+
+						 list.Add(child);
+					 }
+				 }
+
+				 return list.ToArray();
+			 });
+
+			
+			// update the attributes display.
+			// DisplayAttributes(sourceId);
+			nodes.Clear();
+			nodes.AddRange(listNode.ToArray());
+		}
+	
+
+
+		#endregion
+
+		#region 节点打开的时候操作
+
+		private void BrowseNodesTV_MouseClick(object sender, MouseEventArgs e)
+		{
+			if (e.Button == MouseButtons.Right)
+			{
+				TreeNode tn = BrowseNodesTV.GetNodeAt(e.X, e.Y);
+				if (tn != null)
+				{
+					BrowseNodesTV.SelectedNode = tn;
+				}
+			}
+		}
+
+		private async void BrowseNodesTV_BeforeExpand(object sender, TreeViewCancelEventArgs e)
+		{
+			//try
+			//{
+
+			// check if node has already been expanded once.
+			if (e.Node.Nodes.Count != 1)
+			{
+				//return;
+			}
+
+			if (e.Node.Nodes.Count > 0)
+			{
+				if (e.Node.Nodes[0].Text != String.Empty)
+				{
+					return;
+				}
+			}
+
+
+			//	// populate children.
+			// PopulateBranch((NodeId)reference.NodeId, e.Node.Nodes);
+			//}
+			//catch (Exception exception)
+			//{
+			//	ClientUtils.HandleException(this.Text, exception);
+			//}
+
+			BrowseTV_BeforeExpand( sender, e );
+		}
+
+
+
+		private void BrowseNodesTV_AfterSelect(object sender, TreeViewEventArgs e)
+		{
+			try
+			{
+				RemoveAllSubscript( );
+				// get the source for the node.
+				ReferenceDescription reference = e.Node.Tag as ReferenceDescription;
+
+				if (reference == null || reference.NodeId.IsAbsolute)
+				{
+					return;
+				}
+
+				// populate children.
+				ShowMember((NodeId)reference.NodeId);
+			}
+			catch (Exception exception)
+			{
+				ClientUtils.HandleException(Text, exception);
+			}
+		}
+
+
+		private void ClearDataGridViewRows(int index)
+		{
+			for (int i = dataGridView1.Rows.Count - 1; i >= index; i--)
+			{
+				if (i >= 0)
+				{
+					dataGridView1.Rows.RemoveAt(i);
+				}
+			}
+		}
+
+		#endregion
+
+		#region 点击树节点后在数据表显示
+
+		/// <summary>
+		/// 点击了节点名称前的内容进行复制
+		/// </summary>
+		/// <param name="sender"></param>
+		/// <param name="e"></param>
+		private void label2_Click(object sender, EventArgs e)
+		{
+			if (!string.IsNullOrEmpty(textBox_nodeId.Text))
+			{
+				Clipboard.SetText(textBox_nodeId.Text);
+			}
+		}
+		private async void ShowMember(NodeId sourceId)
+		{
+
+			textBox_nodeId.Text = sourceId.ToString();
+
+			// dataGridView1.Rows.Clear();
+			int index = 0;
+			ReferenceDescriptionCollection references;
+			try
+			{
+				references = await Task.Run(() =>
+				 {
+					 return GetReferenceDescriptionCollection(sourceId);
+				 });
+			}
+			catch(Exception exception)
+			{
+				ClientUtils.HandleException(Text, exception);
+				return;
+			}
+
+
+			if (references?.Count > 0)
+			{
+				// 获取所有要读取的子节点
+				List<NodeId> nodeIds = new List<NodeId>();
+				for (int ii = 0; ii < references.Count; ii++)
+				{
+					ReferenceDescription target = references[ii];
+					nodeIds.Add((NodeId)target.NodeId);
+				}
+
+				DateTime dateTimeStart = DateTime.Now;
+
+				// 获取所有的值
+				DataValue[] dataValues = await Task.Run(() =>
+				{
+				  return ReadOneNodeFiveAttributes(nodeIds);
+				});
+				
+				label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
+				
+				// 显示
+				for (int jj = 0; jj < dataValues.Length; jj += 5)
+				{
+					AddDataGridViewNewRow(dataValues, jj, index++, nodeIds[jj / 5]);
+				}
+				
+			}
+			else
+			{
+				// 子节点没有数据的情况
+				try
+				{
+					DateTime dateTimeStart = DateTime.Now;
+					DataValue dataValue = m_OpcUaClient.ReadNode(sourceId);
+
+					if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension)
+					{
+						// 数组显示
+						AddDataGridViewArrayRow(sourceId, out index);
+					}
+					else
+					{
+						// 显示单个数本身
+						label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
+						AddDataGridViewNewRow(ReadOneNodeFiveAttributes(new List<NodeId>() { sourceId }), 0, index++, sourceId);
+					}
+				}
+				catch (Exception exception)
+				{
+					ClientUtils.HandleException(Text, exception);
+					return;
+				}
+			}
+
+			ClearDataGridViewRows(index);
+
+		}
+
+
+		private void AddDataGridViewNewRow(DataValue[] dataValues, int startIndex, int index, NodeId nodeId)
+		{
+			// int index = dataGridView1.Rows.Add();
+			while (index >= dataGridView1.Rows.Count)
+			{
+				dataGridView1.Rows.Add();
+			}
+			DataGridViewRow dgvr = dataGridView1.Rows[index];
+			dgvr.Tag = nodeId;
+
+			if (dataValues[startIndex].WrappedValue.Value == null) return;
+			NodeClass nodeclass = (NodeClass)dataValues[startIndex].WrappedValue.Value;
+
+			dgvr.Cells[1].Value = dataValues[3 + startIndex].WrappedValue.Value;
+			dgvr.Cells[5].Value = dataValues[4 + startIndex].WrappedValue.Value;
+			dgvr.Cells[4].Value = GetDiscriptionFromAccessLevel(dataValues[2 + startIndex]);
+
+			if (nodeclass == NodeClass.Object)
+			{
+				dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
+				dgvr.Cells[2].Value = "";
+				dgvr.Cells[3].Value = nodeclass.ToString();
+			}
+			else if (nodeclass == NodeClass.Method)
+			{
+				dgvr.Cells[0].Value = Properties.Resources.Method_636;
+				dgvr.Cells[2].Value = "";
+				dgvr.Cells[3].Value = nodeclass.ToString();
+			}
+			else if (nodeclass == NodeClass.Variable)
+			{
+				DataValue dataValue = dataValues[1 + startIndex];
+
+				if (dataValue.WrappedValue.TypeInfo != null)
+				{
+					dgvr.Cells[3].Value = dataValue.WrappedValue.TypeInfo.BuiltInType;
+					dgvr.Cells[6].Value = dataValue.StatusCode.ToString();
+					// dgvr.Cells[3].Value = dataValue.Value.GetType().ToString();
+					if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.Scalar)
+					{
+						dgvr.Cells[2].Value = dataValue.WrappedValue.Value;
+						dgvr.Cells[0].Value = Properties.Resources.Enum_582;
+					}
+					else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.OneDimension)
+					{
+						dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
+						dgvr.Cells[0].Value = Properties.Resources.brackets_Square_16xMD;
+					}
+					else if (dataValue.WrappedValue.TypeInfo.ValueRank == ValueRanks.TwoDimensions)
+					{
+						dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
+						dgvr.Cells[0].Value = Properties.Resources.Module_648;
+					}
+					else
+					{
+						dgvr.Cells[2].Value = dataValue.Value.GetType().ToString();
+						dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
+					}
+				}
+				else
+				{
+					dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
+					dgvr.Cells[2].Value = dataValue.Value;
+					dgvr.Cells[3].Value = "null";
+				}
+			}
+			else
+			{
+				dgvr.Cells[2].Value = "";
+				dgvr.Cells[0].Value = Properties.Resources.ClassIcon;
+				dgvr.Cells[3].Value = nodeclass.ToString();
+				dgvr.Cells[6].Value = "";
+			}
+		}
+
+		private void AddDataGridViewArrayRow(NodeId nodeId,out int index)
+		{
+			
+			DateTime dateTimeStart = DateTime.Now;
+			DataValue[] dataValues = ReadOneNodeFiveAttributes(new List<NodeId>() { nodeId });
+			label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
+
+			DataValue dataValue = dataValues[1];
+
+			if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension)
+			{
+				string access= GetDiscriptionFromAccessLevel(dataValues[2]);
+				BuiltInType type = dataValue.WrappedValue.TypeInfo.BuiltInType;
+				object des = dataValues[4].Value ?? "";
+				object dis = dataValues[3].Value ?? type;
+
+				Array array = dataValue.Value as Array;
+				int i = 0;
+				foreach(object obj in array)
+				{
+					while (i >= dataGridView1.Rows.Count)
+					{
+						dataGridView1.Rows.Add();
+					}
+					
+					DataGridViewRow dgvr = dataGridView1.Rows[i];
+
+					dgvr.Tag = null;
+
+					dgvr.Cells[0].Value = Properties.Resources.Enum_582;
+					dgvr.Cells[1].Value = $"{dis} [{i++}]";
+					dgvr.Cells[2].Value = obj;
+					dgvr.Cells[3].Value = type;
+					dgvr.Cells[4].Value = access;
+					dgvr.Cells[5].Value = des;
+				}
+				index = i;
+			}
+			else
+			{
+				index = 0;
+			}
+		}
+
+		private string GetDiscriptionFromAccessLevel(DataValue value)
+		{
+			if (value.WrappedValue.Value != null)
+			{
+				switch ((byte)value.WrappedValue.Value)
+				{
+					case 0: return "None";
+					case 1: return "CurrentRead";
+					case 2: return "CurrentWrite";
+					case 3: return "CurrentReadOrWrite";
+					case 4: return "HistoryRead";
+					case 8: return "HistoryWrite";
+					case 12: return "HistoryReadOrWrite";
+					case 16: return "SemanticChange";
+					case 32: return "StatusWrite";
+					case 64: return "TimestampWrite";
+					default: return "None";
+				}
+			}
+			else
+			{
+				return "null";
+			}
+		}
+
+
+
+		#endregion
+
+		#region 订阅刷新块
+
+
+		private List<string> subNodeIds = new List<string>( );
+		private bool isSingleValueSub = false;
+
+		private void RemoveAllSubscript( )
+		{
+			m_OpcUaClient?.RemoveAllSubscription( );
+		}
+
+
+		private void SubCallBack( string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs eventArgs )
+		{
+			if (InvokeRequired)
+			{
+				Invoke( new Action<string, MonitoredItem, MonitoredItemNotificationEventArgs>( SubCallBack ), key, monitoredItem, eventArgs );
+				return;
+			}
+
+
+			MonitoredItemNotification notification = eventArgs.NotificationValue as MonitoredItemNotification;
+			string nodeId = monitoredItem.StartNodeId.ToString( );
+
+			int index = subNodeIds.IndexOf( nodeId );
+			if (index >= 0)
+			{
+				if (isSingleValueSub)
+				{
+					if (notification.Value.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension)
+					{
+						Array array = notification.Value.WrappedValue.Value as Array;
+						int i = 0;
+						foreach (object obj in array)
+						{
+							DataGridViewRow dgvr = dataGridView1.Rows[i];
+							dgvr.Cells[2].Value = obj;
+							i++;
+						}
+					}
+					else
+					{
+						dataGridView1.Rows[index].Cells[2].Value = notification.Value.WrappedValue.Value;
+					}
+				}
+				else
+				{
+					dataGridView1.Rows[index].Cells[2].Value = notification.Value.WrappedValue.Value;
+				}
+			}
+		}
+
+
+		private async void button2_Click(object sender, EventArgs e)
+		{
+			if (m_OpcUaClient != null)
+			{
+				RemoveAllSubscript( );
+				if (button2.BackColor != Color.LimeGreen)
+				{
+					button2.BackColor = Color.LimeGreen;
+					// 判断当前的选择
+					if (string.IsNullOrEmpty( textBox_nodeId.Text )) return;
+
+					
+					ReferenceDescriptionCollection references;
+					try
+					{
+						references = await Task.Run( ( ) =>
+						{
+							return GetReferenceDescriptionCollection( new NodeId( textBox_nodeId.Text ) );
+						} );
+					}
+					catch (Exception exception)
+					{
+						ClientUtils.HandleException( Text, exception );
+						return;
+					}
+
+					subNodeIds = new List<string>( );
+					if (references?.Count > 0)
+					{
+						isSingleValueSub = false;
+						// 获取所有要订阅的子节点
+						for (int ii = 0; ii < references.Count; ii++)
+						{
+							ReferenceDescription target = references[ii];
+							subNodeIds.Add( ((NodeId)target.NodeId).ToString( ) );
+						}
+					}
+					else
+					{
+						isSingleValueSub = true;
+						// 子节点没有数据的情况
+						subNodeIds.Add( textBox_nodeId.Text );
+					}
+
+					m_OpcUaClient.AddSubscription( "subTest", subNodeIds.ToArray( ), SubCallBack );
+				}
+				else
+				{
+					button2.BackColor = SystemColors.Control;
+				}
+			}
+		}
+
+		#endregion
+
+		#region 点击了表格修改数据
+
+		private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
+		{
+			if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value is BuiltInType builtInType)
+			{
+				dynamic value = null;
+				if (dataGridView1.Rows[e.RowIndex].Tag is NodeId nodeId)
+				{
+					// 节点
+					try
+					{
+						value = GetValueFromString(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), builtInType);
+					}
+					catch
+					{
+						MessageBox.Show("Invalid Input Value");
+						return;
+					}
+
+					if (!m_OpcUaClient.WriteNode(nodeId.ToString(), value))
+					{
+						MessageBox.Show("Failed to write value");
+					}
+				}
+				else
+				{
+					// 点击了数组修改
+					IList<string> list = new List<string>();
+
+					for (int jj = 0; jj < dataGridView1.RowCount; jj++)
+					{
+						list.Add(dataGridView1.Rows[jj].Cells[e.ColumnIndex].Value.ToString());
+					}
+					
+					try
+					{
+						value = GetArrayValueFromString(list, builtInType);
+					}
+					catch(Exception ex)
+					{
+						MessageBox.Show("Invalid Input Value: " + ex.Message);
+						return;
+					}
+
+					if (!m_OpcUaClient.WriteNode(textBox_nodeId.Text, value))
+					{
+						MessageBox.Show("Failed to write value");
+					}
+				}
+			}
+			else
+			{
+				MessageBox.Show("Invalid data type");
+			}
+
+			//MessageBox.Show(
+			//    "Type:" + dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.GetType().ToString() + Environment.NewLine +
+			//    "Value:" + dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
+		}
+		
+		private dynamic GetValueFromString(string value, BuiltInType builtInType)
+		{
+			switch(builtInType)
+			{
+				case BuiltInType.Boolean:
+					{
+						return bool.Parse(value);
+					}
+				case BuiltInType.Byte:
+					{
+						return byte.Parse(value);
+					}
+				case BuiltInType.DateTime:
+					{
+						return DateTime.Parse(value);
+					}
+				case BuiltInType.Double:
+					{
+						return double.Parse(value);
+					}
+				case BuiltInType.Float:
+					{
+						return float.Parse(value);
+					}
+				case BuiltInType.Guid:
+					{
+						return Guid.Parse(value);
+					}
+				case BuiltInType.Int16:
+					{
+						return short.Parse(value);
+					}
+				case BuiltInType.Int32:
+					{
+						return int.Parse(value);
+					}
+				case BuiltInType.Int64:
+					{
+						return long.Parse(value);
+					}
+				case BuiltInType.Integer:
+					{
+						return int.Parse(value);
+					}
+				case BuiltInType.LocalizedText:
+					{
+						return value;
+					}
+				case BuiltInType.SByte:
+					{
+						return sbyte.Parse(value);
+					}
+				case BuiltInType.String:
+					{
+						return value;
+					}
+				case BuiltInType.UInt16:
+					{
+						return ushort.Parse(value);
+					}
+				case BuiltInType.UInt32:
+					{
+						return uint.Parse(value);
+					}
+				case BuiltInType.UInt64:
+					{
+						return ulong.Parse(value);
+					}
+				case BuiltInType.UInteger:
+					{
+						return uint.Parse(value);
+					}
+				default:throw new Exception("Not supported data type");
+			}
+		}
+		
+
+		private dynamic GetArrayValueFromString(IList<string> values, BuiltInType builtInType)
+		{
+			switch (builtInType)
+			{
+				case BuiltInType.Boolean:
+					{
+						bool[] result = new bool[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = bool.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Byte:
+					{
+						byte[] result = new byte[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = byte.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.DateTime:
+					{
+						DateTime[] result = new DateTime[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = DateTime.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Double:
+					{
+						double[] result = new double[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = double.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Float:
+					{
+						float[] result = new float[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = float.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Guid:
+					{
+						Guid[] result = new Guid[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = Guid.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Int16:
+					{
+						short[] result = new short[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = short.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Int32:
+					{
+						int[] result = new int[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = int.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Int64:
+					{
+						long[] result = new long[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = long.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.Integer:
+					{
+						int[] result = new int[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = int.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.LocalizedText:
+					{
+						return values.ToArray();
+					}
+				case BuiltInType.SByte:
+					{
+						sbyte[] result = new sbyte[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = sbyte.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.String:
+					{
+						return values.ToArray();
+					}
+				case BuiltInType.UInt16:
+					{
+						ushort[] result = new ushort[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = ushort.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.UInt32:
+					{
+						uint[] result = new uint[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = uint.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.UInt64:
+					{
+						ulong[] result = new ulong[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = ulong.Parse(values[i]);
+						}
+						return result;
+					}
+				case BuiltInType.UInteger:
+					{
+						uint[] result = new uint[values.Count];
+						for (int i = 0; i < values.Count; i++)
+						{
+							result[i] = uint.Parse(values[i]);
+						}
+						return result;
+					}
+				default: throw new Exception("Not supported data type");
+			}
+		}
+
+		private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
+		{
+			if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value is BuiltInType builtInType)
+			{
+				if (
+					builtInType == BuiltInType.Boolean ||
+					builtInType == BuiltInType.Byte ||
+					builtInType == BuiltInType.DateTime ||
+					builtInType == BuiltInType.Double ||
+					builtInType == BuiltInType.Float ||
+					builtInType == BuiltInType.Guid ||
+					builtInType == BuiltInType.Int16 ||
+					builtInType == BuiltInType.Int32 ||
+					builtInType == BuiltInType.Int64 ||
+					builtInType == BuiltInType.Integer ||
+					builtInType == BuiltInType.LocalizedText ||
+					builtInType == BuiltInType.SByte ||
+					builtInType == BuiltInType.String ||
+					builtInType == BuiltInType.UInt16 ||
+					builtInType == BuiltInType.UInt32 ||
+					builtInType == BuiltInType.UInt64 ||
+					builtInType == BuiltInType.UInteger
+					)
+				{
+
+				}
+				else
+				{
+					e.Cancel = true;
+					MessageBox.Show("Not support the Type of modify value!");
+					return;
+				}
+			}
+			else
+			{
+				e.Cancel = true;
+				MessageBox.Show("Not support the Type of modify value!");
+				return;
+			}
+
+
+			if (!dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 2].Value.ToString().Contains("Write"))
+			{
+				e.Cancel = true;
+				MessageBox.Show("Not support the access of modify value!");
+			}
+		}
+
+
+
+		#endregion
+
+		#region Browser New Method
+
+		private NodeId[] m_referenceTypeIds;
+		private NodeId m_rootId;
+		private Session m_session;
+		private Dictionary<NodeId, string> m_typeImageMapping;
+		private ViewDescription m_view;
+
+		/// <summary>
+		/// The view to use.
+		/// </summary>
+		public ViewDescription View
+		{
+			get
+			{
+				return m_view;
+			}
+
+			set
+			{
+				m_view = value;
+			}
+		}
+		/// <summary>
+		/// Initializes the control with a root and a set of hierarchial reference types to follow. 
+		/// </summary>
+		/// <param name="session">The session.</param>
+		/// <param name="rootId">The root of the hierarchy to browse.</param>
+		/// <param name="referenceTypeIds">The reference types to follow.</param>
+		public void Initialize(
+		   Session session,
+		   NodeId rootId,
+		   params NodeId[] referenceTypeIds )
+		{
+			// set default root.
+			if (NodeId.IsNull( rootId ))
+			{
+				rootId = Opc.Ua.ObjectIds.ObjectsFolder;
+			}
+
+			// set default reference type.
+			if (referenceTypeIds == null)
+			{
+				referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.HierarchicalReferences };
+			}
+
+			m_rootId = rootId;
+			m_referenceTypeIds = referenceTypeIds;
+
+			// save session.
+			ChangeSession( session, true );
+		}
+
+		/// <summary>
+		/// Changes the session used by the control.
+		/// </summary>
+		private void ChangeSession( Session session, bool refresh )
+		{
+			m_session = session;
+
+			BrowseNodesTV.Nodes.Clear( );
+
+			if (m_session != null)
+			{
+				INode node = m_session.NodeCache.Find( m_rootId );
+
+				if (node != null)
+				{
+					TreeNode root = new TreeNode( node.ToString( ) );
+					root.ImageKey = GetImageIndex( m_session, node.NodeClass, node.TypeDefinitionId, false );
+					root.SelectedImageKey = GetImageIndex( m_session, node.NodeClass, node.TypeDefinitionId, true );
+
+					ReferenceDescription reference = new ReferenceDescription( );
+					reference.NodeId = node.NodeId;
+					reference.NodeClass = node.NodeClass;
+					reference.BrowseName = node.BrowseName;
+					reference.DisplayName = node.DisplayName;
+					reference.TypeDefinition = node.TypeDefinitionId;
+					root.Tag = reference;
+
+					root.Nodes.Add( new TreeNode( ) );
+					BrowseNodesTV.Nodes.Add( root );
+					root.Expand( );
+					BrowseNodesTV.SelectedNode = root;
+				}
+			}
+		}
+
+		/// <summary>
+		/// Handles the BeforeExpand event of the BrowseTV control.
+		/// </summary>
+		private async Task BrowseTV_BeforeExpand( object sender, TreeViewCancelEventArgs e )
+		{
+			try
+			{
+				e.Node.Nodes.Clear( );
+				e.Node.Nodes.Add( new TreeNode( "Browsering...", 7, 7 ) );
+				TreeNode[] listNode = await Task.Run( ( ) =>
+				{
+					Console.WriteLine( "BrowseTV_BeforeExpand, m_referenceTypeIds length: " + m_referenceTypeIds.Length );
+					ReferenceDescription reference = (ReferenceDescription)e.Node.Tag;
+					// build list of references to browse.
+					BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+
+					for (int ii = 0; ii < m_referenceTypeIds.Length; ii++)
+					{
+						BrowseDescription nodeToBrowse = new BrowseDescription( );
+
+						nodeToBrowse.NodeId = m_rootId;
+						nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
+						nodeToBrowse.ReferenceTypeId = m_referenceTypeIds[ii];
+						nodeToBrowse.IncludeSubtypes = true;
+						nodeToBrowse.NodeClassMask = 0;
+						nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
+
+						if (reference != null)
+						{
+							nodeToBrowse.NodeId = (NodeId)reference.NodeId;
+						}
+
+						nodesToBrowse.Add( nodeToBrowse );
+					}
+
+					// add the childen to the control.
+					SortedDictionary<ExpandedNodeId, TreeNode> dictionary = new SortedDictionary<ExpandedNodeId, TreeNode>( );
+
+					Console.WriteLine( " ClientUtils.Browse... " );
+					ReferenceDescriptionCollection references = ClientUtils.Browse( m_session, View, nodesToBrowse, false );
+
+					Console.WriteLine( " ClientUtils.Browse: " + (references == null ? "NULL" : "Count:" + references.Count) );
+					for (int ii = 0; references != null && ii < references.Count; ii++)
+					{
+						reference = references[ii];
+
+						// ignore out of server references.
+						if (reference.NodeId.IsAbsolute)
+						{
+							continue;
+						}
+
+						if (dictionary.ContainsKey( reference.NodeId ))
+						{
+							continue;
+						}
+
+						TreeNode child = new TreeNode( reference.ToString( ) );
+						if (!checkBox1.Checked)
+						{
+							if (GetReferenceDescriptionCollection( (NodeId)reference.NodeId ).Count > 0)
+							{
+								child.Nodes.Add( new TreeNode( ) );
+							}
+						}
+						else
+						{
+							child.Nodes.Add( new TreeNode( ) );
+						}
+						child.Tag = reference;
+
+						if (!reference.TypeDefinition.IsAbsolute)
+						{
+							try
+							{
+								if (!m_typeImageMapping.ContainsKey( (NodeId)reference.TypeDefinition ))
+								{
+									DataValue value = m_session.ReadValue( (NodeId)reference.NodeId );
+									m_typeImageMapping[(NodeId)reference.TypeDefinition] = GetImageIndex( value );
+								}
+							}
+							catch (Exception exception)
+							{
+								Utils.LogError( exception, "Error loading image." );
+							}
+						}
+
+						string index = "ClassIcon";
+						if (!m_typeImageMapping.TryGetValue( (NodeId)reference.TypeDefinition, out index ))
+						{
+							child.ImageKey = GetImageIndex( m_session, reference.NodeClass, reference.TypeDefinition, false );
+							child.SelectedImageKey = GetImageIndex( m_session, reference.NodeClass, reference.TypeDefinition, true );
+						}
+						else
+						{
+							child.ImageKey = index;
+							child.SelectedImageKey = index;
+						}
+
+						dictionary[reference.NodeId] = child;
+					}
+
+					// add nodes to tree.
+					List<TreeNode> list = new List<TreeNode>( );
+					foreach (TreeNode node in dictionary.Values)
+					{
+						list.Add( node );
+					}
+					return list.ToArray( );
+				} );
+
+				e.Node.Nodes.Clear( );
+				e.Node.Nodes.AddRange( listNode.ToArray( ) );
+
+
+			}
+			catch (Exception exception)
+			{
+				ClientUtils.HandleException( this.Text, exception );
+			}
+
+
+			if (checkBox2.Checked)
+			{
+				await Task.Run( ( ) =>
+				{
+					List<TreeNodeOpcValue> list = new List<TreeNodeOpcValue>( );
+					foreach (TreeNode node in e.Node.Nodes)
+					{
+						if (node.Tag is ReferenceDescription reference)
+						{
+							list.Add( new TreeNodeOpcValue( ) { Node = node, NodeId = (NodeId)reference.NodeId } );
+						}
+					}
+					try
+					{
+						m_session.ReadValues( list.Select( m => m.NodeId ).ToList( ), out DataValueCollection collections, out IList<ServiceResult> errors );
+						Invoke( new Action( ( ) =>
+						{
+							for (int i = 0; i < list.Count; i++)
+							{
+								if (Opc.Ua.StatusCode.IsGood( errors[i].StatusCode ))
+								{
+									list[i].Value = collections[i];
+									list[i].Node.ImageKey = GetImageIndex( collections[i] );
+									list[i].Node.SelectedImageKey = GetImageIndex( collections[i] );
+								}
+							}
+						} ) );
+					}
+					catch (Exception ex)
+					{
+						Utils.Trace( ex, "Error loading image." );
+					}
+				} );
+			}
+		}
+
+		#endregion
+	}
+
+	public class TreeNodeOpcValue
+	{
+		public TreeNode Node { get; set; }
+
+		public NodeId NodeId { get; set; }
+
+		public DataValue Value { get; set; }
+	}
+}

+ 503 - 0
OpcUaHelper/Forms/FormBrowseServer.designer.cs

@@ -0,0 +1,503 @@
+namespace OpcUaHelper.Forms
+{
+    partial class FormBrowseServer
+    {
+        /// <summary>
+        /// Required designer variable.
+        /// </summary>
+        private System.ComponentModel.IContainer components = null;
+
+        /// <summary>
+        /// Clean up any resources being used.
+        /// </summary>
+        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+        protected override void Dispose(bool disposing)
+        {
+            if (disposing && (components != null))
+            {
+                components.Dispose();
+            }
+            base.Dispose(disposing);
+        }
+
+        #region Windows Form Designer generated code
+
+        /// <summary>
+        /// Required method for Designer support - do not modify
+        /// the contents of this method with the code editor.
+        /// </summary>
+        private void InitializeComponent()
+        {
+            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
+            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBrowseServer));
+            this.textBox1 = new System.Windows.Forms.TextBox();
+            this.button1 = new System.Windows.Forms.Button();
+            this.label1 = new System.Windows.Forms.Label();
+            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
+            this.checkBox2 = new System.Windows.Forms.CheckBox();
+            this.checkBox1 = new System.Windows.Forms.CheckBox();
+            this.pictureBox2 = new System.Windows.Forms.PictureBox();
+            this.label3 = new System.Windows.Forms.Label();
+            this.BrowseNodesTV = new OpcUaHelper.Forms.TreeViewEx();
+            this.dataGridView1 = new System.Windows.Forms.DataGridView();
+            this.Image = new System.Windows.Forms.DataGridViewImageColumn();
+            this.DisplayName = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.Value = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.Type = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.AccessLevel = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.Description = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.StatusCode = new System.Windows.Forms.DataGridViewTextBoxColumn();
+            this.panel1 = new System.Windows.Forms.Panel();
+            this.label_time_spend = new System.Windows.Forms.Label();
+            this.pictureBox3 = new System.Windows.Forms.PictureBox();
+            this.button2 = new System.Windows.Forms.Button();
+            this.textBox_nodeId = new System.Windows.Forms.TextBox();
+            this.pictureBox1 = new System.Windows.Forms.PictureBox();
+            this.label2 = new System.Windows.Forms.Label();
+            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
+            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
+            this.toolStripStatusLabel_opc = new System.Windows.Forms.ToolStripStatusLabel();
+            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
+            this.menuToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+            this.discoverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+            this.v220ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+            this.button3 = new System.Windows.Forms.Button();
+            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
+            this.splitContainer1.Panel1.SuspendLayout();
+            this.splitContainer1.Panel2.SuspendLayout();
+            this.splitContainer1.SuspendLayout();
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
+            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
+            this.panel1.SuspendLayout();
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
+            this.statusStrip1.SuspendLayout();
+            this.menuStrip1.SuspendLayout();
+            this.SuspendLayout();
+            // 
+            // textBox1
+            // 
+            this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.textBox1.Location = new System.Drawing.Point(72, 28);
+            this.textBox1.Name = "textBox1";
+            this.textBox1.Size = new System.Drawing.Size(934, 23);
+            this.textBox1.TabIndex = 0;
+            // 
+            // button1
+            // 
+            this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.button1.Location = new System.Drawing.Point(1009, 27);
+            this.button1.Name = "button1";
+            this.button1.Size = new System.Drawing.Size(89, 25);
+            this.button1.TabIndex = 1;
+            this.button1.Text = "Connect";
+            this.button1.UseVisualStyleBackColor = true;
+            this.button1.Click += new System.EventHandler(this.button1_Click);
+            // 
+            // label1
+            // 
+            this.label1.AutoSize = true;
+            this.label1.Location = new System.Drawing.Point(7, 29);
+            this.label1.Name = "label1";
+            this.label1.Size = new System.Drawing.Size(59, 17);
+            this.label1.TabIndex = 2;
+            this.label1.Text = "Address:";
+            // 
+            // splitContainer1
+            // 
+            this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
+            | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.splitContainer1.Location = new System.Drawing.Point(10, 52);
+            this.splitContainer1.Name = "splitContainer1";
+            // 
+            // splitContainer1.Panel1
+            // 
+            this.splitContainer1.Panel1.Controls.Add(this.checkBox2);
+            this.splitContainer1.Panel1.Controls.Add(this.checkBox1);
+            this.splitContainer1.Panel1.Controls.Add(this.pictureBox2);
+            this.splitContainer1.Panel1.Controls.Add(this.label3);
+            this.splitContainer1.Panel1.Controls.Add(this.BrowseNodesTV);
+            // 
+            // splitContainer1.Panel2
+            // 
+            this.splitContainer1.Panel2.Controls.Add(this.dataGridView1);
+            this.splitContainer1.Panel2.Controls.Add(this.panel1);
+            this.splitContainer1.Size = new System.Drawing.Size(1179, 510);
+            this.splitContainer1.SplitterDistance = 338;
+            this.splitContainer1.TabIndex = 3;
+            // 
+            // checkBox2
+            // 
+            this.checkBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.checkBox2.AutoSize = true;
+            this.checkBox2.Checked = true;
+            this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked;
+            this.checkBox2.Location = new System.Drawing.Point(181, 7);
+            this.checkBox2.Name = "checkBox2";
+            this.checkBox2.Size = new System.Drawing.Size(52, 21);
+            this.checkBox2.TabIndex = 8;
+            this.checkBox2.Text = "Icon";
+            this.checkBox2.UseVisualStyleBackColor = true;
+            // 
+            // checkBox1
+            // 
+            this.checkBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.checkBox1.AutoSize = true;
+            this.checkBox1.Location = new System.Drawing.Point(239, 6);
+            this.checkBox1.Name = "checkBox1";
+            this.checkBox1.Size = new System.Drawing.Size(93, 21);
+            this.checkBox1.TabIndex = 7;
+            this.checkBox1.Text = "Fast Access";
+            this.checkBox1.UseVisualStyleBackColor = true;
+            // 
+            // pictureBox2
+            // 
+            this.pictureBox2.Image = global::OpcUaHelper.Properties.Resources.glasses_16xLG;
+            this.pictureBox2.Location = new System.Drawing.Point(3, 9);
+            this.pictureBox2.Name = "pictureBox2";
+            this.pictureBox2.Size = new System.Drawing.Size(17, 18);
+            this.pictureBox2.TabIndex = 6;
+            this.pictureBox2.TabStop = false;
+            // 
+            // label3
+            // 
+            this.label3.AutoSize = true;
+            this.label3.ForeColor = System.Drawing.Color.Tomato;
+            this.label3.Location = new System.Drawing.Point(19, 8);
+            this.label3.Name = "label3";
+            this.label3.Size = new System.Drawing.Size(104, 17);
+            this.label3.TabIndex = 3;
+            this.label3.Text = "Server Browser :";
+            // 
+            // BrowseNodesTV
+            // 
+            this.BrowseNodesTV.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
+            | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.BrowseNodesTV.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+            this.BrowseNodesTV.Location = new System.Drawing.Point(3, 32);
+            this.BrowseNodesTV.Name = "BrowseNodesTV";
+            this.BrowseNodesTV.ShowLines = false;
+            this.BrowseNodesTV.Size = new System.Drawing.Size(332, 475);
+            this.BrowseNodesTV.TabIndex = 0;
+            this.BrowseNodesTV.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.BrowseNodesTV_BeforeExpand);
+            this.BrowseNodesTV.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.BrowseNodesTV_AfterSelect);
+            this.BrowseNodesTV.MouseClick += new System.Windows.Forms.MouseEventHandler(this.BrowseNodesTV_MouseClick);
+            // 
+            // dataGridView1
+            // 
+            this.dataGridView1.AllowUserToAddRows = false;
+            this.dataGridView1.AllowUserToDeleteRows = false;
+            this.dataGridView1.AllowUserToResizeRows = false;
+            dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightBlue;
+            this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
+            this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
+            | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.dataGridView1.BackgroundColor = System.Drawing.Color.White;
+            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
+            this.Image,
+            this.DisplayName,
+            this.Value,
+            this.Type,
+            this.AccessLevel,
+            this.Description,
+            this.StatusCode});
+            this.dataGridView1.Location = new System.Drawing.Point(3, 32);
+            this.dataGridView1.MultiSelect = false;
+            this.dataGridView1.Name = "dataGridView1";
+            this.dataGridView1.RowHeadersVisible = false;
+            this.dataGridView1.RowTemplate.Height = 23;
+            this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
+            this.dataGridView1.Size = new System.Drawing.Size(833, 475);
+            this.dataGridView1.TabIndex = 1;
+            this.dataGridView1.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.dataGridView1_CellBeginEdit);
+            this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);
+            // 
+            // Image
+            // 
+            this.Image.HeaderText = "";
+            this.Image.Name = "Image";
+            this.Image.Width = 20;
+            // 
+            // DisplayName
+            // 
+            this.DisplayName.HeaderText = "Name";
+            this.DisplayName.Name = "DisplayName";
+            this.DisplayName.ReadOnly = true;
+            this.DisplayName.ToolTipText = "参数的显示名称";
+            this.DisplayName.Width = 145;
+            // 
+            // Value
+            // 
+            this.Value.HeaderText = "Value";
+            this.Value.Name = "Value";
+            this.Value.ToolTipText = "参数的实际数据值";
+            this.Value.Width = 200;
+            // 
+            // Type
+            // 
+            this.Type.HeaderText = "Type";
+            this.Type.Name = "Type";
+            this.Type.ReadOnly = true;
+            this.Type.ToolTipText = "参数的类型";
+            this.Type.Width = 80;
+            // 
+            // AccessLevel
+            // 
+            this.AccessLevel.HeaderText = "AccessLevel";
+            this.AccessLevel.Name = "AccessLevel";
+            this.AccessLevel.ReadOnly = true;
+            this.AccessLevel.ToolTipText = "数据的访问等级";
+            this.AccessLevel.Width = 130;
+            // 
+            // Description
+            // 
+            this.Description.HeaderText = "Description";
+            this.Description.Name = "Description";
+            this.Description.ReadOnly = true;
+            this.Description.ToolTipText = "数据的文本描述";
+            this.Description.Width = 140;
+            // 
+            // StatusCode
+            // 
+            this.StatusCode.HeaderText = "StatusCode";
+            this.StatusCode.Name = "StatusCode";
+            this.StatusCode.ReadOnly = true;
+            // 
+            // panel1
+            // 
+            this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.panel1.Controls.Add(this.label_time_spend);
+            this.panel1.Controls.Add(this.pictureBox3);
+            this.panel1.Controls.Add(this.button2);
+            this.panel1.Controls.Add(this.textBox_nodeId);
+            this.panel1.Controls.Add(this.pictureBox1);
+            this.panel1.Controls.Add(this.label2);
+            this.panel1.Location = new System.Drawing.Point(3, 3);
+            this.panel1.Name = "panel1";
+            this.panel1.Size = new System.Drawing.Size(832, 27);
+            this.panel1.TabIndex = 0;
+            // 
+            // label_time_spend
+            // 
+            this.label_time_spend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.label_time_spend.AutoSize = true;
+            this.label_time_spend.Location = new System.Drawing.Point(768, 4);
+            this.label_time_spend.Name = "label_time_spend";
+            this.label_time_spend.Size = new System.Drawing.Size(32, 17);
+            this.label_time_spend.TabIndex = 9;
+            this.label_time_spend.Text = "0ms";
+            // 
+            // pictureBox3
+            // 
+            this.pictureBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.pictureBox3.Image = global::OpcUaHelper.Properties.Resources.usbcontroller;
+            this.pictureBox3.Location = new System.Drawing.Point(745, 5);
+            this.pictureBox3.Name = "pictureBox3";
+            this.pictureBox3.Size = new System.Drawing.Size(17, 18);
+            this.pictureBox3.TabIndex = 8;
+            this.pictureBox3.TabStop = false;
+            // 
+            // button2
+            // 
+            this.button2.Image = global::OpcUaHelper.Properties.Resources.Activity_16xLG;
+            this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
+            this.button2.Location = new System.Drawing.Point(0, 1);
+            this.button2.Name = "button2";
+            this.button2.Size = new System.Drawing.Size(106, 25);
+            this.button2.TabIndex = 7;
+            this.button2.Text = " Subscript";
+            this.button2.UseVisualStyleBackColor = true;
+            this.button2.Click += new System.EventHandler(this.button2_Click);
+            // 
+            // textBox_nodeId
+            // 
+            this.textBox_nodeId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+            this.textBox_nodeId.Location = new System.Drawing.Point(295, 2);
+            this.textBox_nodeId.Name = "textBox_nodeId";
+            this.textBox_nodeId.ReadOnly = true;
+            this.textBox_nodeId.Size = new System.Drawing.Size(444, 23);
+            this.textBox_nodeId.TabIndex = 6;
+            // 
+            // pictureBox1
+            // 
+            this.pictureBox1.Image = global::OpcUaHelper.Properties.Resources.Copy_6524;
+            this.pictureBox1.Location = new System.Drawing.Point(163, 5);
+            this.pictureBox1.Name = "pictureBox1";
+            this.pictureBox1.Size = new System.Drawing.Size(17, 18);
+            this.pictureBox1.TabIndex = 5;
+            this.pictureBox1.TabStop = false;
+            // 
+            // label2
+            // 
+            this.label2.AutoSize = true;
+            this.label2.Cursor = System.Windows.Forms.Cursors.Hand;
+            this.label2.Location = new System.Drawing.Point(182, 5);
+            this.label2.Name = "label2";
+            this.label2.Size = new System.Drawing.Size(109, 17);
+            this.label2.TabIndex = 3;
+            this.label2.Text = "Selected NodeId:";
+            this.label2.Click += new System.EventHandler(this.label2_Click);
+            // 
+            // statusStrip1
+            // 
+            this.statusStrip1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
+            this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
+            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+            this.toolStripStatusLabel1,
+            this.toolStripStatusLabel_opc});
+            this.statusStrip1.Location = new System.Drawing.Point(0, 565);
+            this.statusStrip1.Name = "statusStrip1";
+            this.statusStrip1.Size = new System.Drawing.Size(1201, 22);
+            this.statusStrip1.TabIndex = 4;
+            this.statusStrip1.Text = "statusStrip1";
+            // 
+            // toolStripStatusLabel1
+            // 
+            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
+            this.toolStripStatusLabel1.Size = new System.Drawing.Size(78, 17);
+            this.toolStripStatusLabel1.Text = "Opc Status: ";
+            // 
+            // toolStripStatusLabel_opc
+            // 
+            this.toolStripStatusLabel_opc.Name = "toolStripStatusLabel_opc";
+            this.toolStripStatusLabel_opc.Size = new System.Drawing.Size(0, 17);
+            // 
+            // menuStrip1
+            // 
+            this.menuStrip1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(118)))), ((int)(((byte)(0)))));
+            this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
+            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+            this.menuToolStripMenuItem,
+            this.v220ToolStripMenuItem});
+            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
+            this.menuStrip1.Name = "menuStrip1";
+            this.menuStrip1.Size = new System.Drawing.Size(1201, 25);
+            this.menuStrip1.TabIndex = 5;
+            this.menuStrip1.Text = "menuStrip1";
+            // 
+            // menuToolStripMenuItem
+            // 
+            this.menuToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+            this.exitToolStripMenuItem,
+            this.discoverToolStripMenuItem});
+            this.menuToolStripMenuItem.Name = "menuToolStripMenuItem";
+            this.menuToolStripMenuItem.Size = new System.Drawing.Size(52, 21);
+            this.menuToolStripMenuItem.Text = "menu";
+            // 
+            // exitToolStripMenuItem
+            // 
+            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
+            this.exitToolStripMenuItem.Size = new System.Drawing.Size(126, 22);
+            this.exitToolStripMenuItem.Text = "Exit";
+            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
+            // 
+            // discoverToolStripMenuItem
+            // 
+            this.discoverToolStripMenuItem.Name = "discoverToolStripMenuItem";
+            this.discoverToolStripMenuItem.Size = new System.Drawing.Size(126, 22);
+            this.discoverToolStripMenuItem.Text = "Discover";
+            this.discoverToolStripMenuItem.Click += new System.EventHandler(this.discoverToolStripMenuItem_Click);
+            // 
+            // v220ToolStripMenuItem
+            // 
+            this.v220ToolStripMenuItem.Name = "v220ToolStripMenuItem";
+            this.v220ToolStripMenuItem.Size = new System.Drawing.Size(53, 21);
+            this.v220ToolStripMenuItem.Text = "v2.2.1";
+            // 
+            // button3
+            // 
+            this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
+            this.button3.Location = new System.Drawing.Point(1102, 27);
+            this.button3.Name = "button3";
+            this.button3.Size = new System.Drawing.Size(89, 25);
+            this.button3.TabIndex = 6;
+            this.button3.Text = "Close";
+            this.button3.UseVisualStyleBackColor = true;
+            this.button3.Click += new System.EventHandler(this.button3_Click);
+            // 
+            // FormBrowseServer
+            // 
+            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
+            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+            this.ClientSize = new System.Drawing.Size(1201, 587);
+            this.Controls.Add(this.button3);
+            this.Controls.Add(this.statusStrip1);
+            this.Controls.Add(this.menuStrip1);
+            this.Controls.Add(this.splitContainer1);
+            this.Controls.Add(this.label1);
+            this.Controls.Add(this.button1);
+            this.Controls.Add(this.textBox1);
+            this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
+            this.MainMenuStrip = this.menuStrip1;
+            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
+            this.Name = "FormBrowseServer";
+            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
+            this.Text = "OPC Monitor [ OPC UA Helper ]";
+            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormBrowseServer_FormClosing);
+            this.Load += new System.EventHandler(this.FormBrowseServer_Load);
+            this.splitContainer1.Panel1.ResumeLayout(false);
+            this.splitContainer1.Panel1.PerformLayout();
+            this.splitContainer1.Panel2.ResumeLayout(false);
+            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
+            this.splitContainer1.ResumeLayout(false);
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
+            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
+            this.panel1.ResumeLayout(false);
+            this.panel1.PerformLayout();
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
+            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
+            this.statusStrip1.ResumeLayout(false);
+            this.statusStrip1.PerformLayout();
+            this.menuStrip1.ResumeLayout(false);
+            this.menuStrip1.PerformLayout();
+            this.ResumeLayout(false);
+            this.PerformLayout();
+
+        }
+
+        #endregion
+
+        private System.Windows.Forms.TextBox textBox1;
+        private System.Windows.Forms.Button button1;
+        private System.Windows.Forms.Label label1;
+        private System.Windows.Forms.SplitContainer splitContainer1;
+        private TreeViewEx BrowseNodesTV;
+        private System.Windows.Forms.DataGridView dataGridView1;
+        private System.Windows.Forms.Panel panel1;
+        private System.Windows.Forms.PictureBox pictureBox1;
+        private System.Windows.Forms.Label label2;
+        private System.Windows.Forms.StatusStrip statusStrip1;
+        private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
+        private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_opc;
+        private System.Windows.Forms.Label label3;
+        private System.Windows.Forms.MenuStrip menuStrip1;
+        private System.Windows.Forms.ToolStripMenuItem menuToolStripMenuItem;
+        private System.Windows.Forms.TextBox textBox_nodeId;
+        private System.Windows.Forms.PictureBox pictureBox2;
+        private System.Windows.Forms.Button button2;
+        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
+        private System.Windows.Forms.ToolStripMenuItem discoverToolStripMenuItem;
+        private System.Windows.Forms.Label label_time_spend;
+        private System.Windows.Forms.PictureBox pictureBox3;
+        private System.Windows.Forms.CheckBox checkBox1;
+        private System.Windows.Forms.DataGridViewImageColumn Image;
+        private System.Windows.Forms.DataGridViewTextBoxColumn DisplayName;
+        private System.Windows.Forms.DataGridViewTextBoxColumn Value;
+        private System.Windows.Forms.DataGridViewTextBoxColumn Type;
+        private System.Windows.Forms.DataGridViewTextBoxColumn AccessLevel;
+        private System.Windows.Forms.DataGridViewTextBoxColumn Description;
+        private System.Windows.Forms.DataGridViewTextBoxColumn StatusCode;
+        private System.Windows.Forms.ToolStripMenuItem v220ToolStripMenuItem;
+        private System.Windows.Forms.Button button3;
+        private System.Windows.Forms.CheckBox checkBox2;
+    }
+}

+ 231 - 0
OpcUaHelper/Forms/FormBrowseServer.resx

@@ -0,0 +1,231 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <metadata name="Image.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="DisplayName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="Value.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="Type.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="AccessLevel.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="Description.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="StatusCode.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+    <value>True</value>
+  </metadata>
+  <metadata name="statusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+    <value>17, 17</value>
+  </metadata>
+  <metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+    <value>138, 17</value>
+  </metadata>
+  <assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+  <data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+    <value>
+        AAABAAQAICAQAAEABADoAgAARgAAABAQEAABAAQAKAEAAC4DAAAgIAAAAQAIAKgIAABWBAAAEBAAAAEA
+        CABoBQAA/gwAACgAAAAgAAAAQAAAAAEABAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACA
+        AAAAgIAAgAAAAIAAgACAgAAAgICAAMDAwAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD///8AAAAAAAAA
+        AAAAD///8AAAAAAAAAAAAAAAAP/3f/8AAAAAAAAAAAAAAA//d3f/8AAAAAAAAAAAAAD/93d3f/8AAAAA
+        AAAAAAAP/3d3d3f/8AAAAAAAAAAA//93d3d3f/8AAAAAAAAA////93d3d3f/8AAAAAAAAP////93d3d3
+        f/8AAAAAAAD/d3d3d3d3d3f/AAAAAAAA/3d3d3d3d3d3/wAAAAAAAP93////93d3f/8AAAAAAAD/d///
+        //93d//wAAAP8AAA/3f/////93//AAAA//8AAP93///3f///8AAAD///8AD/d///d3f//wAAAP/3f/8A
+        /3f/93d3f/8AAA//d3f/8P93/3d3d3f/8AD/93d3f///d/93d3d3f/8A/3d3d3f//3f/93d3d3f/8Pd3
+        d3d3f/93//93d3d3f//3d3d3d3d3d3d3d3d3d3f//3d3d3d3d3d3d3d3d3d3///3d3d3d3f/////93d3
+        f/8P/3d3d3d3f/////93d//wAP/3d3d3d3f/8AD/93//AAAP/3d3d3d3f/8AD///8AAAAP/3d3d3d3f/
+        8AD//wAAAAAP/3d3d3d3//AAD/AAAAAAAP/3d3d3f/8AAAAAAAAAAAAP/3d3d//wAAAAAAAAAAAAAP/3
+        d3//AAAAAAAAAAAAAAAP/3f/8AAAAAAAAAD//+B////AP///gB///wAP//4AB//8AAP/8AAB//AAAP/w
+        AAD/8AAA//AAAP/wAAH58AAD8PAAB+BwAA/AMAAPgBAABwAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAIAA
+        AAHAABwD4AAOB/AABw/4AAef/AAP//4AH///AD///4B//ygAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAgICAAMDAwAAAAP8AAP8AAAD/
+        /wD/AAAA/wD/AP//AAD///8AAAAAAAAP8AAAAAAAAPd/AAAAAAAPd3fwAAAAD/93d38AAAAPd3d3fwAA
+        AA9//3fwAA/wD3/3fwAA938Pf3d38A93d/9/d3d/93d3d3d3d3/3d3d3//938A93d3d/AP8AAPd3d38A
+        AAAAD3d38AAAAAAA938AAAAAAAAP8AAAAAD/5wAA/8MAAP+BAAD+AAAA/gAAAP4BAADmAwAAwgEAAIAA
+        AAAAAAAAAAEAAIAzAADAPwAA4H8AAPD/AAD5/wAAKAAAACAAAABAAAAAAQAIAAAAAAAABAAAAAAAAAAA
+        AAAAAQAAAAEAAAAAAABCQkIAhoaGAJGRkQD29vYA+Pj4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAP///wAAAAAAAAAAAAAAAAAAAAAAAAAABQQEBAQFAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAUEBAICBAQFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBAQCAQECBAQFAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAABQQEAgEBAQECBAQFAAAAAAAAAAAAAAAAAAAAAAAAAAUEBAIBAQEBAQECBAQFAAAAAAAAAAAA
+        AAAAAAAAAAAFBAQEAgEBAQEBAQECBAQFAAAAAAAAAAAAAAAAAAAEBAQEBAQEAgEBAQEBAQECBAQFAAAA
+        AAAAAAAAAAAAAAQEBAQEBAQEAwEBAQEBAQECBAQFAAAAAAAAAAAAAAAABAQBAQEBAQEBAQEBAQEBAQEC
+        BAQAAAAAAAAAAAAAAAAEBAEBAQEBAQEBAQEBAQEBAQIEBAAAAAAAAAAAAAAAAAQEAQEEBAQEBAQEAgEB
+        AQECBAQFAAAAAAAAAAAAAAAABAQBAQQEBAQEBAQEAgEBAgQEBQAAAAAAAAUFAAAAAAAEBAEBBAQEBAQE
+        BAQEAgIEBAUAAAAAAAAFBAQFAAAAAAQEAQEEBAQEBAICBAQEBAQFAAAAAAAABQQEBAQFAAAABAQBAQQE
+        BAQCAQECBAQEBQAAAAAAAAUEBAICBAQFAAAEBAEBBAQEAgEBAQECBAQFAAAAAAAFBAQCAQECBAQFAAQE
+        AQEEBAIBAQEBAQECBAQFAAAABQQEAgEBAQECBAQFBAQBAQQEAgEBAQEBAQECBAQFAAAEBAIBAQEBAQEC
+        BAQEBAEBBAQEAgEBAQEBAQECBAQFAAQCAQEBAQEBAQECBAQEAQEEBAQEAwEBAQEBAQECBAQFBAIBAQEB
+        AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQECBAQEBAIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQIEBAUE
+        BAIBAQEBAQEBAQECBAQEBAQEBAQEAgEBAQECBAQFAAUEBAIBAQEBAQEBAQECBAQEBAQEBAQEAgEBAgQE
+        BQAAAAUEBAIBAQEBAQEBAQECBAQFAAAABQQEAgIEBAUAAAAAAAUEBAIBAQEBAQEBAQECBAQFAAAABQQE
+        BAQFAAAAAAAAAAUEBAIBAQEBAQEBAQECBAQFAAAABQQEBQAAAAAAAAAAAAUEBAIBAQEBAQEBAQIEBAUA
+        AAAABQUAAAAAAAAAAAAAAAUEBAIBAQEBAQECBAQFAAAAAAAAAAAAAAAAAAAAAAAAAAUEBAIBAQEBAgQE
+        BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUEBAIBAQIEBAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUEBAIC
+        BAQFAAAAAAAAAAAAAAAAAAAA///gf///wD///4Af//8AD//+AAf//AAD//AAAf/wAAD/8AAA//AAAP/w
+        AAD/8AAB+fAAA/DwAAfgcAAPwDAAD4AQAAcAAAADAAAAAQAAAAAAAAAAAAAAAAAAAACAAAABwAAcA+AA
+        DgfwAAcP+AAHn/wAD//+AB///wA///+Af/8oAAAAEAAAACAAAAABAAgAAAAAAAABAAAAAAAAAAAAAAAB
+        AAAAAQAAAAAAAEJCQgCGhoYAkZGRAPb29gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+        AAAAAAAA////AAAAAAAAAAAAAAAABAQAAAAAAAAAAAAAAAAABAICBAAAAAAAAAAAAAAABAIBAQIEAAAA
+        AAAAAAAEBAQDAQEBAgQAAAAAAAAABAEBAQEBAQIEAAAAAAAAAAQBBAQEAgIEAAAAAAQEAAAEAQQEAgIE
+        AAAAAAQCAgQABAEEAgEBAgQAAAQCAQECBAQBBAMBAQECBAQCAQEBAQEBAQEBAQEBAgQEAgEBAQEBAgQE
+        BAQCAgQAAAQCAQEBAQECBAAABAQAAAAABAIBAQEBAgQAAAAAAAAAAAAEAgEBAgQAAAAAAAAAAAAAAAQC
+        AgQAAAAAAAAAAAAAAAAABAQAAAAAAAAAAAD/5wAA/8MAAP+BAAD+AAAA/gAAAP4BAADmAwAAwgEAAIAA
+        AAAAAAAAAAEAAIAzAADAPwAA4H8AAPD/AAD5/wAA
+</value>
+  </data>
+</root>

+ 252 - 0
OpcUaHelper/Forms/FormConnectSelect.Designer.cs

@@ -0,0 +1,252 @@
+namespace OpcUaHelper.Forms
+{
+    partial class FormConnectSelect
+    {
+        /// <summary>
+        /// Required designer variable.
+        /// </summary>
+        private System.ComponentModel.IContainer components = null;
+
+        /// <summary>
+        /// Clean up any resources being used.
+        /// </summary>
+        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+        protected override void Dispose( bool disposing )
+        {
+            if (disposing && (components != null))
+            {
+                components.Dispose( );
+            }
+            base.Dispose( disposing );
+        }
+
+        #region Windows Form Designer generated code
+
+        /// <summary>
+        /// Required method for Designer support - do not modify
+        /// the contents of this method with the code editor.
+        /// </summary>
+        private void InitializeComponent( )
+        {
+            this.tabControl1 = new System.Windows.Forms.TabControl();
+            this.tabPage1 = new System.Windows.Forms.TabPage();
+            this.button1 = new System.Windows.Forms.Button();
+            this.tabPage2 = new System.Windows.Forms.TabPage();
+            this.textBox2 = new System.Windows.Forms.TextBox();
+            this.label2 = new System.Windows.Forms.Label();
+            this.textBox1 = new System.Windows.Forms.TextBox();
+            this.label1 = new System.Windows.Forms.Label();
+            this.button2 = new System.Windows.Forms.Button();
+            this.tabPage3 = new System.Windows.Forms.TabPage();
+            this.button4 = new System.Windows.Forms.Button();
+            this.textBox3 = new System.Windows.Forms.TextBox();
+            this.label3 = new System.Windows.Forms.Label();
+            this.textBox4 = new System.Windows.Forms.TextBox();
+            this.label4 = new System.Windows.Forms.Label();
+            this.button3 = new System.Windows.Forms.Button();
+            this.tabControl1.SuspendLayout();
+            this.tabPage1.SuspendLayout();
+            this.tabPage2.SuspendLayout();
+            this.tabPage3.SuspendLayout();
+            this.SuspendLayout();
+            // 
+            // tabControl1
+            // 
+            this.tabControl1.Controls.Add(this.tabPage1);
+            this.tabControl1.Controls.Add(this.tabPage2);
+            this.tabControl1.Controls.Add(this.tabPage3);
+            this.tabControl1.Location = new System.Drawing.Point(12, 12);
+            this.tabControl1.Name = "tabControl1";
+            this.tabControl1.SelectedIndex = 0;
+            this.tabControl1.Size = new System.Drawing.Size(407, 214);
+            this.tabControl1.TabIndex = 0;
+            // 
+            // tabPage1
+            // 
+            this.tabPage1.Controls.Add(this.button1);
+            this.tabPage1.Location = new System.Drawing.Point(4, 26);
+            this.tabPage1.Name = "tabPage1";
+            this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
+            this.tabPage1.Size = new System.Drawing.Size(399, 184);
+            this.tabPage1.TabIndex = 0;
+            this.tabPage1.Text = "匿名登录";
+            this.tabPage1.UseVisualStyleBackColor = true;
+            // 
+            // button1
+            // 
+            this.button1.Location = new System.Drawing.Point(142, 73);
+            this.button1.Name = "button1";
+            this.button1.Size = new System.Drawing.Size(104, 32);
+            this.button1.TabIndex = 0;
+            this.button1.Text = "登录";
+            this.button1.UseVisualStyleBackColor = true;
+            this.button1.Click += new System.EventHandler(this.button1_Click);
+            // 
+            // tabPage2
+            // 
+            this.tabPage2.Controls.Add(this.textBox2);
+            this.tabPage2.Controls.Add(this.label2);
+            this.tabPage2.Controls.Add(this.textBox1);
+            this.tabPage2.Controls.Add(this.label1);
+            this.tabPage2.Controls.Add(this.button2);
+            this.tabPage2.Location = new System.Drawing.Point(4, 26);
+            this.tabPage2.Name = "tabPage2";
+            this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
+            this.tabPage2.Size = new System.Drawing.Size(399, 184);
+            this.tabPage2.TabIndex = 1;
+            this.tabPage2.Text = "用户名登录";
+            this.tabPage2.UseVisualStyleBackColor = true;
+            // 
+            // textBox2
+            // 
+            this.textBox2.Location = new System.Drawing.Point(130, 68);
+            this.textBox2.Name = "textBox2";
+            this.textBox2.Size = new System.Drawing.Size(202, 23);
+            this.textBox2.TabIndex = 5;
+            // 
+            // label2
+            // 
+            this.label2.AutoSize = true;
+            this.label2.Location = new System.Drawing.Point(68, 71);
+            this.label2.Name = "label2";
+            this.label2.Size = new System.Drawing.Size(44, 17);
+            this.label2.TabIndex = 4;
+            this.label2.Text = "密码:";
+            // 
+            // textBox1
+            // 
+            this.textBox1.Location = new System.Drawing.Point(130, 32);
+            this.textBox1.Name = "textBox1";
+            this.textBox1.Size = new System.Drawing.Size(202, 23);
+            this.textBox1.TabIndex = 3;
+            // 
+            // label1
+            // 
+            this.label1.AutoSize = true;
+            this.label1.Location = new System.Drawing.Point(68, 35);
+            this.label1.Name = "label1";
+            this.label1.Size = new System.Drawing.Size(56, 17);
+            this.label1.TabIndex = 2;
+            this.label1.Text = "用户名:";
+            // 
+            // button2
+            // 
+            this.button2.Location = new System.Drawing.Point(141, 117);
+            this.button2.Name = "button2";
+            this.button2.Size = new System.Drawing.Size(104, 32);
+            this.button2.TabIndex = 1;
+            this.button2.Text = "登录";
+            this.button2.UseVisualStyleBackColor = true;
+            this.button2.Click += new System.EventHandler(this.button2_Click);
+            // 
+            // tabPage3
+            // 
+            this.tabPage3.Controls.Add(this.button4);
+            this.tabPage3.Controls.Add(this.textBox3);
+            this.tabPage3.Controls.Add(this.label3);
+            this.tabPage3.Controls.Add(this.textBox4);
+            this.tabPage3.Controls.Add(this.label4);
+            this.tabPage3.Controls.Add(this.button3);
+            this.tabPage3.Location = new System.Drawing.Point(4, 26);
+            this.tabPage3.Name = "tabPage3";
+            this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
+            this.tabPage3.Size = new System.Drawing.Size(399, 184);
+            this.tabPage3.TabIndex = 2;
+            this.tabPage3.Text = "证书登录";
+            this.tabPage3.UseVisualStyleBackColor = true;
+            // 
+            // button4
+            // 
+            this.button4.Location = new System.Drawing.Point(338, 31);
+            this.button4.Name = "button4";
+            this.button4.Size = new System.Drawing.Size(32, 25);
+            this.button4.TabIndex = 11;
+            this.button4.Text = "...";
+            this.button4.UseVisualStyleBackColor = true;
+            this.button4.Click += new System.EventHandler(this.button4_Click);
+            // 
+            // textBox3
+            // 
+            this.textBox3.Location = new System.Drawing.Point(130, 68);
+            this.textBox3.Name = "textBox3";
+            this.textBox3.Size = new System.Drawing.Size(202, 23);
+            this.textBox3.TabIndex = 10;
+            // 
+            // label3
+            // 
+            this.label3.AutoSize = true;
+            this.label3.Location = new System.Drawing.Point(68, 71);
+            this.label3.Name = "label3";
+            this.label3.Size = new System.Drawing.Size(44, 17);
+            this.label3.TabIndex = 9;
+            this.label3.Text = "密钥:";
+            // 
+            // textBox4
+            // 
+            this.textBox4.Location = new System.Drawing.Point(130, 32);
+            this.textBox4.Name = "textBox4";
+            this.textBox4.Size = new System.Drawing.Size(202, 23);
+            this.textBox4.TabIndex = 8;
+            // 
+            // label4
+            // 
+            this.label4.AutoSize = true;
+            this.label4.Location = new System.Drawing.Point(68, 35);
+            this.label4.Name = "label4";
+            this.label4.Size = new System.Drawing.Size(44, 17);
+            this.label4.TabIndex = 7;
+            this.label4.Text = "证书:";
+            // 
+            // button3
+            // 
+            this.button3.Location = new System.Drawing.Point(141, 117);
+            this.button3.Name = "button3";
+            this.button3.Size = new System.Drawing.Size(104, 32);
+            this.button3.TabIndex = 6;
+            this.button3.Text = "登录";
+            this.button3.UseVisualStyleBackColor = true;
+            this.button3.Click += new System.EventHandler(this.button3_Click);
+            // 
+            // FormConnectSelect
+            // 
+            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
+            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+            this.BackColor = System.Drawing.Color.AliceBlue;
+            this.ClientSize = new System.Drawing.Size(431, 238);
+            this.Controls.Add(this.tabControl1);
+            this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
+            this.Name = "FormConnectSelect";
+            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+            this.Text = "登录方式选择";
+            this.Load += new System.EventHandler(this.FormConnectSelect_Load);
+            this.tabControl1.ResumeLayout(false);
+            this.tabPage1.ResumeLayout(false);
+            this.tabPage2.ResumeLayout(false);
+            this.tabPage2.PerformLayout();
+            this.tabPage3.ResumeLayout(false);
+            this.tabPage3.PerformLayout();
+            this.ResumeLayout(false);
+
+        }
+
+        #endregion
+
+        private System.Windows.Forms.TabControl tabControl1;
+        private System.Windows.Forms.TabPage tabPage1;
+        private System.Windows.Forms.Button button1;
+        private System.Windows.Forms.TabPage tabPage2;
+        private System.Windows.Forms.TextBox textBox2;
+        private System.Windows.Forms.Label label2;
+        private System.Windows.Forms.TextBox textBox1;
+        private System.Windows.Forms.Label label1;
+        private System.Windows.Forms.Button button2;
+        private System.Windows.Forms.TabPage tabPage3;
+        private System.Windows.Forms.Button button4;
+        private System.Windows.Forms.TextBox textBox3;
+        private System.Windows.Forms.Label label3;
+        private System.Windows.Forms.TextBox textBox4;
+        private System.Windows.Forms.Label label4;
+        private System.Windows.Forms.Button button3;
+    }
+}

+ 96 - 0
OpcUaHelper/Forms/FormConnectSelect.cs

@@ -0,0 +1,96 @@
+using Opc.Ua;
+using Opc.Ua.Configuration;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace OpcUaHelper.Forms
+{
+	public partial class FormConnectSelect : Form
+	{
+		public FormConnectSelect( OpcUaClient opcUaClient )
+		{
+			InitializeComponent( );
+			this.m_OpcUaClient = opcUaClient;
+		}
+
+		private void FormConnectSelect_Load( object sender, EventArgs e )
+		{
+
+		}
+
+
+		private OpcUaClient m_OpcUaClient;
+
+		private void button1_Click( object sender, EventArgs e )
+		{
+			// 匿名登录
+			m_OpcUaClient.UserIdentity = new UserIdentity( new AnonymousIdentityToken( ) );
+			DialogResult = DialogResult.OK;
+			return;
+		}
+
+		private void button2_Click( object sender, EventArgs e )
+		{
+			// 用户名密码登录
+			m_OpcUaClient.UserIdentity = new UserIdentity( textBox1.Text, Encoding.UTF8.GetBytes( textBox2.Text ) );
+			DialogResult = DialogResult.OK;
+			return;
+		}
+
+		private async void button3_Click( object sender, EventArgs e )
+		{
+			// 证书登录
+			try
+			{
+				// 如果需要生成自签名的证书,可以参考网址:http://www.hsltechnology.cn/Doc/HslCommunication?chapter=HslCommChapter6-5
+				X509Certificate2 certificate = new X509Certificate2( textBox4.Text, textBox3.Text, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable );
+				m_OpcUaClient.UserIdentity = new UserIdentity( certificate );
+
+				FileInfo fileInfo = new FileInfo( textBox4.Text );
+				m_OpcUaClient.AppConfig.SecurityConfiguration.ApplicationCertificate.StoreType = CertificateStoreType.Directory;
+				m_OpcUaClient.AppConfig.SecurityConfiguration.ApplicationCertificate.StorePath = fileInfo.DirectoryName;
+				m_OpcUaClient.AppConfig.SecurityConfiguration.ApplicationCertificate.SubjectName = null;
+
+				m_OpcUaClient.AppConfig.SecurityConfiguration.TrustedPeerCertificates.StoreType = CertificateStoreType.Directory;
+				m_OpcUaClient.AppConfig.SecurityConfiguration.TrustedPeerCertificates.StorePath = fileInfo.DirectoryName;
+
+				m_OpcUaClient.AppConfig.SecurityConfiguration.TrustedIssuerCertificates.StoreType = CertificateStoreType.Directory;
+				m_OpcUaClient.AppConfig.SecurityConfiguration.TrustedIssuerCertificates.StorePath = fileInfo.DirectoryName;
+
+				// 创建一个应用实例对象,用于检查证书
+				var application = new ApplicationInstance( m_OpcUaClient.AppConfig, null );
+				// 检查应用实例对象的证书
+				bool check = await application.CheckApplicationInstanceCertificatesAsync( false, 2048 );
+
+				DialogResult = DialogResult.OK;
+				return;
+			}
+			catch(Exception ex)
+			{
+				ClientUtils.HandleException( this.Text, ex );
+			}
+		}
+
+		private void button4_Click( object sender, EventArgs e )
+		{
+
+			using (OpenFileDialog openFileDialog = new OpenFileDialog( ))
+			{
+				openFileDialog.Multiselect = false;
+				if (openFileDialog.ShowDialog( ) == DialogResult.OK)
+				{
+					textBox4.Text = openFileDialog.FileName;
+				}
+			}
+		}
+	}
+}

+ 120 - 0
OpcUaHelper/Forms/FormConnectSelect.resx

@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+</root>

+ 49 - 0
OpcUaHelper/Forms/TreeViewEx.cs

@@ -0,0 +1,49 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace OpcUaHelper.Forms
+{
+    /// <summary>
+    /// 无闪烁的树节点控件,结果还是没有实现
+    /// </summary>
+    public class TreeViewEx : TreeView
+    {
+        /// <summary>
+        /// 实例化一个新的控件
+        /// </summary>
+        public TreeViewEx()
+        {
+            // 开启双缓冲
+            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
+
+            // Enable the OnNotifyMessage event so we get a chance to filter out 
+            // Windows messages before they get to the form's WndProc
+            SetStyle(ControlStyles.EnableNotifyMessage, true);
+        }
+
+        /// <summary>
+        /// 通知
+        /// </summary>
+        /// <param name="m"></param>
+        protected override void OnNotifyMessage(Message m)
+        {
+            //Filter out the WM_ERASEBKGND message
+            if (m.Msg != 0x14)
+            {
+                base.OnNotifyMessage(m);
+            }
+
+        }
+
+        //protected override void WndProc(ref Message m)
+        //{
+        //    if (m.Msg == 0x0014) // 禁掉清除背景消息
+        //        return;
+        //    base.WndProc(ref m);
+        //}
+    }
+}

+ 1462 - 0
OpcUaHelper/OpcUaClient.cs

@@ -0,0 +1,1462 @@
+using Opc.Ua;
+using Opc.Ua.Bindings;
+using Opc.Ua.Client;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace OpcUaHelper
+{
+	/// <summary>
+	/// 一个二次封装了的OPC UA库,支持从opc ua服务器读写节点数据,批量读写,订阅,批量订阅,历史数据读取,方法调用操作。
+	/// </summary>
+	public class OpcUaClient
+	{
+		#region Constructors
+
+		/// <summary>
+		/// 默认的构造函数,实例化一个新的OPC UA类
+		/// </summary>
+		public OpcUaClient( )
+		{
+			dic_subscriptions = new Dictionary<string, Subscription>( );
+
+			var certificateValidator = new CertificateValidator( );
+			certificateValidator.CertificateValidation += ( sender, eventArgs ) =>
+			{
+				if (ServiceResult.IsGood( eventArgs.Error ))
+					eventArgs.Accept = true;
+				else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)
+					eventArgs.Accept = true;
+				else
+					throw new Exception( string.Format( "Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo ) );
+			};
+
+			SecurityConfiguration securityConfigurationcv = new SecurityConfiguration
+			{
+				AutoAcceptUntrustedCertificates = true,
+				RejectSHA1SignedCertificates = false,
+				MinimumCertificateKeySize = 1024,
+			};
+
+			// Build the application configuration
+			var configuration = new ApplicationConfiguration
+			{
+				ApplicationName = OpcUaName,
+				ApplicationType = ApplicationType.Client,
+				CertificateValidator = certificateValidator,
+				ApplicationUri = "urn:MyClient", //Kepp this syntax
+				ProductUri = "OpcUaClient",
+
+				ServerConfiguration = new ServerConfiguration
+				{
+					MaxSubscriptionCount = 100000,
+					MaxMessageQueueSize = 1000000,
+					MaxNotificationQueueSize = 1000000,
+					MaxPublishRequestCount = 10000000,
+				},
+
+				SecurityConfiguration = new SecurityConfiguration
+				{
+					AutoAcceptUntrustedCertificates = true,
+					RejectSHA1SignedCertificates = false,
+					MinimumCertificateKeySize = 1024,
+					SuppressNonceValidationErrors = true,
+
+					ApplicationCertificate = new CertificateIdentifier
+					{
+						StoreType = CertificateStoreType.X509Store,
+						StorePath = "CurrentUser\\My",
+						SubjectName = OpcUaName,
+					},
+					TrustedIssuerCertificates = new CertificateTrustList
+					{
+						StoreType = CertificateStoreType.X509Store,
+						StorePath = "CurrentUser\\Root",
+					},
+					TrustedPeerCertificates = new CertificateTrustList
+					{
+						StoreType = CertificateStoreType.X509Store,
+						StorePath = "CurrentUser\\Root",
+					}
+				},
+
+				TransportQuotas = new TransportQuotas
+				{
+					OperationTimeout = 6000000,
+					MaxStringLength = int.MaxValue,
+					MaxByteStringLength = int.MaxValue,
+					MaxArrayLength = 65535,
+					MaxMessageSize = 419430400,
+					MaxBufferSize = 65535,
+					ChannelLifetime = -1,
+					SecurityTokenLifetime = TcpMessageLimits.DefaultSecurityTokenLifeTime
+				},
+				ClientConfiguration = new ClientConfiguration
+				{
+					DefaultSessionTimeout = -1,
+					MinSubscriptionLifetime = -1,
+				},
+				DisableHiResClock = true
+			};
+
+			configuration.Validate( ApplicationType.Client );
+			m_configuration = configuration;
+		}
+
+		#endregion Constructor
+
+		#region Connect And Disconnect
+
+		/// <summary>
+		/// connect to server
+		/// </summary>
+		/// <param name="serverUrl">remote url</param>
+		public async Task ConnectServer( string serverUrl )
+		{
+			m_session = await Connect( serverUrl );
+		}
+
+		/// <summary>
+		/// Creates a new session.
+		/// </summary>
+		/// <returns>The new session object.</returns>
+		private async Task<ISession> Connect( string serverUrl )
+		{
+			// disconnect from existing session.
+			Disconnect( );
+
+			if (m_configuration == null)
+			{
+				throw new ArgumentNullException( "_configuration" );
+			}
+
+			// select the best endpoint.
+			EndpointDescription endpointDescription = await CoreClientUtils.SelectEndpointAsync( m_configuration, serverUrl, UseSecurity, null );
+			EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create( m_configuration );
+
+			ConfiguredEndpoint endpoint = new ConfiguredEndpoint( null, endpointDescription, endpointConfiguration );
+
+			m_session = await Opc.Ua.Client.Session.Create(
+				m_configuration,
+				endpoint,
+				false,
+				false,
+				(string.IsNullOrEmpty( OpcUaName )) ? m_configuration.ApplicationName : OpcUaName,
+				60000,
+				UserIdentity,
+				new string[] { } );
+
+			// set up keep alive callback.
+			m_session.KeepAlive += new KeepAliveEventHandler( Session_KeepAlive );
+
+			// update the client status
+			m_IsConnected = true;
+
+			// raise an event.
+			DoConnectComplete( null );
+
+			// return the new session.
+			return m_session;
+		}
+
+		/// <summary>
+		/// Disconnects from the server.
+		/// </summary>
+		public void Disconnect( )
+		{
+			UpdateStatus( false, DateTime.UtcNow, "Disconnected" );
+
+			// stop any reconnect operation.
+			if (m_reConnectHandler != null)
+			{
+				m_reConnectHandler.Dispose( );
+				m_reConnectHandler = null;
+			}
+
+			// disconnect any existing session.
+			if (m_session != null)
+			{
+				m_session.Close( 3000 );
+				m_session.Dispose( );
+				m_session = null;
+			}
+
+			// update the client status
+			m_IsConnected = false;
+
+			// raise an event.
+			DoConnectComplete( null );
+		}
+
+		#endregion Connect And Disconnect
+
+		#region Event Handlers
+
+		/// <summary>
+		/// Report the client status
+		/// </summary>
+		/// <param name="error">Whether the status represents an error.</param>
+		/// <param name="time">The time associated with the status.</param>
+		/// <param name="status">The status message.</param>
+		/// <param name="args">Arguments used to format the status message.</param>
+		private void UpdateStatus( bool error, DateTime time, string status, params object[] args )
+		{
+			m_OpcStatusChange?.Invoke( this, new OpcUaStatusEventArgs( )
+			{
+				Error = error,
+				Time = time.ToLocalTime( ),
+				Text = String.Format( status, args ),
+			} );
+		}
+
+		/// <summary>
+		/// Handles a keep alive event from a session.
+		/// </summary>
+		private void Session_KeepAlive( ISession session, KeepAliveEventArgs e )
+		{
+			try
+			{
+				// check for events from discarded sessions.
+				if (!Object.ReferenceEquals( session, m_session ))
+				{
+					return;
+				}
+
+				// start reconnect sequence on communication error.
+				if (ServiceResult.IsBad( e.Status ))
+				{
+					if (m_reconnectPeriod <= 0)
+					{
+						UpdateStatus( true, e.CurrentTime, "Communication Error ({0})", e.Status );
+						return;
+					}
+
+					UpdateStatus( true, e.CurrentTime, "Reconnecting in {0}s", m_reconnectPeriod );
+
+					if (m_reConnectHandler == null)
+					{
+						m_ReconnectStarting?.Invoke( this, e );
+
+						m_reConnectHandler = new SessionReconnectHandler( );
+						m_reConnectHandler.BeginReconnect( m_session, m_reconnectPeriod * 1000, Server_ReconnectComplete );
+					}
+
+					return;
+				}
+
+				// update status.
+				UpdateStatus( false, e.CurrentTime, "Connected [{0}]", session.Endpoint.EndpointUrl );
+
+				// raise any additional notifications.
+				m_KeepAliveComplete?.Invoke( this, e );
+			}
+			catch (Exception exception)
+			{
+#if !NETSTANDARD2_0 && !NETSTANDARD2_1
+				ClientUtils.HandleException( OpcUaName, exception );
+#else
+				throw;
+#endif
+			}
+		}
+
+		/// <summary>
+		/// Handles a reconnect event complete from the reconnect handler.
+		/// </summary>
+		private void Server_ReconnectComplete( object sender, EventArgs e )
+		{
+			try
+			{
+				// ignore callbacks from discarded objects.
+				if (!Object.ReferenceEquals( sender, m_reConnectHandler ))
+				{
+					return;
+				}
+
+				m_session = m_reConnectHandler.Session;
+				m_reConnectHandler.Dispose( );
+				m_reConnectHandler = null;
+
+				// raise any additional notifications.
+				m_ReconnectComplete?.Invoke( this, e );
+			}
+			catch (Exception exception)
+			{
+#if !NETSTANDARD2_0 && !NETSTANDARD2_1
+				ClientUtils.HandleException( OpcUaName, exception );
+#else
+				throw;
+#endif
+			}
+		}
+
+		#endregion Event Handlers
+
+		#region LogOut Setting
+
+		/// <summary>
+		/// 设置OPC客户端的日志输出
+		/// </summary>
+		/// <param name="filePath">完整的文件路径</param>
+		/// <param name="deleteExisting">是否删除原文件</param>
+		public void SetLogPathName( string filePath, bool deleteExisting )
+		{
+			Utils.SetTraceLog( filePath, deleteExisting );
+			Utils.SetTraceMask( 515 );
+		}
+
+		#endregion LogOut Setting
+
+		#region Public Members
+
+		/// <summary>
+		/// a name of application name show on server
+		/// </summary>
+		public string OpcUaName { get; set; } = "Opc Ua Helper";
+
+		/// <summary>
+		/// Whether to use security when connecting.
+		/// </summary>
+		public bool UseSecurity
+		{
+			get { return m_useSecurity; }
+			set { m_useSecurity = value; }
+		}
+
+		/// <summary>
+		/// The user identity to use when creating the session.
+		/// </summary>
+		public IUserIdentity UserIdentity { get; set; }
+
+		/// <summary>
+		/// The currently active session.
+		/// </summary>
+		public ISession Session
+		{
+			get { return m_session; }
+		}
+
+		/// <summary>
+		/// Indicate the connect status
+		/// </summary>
+		public bool Connected
+		{
+			get { return m_IsConnected; }
+		}
+
+		/// <summary>
+		/// The number of seconds between reconnect attempts (0 means reconnect is disabled).
+		/// </summary>
+		public int ReconnectPeriod
+		{
+			get { return m_reconnectPeriod; }
+			set { m_reconnectPeriod = value; }
+		}
+
+		/// <summary>
+		/// Raised when a good keep alive from the server arrives.
+		/// </summary>
+		public event EventHandler KeepAliveComplete
+		{
+			add { m_KeepAliveComplete += value; }
+			remove { m_KeepAliveComplete -= value; }
+		}
+
+		/// <summary>
+		/// Raised when a reconnect operation starts.
+		/// </summary>
+		public event EventHandler ReconnectStarting
+		{
+			add { m_ReconnectStarting += value; }
+			remove { m_ReconnectStarting -= value; }
+		}
+
+		/// <summary>
+		/// Raised when a reconnect operation completes.
+		/// </summary>
+		public event EventHandler ReconnectComplete
+		{
+			add { m_ReconnectComplete += value; }
+			remove { m_ReconnectComplete -= value; }
+		}
+
+		/// <summary>
+		/// Raised after successfully connecting to or disconnecing from a server.
+		/// </summary>
+		public event EventHandler ConnectComplete
+		{
+			add { m_ConnectComplete += value; }
+			remove { m_ConnectComplete -= value; }
+		}
+
+		/// <summary>
+		/// Raised after the client status change
+		/// </summary>
+		public event EventHandler<OpcUaStatusEventArgs> OpcStatusChange
+		{
+			add { m_OpcStatusChange += value; }
+			remove { m_OpcStatusChange -= value; }
+		}
+
+		/// <summary>
+		/// 配置信息
+		/// </summary>
+		public ApplicationConfiguration AppConfig => m_configuration;
+
+		#endregion Public Members
+
+		#region Node Write/Read Support
+
+		/// <summary>
+		/// Read a value node from server
+		/// </summary>
+		/// <param name="nodeId">node id</param>
+		/// <returns>DataValue</returns>
+		public DataValue ReadNode( NodeId nodeId )
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection
+			{
+				new ReadValueId( )
+				{
+					NodeId = nodeId,
+					AttributeId = Attributes.Value
+				}
+			};
+
+			// read the current value
+			m_session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out DataValueCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			return results[0];
+		}
+
+		/// <summary>
+		/// Read a value node from server
+		/// </summary>
+		/// <typeparam name="T">type of value</typeparam>
+		/// <param name="tag">node id</param>
+		/// <returns>实际值</returns>
+		public T ReadNode<T>( string tag )
+		{
+			DataValue dataValue = ReadNode( new NodeId( tag ) );
+			return (T)dataValue.Value;
+		}
+
+		/// <summary>
+		/// Read a tag asynchronously
+		/// </summary>
+		/// <typeparam name="T">The type of tag to read</typeparam>
+		/// <param name="tag">tag值</param>
+		/// <returns>The value retrieved from the OPC</returns>
+		public Task<T> ReadNodeAsync<T>( string tag )
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection
+			{
+				new ReadValueId()
+				{
+					NodeId = new NodeId(tag),
+					AttributeId = Attributes.Value
+				}
+			};
+
+			// Wrap the ReadAsync logic in a TaskCompletionSource, so we can use C# async/await syntax to call it:
+			var taskCompletionSource = new TaskCompletionSource<T>( );
+			m_session.BeginRead(
+				requestHeader: null,
+				maxAge: 0,
+				timestampsToReturn: TimestampsToReturn.Neither,
+				nodesToRead: nodesToRead,
+				callback: ar =>
+				{
+					DataValueCollection results;
+					DiagnosticInfoCollection diag;
+					var response = m_session.EndRead(
+					  result: ar,
+					  results: out results,
+					  diagnosticInfos: out diag );
+
+					try
+					{
+						CheckReturnValue( response.ServiceResult );
+						CheckReturnValue( results[0].StatusCode );
+						var val = results[0];
+						taskCompletionSource.TrySetResult( (T)val.Value );
+					}
+					catch (Exception ex)
+					{
+						taskCompletionSource.TrySetException( ex );
+					}
+				},
+				asyncState: null );
+
+			return taskCompletionSource.Task;
+		}
+
+		/// <summary>
+		/// read several value nodes from server
+		/// </summary>
+		/// <param name="nodeIds">all NodeIds</param>
+		/// <returns>all values</returns>
+		public List<DataValue> ReadNodes( NodeId[] nodeIds )
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+			for (int i = 0; i < nodeIds.Length; i++)
+			{
+				nodesToRead.Add( new ReadValueId( )
+				{
+					NodeId = nodeIds[i],
+					AttributeId = Attributes.Value
+				} );
+			}
+
+			// 读取当前的值
+			m_session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out DataValueCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			return results.ToList( );
+		}
+
+		/// <summary>
+		/// read several value nodes from server
+		/// </summary>
+		/// <param name="nodeIds">all NodeIds</param>
+		/// <returns>all values</returns>
+		public Task<List<DataValue>> ReadNodesAsync( NodeId[] nodeIds )
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+			for (int i = 0; i < nodeIds.Length; i++)
+			{
+				nodesToRead.Add( new ReadValueId( )
+				{
+					NodeId = nodeIds[i],
+					AttributeId = Attributes.Value
+				} );
+			}
+
+			var taskCompletionSource = new TaskCompletionSource<List<DataValue>>( );
+			// 读取当前的值
+			m_session.BeginRead(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				callback: ar =>
+				{
+					DataValueCollection results;
+					DiagnosticInfoCollection diag;
+					var response = m_session.EndRead(
+					  result: ar,
+					  results: out results,
+					  diagnosticInfos: out diag );
+
+					try
+					{
+						CheckReturnValue( response.ServiceResult );
+						taskCompletionSource.TrySetResult( results.ToList( ) );
+					}
+					catch (Exception ex)
+					{
+						taskCompletionSource.TrySetException( ex );
+					}
+				},
+				asyncState: null );
+
+			return taskCompletionSource.Task;
+		}
+
+		/// <summary>
+		/// read several value nodes from server
+		/// </summary>
+		/// <param name="tags">所以的节点数组信息</param>
+		/// <returns>all values</returns>
+		public List<T> ReadNodes<T>( string[] tags )
+		{
+			List<T> result = new List<T>( );
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+			for (int i = 0; i < tags.Length; i++)
+			{
+				nodesToRead.Add( new ReadValueId( )
+				{
+					NodeId = new NodeId( tags[i] ),
+					AttributeId = Attributes.Value
+				} );
+			}
+
+			// 读取当前的值
+			m_session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out DataValueCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			foreach (var item in results)
+			{
+				result.Add( (T)item.Value );
+			}
+			return result;
+		}
+
+		/// <summary>
+		/// read several value nodes from server
+		/// </summary>
+		/// <param name="tags">all NodeIds</param>
+		/// <returns>all values</returns>
+		public Task<List<T>> ReadNodesAsync<T>( string[] tags )
+		{
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+			for (int i = 0; i < tags.Length; i++)
+			{
+				nodesToRead.Add( new ReadValueId( )
+				{
+					NodeId = new NodeId( tags[i] ),
+					AttributeId = Attributes.Value
+				} );
+			}
+
+			var taskCompletionSource = new TaskCompletionSource<List<T>>( );
+			// 读取当前的值
+			m_session.BeginRead(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				callback: ar =>
+				{
+					DataValueCollection results;
+					DiagnosticInfoCollection diag;
+					var response = m_session.EndRead(
+					  result: ar,
+					  results: out results,
+					  diagnosticInfos: out diag );
+
+					try
+					{
+						CheckReturnValue( response.ServiceResult );
+						List<T> result = new List<T>( );
+						foreach (var item in results)
+						{
+							result.Add( (T)item.Value );
+						}
+						taskCompletionSource.TrySetResult( result );
+					}
+					catch (Exception ex)
+					{
+						taskCompletionSource.TrySetException( ex );
+					}
+				},
+				asyncState: null );
+
+			return taskCompletionSource.Task;
+		}
+
+		/// <summary>
+		/// write a note to server(you should use try catch)
+		/// </summary>
+		/// <typeparam name="T">The type of tag to write on</typeparam>
+		/// <param name="tag">节点名称</param>
+		/// <param name="value">值</param>
+		/// <returns>if success True,otherwise False</returns>
+		public bool WriteNode<T>( string tag, T value )
+		{
+			WriteValue valueToWrite = new WriteValue( )
+			{
+				NodeId = new NodeId( tag ),
+				AttributeId = Attributes.Value
+			};
+			valueToWrite.Value.Value = value;
+			valueToWrite.Value.StatusCode = StatusCodes.Good;
+			valueToWrite.Value.ServerTimestamp = DateTime.MinValue;
+			valueToWrite.Value.SourceTimestamp = DateTime.MinValue;
+
+			WriteValueCollection valuesToWrite = new WriteValueCollection
+			{
+				valueToWrite
+			};
+
+			// 写入当前的值
+
+			m_session.Write(
+				null,
+				valuesToWrite,
+				out StatusCodeCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, valuesToWrite );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, valuesToWrite );
+
+			if (StatusCode.IsBad( results[0] ))
+			{
+				throw new ServiceResultException( results[0] );
+			}
+
+			return !StatusCode.IsBad( results[0] );
+		}
+
+		/// <summary>
+		/// Write a value on the specified opc tag asynchronously
+		/// </summary>
+		/// <typeparam name="T">The type of tag to write on</typeparam>
+		/// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name. E.g: the tag `foo.bar` writes on the tag `bar` on the folder `foo`</param>
+		/// <param name="value">The value for the item to write</param>
+		public Task<bool> WriteNodeAsync<T>( string tag, T value )
+		{
+			WriteValue valueToWrite = new WriteValue( )
+			{
+				NodeId = new NodeId( tag ),
+				AttributeId = Attributes.Value,
+			};
+			valueToWrite.Value.Value = value;
+			valueToWrite.Value.StatusCode = StatusCodes.Good;
+			valueToWrite.Value.ServerTimestamp = DateTime.MinValue;
+			valueToWrite.Value.SourceTimestamp = DateTime.MinValue;
+			WriteValueCollection valuesToWrite = new WriteValueCollection
+			{
+				valueToWrite
+			};
+
+			// Wrap the WriteAsync logic in a TaskCompletionSource, so we can use C# async/await syntax to call it:
+			var taskCompletionSource = new TaskCompletionSource<bool>( );
+			m_session.BeginWrite(
+				requestHeader: null,
+				nodesToWrite: valuesToWrite,
+				callback: ar =>
+				{
+					var response = m_session.EndWrite(
+					  result: ar,
+					  results: out StatusCodeCollection results,
+					  diagnosticInfos: out DiagnosticInfoCollection diag );
+
+					try
+					{
+						ClientBase.ValidateResponse( results, valuesToWrite );
+						ClientBase.ValidateDiagnosticInfos( diag, valuesToWrite );
+						taskCompletionSource.SetResult( StatusCode.IsGood( results[0] ) );
+					}
+					catch (Exception ex)
+					{
+						taskCompletionSource.TrySetException( ex );
+					}
+				},
+				asyncState: null );
+			return taskCompletionSource.Task;
+		}
+
+		/// <summary>
+		/// 所有的节点都写入成功,返回<c>True</c>,否则返回<c>False</c>
+		/// </summary>
+		/// <param name="tags">节点名称数组</param>
+		/// <param name="values">节点的值数据</param>
+		/// <returns>所有的是否都写入成功</returns>
+		public bool WriteNodes( string[] tags, object[] values )
+		{
+			WriteValueCollection valuesToWrite = new WriteValueCollection( );
+
+			for (int i = 0; i < tags.Length; i++)
+			{
+				if (i < values.Length)
+				{
+					WriteValue valueToWrite = new WriteValue( )
+					{
+						NodeId = new NodeId( tags[i] ),
+						AttributeId = Attributes.Value
+					};
+					valueToWrite.Value.Value = values[i];
+					valueToWrite.Value.StatusCode = StatusCodes.Good;
+					valueToWrite.Value.ServerTimestamp = DateTime.MinValue;
+					valueToWrite.Value.SourceTimestamp = DateTime.MinValue;
+					valuesToWrite.Add( valueToWrite );
+				}
+			}
+
+			// 写入当前的值
+
+			m_session.Write(
+				null,
+				valuesToWrite,
+				out StatusCodeCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, valuesToWrite );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, valuesToWrite );
+
+			bool result = true;
+			foreach (var r in results)
+			{
+				if (StatusCode.IsBad( r ))
+				{
+					result = false;
+					break;
+				}
+			}
+
+			return result;
+		}
+
+		#endregion Node Write/Read Support
+
+		#region DeleteNode Support
+
+		/// <summary>
+		/// 删除一个节点的操作,除非服务器配置允许,否则引发异常,成功返回<c>True</c>,否则返回<c>False</c>
+		/// </summary>
+		/// <param name="tag">节点文本描述</param>
+		/// <returns>是否删除成功</returns>
+		public bool DeleteExsistNode( string tag )
+		{
+			DeleteNodesItemCollection waitDelete = new DeleteNodesItemCollection( );
+
+			DeleteNodesItem nodesItem = new DeleteNodesItem( )
+			{
+				NodeId = new NodeId( tag ),
+			};
+
+			m_session.DeleteNodes(
+				null,
+				waitDelete,
+				out StatusCodeCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, waitDelete );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, waitDelete );
+
+			return !StatusCode.IsBad( results[0] );
+		}
+
+		#endregion DeleteNode Support
+
+		#region Test Function
+
+		/// <summary>
+		/// 新增一个节点数据
+		/// </summary>
+		/// <param name="parent">父节点tag名称</param>
+		[Obsolete( "还未经过测试,无法使用" )]
+		public void AddNewNode( NodeId parent )
+		{
+			// Create a Variable node.
+			AddNodesItem node2 = new AddNodesItem( );
+			node2.ParentNodeId = new NodeId( parent );
+			node2.ReferenceTypeId = ReferenceTypes.HasComponent;
+			node2.RequestedNewNodeId = null;
+			node2.BrowseName = new QualifiedName( "DataVariable1" );
+			node2.NodeClass = NodeClass.Variable;
+			node2.NodeAttributes = null;
+			node2.TypeDefinition = VariableTypeIds.BaseDataVariableType;
+
+			//specify node attributes.
+			VariableAttributes node2Attribtues = new VariableAttributes( );
+			node2Attribtues.DisplayName = "DataVariable1";
+			node2Attribtues.Description = "DataVariable1 Description";
+			node2Attribtues.Value = new Variant( 123 );
+			node2Attribtues.DataType = (uint)BuiltInType.Int32;
+			node2Attribtues.ValueRank = ValueRanks.Scalar;
+			node2Attribtues.ArrayDimensions = new UInt32Collection( );
+			node2Attribtues.AccessLevel = AccessLevels.CurrentReadOrWrite;
+			node2Attribtues.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
+			node2Attribtues.MinimumSamplingInterval = 0;
+			node2Attribtues.Historizing = false;
+			node2Attribtues.WriteMask = (uint)AttributeWriteMask.None;
+			node2Attribtues.UserWriteMask = (uint)AttributeWriteMask.None;
+			node2Attribtues.SpecifiedAttributes = (uint)NodeAttributesMask.All;
+
+			node2.NodeAttributes = new ExtensionObject( node2Attribtues );
+
+			AddNodesItemCollection nodesToAdd = new AddNodesItemCollection { node2 };
+
+			m_session.AddNodes(
+				null,
+				nodesToAdd,
+				out AddNodesResultCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToAdd );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToAdd );
+		}
+
+		#endregion Test Function
+
+		#region Monitor Support
+
+		/// <summary>
+		/// 新增一个订阅,需要指定订阅的关键字,订阅的tag名,以及回调方法
+		/// </summary>
+		/// <param name="key">关键字</param>
+		/// <param name="tag">tag</param>
+		/// <param name="callback">回调方法</param>
+		public void AddSubscription( string key, string tag, Action<string, MonitoredItem, MonitoredItemNotificationEventArgs> callback )
+		{
+			AddSubscription( key, new string[] { tag }, callback );
+		}
+
+		/// <inheritdoc cref="AddSubscription(string, string[], Action{string, MonitoredItem, MonitoredItemNotificationEventArgs}, Action{Subscription})"/>
+		public void AddSubscription( string key, string[] tags, Action<string, MonitoredItem, MonitoredItemNotificationEventArgs> callback )
+		{
+			AddSubscription( key, tags, callback, null );
+		}
+
+		/// <summary>
+		/// 新增一批订阅,需要指定订阅的关键字,订阅的tag名数组,以及回调方法
+		/// </summary>
+		/// <param name="key">关键字</param>
+		/// <param name="tags">节点名称数组</param>
+		/// <param name="callback">回调方法</param>
+		/// <param name="subAction">关于订阅参数的自定义的设置</param>
+		public void AddSubscription( string key, string[] tags, Action<string, MonitoredItem, MonitoredItemNotificationEventArgs> callback, Action<Subscription> subAction )
+		{
+			Subscription m_subscription = new Subscription( m_session.DefaultSubscription );
+			m_subscription.PublishingEnabled = true;
+			m_subscription.PublishingInterval = 0;
+			m_subscription.KeepAliveCount = ushort.MaxValue;
+			m_subscription.LifetimeCount = 2400;
+			m_subscription.MaxNotificationsPerPublish = ushort.MaxValue;
+			m_subscription.Priority = 100;
+			m_subscription.DisplayName = key;
+			subAction?.Invoke( m_subscription );
+
+			for (int i = 0; i < tags.Length; i++)
+			{
+				var item = new MonitoredItem
+				{
+					StartNodeId = new NodeId( tags[i] ),
+					AttributeId = Attributes.Value,
+					DisplayName = tags[i],
+					SamplingInterval = 100,
+				};
+				item.Notification += ( MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args ) =>
+				{
+					callback?.Invoke( key, monitoredItem, args );
+				};
+				m_subscription.AddItem( item );
+			}
+
+			m_session.AddSubscription( m_subscription );
+			m_subscription.Create( );
+
+			lock (dic_subscriptions)
+			{
+				if (dic_subscriptions.ContainsKey( key ))
+				{
+					// remove
+					dic_subscriptions[key].Delete( true );
+					m_session.RemoveSubscription( dic_subscriptions[key] );
+					dic_subscriptions[key].Dispose( );
+					dic_subscriptions[key] = m_subscription;
+				}
+				else
+				{
+					dic_subscriptions.Add( key, m_subscription );
+				}
+			}
+		}
+
+		/// <summary>
+		/// 移除订阅消息,如果该订阅消息是批量的,也直接移除
+		/// </summary>
+		/// <param name="key">订阅关键值</param>
+		public void RemoveSubscription( string key )
+		{
+			lock (dic_subscriptions)
+			{
+				if (dic_subscriptions.ContainsKey( key ))
+				{
+					// remove
+					dic_subscriptions[key].Delete( true );
+					m_session.RemoveSubscription( dic_subscriptions[key] );
+					dic_subscriptions[key].Dispose( );
+					dic_subscriptions.Remove( key );
+				}
+			}
+		}
+
+		/// <summary>
+		/// 移除所有的订阅消息
+		/// </summary>
+		public void RemoveAllSubscription( )
+		{
+			lock (dic_subscriptions)
+			{
+				foreach (var item in dic_subscriptions)
+				{
+					item.Value.Delete( true );
+					m_session.RemoveSubscription( item.Value );
+					item.Value.Dispose( );
+				}
+				dic_subscriptions.Clear( );
+			}
+		}
+
+		#endregion Monitor Support
+
+		#region ReadHistory Support
+
+		/// <summary>
+		/// read History data
+		/// </summary>
+		/// <param name="tag">节点的索引</param>
+		/// <param name="start">开始时间</param>
+		/// <param name="end">结束时间</param>
+		/// <param name="count">读取的个数</param>
+		/// <param name="containBound">是否包含边界</param>
+		/// <returns>读取的数据列表</returns>
+		public IEnumerable<DataValue> ReadHistoryRawDataValues( string tag, DateTime start, DateTime end, uint count = 1, bool containBound = false )
+		{
+			HistoryReadValueId m_nodeToContinue = new HistoryReadValueId( )
+			{
+				NodeId = new NodeId( tag ),
+			};
+
+			ReadRawModifiedDetails m_details = new ReadRawModifiedDetails
+			{
+				StartTime = start,
+				EndTime = end,
+				NumValuesPerNode = count,
+				IsReadModified = false,
+				ReturnBounds = containBound
+			};
+
+			HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection( );
+			nodesToRead.Add( m_nodeToContinue );
+
+			m_session.HistoryRead(
+				null,
+				new ExtensionObject( m_details ),
+				TimestampsToReturn.Both,
+				false,
+				nodesToRead,
+				out HistoryReadResultCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			if (StatusCode.IsBad( results[0].StatusCode ))
+			{
+				throw new ServiceResultException( results[0].StatusCode );
+			}
+
+			HistoryData values = ExtensionObject.ToEncodeable( results[0].HistoryData ) as HistoryData;
+			foreach (var value in values.DataValues)
+			{
+				yield return value;
+			}
+		}
+
+		/// <summary>
+		/// 读取一连串的历史数据,并将其转化成指定的类型
+		/// </summary>
+		/// <param name="tag">节点的索引</param>
+		/// <param name="start">开始时间</param>
+		/// <param name="end">结束时间</param>
+		/// <param name="count">读取的个数</param>
+		/// <param name="containBound">是否包含边界</param>
+		/// <returns>读取的数据列表</returns>
+		public IEnumerable<T> ReadHistoryRawDataValues<T>( string tag, DateTime start, DateTime end, uint count = 1, bool containBound = false )
+		{
+			HistoryReadValueId m_nodeToContinue = new HistoryReadValueId( )
+			{
+				NodeId = new NodeId( tag ),
+			};
+
+			ReadRawModifiedDetails m_details = new ReadRawModifiedDetails
+			{
+				StartTime = start.ToUniversalTime( ),
+				EndTime = end.ToUniversalTime( ),
+				NumValuesPerNode = count,
+				IsReadModified = false,
+				ReturnBounds = containBound
+			};
+
+			HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection( );
+			nodesToRead.Add( m_nodeToContinue );
+
+			m_session.HistoryRead(
+				null,
+				new ExtensionObject( m_details ),
+				TimestampsToReturn.Both,
+				false,
+				nodesToRead,
+				out HistoryReadResultCollection results,
+				out DiagnosticInfoCollection diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			if (StatusCode.IsBad( results[0].StatusCode ))
+			{
+				throw new ServiceResultException( results[0].StatusCode );
+			}
+
+			HistoryData values = ExtensionObject.ToEncodeable( results[0].HistoryData ) as HistoryData;
+			foreach (var value in values.DataValues)
+			{
+				yield return (T)value.Value;
+			}
+		}
+
+		#endregion ReadHistory Support
+
+		#region BrowseNode Support
+
+		/// <summary>
+		/// 浏览一个节点的引用
+		/// </summary>
+		/// <param name="tag">节点值</param>
+		/// <returns>引用节点描述</returns>
+		public ReferenceDescription[] BrowseNodeReference( string tag )
+		{
+			NodeId sourceId = new NodeId( tag );
+
+			// 该节点可以读取到方法
+			BrowseDescription nodeToBrowse1 = new BrowseDescription( );
+
+			nodeToBrowse1.NodeId = sourceId;
+			nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates;
+			nodeToBrowse1.IncludeSubtypes = true;
+			nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method);
+			nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
+
+			// 该节点无论怎么样都读取不到方法
+			// find all nodes organized by the node.
+			BrowseDescription nodeToBrowse2 = new BrowseDescription( );
+
+			nodeToBrowse2.NodeId = sourceId;
+			nodeToBrowse2.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse2.ReferenceTypeId = ReferenceTypeIds.Organizes;
+			nodeToBrowse2.IncludeSubtypes = true;
+			nodeToBrowse2.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable);
+			nodeToBrowse2.ResultMask = (uint)BrowseResultMask.All;
+
+			BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+			nodesToBrowse.Add( nodeToBrowse1 );
+			nodesToBrowse.Add( nodeToBrowse2 );
+
+			// fetch references from the server.
+			ReferenceDescriptionCollection references = FormUtils.Browse( m_session, nodesToBrowse, false );
+
+			return references.ToArray( );
+		}
+
+		#endregion BrowseNode Support
+
+		#region Read Attributes Support
+
+		/// <summary>
+		/// 读取一个节点的所有属性
+		/// </summary>
+		/// <param name="tag">节点信息</param>
+		/// <returns>节点的特性值</returns>
+		public OpcNodeAttribute[] ReadNoteAttributes( string tag )
+		{
+			NodeId sourceId = new NodeId( tag );
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+
+			// attempt to read all possible attributes.
+			// 尝试着去读取所有可能的特性
+			for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++)
+			{
+				ReadValueId nodeToRead = new ReadValueId( );
+				nodeToRead.NodeId = sourceId;
+				nodeToRead.AttributeId = ii;
+				nodesToRead.Add( nodeToRead );
+			}
+
+			int startOfProperties = nodesToRead.Count;
+
+			// find all of the pror of the node.
+			BrowseDescription nodeToBrowse1 = new BrowseDescription( );
+
+			nodeToBrowse1.NodeId = sourceId;
+			nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
+			nodeToBrowse1.IncludeSubtypes = true;
+			nodeToBrowse1.NodeClassMask = 0;
+			nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
+
+			BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+			nodesToBrowse.Add( nodeToBrowse1 );
+
+			// fetch property references from the server.
+			ReferenceDescriptionCollection references = FormUtils.Browse( m_session, nodesToBrowse, false );
+
+			if (references == null)
+			{
+				return new OpcNodeAttribute[0];
+			}
+
+			for (int ii = 0; ii < references.Count; ii++)
+			{
+				// ignore external references.
+				if (references[ii].NodeId.IsAbsolute)
+				{
+					continue;
+				}
+
+				ReadValueId nodeToRead = new ReadValueId( );
+				nodeToRead.NodeId = (NodeId)references[ii].NodeId;
+				nodeToRead.AttributeId = Attributes.Value;
+				nodesToRead.Add( nodeToRead );
+			}
+
+			// read all values.
+			DataValueCollection results = null;
+			DiagnosticInfoCollection diagnosticInfos = null;
+
+			m_session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out results,
+				out diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			// process results.
+
+			List<OpcNodeAttribute> nodeAttribute = new List<OpcNodeAttribute>( );
+			for (int ii = 0; ii < results.Count; ii++)
+			{
+				OpcNodeAttribute item = new OpcNodeAttribute( );
+
+				// process attribute value.
+				if (ii < startOfProperties)
+				{
+					// ignore attributes which are invalid for the node.
+					if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
+					{
+						continue;
+					}
+
+					// get the name of the attribute.
+					item.Name = Attributes.GetBrowseName( nodesToRead[ii].AttributeId );
+
+					// display any unexpected error.
+					if (StatusCode.IsBad( results[ii].StatusCode ))
+					{
+						item.Type = Utils.Format( "{0}", Attributes.GetDataTypeId( nodesToRead[ii].AttributeId ) );
+						item.Value = Utils.Format( "{0}", results[ii].StatusCode );
+					}
+
+					// display the value.
+					else
+					{
+						TypeInfo typeInfo = TypeInfo.Construct( results[ii].Value );
+
+						item.Type = typeInfo.BuiltInType.ToString( );
+
+						if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
+						{
+							item.Type += "[]";
+						}
+
+						item.Value = results[ii].Value;//Utils.Format("{0}", results[ii].Value);
+					}
+				}
+
+				// process property value.
+				else
+				{
+					// ignore properties which are invalid for the node.
+					if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown)
+					{
+						continue;
+					}
+
+					// get the name of the property.
+					item.Name = Utils.Format( "{0}", references[ii - startOfProperties] );
+
+					// display any unexpected error.
+					if (StatusCode.IsBad( results[ii].StatusCode ))
+					{
+						item.Type = String.Empty;
+						item.Value = Utils.Format( "{0}", results[ii].StatusCode );
+					}
+
+					// display the value.
+					else
+					{
+						TypeInfo typeInfo = TypeInfo.Construct( results[ii].Value );
+
+						item.Type = typeInfo.BuiltInType.ToString( );
+
+						if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
+						{
+							item.Type += "[]";
+						}
+
+						item.Value = results[ii].Value; //Utils.Format("{0}", results[ii].Value);
+					}
+				}
+
+				nodeAttribute.Add( item );
+			}
+
+			return nodeAttribute.ToArray( );
+		}
+
+		/// <summary>
+		/// 读取一个节点的所有属性
+		/// </summary>
+		/// <param name="tag">节点值</param>
+		/// <returns>所有的数据</returns>
+		public DataValue[] ReadNoteDataValueAttributes( string tag )
+		{
+			NodeId sourceId = new NodeId( tag );
+			ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );
+
+			// attempt to read all possible attributes.
+			// 尝试着去读取所有可能的特性
+			for (uint ii = Attributes.NodeId; ii <= Attributes.UserExecutable; ii++)
+			{
+				ReadValueId nodeToRead = new ReadValueId( );
+				nodeToRead.NodeId = sourceId;
+				nodeToRead.AttributeId = ii;
+				nodesToRead.Add( nodeToRead );
+			}
+
+			int startOfProperties = nodesToRead.Count;
+
+			// find all of the pror of the node.
+			BrowseDescription nodeToBrowse1 = new BrowseDescription( );
+
+			nodeToBrowse1.NodeId = sourceId;
+			nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
+			nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
+			nodeToBrowse1.IncludeSubtypes = true;
+			nodeToBrowse1.NodeClassMask = 0;
+			nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All;
+
+			BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );
+			nodesToBrowse.Add( nodeToBrowse1 );
+
+			// fetch property references from the server.
+			ReferenceDescriptionCollection references = FormUtils.Browse( m_session, nodesToBrowse, false );
+
+			if (references == null)
+			{
+				return new DataValue[0];
+			}
+
+			for (int ii = 0; ii < references.Count; ii++)
+			{
+				// ignore external references.
+				if (references[ii].NodeId.IsAbsolute)
+				{
+					continue;
+				}
+
+				ReadValueId nodeToRead = new ReadValueId( );
+				nodeToRead.NodeId = (NodeId)references[ii].NodeId;
+				nodeToRead.AttributeId = Attributes.Value;
+				nodesToRead.Add( nodeToRead );
+			}
+
+			// read all values.
+			DataValueCollection results = null;
+			DiagnosticInfoCollection diagnosticInfos = null;
+
+			m_session.Read(
+				null,
+				0,
+				TimestampsToReturn.Neither,
+				nodesToRead,
+				out results,
+				out diagnosticInfos );
+
+			ClientBase.ValidateResponse( results, nodesToRead );
+			ClientBase.ValidateDiagnosticInfos( diagnosticInfos, nodesToRead );
+
+			return results.ToArray( );
+		}
+
+		#endregion Read Attributes Support
+
+		#region Method Call Support
+
+		/// <summary>
+		/// call a server method
+		/// </summary>
+		/// <param name="tagParent">方法的父节点tag</param>
+		/// <param name="tag">方法的节点tag</param>
+		/// <param name="args">传递的参数</param>
+		/// <returns>输出的结果值</returns>
+		public object[] CallMethodByNodeId( string tagParent, string tag, params object[] args )
+		{
+			if (m_session == null)
+			{
+				return null;
+			}
+
+			IList<object> outputArguments = m_session.Call(
+				new NodeId( tagParent ),
+				new NodeId( tag ),
+				args );
+
+			return outputArguments.ToArray( );
+		}
+
+		#endregion Method Call Support
+
+		#region Private Methods
+
+		/// <summary>
+		/// Raises the connect complete event on the main GUI thread.
+		/// </summary>
+		private void DoConnectComplete( object state )
+		{
+			m_ConnectComplete?.Invoke( this, null );
+		}
+
+		private void CheckReturnValue( StatusCode status )
+		{
+			if (!StatusCode.IsGood( status ))
+				throw new Exception( string.Format( "Invalid response from the server. (Response Status: {0})", status ) );
+		}
+
+		#endregion Private Methods
+
+		#region Private Fields
+
+		private ApplicationConfiguration m_configuration;
+		private ISession m_session;
+		private bool m_IsConnected;                       //是否已经连接过
+		private int m_reconnectPeriod = 10;               // 重连状态
+		private bool m_useSecurity;
+
+		private SessionReconnectHandler m_reConnectHandler;
+		private EventHandler m_ReconnectComplete;
+		private EventHandler m_ReconnectStarting;
+		private EventHandler m_KeepAliveComplete;
+		private EventHandler m_ConnectComplete;
+		private EventHandler<OpcUaStatusEventArgs> m_OpcStatusChange;
+
+		private Dictionary<string, Subscription> dic_subscriptions;        // 系统所有的节点信息
+
+		#endregion Private Fields
+	}
+}

+ 191 - 0
OpcUaHelper/OpcUaHelper.csproj

@@ -0,0 +1,191 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{7693C6F9-3846-4310-B0F1-194874C5047D}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>OpcUaHelper</RootNamespace>
+    <AssemblyName>OpcUaHelper</AssemblyName>
+    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Debug\OpcUaHelper.xml</DocumentationFile>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Opc.Ua.Client, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Client.1.5.378.152\lib\net48\Opc.Ua.Client.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Configuration, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Configuration.1.5.378.152\lib\net48\Opc.Ua.Configuration.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Core, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Core.1.5.378.152\lib\net48\Opc.Ua.Core.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Types, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Types.1.5.378.152\lib\net48\Opc.Ua.Types.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Security.Certificates, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Security.Certificates.1.5.378.152\lib\net48\Opc.Ua.Security.Certificates.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Server, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Server.1.5.378.152\lib\net48\Opc.Ua.Server.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Gds.Client.Common, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Client.Common.1.5.378.152\lib\net48\Opc.Ua.Gds.Client.Common.dll</HintPath>
+    </Reference>
+    <Reference Include="Opc.Ua.Gds.Server.Common, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Server.Common.1.5.378.152\lib\net48\Opc.Ua.Gds.Server.Common.dll</HintPath>
+    </Reference>
+    <Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL">
+      <HintPath>..\packages\BouncyCastle.Cryptography.2.6.2\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Bcl.HashCode, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Bcl.HashCode.6.0.0\lib\netstandard2.0\Microsoft.Bcl.HashCode.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.10.0.8\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+      <HintPath>..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Diagnostics.DiagnosticSource, Version=10.0.0.8, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Diagnostics.DiagnosticSource.10.0.8\lib\net462\System.Diagnostics.DiagnosticSource.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Formats.Asn1, Version=10.0.0.8, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Formats.Asn1.10.0.8\lib\net462\System.Formats.Asn1.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Memory, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Memory.4.6.3\lib\net462\System.Memory.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Numerics.Vectors, Version=4.1.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Numerics.Vectors.4.6.1\lib\net462\System.Numerics.Vectors.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Windows.Forms" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="ClientUtils.cs" />
+    <Compile Include="Forms\DiscoverServerDlg.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="Forms\DiscoverServerDlg.designer.cs">
+      <DependentUpon>DiscoverServerDlg.cs</DependentUpon>
+    </Compile>
+    <Compile Include="ExceptionDlg.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="ExceptionDlg.designer.cs">
+      <DependentUpon>ExceptionDlg.cs</DependentUpon>
+    </Compile>
+    <Compile Include="FilterDeclaration.cs" />
+    <Compile Include="Forms\FormBrowseServer.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="Forms\FormBrowseServer.designer.cs">
+      <DependentUpon>FormBrowseServer.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Forms\FormConnectSelect.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="Forms\FormConnectSelect.Designer.cs">
+      <DependentUpon>FormConnectSelect.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Forms\TreeViewEx.cs">
+      <SubType>Component</SubType>
+    </Compile>
+    <Compile Include="OpcUaClient.cs" />
+    <Compile Include="OpcUaStatusEventArgs.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="FormUtils.cs" />
+    <Compile Include="Properties\Resources.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DesignTime>True</DesignTime>
+      <DependentUpon>Resources.resx</DependentUpon>
+    </Compile>
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="img\Activity_16xLG.png" />
+    <Content Include="img\brackets_Square_16xMD.png" />
+    <Content Include="img\ClassIcon.ico" />
+    <Content Include="img\ClassIcon.png" />
+    <Content Include="img\Class_489.png" />
+    <Content Include="img\Cloud_16xLG.png" />
+    <Content Include="img\Copy_6524.png" />
+    <Content Include="img\Delegate_8339.png" />
+    <Content Include="img\docview_xaml_on_16x16.png" />
+    <Content Include="img\Enum_582.png" />
+    <Content Include="img\Event_594.png" />
+    <Content Include="img\Event_594_exp.png" />
+    <Content Include="img\glasses_16xLG.png" />
+    <Content Include="img\grid_Data_16xLG.png" />
+    <Content Include="img\lightningBolt_16xLG.png" />
+    <Content Include="img\ListView_687.png" />
+    <Content Include="img\loading.gif" />
+    <Content Include="img\Method_636.png" />
+    <Content Include="img\Module_648.png" />
+    <Content Include="img\RegistryEditor_5838.ico" />
+    <Content Include="img\SingleMessage_5727.ico" />
+    <Content Include="img\Structure_507.png" />
+    <Content Include="img\Table_748.png" />
+    <Content Include="img\Tag_7213.png" />
+    <Content Include="img\usbcontroller.png" />
+    <Content Include="img\UserInterfaceEditor_5845.ico" />
+    <Content Include="img\VirtualMachine.png" />
+    <Content Include="img\WindowsForm_817.ico" />
+  </ItemGroup>
+  <ItemGroup>
+    <EmbeddedResource Include="Forms\DiscoverServerDlg.resx">
+      <DependentUpon>DiscoverServerDlg.cs</DependentUpon>
+    </EmbeddedResource>
+    <EmbeddedResource Include="ExceptionDlg.resx">
+      <DependentUpon>ExceptionDlg.cs</DependentUpon>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Forms\FormBrowseServer.resx">
+      <DependentUpon>FormBrowseServer.cs</DependentUpon>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Forms\FormConnectSelect.resx">
+      <DependentUpon>FormConnectSelect.cs</DependentUpon>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Properties\Resources.resx">
+      <Generator>ResXFileCodeGenerator</Generator>
+      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
+    </EmbeddedResource>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+</Project>

+ 61 - 0
OpcUaHelper/OpcUaStatusEventArgs.cs

@@ -0,0 +1,61 @@
+using Opc.Ua;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OpcUaHelper
+{
+	/// <summary>
+	/// OPC UA的状态更新消息
+	/// </summary>
+	public class OpcUaStatusEventArgs
+	{
+		/// <summary>
+		/// 是否异常
+		/// </summary>
+		public bool Error { get; set; }
+		/// <summary>
+		/// 时间
+		/// </summary>
+		public DateTime Time { get; set; }
+		/// <summary>
+		/// 文本
+		/// </summary>
+		public string Text { get; set; }
+
+		/// <summary>
+		/// 转化为字符串
+		/// </summary>
+		/// <returns></returns>
+		public override string ToString( )
+		{
+			return Error ? "[异常]" : "[正常]" + Time.ToString( "  yyyy-MM-dd HH:mm:ss  " ) + Text;
+		}
+	}
+
+	/// <summary>
+	/// 读取属性过程中用于描述的
+	/// </summary>
+	public class OpcNodeAttribute
+	{
+		/// <summary>
+		/// 属性的名称
+		/// </summary>
+		public string Name { get; set; }
+		/// <summary>
+		/// 属性的类型描述
+		/// </summary>
+		public string Type { get; set; }
+		/// <summary>
+		/// 操作结果状态描述
+		/// </summary>
+		public StatusCode StatusCode { get; set; }
+		/// <summary>
+		/// 属性的值,如果读取错误,返回文本描述
+		/// </summary>
+		public object Value { get; set; }
+
+	}
+}

+ 36 - 0
OpcUaHelper/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("OpcUaHelper")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("OpcUaHelper")]
+[assembly: AssemblyCopyright( "Copyright © Richard.Hu 2018 - 2025" )]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+[assembly: Guid("7693c6f9-3846-4310-b0f1-194874c5047d")]
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
+//通过使用 "*",如下所示:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion( "2.2.1.0" )]
+[assembly: AssemblyFileVersion( "2.2.1.0" )]

+ 293 - 0
OpcUaHelper/Properties/Resources.Designer.cs

@@ -0,0 +1,293 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     此代码由工具生成。
+//     运行时版本:4.0.30319.42000
+//
+//     对此文件的更改可能会导致不正确的行为,并且如果
+//     重新生成代码,这些更改将会丢失。
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace OpcUaHelper.Properties {
+    using System;
+    
+    
+    /// <summary>
+    ///   一个强类型的资源类,用于查找本地化的字符串等。
+    /// </summary>
+    // 此类是由 StronglyTypedResourceBuilder
+    // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
+    // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
+    // (以 /str 作为命令选项),或重新生成 VS 项目。
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
+    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    internal class Resources {
+        
+        private static global::System.Resources.ResourceManager resourceMan;
+        
+        private static global::System.Globalization.CultureInfo resourceCulture;
+        
+        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+        internal Resources() {
+        }
+        
+        /// <summary>
+        ///   返回此类使用的缓存的 ResourceManager 实例。
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Resources.ResourceManager ResourceManager {
+            get {
+                if (object.ReferenceEquals(resourceMan, null)) {
+                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpcUaHelper.Properties.Resources", typeof(Resources).Assembly);
+                    resourceMan = temp;
+                }
+                return resourceMan;
+            }
+        }
+        
+        /// <summary>
+        ///   重写当前线程的 CurrentUICulture 属性
+        ///   重写当前线程的 CurrentUICulture 属性。
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Globalization.CultureInfo Culture {
+            get {
+                return resourceCulture;
+            }
+            set {
+                resourceCulture = value;
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Activity_16xLG {
+            get {
+                object obj = ResourceManager.GetObject("Activity_16xLG", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap brackets_Square_16xMD {
+            get {
+                object obj = ResourceManager.GetObject("brackets_Square_16xMD", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Class_489 {
+            get {
+                object obj = ResourceManager.GetObject("Class_489", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap ClassIcon {
+            get {
+                object obj = ResourceManager.GetObject("ClassIcon", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Cloud_16xLG {
+            get {
+                object obj = ResourceManager.GetObject("Cloud_16xLG", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Copy_6524 {
+            get {
+                object obj = ResourceManager.GetObject("Copy_6524", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Delegate_8339 {
+            get {
+                object obj = ResourceManager.GetObject("Delegate_8339", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap docview_xaml_on_16x16 {
+            get {
+                object obj = ResourceManager.GetObject("docview_xaml_on_16x16", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Enum_582 {
+            get {
+                object obj = ResourceManager.GetObject("Enum_582", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Event_594 {
+            get {
+                object obj = ResourceManager.GetObject("Event_594", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Event_594_exp {
+            get {
+                object obj = ResourceManager.GetObject("Event_594_exp", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap glasses_16xLG {
+            get {
+                object obj = ResourceManager.GetObject("glasses_16xLG", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap grid_Data_16xLG {
+            get {
+                object obj = ResourceManager.GetObject("grid_Data_16xLG", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap lightningBolt_16xLG {
+            get {
+                object obj = ResourceManager.GetObject("lightningBolt_16xLG", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap ListView_687 {
+            get {
+                object obj = ResourceManager.GetObject("ListView_687", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap loading {
+            get {
+                object obj = ResourceManager.GetObject("loading", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Method_636 {
+            get {
+                object obj = ResourceManager.GetObject("Method_636", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Module_648 {
+            get {
+                object obj = ResourceManager.GetObject("Module_648", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Structure_507 {
+            get {
+                object obj = ResourceManager.GetObject("Structure_507", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Table_748 {
+            get {
+                object obj = ResourceManager.GetObject("Table_748", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap Tag_7213 {
+            get {
+                object obj = ResourceManager.GetObject("Tag_7213", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap usbcontroller {
+            get {
+                object obj = ResourceManager.GetObject("usbcontroller", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+        
+        /// <summary>
+        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
+        /// </summary>
+        internal static System.Drawing.Bitmap VirtualMachine {
+            get {
+                object obj = ResourceManager.GetObject("VirtualMachine", resourceCulture);
+                return ((System.Drawing.Bitmap)(obj));
+            }
+        }
+    }
+}

+ 190 - 0
OpcUaHelper/Properties/Resources.resx

@@ -0,0 +1,190 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" use="required" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+              <xsd:attribute ref="xml:space" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+  <data name="Enum_582" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Enum_582.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="docview_xaml_on_16x16" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\docview_xaml_on_16x16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Copy_6524" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Copy_6524.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="glasses_16xLG" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\glasses_16xLG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="grid_Data_16xLG" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\grid_Data_16xLG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="lightningBolt_16xLG" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\lightningBolt_16xLG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="ListView_687" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\ListView_687.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Event_594" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Event_594.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Event_594_exp" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Event_594_exp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Delegate_8339" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Delegate_8339.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="brackets_Square_16xMD" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\brackets_Square_16xMD.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Module_648" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Module_648.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Activity_16xLG" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Activity_16xLG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Class_489" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Class_489.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="VirtualMachine" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\VirtualMachine.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="usbcontroller" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\usbcontroller.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Method_636" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Method_636.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Cloud_16xLG" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Cloud_16xLG.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Tag_7213" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Tag_7213.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Structure_507" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Structure_507.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="ClassIcon" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\ClassIcon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="Table_748" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\Table_748.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+  <data name="loading" type="System.Resources.ResXFileRef, System.Windows.Forms">
+    <value>..\img\loading.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
+  </data>
+</root>

+ 51 - 0
OpcUaHelper/app.config

@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.2.1.0" newVersion="1.2.1.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.IO.Compression" publicKeyToken="b77a5c561934e089" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-6.0.0.1" newVersion="6.0.0.1" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Security.Cryptography.Cng" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.32.0" newVersion="3.1.32.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Opc.Ua.Core" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.5.374.0" newVersion="1.5.374.0" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
+</configuration>

BIN
OpcUaHelper/img/Activity_16xLG.png


BIN
OpcUaHelper/img/ClassIcon.ico


BIN
OpcUaHelper/img/ClassIcon.png


BIN
OpcUaHelper/img/Class_489.png


BIN
OpcUaHelper/img/Cloud_16xLG.png


BIN
OpcUaHelper/img/Copy_6524.png


BIN
OpcUaHelper/img/Delegate_8339.png


BIN
OpcUaHelper/img/Enum_582.png


BIN
OpcUaHelper/img/Event_594.png


BIN
OpcUaHelper/img/Event_594_exp.png


BIN
OpcUaHelper/img/ListView_687.png


BIN
OpcUaHelper/img/Method_636.png


BIN
OpcUaHelper/img/Module_648.png


BIN
OpcUaHelper/img/RegistryEditor_5838.ico


BIN
OpcUaHelper/img/SingleMessage_5727.ico


BIN
OpcUaHelper/img/Structure_507.png


BIN
OpcUaHelper/img/Table_748.png


BIN
OpcUaHelper/img/Tag_7213.png


BIN
OpcUaHelper/img/UserInterfaceEditor_5845.ico


BIN
OpcUaHelper/img/VirtualMachine.png


BIN
OpcUaHelper/img/WindowsForm_817.ico


BIN
OpcUaHelper/img/brackets_Square_16xMD.png


BIN
OpcUaHelper/img/docview_xaml_on_16x16.png


BIN
OpcUaHelper/img/glasses_16xLG.png


BIN
OpcUaHelper/img/grid_Data_16xLG.png


BIN
OpcUaHelper/img/lightningBolt_16xLG.png


BIN
OpcUaHelper/img/loading.gif


BIN
OpcUaHelper/img/usbcontroller.png


+ 7 - 1
TeamAAS-VM.sln

@@ -1,12 +1,14 @@
 
 Microsoft Visual Studio Solution File, Format Version 12.00
 # Visual Studio Version 18
-VisualStudioVersion = 18.5.11709.299 stable
+VisualStudioVersion = 18.5.11709.299
 MinimumVisualStudioVersion = 10.0.40219.1
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeamAAS-VP", "TeamAAS-VM\TeamAAS-VP.csproj", "{08877F07-4A1C-4530-9105-CF24945AF83C}"
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Team.FFFeederService", "Team.FFFeederService\Team.FFFeederService.csproj", "{26DA3704-77D7-46A7-8651-684878DAC898}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpcUaHelper", "OpcUaHelper\OpcUaHelper.csproj", "{7693C6F9-3846-4310-B0F1-194874C5047D}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -21,6 +23,10 @@ Global
 		{26DA3704-77D7-46A7-8651-684878DAC898}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{26DA3704-77D7-46A7-8651-684878DAC898}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{26DA3704-77D7-46A7-8651-684878DAC898}.Release|Any CPU.Build.0 = Release|Any CPU
+		{7693C6F9-3846-4310-B0F1-194874C5047D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{7693C6F9-3846-4310-B0F1-194874C5047D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{7693C6F9-3846-4310-B0F1-194874C5047D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{7693C6F9-3846-4310-B0F1-194874C5047D}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 21 - 5
TeamAAS-VM/App.config

@@ -269,11 +269,11 @@
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
-        <bindingRedirect oldVersion="0.0.0.0-8.0.0.3" newVersion="8.0.0.3" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
-        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="System.Reflection.Metadata" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
@@ -305,11 +305,11 @@
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="System.Formats.Asn1" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
-        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
-        <bindingRedirect oldVersion="0.0.0.0-9.0.0.9" newVersion="9.0.0.9" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
@@ -325,7 +325,23 @@
       </dependentAssembly>
       <dependentAssembly>
         <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
-        <bindingRedirect oldVersion="0.0.0.0-10.0.0.1" newVersion="10.0.0.1" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Text.Encodings.Web" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-10.0.0.8" newVersion="10.0.0.8" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Opc.Ua.Client" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.5.378.0" newVersion="1.5.378.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Opc.Ua.Core" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.5.378.0" newVersion="1.5.378.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Opc.Ua.Configuration" publicKeyToken="bfa7a73c5cf4b6e8" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-1.5.378.0" newVersion="1.5.378.0" />
       </dependentAssembly>
     </assemblyBinding>
   </runtime>

+ 14 - 10
TeamAAS-VM/Core/PLCs/OPCuaClientPLC.cs

@@ -45,7 +45,7 @@ namespace TeamAAS_VP.Core.PLCs
         /// 仅在 <see cref="Mode"/> 为 <see cref="OpcUaSubscriptionMode.CustomPolling"/> 时生效。
         /// 默认值为 50。
         /// </summary>
-        public int PollingInterval { get; set; } = 25;
+        public int PollingInterval { get; set; } = 50;
 
         /// <summary>
         /// 获取或设置首次扫描时是否立即通知当前值。
@@ -59,13 +59,13 @@ namespace TeamAAS_VP.Core.PLCs
         private readonly object _pollingSubscriptionLock = new object();
         private readonly Dictionary<string, PollingSubscriptionContext> _pollingSubscriptions = new Dictionary<string, PollingSubscriptionContext>();
 
-        public Guid Id{ get; private set; }
+        public Guid Id { get; private set; }
 
         public CommunicationType CommunicationType { get; private set; }
 
         public string EndpointUrl { get; private set; }
 
-        public int Index { get; set; } 
+        public int Index { get; set; }
 
         public string Name { get; private set; }
 
@@ -90,7 +90,7 @@ namespace TeamAAS_VP.Core.PLCs
         /// 仅当默认订阅模式或实际订阅选项使用自定义轮询时生效。
         /// 默认值为 `100`。
         /// </summary>
-        public int DefaultSubscriptionPollingInterval { get; set; } = 25;
+        public int DefaultSubscriptionPollingInterval { get; set; } = 100;
 
         /// <summary>
         /// 获取或设置在默认轮询订阅模式下,首次扫描节点时是否立即触发一次数据变更通知。
@@ -145,7 +145,7 @@ namespace TeamAAS_VP.Core.PLCs
             public bool NotifyOnFirstScan { get; set; }
         }
 
-        public OpcUaClientPLC(Guid id,int index, string name, string endpointUrl,string nodeHeader, CommunicationType communicationType)
+        public OpcUaClientPLC(Guid id, int index, string name, string endpointUrl, string nodeHeader, CommunicationType communicationType)
         {
             Id = id;
             Index = index;
@@ -173,9 +173,9 @@ namespace TeamAAS_VP.Core.PLCs
         public OpcUaClientPLC(PlcInfo plcInfo)
         {
             Id = plcInfo.Id;
-            Index=plcInfo.Index;
+            Index = plcInfo.Index;
             Name = plcInfo.Name;
-            NodeHeader=plcInfo.NodeHeader;
+            NodeHeader = plcInfo.NodeHeader;
             EndpointUrl = plcInfo.EndpointUrl;
             CommunicationType = plcInfo.CommunicationType;
             OpcUaClient = new OpcUaClient();
@@ -419,7 +419,7 @@ namespace TeamAAS_VP.Core.PLCs
         /// <param name="key">订阅唯一标识,用于区分和管理同一客户端上的不同订阅任务。</param>
         /// <param name="nodeIds">需要订阅的节点标识集合,可传入带或不带 <see cref="NodeHeader"/> 前缀的节点名。</param>
         /// <param name="dataChangeHandler">节点值变化时触发的回调,返回订阅键、节点标识和值。</param>
-        public void SubscribeNodes(string key, List<string> nodeIds, Action<(string key,string nodeId,object value)> dataChangeHandler)
+        public void SubscribeNodes(string key, List<string> nodeIds, Action<(string key, string nodeId, object value)> dataChangeHandler)
         {
             SubscribeNodes(key, nodeIds, dataChangeHandler, new OpcUaSubscriptionOptions
             {
@@ -562,6 +562,9 @@ namespace TeamAAS_VP.Core.PLCs
         {
             while (!context.CancellationTokenSource.IsCancellationRequested)
             {
+                // 提前启动 Delay,保证两次读取之间的真实间隔至少为 PollingInterval
+                var delayTask = Task.Delay(context.PollingInterval, context.CancellationTokenSource.Token);
+
                 try
                 {
                     if (IsConnected && context.NodeIds.Count > 0)
@@ -598,13 +601,14 @@ namespace TeamAAS_VP.Core.PLCs
                 {
                     break;
                 }
-                catch (Exception)
+                catch (Exception ex)
                 {
+                    LogHelper.WriteLogError($"轮询订阅 [{context.Key}] 发生异常", ex);
                 }
 
                 try
                 {
-                    await Task.Delay(context.PollingInterval, context.CancellationTokenSource.Token).ConfigureAwait(false);
+                    await delayTask.ConfigureAwait(false);
                 }
                 catch (OperationCanceledException)
                 {

+ 40 - 24
TeamAAS-VM/TeamAAS-VP.csproj

@@ -86,7 +86,7 @@
       <SpecificVersion>False</SpecificVersion>
     </Reference>
     <Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL">
-      <HintPath>..\packages\BouncyCastle.Cryptography.2.5.0\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
+      <HintPath>..\packages\BouncyCastle.Cryptography.2.6.2\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
     </Reference>
     <Reference Include="Cognex.VisionPro, Version=59.2.0.0, Culture=neutral, PublicKeyToken=ef0f902af9dee505, processorArchitecture=AMD64" />
     <Reference Include="Cognex.VisionPro.ApplicationWizard.Core, Version=59.2.0.0, Culture=neutral, PublicKeyToken=ef0f902af9dee505, processorArchitecture=AMD64" />
@@ -208,8 +208,8 @@
     <Reference Include="itextsharp">
       <HintPath>..\packages\iTextSharp.5.5.13.4\lib\net461\itextsharp.dll</HintPath>
     </Reference>
-    <Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
-      <HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
+    <Reference Include="log4net, Version=3.3.2.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
+      <HintPath>..\packages\log4net.3.3.2\lib\net462\log4net.dll</HintPath>
     </Reference>
     <Reference Include="MaterialDesignColors, Version=5.2.1.0, Culture=neutral, PublicKeyToken=df2a72020bd7962a, processorArchitecture=MSIL">
       <HintPath>..\packages\MaterialDesignColors.5.2.1\lib\net462\MaterialDesignColors.dll</HintPath>
@@ -238,14 +238,26 @@
     <Reference Include="Microsoft.CodeAnalysis.Scripting, Version=4.14.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
       <HintPath>..\packages\Microsoft.CodeAnalysis.Scripting.Common.4.14.0\lib\netstandard2.0\Microsoft.CodeAnalysis.Scripting.dll</HintPath>
     </Reference>
-    <Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=9.0.0.9, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
-      <HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.9.0.9\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
+    <Reference Include="Microsoft.Extensions.DependencyInjection, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.DependencyInjection.10.0.8\lib\net462\Microsoft.Extensions.DependencyInjection.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.10.0.8\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
     </Reference>
     <Reference Include="Microsoft.Extensions.DependencyModel, Version=9.0.0.9, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
       <HintPath>..\packages\Microsoft.Extensions.DependencyModel.9.0.9\lib\net462\Microsoft.Extensions.DependencyModel.dll</HintPath>
     </Reference>
-    <Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=9.0.0.9, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
-      <HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.9.0.9\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
+    <Reference Include="Microsoft.Extensions.Logging, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Logging.10.0.8\lib\net462\Microsoft.Extensions.Logging.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.10.0.8\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Options, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Options.10.0.8\lib\net462\Microsoft.Extensions.Options.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Primitives, Version=10.0.0.8, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Primitives.10.0.8\lib\net462\Microsoft.Extensions.Primitives.dll</HintPath>
     </Reference>
     <Reference Include="Microsoft.IO.RecyclableMemoryStream, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
       <HintPath>..\packages\Microsoft.IO.RecyclableMemoryStream.3.0.1\lib\netstandard2.0\Microsoft.IO.RecyclableMemoryStream.dll</HintPath>
@@ -279,29 +291,29 @@
     <Reference Include="NPOI.OpenXmlFormats, Version=2.7.4.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
       <HintPath>..\packages\NPOI.2.7.4\lib\net472\NPOI.OpenXmlFormats.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Client, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Client.1.5.374.158\lib\net48\Opc.Ua.Client.dll</HintPath>
+    <Reference Include="Opc.Ua.Client, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Client.1.5.378.152\lib\net48\Opc.Ua.Client.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Configuration, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Configuration.1.5.374.158\lib\net48\Opc.Ua.Configuration.dll</HintPath>
+    <Reference Include="Opc.Ua.Configuration, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Configuration.1.5.378.152\lib\net48\Opc.Ua.Configuration.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Core, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Core.1.5.374.158\lib\net48\Opc.Ua.Core.dll</HintPath>
+    <Reference Include="Opc.Ua.Core, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Core.1.5.378.152\lib\net48\Opc.Ua.Core.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Gds.Client.Common, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Client.Common.1.5.374.158\lib\net48\Opc.Ua.Gds.Client.Common.dll</HintPath>
+    <Reference Include="Opc.Ua.Gds.Client.Common, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Client.Common.1.5.378.152\lib\net48\Opc.Ua.Gds.Client.Common.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Gds.Server.Common, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Server.Common.1.5.374.158\lib\net48\Opc.Ua.Gds.Server.Common.dll</HintPath>
+    <Reference Include="Opc.Ua.Gds.Server.Common, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Gds.Server.Common.1.5.378.152\lib\net48\Opc.Ua.Gds.Server.Common.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Security.Certificates, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Security.Certificates.1.5.374.158\lib\net48\Opc.Ua.Security.Certificates.dll</HintPath>
+    <Reference Include="Opc.Ua.Security.Certificates, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Security.Certificates.1.5.378.152\lib\net48\Opc.Ua.Security.Certificates.dll</HintPath>
     </Reference>
-    <Reference Include="Opc.Ua.Server, Version=1.5.374.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
-      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Server.1.5.374.158\lib\net48\Opc.Ua.Server.dll</HintPath>
+    <Reference Include="Opc.Ua.Server, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Server.1.5.378.152\lib\net48\Opc.Ua.Server.dll</HintPath>
     </Reference>
-    <Reference Include="OpcUaHelper, Version=2.2.1.0, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\packages\OpcUaHelper.2.2.1\lib\net461\OpcUaHelper.dll</HintPath>
+    <Reference Include="Opc.Ua.Types, Version=1.5.378.0, Culture=neutral, PublicKeyToken=bfa7a73c5cf4b6e8, processorArchitecture=MSIL">
+      <HintPath>..\packages\OPCFoundation.NetStandard.Opc.Ua.Types.1.5.378.152\lib\net48\Opc.Ua.Types.dll</HintPath>
     </Reference>
     <Reference Include="OpenCvSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6adad1e807fea099, processorArchitecture=MSIL">
       <HintPath>..\packages\OpenCvSharp4.4.11.0.20250507\lib\net48\OpenCvSharp.dll</HintPath>
@@ -466,7 +478,7 @@
       <HintPath>..\packages\Unity.Container.5.11.11\lib\net48\Unity.Container.dll</HintPath>
     </Reference>
     <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
-      <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
+      <HintPath>..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
     </Reference>
     <Reference Include="NModbus4, Version=2.1.0.0, Culture=neutral, processorArchitecture=MSIL">
       <HintPath>..\packages\NModbus4.2.1.0\lib\net40\NModbus4.dll</HintPath>
@@ -1637,6 +1649,10 @@
       <Project>{26da3704-77d7-46a7-8651-684878dac898}</Project>
       <Name>Team.FFFeederService</Name>
     </ProjectReference>
+    <ProjectReference Include="..\OpcUaHelper\OpcUaHelper.csproj">
+      <Project>{7693C6F9-3846-4310-B0F1-194874C5047D}</Project>
+      <Name>OpcUaHelper</Name>
+    </ProjectReference>
   </ItemGroup>
   <ItemGroup>
     <Resource Include="TeamAAS-VM.ico" />

+ 21 - 15
TeamAAS-VM/packages.config

@@ -1,19 +1,22 @@
 <?xml version="1.0" encoding="utf-8"?>
 <packages>
   <package id="AvalonEdit" version="6.3.0.90" targetFramework="net48" />
-  <package id="BouncyCastle.Cryptography" version="2.5.0" targetFramework="net48" />
+  <package id="BitFaster.Caching" version="2.6.0" targetFramework="net48" />
+  <package id="BouncyCastle.Cryptography" version="2.6.2" targetFramework="net48" />
   <package id="ControlzEx" version="4.4.0" targetFramework="net48" />
   <package id="CS-Script" version="4.8.1" targetFramework="net48" />
   <package id="EntityFramework" version="6.5.1" targetFramework="net48" />
   <package id="Enums.NET" version="5.0.0" targetFramework="net48" />
   <package id="ExtendedNumerics.BigDecimal" version="3001.0.1.201" targetFramework="net48" />
-  <package id="log4net" version="3.2.0" targetFramework="net48" />
+  <package id="FluentFTP" version="53.0.2" targetFramework="net48" />
+  <package id="iTextSharp" version="5.5.13.4" targetFramework="net48" />
+  <package id="log4net" version="3.3.2" targetFramework="net48" />
   <package id="MahApps.Metro" version="2.4.10" targetFramework="net48" />
   <package id="MaterialDesignColors" version="5.2.1" targetFramework="net48" />
   <package id="MaterialDesignThemes" version="5.2.1" targetFramework="net48" />
   <package id="MathNet.Numerics" version="5.0.0" targetFramework="net48" />
   <package id="MathNet.Numerics.Signed" version="5.0.0" targetFramework="net48" />
-  <package id="Microsoft.Bcl.AsyncInterfaces" version="10.0.1" targetFramework="net48" />
+  <package id="Microsoft.Bcl.AsyncInterfaces" version="10.0.8" targetFramework="net48" />
   <package id="Microsoft.Bcl.Cryptography" version="9.0.9" targetFramework="net48" />
   <package id="Microsoft.Bcl.HashCode" version="6.0.0" targetFramework="net48" />
   <package id="Microsoft.CodeAnalysis.Analyzers" version="3.11.0" targetFramework="net48" developmentDependency="true" />
@@ -22,26 +25,29 @@
   <package id="Microsoft.CodeAnalysis.CSharp.Scripting" version="4.14.0" targetFramework="net48" />
   <package id="Microsoft.CodeAnalysis.Scripting.Common" version="4.14.0" targetFramework="net48" />
   <package id="Microsoft.CSharp" version="4.7.0" targetFramework="net48" />
-  <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="9.0.9" targetFramework="net48" />
+  <package id="Microsoft.Extensions.DependencyInjection" version="10.0.8" targetFramework="net48" />
+  <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="10.0.8" targetFramework="net48" />
   <package id="Microsoft.Extensions.DependencyModel" version="9.0.9" targetFramework="net48" />
-  <package id="Microsoft.Extensions.Logging.Abstractions" version="9.0.9" targetFramework="net48" />
+  <package id="Microsoft.Extensions.Logging" version="10.0.8" targetFramework="net48" />
+  <package id="Microsoft.Extensions.Logging.Abstractions" version="10.0.8" targetFramework="net48" />
+  <package id="Microsoft.Extensions.Options" version="10.0.8" targetFramework="net48" />
+  <package id="Microsoft.Extensions.Primitives" version="10.0.8" targetFramework="net48" />
   <package id="Microsoft.IO.RecyclableMemoryStream" version="3.0.1" targetFramework="net48" />
   <package id="Microsoft.NETFramework.ReferenceAssemblies" version="1.0.3" targetFramework="net48" developmentDependency="true" />
   <package id="Microsoft.NETFramework.ReferenceAssemblies.net48" version="1.0.3" targetFramework="net48" developmentDependency="true" />
   <package id="Microsoft.Xaml.Behaviors.Wpf" version="1.1.135" targetFramework="net48" />
   <package id="netDxf" version="2023.11.10" targetFramework="net48" />
-  <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
+  <package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" />
   <package id="NModbus4" version="2.1.0" targetFramework="net48" />
   <package id="NPOI" version="2.7.4" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Client" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Configuration" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Core" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Gds.Client.Common" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Gds.Server.Common" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Security.Certificates" version="1.5.374.158" targetFramework="net48" />
-  <package id="OPCFoundation.NetStandard.Opc.Ua.Server" version="1.5.374.158" targetFramework="net48" />
-  <package id="OpcUaHelper" version="2.2.1" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Client" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Configuration" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Core" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Gds.Client.Common" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Gds.Server.Common" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Security.Certificates" version="1.5.378.152" targetFramework="net48" />
+  <package id="OPCFoundation.NetStandard.Opc.Ua.Server" version="1.5.378.152" targetFramework="net48" />
   <package id="OpenCvSharp4" version="4.11.0.20250507" targetFramework="net48" />
   <package id="OpenCvSharp4.Extensions" version="4.11.0.20250507" targetFramework="net48" />
   <package id="OpenCvSharp4.runtime.win" version="4.11.0.20250507" targetFramework="net48" />