Exemple #1
0
        public void SendCommandLog(string commandId, DateTime startTime, DateTime endTime, Dictionary <string, string> comp, bool screenshots)
        {
            var logData = new Dictionary <string, IValue>();
            var encoder = new JsonEncoder();

            logData["time"] = new StringValue(startTime.ToString("yyyy-M-d HH:mm:ss"));
            logData["name"] = new StringValue($"{commandId,-20}");
            var duration = endTime.Subtract(startTime);

            logData["duration"] = new StringValue(duration.ToString(@"mm\:ss"));
            logData["result"]   = new StringValue(comp["result"]);
            logData["arg"]      = new StringValue(comp["arg"]);
            if (screenshots)
            {
                _screenshotReport = screenshots;
            }

            var bytes = encoder.Encode(new DictionaryValue(logData));

            string result     = Encoding.UTF8.GetString(bytes);
            string channelStr = "<color=#94D8FF>[COMMAND]</color> " + result;

            Debug.Log(channelStr);
            _logData.Add(result);
        }
            public void Should_Add_Request_Body()
            {
                //Given
                HttpSettings settings = new HttpSettings();
                BodyModel    model    = new BodyModel
                {
                    Id     = 1234567,
                    Active = true,
                    name   = "Rob Test",
                    Parts  = new []
                    {
                        "Legs",
                        "Arms",
                        "Head"
                    },
                    SubModel = new BodySubModel
                    {
                        Description = "Body Sub Model Description",
                        Dttm        = DateTime.Now.Date,
                        Type        = "different type"
                    }
                };

                //When
                settings.SetJsonRequestBody(model);

                //Then
                Assert.NotNull(settings.RequestBody);

                var actual = JsonEncoder.DeserializeObject <BodyModel>(Encoding.UTF8.GetString(settings.RequestBody));

                Assert.Equal(model, actual);
            }
Exemple #3
0
        /// <summary>
        /// Will encode the argument to a Json string using the Connection's JsonEncoder, then will send it to the server.
        /// </summary>
        /// <returns>True if the plugin was able to send out the message</returns>
        public bool Send(object arg)
        {
            if (arg == null)
            {
                throw new ArgumentNullException("arg");
            }

            lock (SyncRoot)
            {
                if (this.State != ConnectionStates.Connected)
                {
                    return(false);
                }

                string json = JsonEncoder.Encode(arg);

                if (string.IsNullOrEmpty(json))
                {
                    HTTPManager.Logger.Error("SignalR Connection", "Failed to JSon encode the given argument. Please try to use an advanced JSon encoder(check the documentation how you can do it).");
                }
                else
                {
                    Transport.Send(json);
                }
            }

            return(true);
        }
Exemple #4
0
                public override void EncodeTyped(ref JsonEncoder encoder, T pairs)
                {
                    encoder.Write("{");

                    bool first = true;

                    foreach (var kvp in pairs)
                    {
                        if (!first)
                        {
                            encoder.Write(", ");
                        }
                        else
                        {
                            first = false;
                        }

                        encoder.EncodeString(kvp.Key);
                        encoder.Write(": ");
                        this.valueEncoder.EncodeTyped(ref encoder, kvp.Value);
                    }

                    encoder.Write("}");
                    return;
                }
Exemple #5
0
        /// <summary>
        /// Encodes the object in the specified stream.
        /// </summary>
        /// <param name="messageContext">The context.</param>
        /// <param name="stream">The stream to use.</param>
        public override void Encode(IServiceMessageContext messageContext, Stream stream)
        {
            bool topLevelIsArray = !HasNetworkMessageHeader && !HasSingleDataSetMessage && !IsMetaDataMessage;

            using (JsonEncoder encoder = new JsonEncoder(messageContext, true, topLevelIsArray, stream))
            {
                if (IsMetaDataMessage)
                {
                    EncodeNetworkMessageHeader(encoder);

                    encoder.WriteEncodeable(kFieldMetaData, m_metadata, null);

                    return;
                }

                // handle no header
                if (HasNetworkMessageHeader)
                {
                    Encode(encoder);
                }
                else if (DataSetMessages != null && DataSetMessages.Count > 0)
                {
                    if (HasSingleDataSetMessage)
                    {
                        // encode single dataset message
                        JsonDataSetMessage jsonDataSetMessage = DataSetMessages[0] as JsonDataSetMessage;

                        if (jsonDataSetMessage != null)
                        {
                            if (!jsonDataSetMessage.HasDataSetMessageHeader)
                            {
                                // If the NetworkMessageHeader and the DataSetMessageHeader bits are not set
                                // and SingleDataSetMessage bit is set, the NetworkMessage is a JSON object
                                // containing the set of name/value pairs defined for a single DataSet.
                                jsonDataSetMessage.EncodePayload(encoder, false);
                            }
                            else
                            {
                                // If the SingleDataSetMessage bit of the NetworkMessageContentMask is set,
                                // the content of the Messages field is a JSON object containing a single DataSetMessage.
                                jsonDataSetMessage.Encode(encoder);
                            }
                        }
                    }
                    else
                    {
                        // If the NetworkMessageHeader bit of the NetworkMessageContentMask is not set,
                        // the NetworkMessage is the contents of the Messages field (e.g. a JSON array of DataSetMessages).
                        foreach (var message in DataSetMessages)
                        {
                            JsonDataSetMessage jsonDataSetMessage = message as JsonDataSetMessage;
                            if (jsonDataSetMessage != null)
                            {
                                jsonDataSetMessage.Encode(encoder);
                            }
                        }
                    }
                }
            }
        }
Exemple #6
0
        private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                if (e.NotificationValue == null || monitoredItem.Subscription.Session == null)
                {
                    return;
                }

                JsonEncoder encoder = new JsonEncoder(
                    monitoredItem.Subscription.Session.MessageContext, false);
                encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId);
                e.NotificationValue.Encode(encoder);

                var json  = encoder.Close();
                var bytes = new UTF8Encoding(false).GetBytes(json);

                foreach (var publisher in m_publishers)
                {
                    try
                    {
                        publisher.Publish(new ArraySegment <byte>(bytes));
                    }
                    catch (Exception ex)
                    {
                        Utils.Trace(ex, "Failed to publish message, dropping....");
                    }
                }
            }
            catch (Exception exception)
            {
                Utils.Trace(exception, "Error processing monitored item notification.");
            }
        }
        public void Test_WriteMultipleEncodeablesWithFieldNames()
        {
            var expected = "{\"bar_1\":{\"Foo\":\"bar_1\"},\"bar_2\":{\"Foo\":\"bar_2\"},\"bar_3\":{\"Foo\":\"bar_3\"}}";

            TestContext.Out.WriteLine("Expected:");
            _ = PrettifyAndValidateJson(expected);

            var encodeables = new List <FooBarEncodeable> {
                new FooBarEncodeable(), new FooBarEncodeable(), new FooBarEncodeable()
            };

            try
            {
                var encoder = new JsonEncoder(Context, true, null, false);

                foreach (var encodeable in encodeables)
                {
                    encoder.WriteEncodeable(encodeable.Foo, encodeable, typeof(FooBarEncodeable));
                }

                var encoded = encoder.CloseAndReturnText();
                TestContext.Out.WriteLine("Encoded:");
                TestContext.Out.WriteLine(encoded);

                TestContext.Out.WriteLine("Formatted Encoded:");
                _ = PrettifyAndValidateJson(encoded);

                Assert.That(encoded, Is.EqualTo(expected));
            }
            finally
            {
                encodeables.ForEach(e => e.Dispose());
            }
        }
        public void Test_WriteMultipleEncodeablesWithoutFieldNames(bool topLevelIsArray, string expected)
        {
            TestContext.Out.WriteLine("Expected:");
            _ = PrettifyAndValidateJson(expected);


            var encodeables = new List <FooBarEncodeable> {
                new FooBarEncodeable(), new FooBarEncodeable(), new FooBarEncodeable()
            };

            try
            {
                var encoder = new JsonEncoder(Context, true, null, topLevelIsArray);

                foreach (var encodeable in encodeables)
                {
                    encoder.WriteEncodeable(null, encodeable, typeof(FooBarEncodeable));
                }

                var encoded = encoder.CloseAndReturnText();
                TestContext.Out.WriteLine("Encoded:");
                TestContext.Out.WriteLine(encoded);

                TestContext.Out.WriteLine("Formatted Encoded:");
                _ = PrettifyAndValidateJson(encoded);

                Assert.That(encoded, Is.EqualTo(expected));
            }
            finally
            {
                encodeables.ForEach(e => e.Dispose());
            }
        }
Exemple #9
0
        public void TestFieldValueEscapedArray(string fieldname, string foo, string expected)
        {
            TestContext.Out.WriteLine("Expected:");
            _ = PrettifyAndValidateJson(expected);

            using (var encodeable = new FooBarEncodeable(fieldname, foo))
            {
                var list = new List <IEncodeable>()
                {
                    encodeable, encodeable
                };
                using (var encoder = new JsonEncoder(Context, true))
                {
                    encoder.WriteEncodeableArray(encodeable.FieldName, list, typeof(FooBarEncodeable));

                    var encoded = encoder.CloseAndReturnText();
                    TestContext.Out.WriteLine("Encoded:");
                    TestContext.Out.WriteLine(encoded);

                    TestContext.Out.WriteLine("Formatted Encoded:");
                    _ = PrettifyAndValidateJson(encoded);

                    Assert.That(encoded, Is.EqualTo(expected));
                }
            }
        }
        private void RunWriteEncodeableArrayTest(string fieldName, List <FooBarEncodeable> encodeables, string expected, bool topLevelIsArray, bool noExpectedValidation = false)
        {
            try
            {
                if (!noExpectedValidation)
                {
                    TestContext.Out.WriteLine("Expected:");
                    _ = PrettifyAndValidateJson(expected);
                }

                var encoder = new JsonEncoder(Context, true, null, topLevelIsArray);

                encoder.WriteEncodeableArray(
                    fieldName,
                    encodeables.Cast <IEncodeable>().ToList(),
                    typeof(FooBarEncodeable));

                var encoded = encoder.CloseAndReturnText();
                TestContext.Out.WriteLine("Encoded:");
                TestContext.Out.WriteLine(encoded);

                TestContext.Out.WriteLine("Formatted Encoded:");
                _ = PrettifyAndValidateJson(encoded);

                Assert.That(encoded, Is.EqualTo(expected));
            }
            finally
            {
                encodeables.ForEach(e => e.Dispose());
            }
        }
 /// <summary>
 /// Encode DataSetMessages
 /// </summary>
 private void EncodeMessages(JsonEncoder encoder)
 {
     if (DataSetMessages != null && DataSetMessages.Count > 0)
     {
         if (HasSingleDataSetMessage)
         {
             // encode single dataset message
             JsonDataSetMessage jsonDataSetMessage = DataSetMessages[0] as JsonDataSetMessage;
             if (jsonDataSetMessage != null)
             {
                 jsonDataSetMessage.Encode(encoder, kFieldMessages);
             }
         }
         else
         {
             encoder.PushArray(kFieldMessages);
             foreach (var message in DataSetMessages)
             {
                 JsonDataSetMessage jsonDataSetMessage = message as JsonDataSetMessage;
                 if (jsonDataSetMessage != null)
                 {
                     jsonDataSetMessage.Encode(encoder);
                 }
             }
             encoder.PopArray();
         }
     }
 }
Exemple #12
0
        public void Test_WriteSingleEncodeableWithName()
        {
            var expected = "{\"bar_1\":{\"Foo\":\"bar_1\"}}";

            TestContext.Out.WriteLine("Expected:");
            _ = PrettifyAndValidateJson(expected);

            using (var encodeable = new FooBarEncodeable())
            {
                using (var encoder = new JsonEncoder(Context, true, false))
                {
                    encoder.WriteEncodeable(encodeable.Foo, encodeable, typeof(FooBarEncodeable));

                    var encoded = encoder.CloseAndReturnText();

                    TestContext.Out.WriteLine("Encoded:");
                    TestContext.Out.WriteLine(encoded);

                    TestContext.Out.WriteLine("Formatted Encoded:");
                    _ = PrettifyAndValidateJson(encoded);

                    Assert.That(encoded, Is.EqualTo(expected));
                }
            }
        }
Exemple #13
0
            public static void Encode <T>(TextWriter writer, T value)
            {
                var jsonEncoder = new JsonEncoder(writer);
                var encoder     = GetEncoder <T>();

                encoder.EncodeTyped(ref jsonEncoder, value);
            }
Exemple #14
0
        private void PrintValueAsJson(string name, DataValue value)
        {
            var jsonEncoder = new JsonEncoder(m_session.MessageContext, JsonReversible);

            jsonEncoder.WriteDataValue(name, value);
            var textbuffer = jsonEncoder.CloseAndReturnText();

            // prettify
            using (var stringWriter = new StringWriter())
            {
                try
                {
                    using (var stringReader = new StringReader(textbuffer))
                    {
                        var jsonReader = new JsonTextReader(stringReader);
                        var jsonWriter = new JsonTextWriter(stringWriter)
                        {
                            Formatting = Formatting.Indented,
                            Culture    = CultureInfo.InvariantCulture
                        };
                        jsonWriter.WriteToken(jsonReader);
                        Console.WriteLine(stringWriter.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to format the JSON output:", ex.Message);
                    Console.WriteLine(textbuffer);
                    Console.WriteLine(stringWriter.ToString());
                    ExitCode = ExitCode.ErrorJSONDecode;
                    throw;
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Encode DataSet message header
        /// </summary>
        private void EncodeDataSetMessageHeader(JsonEncoder encoder)
        {
            if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.DataSetWriterId) != 0)
            {
                encoder.WriteString(nameof(DataSetWriterId), DataSetWriterId.ToString());
            }

            if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.SequenceNumber) != 0)
            {
                encoder.WriteUInt32(nameof(SequenceNumber), SequenceNumber);
            }

            if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.MetaDataVersion) != 0)
            {
                encoder.WriteEncodeable(nameof(MetaDataVersion), MetaDataVersion, typeof(ConfigurationVersionDataType));
            }

            if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.Timestamp) != 0)
            {
                encoder.WriteDateTime(nameof(Timestamp), Timestamp);
            }

            if ((DataSetMessageContentMask & JsonDataSetMessageContentMask.Status) != 0)
            {
                encoder.WriteStatusCode(nameof(Status), Status);
            }
        }
 /// <summary>
 /// Encode ReplyTo
 /// </summary>
 private void EncodeReplyTo(JsonEncoder jsonEncoder)
 {
     if ((NetworkMessageContentMask & JsonNetworkMessageContentMask.ReplyTo) != 0)
     {
         jsonEncoder.WriteString("ReplyTo", ReplyTo);
     }
 }
        /// <summary>
        /// Encodes the object and returns the resulting byte array.
        /// </summary>
        /// <returns></returns>
        public override byte[] Encode()
        {
            ServiceMessageContext messageContext = new ServiceMessageContext();

            messageContext.NamespaceUris = ServiceMessageContext.GlobalContext.NamespaceUris;
            messageContext.ServerUris    = ServiceMessageContext.GlobalContext.ServerUris;

            bool topLevelIsArray = !HasNetworkMessageHeader && !HasSingleDataSetMessage;

            using (JsonEncoder encoder = new JsonEncoder(messageContext, false, null, topLevelIsArray))
            {
                // handle no header
                if (HasNetworkMessageHeader)
                {
                    Encode(encoder);
                }
                else if (DataSetMessages != null && DataSetMessages.Count > 0)
                {
                    if (HasSingleDataSetMessage)
                    {
                        // encode single dataset message
                        JsonDataSetMessage jsonDataSetMessage = DataSetMessages[0] as JsonDataSetMessage;
                        if (jsonDataSetMessage != null)
                        {
                            if (!jsonDataSetMessage.HasDataSetMessageHeader)
                            {
                                // (UA Specs:) If the NetworkMessageHeader and the DataSetMessageHeader bits are not set
                                // and SingleDataSetMessage bit is set, the NetworkMessage
                                // is a JSON object containing the set of name/value pairs defined for a single DataSet.
                                jsonDataSetMessage.EncodePayload(encoder, false);
                            }
                            else
                            {
                                // If the SingleDataSetMessage bit of the NetworkMessageContentMask is set,
                                // the content of the Messages field is a JSON object containing a single DataSetMessage.
                                jsonDataSetMessage.Encode(encoder);
                            }
                        }
                    }
                    else
                    {
                        // If the NetworkMessageHeader bit of the NetworkMessageContentMask is not set,
                        // the NetworkMessage is the contents of the Messages field (e.g. a JSON array of DataSetMessages).
                        foreach (var message in DataSetMessages)
                        {
                            JsonDataSetMessage jsonDataSetMessage = message as JsonDataSetMessage;
                            if (jsonDataSetMessage != null)
                            {
                                jsonDataSetMessage.Encode(encoder);
                            }
                        }
                    }
                }

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(encoder.CloseAndReturnText());

                return(bytes);
            }
        }
        public static ISagaConfigurator <TS, TD> UseRabbitMQTransport <TS, TD>(this ISagaConfigurator <TS, TD> sagaConfigurator,
                                                                               RabbitConfiguration config)
            where TS : Saga <TD>
            where TD : SagaState
        {
            var sagaType           = typeof(TS);
            var messageHandlerType = typeof(IHandleMessage <>).GetGenericTypeDefinition();
            var interfaces         = sagaType.GetInterfaces();

            foreach (var i in interfaces)
            {
                if (!i.IsGenericType)
                {
                    continue;
                }

                var openGeneric = i.GetGenericTypeDefinition();
                if (!openGeneric.IsAssignableFrom(messageHandlerType))
                {
                    continue;
                }

                var messageType = i.GetGenericArguments().First();

                sagaConfigurator.Services.AddSingleton(typeof(ISubscriber),
                                                       typeof(RabbitSubscriber <>).MakeGenericType(messageType));
            }

            if (!_initialized)
            {
                var encoder = new JsonEncoder();
                sagaConfigurator.Services.AddSingleton <IEncoder>(encoder);
                sagaConfigurator.Services.AddSingleton <IDecoder>(encoder);

                sagaConfigurator.Services.AddSingleton <IQueueReferenceFactory, QueueReferenceFactory>();
                sagaConfigurator.Services.AddSingleton <IMessageParser, MessageParser>();
                sagaConfigurator.Services.AddSingleton <IPublisher, RabbitPublisher>();
                sagaConfigurator.Services.AddSingleton <IPublisherChannelFactory, PublisherChannelFactory>();

                sagaConfigurator.Services.AddSingleton <IConnectionFactory>(ctx =>
                {
                    var connectionFactory = new ConnectionFactory()
                    {
                        HostName = config.HostName,
                        UserName = config.UserName,
                        Password = config.Password,
                        Port     = AmqpTcpEndpoint.UseDefaultPort,
                        DispatchConsumersAsync = true
                    };
                    return(connectionFactory);
                });

                sagaConfigurator.Services.AddSingleton <IBusConnection, RabbitPersistentConnection>();

                _initialized = true;
            }

            return(sagaConfigurator);
        }
 public void JsonEncoder_Constructor2()
 {
     using (var jsonEncoder = new JsonEncoder(m_context, false))
     {
         TestEncoding(jsonEncoder);
         _ = jsonEncoder.CloseAndReturnText();
     }
 }
 public void JsonEncoder_Constructor_Streamwriter_Reflection2()
 {
     using (var jsonEncoder = new JsonEncoder(m_context, false, false, m_memoryStream, true, StreamSize))
     {
         TestEncoding(jsonEncoder);
         var result = jsonEncoder.CloseAndReturnText();
     }
 }
 public void JsonEncoder_Constructor_Streamwriter2()
 {
     using (var jsonEncoder = new JsonEncoder(m_context, false, false, m_memoryStream, true, StreamSize))
     {
         TestEncoding(jsonEncoder);
         int length = jsonEncoder.Close();
         var result = Encoding.UTF8.GetString(m_memoryStream.ToArray());
     }
 }
        public void Test_WriteSingleEncodeableWithNameAndArrayAsTopLevel_Expect_Exception()
        {
            using (var encodeable = new FooBarEncodeable())
            {
                var encoder = new JsonEncoder(Context, true, null, true);

                Assert.Throws <ServiceResultException>(() => encoder.WriteEncodeable(encodeable.Foo, encodeable, typeof(FooBarEncodeable)));
            }
        }
 public void JsonEncoder_Constructor_Recyclable_Streamwriter2()
 {
     using (var memoryStream = new Microsoft.IO.RecyclableMemoryStream(m_memoryManager))
         using (var jsonEncoder = new JsonEncoder(m_context, false, false, memoryStream, false, StreamSize))
         {
             TestEncoding(jsonEncoder);
             int length = jsonEncoder.Close();
             var result = Encoding.UTF8.GetString(m_memoryStream.ToArray());
         }
 }
Exemple #24
0
        public void BeforeTest()
        {
            container  = new CompositionContainer();
            fileSystem = new MockFileSystem();
            encoder    = new JsonEncoder(fileSystem);
            config     = new JsonEncoderConfiguration();

            input = new EncodeEventQueueImp();
            input.Open();
        }
Exemple #25
0
        async Task DiscoverUdp(IPAddress local, IPEndPoint ep)
        {
            XTrace.WriteLine("DiscoverUdp: {0} -> {1}", local, ep);

            // 构建请求
            var enc = new JsonEncoder();
            var msg = enc.CreateRequest("Api/Info", null);
            var req = msg.ToPacket().ReadBytes();

            var udp = new UdpClient(ep.AddressFamily)
            {
                EnableBroadcast = true
            };

            if (local != null)
            {
                udp.Client.Bind(new IPEndPoint(local, Rand.Next(1000, 60000)));
            }

            // 发送
            udp.Send(req, req.Length, ep);

            // 多次接收
            while (true)
            {
                try
                {
                    var source = new CancellationTokenSource(3_000);
                    var rs     = await udp.ReceiveAsync(source.Token);

                    if (rs.Buffer != null)
                    {
                        msg = new DefaultMessage();
                        msg.Read(rs.Buffer);

                        if (enc.Decode(msg, out var action, out var code, out var data) && code == 0)
                        {
                            // 解码结果
                            var result = enc.DecodeResult(action, data, msg);
                            XTrace.WriteLine("Receive[{0}] {1}", udp.Client.LocalEndPoint, result.ToJson());

                            var ai = enc.Convert(result, typeof(ApiItem)) as ApiItem;
                            if (ai != null)
                            {
                                Invoke(() => ShowItem(ai));
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    break;
                }
            }
        }
        private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                if (notification == null)
                {
                    return;
                }

                DataValue value = notification.Value as DataValue;
                if (value == null)
                {
                    return;
                }

                using (var encoder = new JsonEncoder(monitoredItem.Subscription.Session.MessageContext, false))
                {
                    string applicationURI = monitoredItem.Subscription.Session.Endpoint.Server.ApplicationUri;
                    encoder.WriteString("ApplicationUri", applicationURI);
                    encoder.WriteString("DisplayName", monitoredItem.DisplayName);
                    encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId);
                    // suppress output of server timestamp in json by setting it to minvalue
                    value.ServerTimestamp = DateTime.MinValue;
                    encoder.WriteDataValue("Value", value);

                    string json = encoder.CloseAndReturnText();

                    var properties = new Dictionary <string, string>();
                    properties.Add("content-type", "application/opcua+uajson");
                    properties.Add("deviceName", Id);

                    if (SharedAccessKey != null)
                    {
                        properties.Add("source", "mapping");
                        properties.Add("deviceKey", SharedAccessKey);
                    }

                    try
                    {
                        Module.Publish(new Message(json, properties));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Opc.Ua.Client.SampleModule: Failed to publish message, dropping...");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Opc.Ua.Client.SampleModule: Error processing monitored item notification.");
                Console.WriteLine(exception.ToString());
            }
        }
Exemple #27
0
 public override void EncodeTyped(ref JsonEncoder encoder, T?value)
 {
     if (value == null)
     {
         encoder.Write("null");
     }
     else
     {
         this.valueEncoder.EncodeTyped(ref encoder, value.GetValueOrDefault());
     }
 }
Exemple #28
0
 public override void EncodeTyped(ref JsonEncoder encoder, T value)
 {
     if (value == null)
     {
         encoder.Write("null");
     }
     else
     {
         this.valueEncoder.EncodeTyped(ref encoder, value);
     }
 }
Exemple #29
0
        public void AfterTest()
        {
            container.Dispose();
            container = null;

            fileSystem = null;
            encoder    = null;
            config     = null;

            input = null;
        }
Exemple #30
0
        /// <summary>
        /// Serialize the specified object into a json string.
        /// </summary>
        /// <param name="obj">Object to convert to a json string.</param>
        public static string Serialize(object obj)
        {
            string result = JsonEncoder.Encode(CurrentJsonSerializer, obj);

            if (!string.IsNullOrEmpty(result) && (CurrentJsonSerializer.Options & EncodeOptions.PrettyPrint) == EncodeOptions.PrettyPrint)
            {
                return(JsonFormatter.PrettyPrint(result));
            }

            return(result);
        }
        private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                if (e.NotificationValue == null || monitoredItem.Subscription.Session == null)
                {
                    return;
                }

                JsonEncoder encoder = new JsonEncoder(
                    monitoredItem.Subscription.Session.MessageContext, false);
                encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId);
                e.NotificationValue.Encode(encoder);

                var json = encoder.Close();
                var bytes = new UTF8Encoding(false).GetBytes(json);

                foreach (var publisher in m_publishers)
                {
                    try
                    {
                        publisher.Publish(new ArraySegment<byte>(bytes));
                    }
                    catch(Exception ex)
                    {
                        Utils.Trace(ex, "Failed to publish message, dropping....");
                    }
                }
            }
            catch (Exception exception)
            {
                Utils.Trace(exception, "Error processing monitored item notification.");
            }
        }
Exemple #32
0
        private void NotificationsCTRL_ItemsAdded(object sender, ListItemActionEventArgs e)
        {
            try
            {
                foreach (NotificationMessageListCtrl.ItemData item in e.Items)
                {
                    if (item.NotificationMessage == null || item.Subscription.Session == null)
                    {
                        return;
                    }

                    JsonEncoder encoder = new JsonEncoder(
                        item.Subscription.Session.MessageContext, false);

                    foreach (MonitoredItem monitoredItem in item.Subscription.MonitoredItems)
                    {
                        encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId);
                        item.NotificationMessage.Encode(encoder);

                        var json = encoder.Close();
                        try
                        {
                            m_massTransitPublisher.Publish(json);
                            Utils.Trace(null, "Publishing: " + json);
                        }
                        catch (Exception ex)
                        {
                            Utils.Trace(ex, "Failed to publish message, dropping....");
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Utils.Trace(exception, "Error processing monitored item notification.");
            }
        }
        private void NotificationsCTRL_ItemsAdded(object sender, ListItemActionEventArgs e)
        {
            try
            {
                foreach (NotificationMessageListCtrl.ItemData item in e.Items)
                {
                    if (item.NotificationMessage == null || item.Subscription.Session == null)
                    {
                        return;
                    }

                    JsonEncoder encoder = new JsonEncoder(
                        item.Subscription.Session.MessageContext, false);

                    foreach (MonitoredItem monitoredItem in item.Subscription.MonitoredItems)
                    {
                        encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId);
                        ((DataChangeNotification)((NotificationData)item.NotificationMessage.NotificationData[0].Body)).MonitoredItems[0].Encode(encoder);

                        string json = encoder.Close();
                        json = json.Replace("\\", "");
                        byte[] bytes = new UTF8Encoding(false).GetBytes(json);

                        foreach (var publisher in m_publishers)
                        {
                            try
                            {
                                publisher.Publish(new ArraySegment<byte>(bytes));
                                Utils.Trace(null, "Publishing: " + json);
                            }
                            catch (Exception ex)
                            {
                                Utils.Trace(ex, "Failed to publish message, dropping....");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Utils.Trace(exception, "Error processing monitored item notification.");
            }
        }