简体   繁体   English

从公共访问ServerManager类启动Opc Ua Server会引发NullPointerException

[英]Starting Opc Ua Server from public access to ServerManager Class throws NullPointerException

I tried to start an OPC UA Server this way: http://documentation.unified-automation.com/uasdkdotnet/2.1.0/html/L3ServerTutGSLess01.html 我试图以这种方式启动OPC UA服务器: http : //documentation.unified-automation.com/uasdkdotnet/2.1.0/html/L3ServerTutGSLess01.html

ApplicationLicenseManager.AddProcessLicenses(Assembly.GetExecutingAssembly(), "License.lic");
MyServerManager server = new MyServerManager();
ApplicationInstance.Default.Start(server, null, server); //Start the server

At ApplicationInstance.Default.Start(server, null, server)" following Error Appears: System.NullReferenceException: Object reference not set to an object instance. at UnifiedAutomation.UaServer.ServerSettings..ctor ( ApplicationInstance application ) at UnifiedAutomation.UaServer.ServerManager.OnServerStarting ( ApplicationInstance application ) at UnifiedAutomation.UaBase.ServerBase.Start ( ApplicationInstance application ) at UnifiedAutomation.UaServer.ServerManager.Start ( ApplicationInstance application ) at UnifiedAutomation.UaBase.ApplicationInstance.Start ( ServerBase server , WaitCallback callback , Object userData ) at VeitsServer.TapakoServerStarter.StartAkomiServer ( IDevice testDeviceToLink ) in TapakoServerStarter.cs : line . 39 at Implementationstests.OpcUaServerTest.ServerShouldRun ( ) in OpcUaServerTest.cs : line 44 ApplicationInstance.Default.Start(server, null, server)"出现以下错误:System.NullReferenceException:对象引用未设置为对象实例。在UnifiedAutomation.UaServer.ServerSettings..ctor(ApplicationInstance应用程序)上的UnifiedAutomation.UaServer.ServerManager .UnServerAutoing.UaBase.ServerBase.Start处的.OnServerStarting(ApplicationInstance应用程序)UnifiedAutomation.UaServer.ServerManager.Start(ApplicationInstance应用程序)处的UnifiedAutomation.UaBase.ApplicationInstance.Start(VeitsServer的ServerBase服务器,WaitCallback回调,对象userData) TapakoServerStarter.cs中的.TapakoServerStarter.StartAkomiServer(IDevice testDeviceToLink):第39行,OpcUaServerTest.cs中的Implementationstests.OpcUaServerTest.ServerShouldRun():第44行

The same code works fine, if it's started internal from Main() . 如果从Main()内部启动,则相同的代码也可以正常工作。 But as soon as i try to call the OpcUaServerStarter over an external Project in the same Project Map (for example a Test Project) the NullReferenceException appears. 但是,一旦我尝试通过同一项目映射(例如测试项目)中的外部项目调用OpcUaServerStarter,就会出现NullReferenceException。

Maybe the Project has to be compiled as a .dll or I have to add some references? 也许项目必须编译为.dll或我必须添加一些引用? Or it has some reason, that the visibility of MyServerManager is internal at the OPC-UA Website. MyServerManager某种原因, MyServerManager的可见性在OPC-UA网站上是internal的。

The Debug Session before the Exception looks this way: 异常之前的调试会话如下所示: 在此处输入图片说明

MyServerManager Class (only critical difference to the working MyServerManager may be the public encapsulation): MyServerManager类(与工作的MyServerManager唯一的关键区别可能是public封装):

 public class MyServerManager : ServerManager
{

    private NodeManager _nodeManager;
    private ObjectModel _objectModel;

    /// <summary>
    /// Method is called (from SDK) when NodeManager starts up.
    /// </summary>
    /// <param name="rootNodeManager"></param>
    protected override void OnRootNodeManagerStarted(RootNodeManager rootNodeManager)
    {
        Console.WriteLine("Creating Node Manager.");

        _nodeManager = new NodeManager(this);
        _nodeManager.Startup();

        _objectModel = new ObjectModel(_nodeManager);
    }

    /// <summary>
    /// Creates an internal model of the given device and automatically creates nodes and callbacks
    /// </summary>
    /// <param name="device">AKOMI Device that will be shown on the Server</param>
    public void LinkObjectToModel(IDevice device)
    {
        if (_objectModel == null)
        {
            throw new NullReferenceException("hv: objectModel is not initilized, try starting the server first.");
        }

        Console.WriteLine("Register Device: " + device.GetType().Name);
        _objectModel.RegisterAkomiDevice(device, 0, 4);
    }

    /// <summary>
    /// Creates an internal model of the given entity and automatically creates nodes and callbacks
    /// </summary>
    public void LinkObjectToModel(object entity, string name, int curLvl, int maxLvl)
    {
        if (_objectModel == null)
        {
            throw new NullReferenceException("hv: objectModel is not initilized, try starting the server first.");
        }

        Console.WriteLine("Register Entity: " + name);
        _objectModel.RegisterEntity(entity, name, curLvl, maxLvl);
    }

}

Thanks! 谢谢!

Finally I found a Solution. 终于我找到了解决方案。 I had to add the following code to the "App.config" File. 我必须将以下代码添加到“ App.config”文件中。 Hope it will solve your problem! 希望它能解决您的问题!

<?xml version="1.0"?> <!--The UA Server needs this App.config!-->
<configuration>
  <configSections>
    <section name="UaApplicationConfiguration" type="UnifiedAutomation.UaBase.ApplicationConfigurationSection,UnifiedAutomation.UaBase"/>
  </configSections>
  <UaApplicationConfiguration>

    <SecuredApplication xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://opcfoundation.org/UA/2011/03/SecuredApplication.xsd" xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd">

      <!-- Identify the Application -->
      <ApplicationName>My Server</ApplicationName>
      <ApplicationUri>urn:localhost:UnifiedAutomation:MyServer</ApplicationUri>
      <ApplicationType>Server_0</ApplicationType>

      <!-- Specify location of Certificates and Trust Lists -->
      <ApplicationCertificate>
        <StoreType>Directory</StoreType>
        <StorePath>%CommonApplicationData%\unifiedautomation\UaSdkNet\pki\own</StorePath>
        <SubjectName>CN=GettingStartedServer/O=UnifiedAutomation/DC=localhost</SubjectName>
        <ValidationOptions>0</ValidationOptions>
      </ApplicationCertificate>
      <TrustedCertificateStore>
        <StoreType>Directory</StoreType>
        <StorePath>%CommonApplicationData%\unifiedautomation\UaSdkNet\pki\trusted</StorePath>
        <ValidationOptions>0</ValidationOptions>
      </TrustedCertificateStore>
      <IssuerCertificateStore>
        <StoreType>Directory</StoreType>
        <StorePath>%CommonApplicationData%\unifiedautomation\UaSdkNet\pki\issuers</StorePath>
        <ValidationOptions>0</ValidationOptions>
      </IssuerCertificateStore>
      <RejectedCertificatesStore>
        <StoreType>Directory</StoreType>
        <StorePath>%CommonApplicationData%\unifiedautomation\UaSdkNet\pki\rejected</StorePath>
        <ValidationOptions>0</ValidationOptions>
      </RejectedCertificatesStore>

      <!-- Specify Endpoints the Server will use -->
      <BaseAddresses>
        <BaseAddress>opc.tcp://localhost:48030</BaseAddress>

        <!--
        Uncomment this line to enable the HTTPS based profiles.

        This profile works but is not officially supported in this version of the SDK.
        This is the HTTP based protocol that will be supported by embedded devices.

        Enabling this profile requires that you have a HTTPS certificate issued by a certificate authority
        in your root certificate store. You can create your own authority and add it to the root store or
        you can use authorities like VeriSign or Thawte.
        -->
        <!--
        <BaseAddress>https://localhost:48031/</BaseAddress>
         -->

        <!--
        Uncomment this line to enable the WS-Secure Conversation based profiles.

        This profile works but is not officially supported since it is not practical to support on embedded devices.
        You should not enable this protocol unless you have an application that must support XML Web Services.
        -->
        <!--
        <BaseAddress>http://localhost:48032/wssecurity/</BaseAddress>
        -->
      </BaseAddresses>

      <!-- Specify the SecurityProfiles the Server supports -->
      <SecurityProfiles>
        <SecurityProfile>
          <ProfileUri>http://opcfoundation.org/UA/SecurityPolicy#Basic256</ProfileUri>
          <Enabled>true</Enabled>
        </SecurityProfile>
        <SecurityProfile>
          <ProfileUri>http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15</ProfileUri>
          <Enabled>true</Enabled>
        </SecurityProfile>
        <SecurityProfile>
          <ProfileUri>http://opcfoundation.org/UA/SecurityPolicy#None</ProfileUri>
          <Enabled>true</Enabled>
        </SecurityProfile>
      </SecurityProfiles>

      <!-- Specify Configuration for Different Components (Can include 'YourCompany' Configuration) -->
      <Extensions>

        <!-- Specify the Trace settings for the Application -->
        <Extension>
          <TraceSettings xmlns="http://unifiedautomation.com/schemas/2011/12/Application.xsd" MasterTraceEnabled="false" DefaultTraceLevel="Info">
            <TraceFile>%CommonApplicationData%\unifiedautomation\logs\GettingStartedServer.log.txt</TraceFile>
            <MaxEntriesPerLog>100000</MaxEntriesPerLog>
            <MaxLogFileBackups>3</MaxLogFileBackups>
            <FastTrace>false</FastTrace>
            <ModuleSettings>
              <ModuleTraceSettings ModuleName="UnifiedAutomation.Stack"/>
              <ModuleTraceSettings ModuleName="UnifiedAutomation.Server"/>
            </ModuleSettings>
          </TraceSettings>
        </Extension>

        <!-- Specify Settings when EXE is run with the /install argument -->
        <Extension>
          <InstallationSettings xmlns="http://unifiedautomation.com/schemas/2011/12/Application.xsd">
            <GenerateCertificateIfNone>true</GenerateCertificateIfNone>
            <DeleteCertificateOnUninstall>true</DeleteCertificateOnUninstall>
          </InstallationSettings>
        </Extension>

        <!-- Specify Settings for the ServerManager -->
        <Extension>
          <ServerSettings xmlns="http://unifiedautomation.com/schemas/2011/12/Application.xsd">
            <ProductName>UnifiedAutomation GettingStartedServer</ProductName>
            <DiscoveryRegistration>
              <Enabled>false</Enabled>
            </DiscoveryRegistration>
          </ServerSettings>
        </Extension>

        <Extension>
          <SessionSettings xmlns="http://unifiedautomation.com/schemas/2011/12/Application.xsd">
            <MaxSessionCount>100</MaxSessionCount>
          </SessionSettings>
        </Extension>

        <!-- Specify Settings for the SubscriptionManager -->
        <Extension>
          <SubscriptionSettings xmlns="http://unifiedautomation.com/schemas/2011/12/Application.xsd">
            <MaxSubscriptionCount>500</MaxSubscriptionCount>
          </SubscriptionSettings>
        </Extension>

      </Extensions>
    </SecuredApplication>
  </UaApplicationConfiguration>

  <system.serviceModel>
    <services>
      <service name="UnifiedAutomation.UaBase.SessionEndpoint" behaviorConfiguration="SessionEndpoint.Behavior">
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <!--
        Must turn on mexHttpsBinding instead of mexHttpBinding if only HTTPS endpoint configured.
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
        -->
      </service>
    </services>

    <!-- Servers deployed in production environments should turn the httpGetEnabled and includeExceptionDetailInFaults options off -->
    <behaviors>
      <serviceBehaviors>
        <behavior name="SessionEndpoint.Behavior">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
          <!--
          Must turn on httpsGetEnabled instead of httpGetEnabled if only HTTPS endpoint configured.
          <serviceMetadata httpsGetEnabled="true" />
          -->
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <!--
    <diagnostics>
        <messageLogging logEntireMessage="true" maxMessagesToLog="3000" logMessagesAtServiceLevel="true" logMalformedMessages="true" logMessagesAtTransportLevel="true"/>
    </diagnostics>
    -->

  </system.serviceModel>

  <!--
  <system.diagnostics>
      <sources>
          <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing">
              <listeners>
                  <add type="System.Diagnostics.DefaultTraceListener" name="Default"/>
                  <add name="ServiceModel Listener"/>
              </listeners>
          </source>
          <source name="System.ServiceModel.MessageLogging">
              <listeners>
                  <add type="System.Diagnostics.DefaultTraceListener" name="Default"/>
                  <add name="ServiceModel Listener"/>
              </listeners>
          </source>
      </sources>
      <sharedListeners>
          <add initializeData="VendorServer.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModel Listener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"/>
      </sharedListeners>
  </system.diagnostics>
  -->
</configuration>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM