title: Read structured data from OPC UA server
body: <p>I'm triying to read some data form an OPC UA server using <a href="https://github.com/convertersystems/opc-ua-client" rel="nofollow noreferrer">opc-ua-client</a> library. Managed to connect to server and read some simple variables, but facing issues when reading structured values. However, I'm able to browse those structured values using 3rd party tools, such as UAExpert.</p>
  <p>This is the code snippet:</p>
  <pre><code>var readRequest = new ReadRequest
  {
      NodesToRead = new[] { new ReadValueId { NodeId = NodeId.Parse(nodeId), AttributeId = AttributeIds.Value } }
  };
  var response = channel.ReadAsync(readRequest).Result;
  
  var result = response.Results[0].GetValueOrDefault&lt;ExtensionObject&gt;();
  </code></pre>
  <p>The point is: how should I cast the ExtensionObject into the underlying real object? Response's body is binary serialized into a System.Byte[] field, and don't know how to deserialize it. I know the fields and types of the structure, so defined it in the code (even decorating with the namespace provided by the server) as follow:</p>
  <pre><code>    [BinaryEncodingId(&quot;nsu=urn:OMRON:NxOpcUaServer:FactoryAutomation;i=5005&quot;)]
      private class MES_WRITE_STRUCT : Structure
      {
          uint Message_NUM { get; set; }
          //Some other fields
          DateTime Time_Stamp { get; set; }
      }
  </code></pre>
  <p>Things I've tried (and failed) so far:</p>
  <ul>
  <li><p>Brute-force cast:</p>
  <pre><code>var eObject = (MES_WRITE_STRUCT)result.GetValueOrDefault&lt;ExtensionObject&gt;();
  </code></pre>
  </li>
  <li><p>Read the response as the expected type rather than using generic object:</p>
  <pre><code>var eObject = result.GetValueOrDefault&lt;MES_WRITE_STRUCT&gt;();
  </code></pre>
  </li>
  <li><p>Use the Variant property rather than Value (same result as
  using Value):</p>
  <pre><code>result.Variant.GetValue();
  </code></pre>
  </li>
  <li><p>Create a binary reader and attempt to deserialize it into expected
  class.</p>
  </li>
  </ul>
  <p>Maybe I'm using a wrong approach and structured values should be read in a different way. Or even the library does not support structured variables (not much documentation available). Or just using an incorrect type when defining custom class in .NET and hence casting is failing.</p>
  <p>I'm totally stuck, any information or guidance is wellcome.</p>
  <p>PS: I'm not tied to this library and can switch to another one (preferably with no licenses, but if really worths can consider buying).</p>