Esempio n. 1
0
        public void NetworkTargetDefaultsTest()
        {
            var target = new NetworkTarget();

            Assert.True(target.KeepConnection);
            Assert.False(target.NewLine);
            Assert.Equal("\r\n", target.LineEnding.NewLineCharacters);
            Assert.Equal(65000, target.MaxMessageSize);
            Assert.Equal(5, target.ConnectionCacheSize);
            Assert.Equal(0, target.MaxConnections);
            Assert.Equal(0, target.MaxQueueSize);
            Assert.Equal(Encoding.UTF8, target.Encoding);
        }
Esempio n. 2
0
        public void NetworkTargetMultipleConnectionsWithMessageErrorTest()
        {
            var senderFactory = new MySenderFactory();
            var target        = new NetworkTarget();

            target.Address        = "tcp://${logger}.company.lan/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.KeepConnection = true;
            target.MaxMessageSize = 10;
            target.OnOverflow     = NetworkTargetOverflowAction.Error;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 3;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation));

            mre.WaitOne();
            Assert.IsNull(exceptions[0]);
            Assert.IsNotNull(exceptions[1]);
            Assert.AreEqual("Attempted to send a message larger than MaxMessageSize (10). Actual size was: 15. Adjust OnOverflow and MaxMessageSize parameters accordingly.", exceptions[1].Message);
            Assert.IsNull(exceptions[2]);

            target.Close();

            string expectedLog = @"1: connect tcp://logger1.company.lan/
1: send 0 7
1: close
2: connect tcp://logger2.company.lan/
2: send 0 5
2: close
";

            Assert.AreEqual(expectedLog, senderFactory.Log.ToString());
        }
Esempio n. 3
0
        protected override void ConfigureLogging(LoggingConfiguration config)
        {
            base.ConfigureLogging(config);

            if (Debugger.IsAttached)
            {
                var udpTarget = new NetworkTarget {
                    Address = "udp4://localhost:962",
                    Layout  = new Log4JXmlEventLayout()
                };
                config.AddTarget("udp", udpTarget);
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, udpTarget));
            }
        }
Esempio n. 4
0
        void RemoteInvocation(EntityBase target, MethodInfo method, NetworkTarget netTarget, params object[] args)
        {
#if !(RELEASE && RELEASE_DISABLE_CHECKS)
            if (!method.ContainsAttribute <RemoteInvocationAttribute>())
            {
                throw new AttributeUsageException("Method did not contain RemoteInvocation attribute");
            }
            if (target == null)
            {
                throw new RemoteInvocationException("Non-static method owner does not derive from EntityBase.");
            }
#endif

            NativeEntityMethods.RemoteInvocation(Id, target.Id, method.Name, args, netTarget, -1);
        }
Esempio n. 5
0
        public void NetworkTargetNotConnectedTest()
        {
            var target = new NetworkTarget()
            {
                Address        = "tcp4://127.0.0.1:33415",
                Layout         = "${message}\n",
                KeepConnection = true,
            };

            target.Initialize(new LoggingConfiguration());

            int toWrite        = 10;
            int pendingWrites  = toWrite;
            var writeCompleted = new ManualResetEvent(false);
            var exceptions     = new List <Exception>();

            AsyncContinuation writeFinished =
                ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    pendingWrites--;
                    if (pendingWrites == 0)
                    {
                        writeCompleted.Set();
                    }
                }
            };

            for (int i = 0; i < toWrite; ++i)
            {
                var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
                target.WriteAsyncLogEvent(ev);
            }

            writeCompleted.WaitOne();


            // no exception
            target.Close();

            Assert.Equal(toWrite, exceptions.Count);
            foreach (var ex in exceptions)
            {
                Assert.NotNull(ex);
            }
        }
Esempio n. 6
0
    static void Main(string[] args)
    {
        NetworkTarget target = new NetworkTarget();

        target.Layout  = "${level} ${logger} ${message}${newline}";
        target.Address = "tcp://localhost:5555";

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");

        logger.Trace("log message 1");
        logger.Debug("log message 2");
        logger.Info("log message 3");
        logger.Warn("log message 4");
        logger.Error("log message 5");
        logger.Fatal("log message 6");
    }
        public void HttpNetworkSenderViaNetworkTargetRecoveryTest()
        {
            // Arrange
            var networkTarget = new NetworkTarget("target1")
            {
                Address = "http://test.with.mock",
                Layout  = "${logger}|${message}|${exception}"
            };

            var webRequestMock = new WebRequestMock();

            webRequestMock.FirstRequestMustFail = true;
            var networkSenderFactoryMock = CreateNetworkSenderFactoryMock(webRequestMock);

            networkTarget.SenderFactory = networkSenderFactoryMock;

            var logFactory = new LogFactory();
            var config     = new LoggingConfiguration(logFactory);

            config.AddRuleForAllLevels(networkTarget);
            logFactory.Configuration = config;

            var logger = logFactory.GetLogger("HttpHappyPathTestLogger");

            // Act
            logger.Info("test message1");   // Will fail after short delay
            logger.Info("test message2");   // Will be queued and sent after short delay
            logFactory.Flush();

            // Assert
            var mock = webRequestMock;

            var requestedString = mock.GetRequestContentAsString();

            Assert.Equal("http://test.with.mock/", mock.RequestedAddress.ToString());
            Assert.Equal("HttpHappyPathTestLogger|test message2|", requestedString);
            Assert.Equal("POST", mock.Method);

            networkSenderFactoryMock.Received(1).Create("http://test.with.mock", 0, SslProtocols.None, new TimeSpan()); // Only created one HttpNetworkSender

            // Cleanup
            mock.Dispose();
        }
Esempio n. 8
0
        private void RemoteInvocation(EntityBase target, MethodInfo method, NetworkTarget netTarget, int channelId,
                                      params object[] args)
        {
            if (!method.ContainsAttribute <RemoteInvocationAttribute>())
            {
#if RELEASE
                return;
#else
                throw new AttributeUsageException("Method did not contain RemoteInvocation attribute");
#endif
            }

#if !(RELEASE && RELEASE_DISABLE_CHECKS)
            if (target == null)
            {
                throw new RemoteInvocationException("Non-static method owner does not derive from EntityBase.");
            }
#endif

            EntityInterop.RemoteInvocation(this.Id, target.Id, method.Name, args, netTarget, channelId);
        }
Esempio n. 9
0
        public void NetworkTargetMultipleConnectionsWithCacheOverflowTest()
        {
            var senderFactory = new MySenderFactory();
            var target        = new NetworkTarget();

            target.Address             = "tcp://${logger}.company.lan/";
            target.SenderFactory       = senderFactory;
            target.Layout              = "${message}";
            target.KeepConnection      = true;
            target.ConnectionCacheSize = 2;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 6;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            // logger1 should be kept alive because it's being referenced frequently
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation));

            mre.WaitOne();
            foreach (var ex in exceptions)
            {
                if (ex != null)
                {
                    Assert.True(false, ex.ToString());
                }
            }

            target.Close();

            string result = senderFactory.Log.ToString();

            Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
            Assert.True(result.IndexOf("1: send 0 4") != -1);
            Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
            Assert.True(result.IndexOf("2: send 0 4") != -1);
            Assert.True(result.IndexOf("1: send 0 4") != -1);
            Assert.True(result.IndexOf("2: close") != -1);
            Assert.True(result.IndexOf("3: connect tcp://logger3.company.lan/") != -1);
            Assert.True(result.IndexOf("3: send 0 4") != -1);
            Assert.True(result.IndexOf("1: send 0 4") != -1);
            Assert.True(result.IndexOf("3: close") != -1);
            Assert.True(result.IndexOf("4: connect tcp://logger2.company.lan/") != -1);
            Assert.True(result.IndexOf("4: send 0 4") != -1);
            Assert.True(result.IndexOf("1: close") != -1);
            Assert.True(result.IndexOf("4: close") != -1);
        }
Esempio n. 10
0
        public void NetworkTargetMultipleConnectionsTest()
        {
            var senderFactory = new MySenderFactory();
            var target        = new NetworkTarget();

            target.Address        = "tcp://${logger}.company.lan/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.KeepConnection = true;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 3;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg3").WithContinuation(asyncContinuation));

            mre.WaitOne();
            foreach (var ex in exceptions)
            {
                if (ex != null)
                {
                    Assert.True(false, ex.ToString());
                }
            }

            mre.Reset();
            AsyncContinuation flushContinuation = ex =>
            {
                mre.Set();
            };

            target.Flush(flushContinuation);
            mre.WaitOne();
            target.Close();

            var actual = senderFactory.Log.ToString();

            Assert.True(actual.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
            Assert.True(actual.IndexOf("1: send 0 4") != -1);
            Assert.True(actual.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
            Assert.True(actual.IndexOf("2: send 0 4") != -1);
            Assert.True(actual.IndexOf("3: connect tcp://logger3.company.lan/") != -1);
            Assert.True(actual.IndexOf("3: send 0 4") != -1);
            Assert.True(actual.IndexOf("1: flush") != -1);
            Assert.True(actual.IndexOf("2: flush") != -1);
            Assert.True(actual.IndexOf("3: flush") != -1);
            Assert.True(actual.IndexOf("1: close") != -1);
            Assert.True(actual.IndexOf("2: close") != -1);
            Assert.True(actual.IndexOf("3: close") != -1);
        }
Esempio n. 11
0
 public void RemoteInvocation(Action action, NetworkTarget netTarget, int channelId = -1)
 {
     this.RemoteInvocation(action.Target as EntityBase, action.Method, netTarget, channelId, null);
 }
Esempio n. 12
0
        public void RemoteInvocation <T1, T2, T3, T4, T5, T6>(Action <T1, T2, T3, T4, T5, T6> action, NetworkTarget netTarget,
                                                              T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, int channelId = -1)
        {
            object[] args = new object[6];
            args[0] = param1;
            args[1] = param2;
            args[2] = param3;
            args[3] = param4;
            args[4] = param5;
            args[5] = param6;

            this.RemoteInvocation(action.Target as EntityBase, action.Method, netTarget, channelId, args);
        }
Esempio n. 13
0
 public void Position(NetworkTarget player, Vector3 position)
 {
     Debug.Log("Player " + player.connectionId + " position " + position);
 }
Esempio n. 14
0
            static void Prefix(NetworkGroup group, string rpcName, NetworkTarget networkTarget, int eventIndex, IBitSerializable serializable)
            {
                var outputTxt = "";

                outputTxt += $"{debugCount} SEND {rpcName}\n";
                debugCount++;
                if (networkTarget.UsingRPCMode_)
                {
                    var mode = typeof(NetworkTarget)
                               .GetField(
                        "mode_",
                        BindingFlags.Instance | BindingFlags.NonPublic
                        )
                               .GetValue(networkTarget);
                    if (networkTarget.SendToSelf_)
                    {
                        mode = RPCMode.All;
                    }
                    outputTxt += $"\tTo RPCMode {mode}\n";
                }
                else
                {
                    var recipient = typeof(NetworkTarget)
                                    .GetField(
                        "recipient_",
                        BindingFlags.Instance | BindingFlags.NonPublic
                        )
                                    .GetValue(networkTarget);
                    outputTxt += $"\tTo Player {recipient}\n";
                }
                outputTxt += $"\tIn {group}\n";

                List <Type> dataLookup = null;

                if (rpcName == "ReceiveBroadcastAllEvent")
                {
                    dataLookup = ClientToClientDataList;
                }
                else if (rpcName == "ReceiveClientToServerEvent")
                {
                    dataLookup = ClientToServerDataList;
                }
                else if (rpcName == "ReceiveServerToClientEvent" || rpcName == "ReceiveTargetedEventServerToClient")
                {
                    dataLookup = ServerToClientDataList;
                }
                else
                {
                    outputTxt += "\tUnknown Event\n";
                }
                if (dataLookup != null)
                {
                    if (eventIndex < 0 || eventIndex >= dataLookup.Count)
                    {
                        outputTxt += $"\tSending invalid event index: {eventIndex} out of {dataLookup.Count}\n";
                    }
                }
                try
                {
                    var data = serializable;
                    if (dataLookup != null)
                    {
                        outputTxt += $"\t{dataLookup[eventIndex]}\n";
                    }
                    else
                    {
                        outputTxt += $"\t{data.GetType()}";
                    }
                    outputTxt += DeepPrint(data, 2, printableProps) + "\n";
                }
                catch (Exception e)
                {
                    outputTxt += $"\tFailed to read data because: {e}\n";
                }

                if (outputTxt.Length > 0)
                {
                    outputTxt = outputTxt.Substring(0, outputTxt.Length - 1);
                }

                Console.WriteLine(outputTxt);
            }
Esempio n. 15
0
        public void NetworkTargetUdpTest()
        {
            var target = new NetworkTarget()
            {
                Address        = "udp://127.0.0.1:3002",
                Layout         = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                Exception receiveException = null;
                var       receivedMessages = new List <string>();
                var       receiveFinished  = new ManualResetEvent(false);

                byte[] receiveBuffer = new byte[4096];

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
                EndPoint      remoteEndPoint   = null;
                AsyncCallback receivedDatagram = null;

                receivedDatagram = result =>
                {
                    try
                    {
                        int    got     = listener.EndReceiveFrom(result, ref remoteEndPoint);
                        string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
                        lock (receivedMessages)
                        {
                            receivedMessages.Add(message);
                            if (receivedMessages.Count == 100)
                            {
                                receiveFinished.Set();
                            }
                        }

                        remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
                    }
                    catch (Exception ex)
                    {
                        receiveException = ex;
                    }
                };

                remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites  = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions     = new List <Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                {
                    lock (exceptions)
                    {
                        exceptions.Add(ex);
                        pendingWrites--;
                        if (pendingWrites == 0)
                        {
                            writeCompleted.Set();
                        }
                    }
                };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "message" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(10000, false));
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(10000, false));
                Assert.AreEqual(toWrite, receivedMessages.Count);
                for (int i = 0; i < toWrite; ++i)
                {
                    Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
                }

                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
            }
        }
Esempio n. 16
0
 extern public static void RemoteInvocation(EntityId entityId, EntityId targetId, string methodName, object[] args, NetworkTarget target, int channelId);
Esempio n. 17
0
 // Remove
 public static void Remove(NetworkTarget player)
 {
     map.Remove(player.connectionId);
     list.Remove(player);
 }
Esempio n. 18
0
        public void NetworkTargetSendFailureTests()
        {
            var senderFactory = new MySenderFactory()
            {
                FailCounter = 3, // first 3 sends will fail
            };

            var target = new NetworkTarget();

            target.Address        = "tcp://${logger}.company.lan/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.KeepConnection = true;
            target.OnOverflow     = NetworkTargetOverflowAction.Discard;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 5;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation));

            mre.WaitOne();
            Assert.NotNull(exceptions[0]);
            Assert.NotNull(exceptions[1]);
            Assert.NotNull(exceptions[2]);
            Assert.Null(exceptions[3]);
            Assert.Null(exceptions[4]);

            target.Close();

            var result = senderFactory.Log.ToString();

            Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
            Assert.True(result.IndexOf("1: send 0 7") != -1);
            Assert.True(result.IndexOf("1: failed") != -1);
            Assert.True(result.IndexOf("1: close") != -1);
            Assert.True(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1);
            Assert.True(result.IndexOf("2: send 0 7") != -1);
            Assert.True(result.IndexOf("2: failed") != -1);
            Assert.True(result.IndexOf("2: close") != -1);
            Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1);
            Assert.True(result.IndexOf("3: send 0 7") != -1);
            Assert.True(result.IndexOf("3: failed") != -1);
            Assert.True(result.IndexOf("3: close") != -1);
            Assert.True(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1);
            Assert.True(result.IndexOf("4: send 0 7") != -1);
            Assert.True(result.IndexOf("4: send 0 5") != -1);
            Assert.True(result.IndexOf("4: close") != -1);
        }
Esempio n. 19
0
        public void RemoteInvocation <T1, T2, T3, T4, T5>(Action <T1, T2, T3, T4, T5> action, NetworkTarget netTarget, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
        {
            object[] args = new object[5];
            args[0] = param1;
            args[1] = param2;
            args[2] = param3;
            args[3] = param4;
            args[4] = param5;

            RemoteInvocation(action.Target as EntityBase, action.Method, netTarget, args);
        }
Esempio n. 20
0
 public void RemoteInvocation(Action action, NetworkTarget netTarget)
 {
     RemoteInvocation(action.Target as EntityBase, action.Method, netTarget, null);
 }
 public static extern void RemoteInvocation(EntityId entityId, EntityId targetId, string methodName, object[] args, NetworkTarget target, int channelId);
Esempio n. 22
0
 // Add
 public static void Add(NetworkTarget player)
 {
     map.Add(player.connectionId, player);
     list.Add(player);
 }
Esempio n. 23
0
        private void HappyPathTest(bool newLine, LineEndingMode lineEnding, params string[] messages)
        {
            var senderFactory = new MySenderFactory();
            var target        = new NetworkTarget();

            target.Address        = "tcp://someaddress/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.NewLine        = newLine;
            target.LineEnding     = lineEnding;
            target.KeepConnection = true;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 3;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg3").WithContinuation(asyncContinuation));

            mre.WaitOne();
            foreach (var ex in exceptions)
            {
                if (ex != null)
                {
                    Assert.True(false, ex.ToString());
                }
            }

            Assert.Single(senderFactory.Senders);

            var sender = senderFactory.Senders[0];

            target.Close();

            // Get the length of all the messages and their line endings
            var eol       = newLine ? lineEnding.NewLineCharacters : string.Empty;
            var eolLength = eol.Length;
            var length    = messages.Sum(m => m.Length) + (eolLength * messages.Length);

            Assert.Equal(length, sender.MemoryStream.Length);
            Assert.Equal(string.Join(eol, messages) + eol, target.Encoding.GetString(sender.MemoryStream.GetBuffer(), 0, (int)sender.MemoryStream.Length));

            // we invoke the sender for each message, each time sending 4 bytes
            var actual = senderFactory.Log.ToString();

            Assert.True(actual.IndexOf("1: connect tcp://someaddress/") != -1);
            foreach (var message in messages)
            {
                Assert.True(actual.IndexOf($"1: send 0 {message.Length + eolLength}") != -1);
            }
            Assert.True(actual.IndexOf("1: close") != -1);
        }
Esempio n. 24
0
        public void RemoteInvocation <T1, T2, T3, T4>(Action <T1, T2, T3, T4> action, NetworkTarget netTarget, T1 param1, T2 param2, T3 param3, T4 param4, int channelId = -1)
        {
            object[] args = new object[4];
            args[0] = param1;
            args[1] = param2;
            args[2] = param3;
            args[3] = param4;

            RemoteInvocation(action.Target as EntityBase, action.Method, netTarget, channelId, args);
        }
Esempio n. 25
0
        public void NetworkTargetMultipleConnectionsWithoutKeepAliveTest()
        {
            var senderFactory = new MySenderFactory();
            var target        = new NetworkTarget();

            target.Address        = "tcp://${logger}.company.lan/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.KeepConnection = false;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 6;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation));

            mre.WaitOne();
            foreach (var ex in exceptions)
            {
                if (ex != null)
                {
                    Assert.Fail(ex.ToString());
                }
            }

            target.Close();

            string expectedLog = @"1: connect tcp://logger1.company.lan/
1: send 0 4
1: close
2: connect tcp://logger2.company.lan/
2: send 0 4
2: close
3: connect tcp://logger1.company.lan/
3: send 0 4
3: close
4: connect tcp://logger3.company.lan/
4: send 0 4
4: close
5: connect tcp://logger1.company.lan/
5: send 0 4
5: close
6: connect tcp://logger2.company.lan/
6: send 0 4
6: close
";

            Assert.AreEqual(expectedLog, senderFactory.Log.ToString());
        }
Esempio n. 26
0
 extern internal static void RemoteInvocation(uint entityId, uint targetId, string methodName, object[] args, NetworkTarget target, int channelId);
Esempio n. 27
0
        public void NetworkTargetTcpTest()
        {
            NetworkTarget target;

            target = new NetworkTarget()
            {
                Address        = "tcp://127.0.0.1:3004",
                Layout         = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                Exception receiveException = null;
                var       resultStream     = new MemoryStream();
                var       receiveFinished  = new ManualResetEvent(false);

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3004));
                listener.Listen(10);
                listener.BeginAccept(
                    result =>
                {
                    try
                    {
                        // Console.WriteLine("Accepting...");
                        byte[] buffer = new byte[4096];
                        using (Socket connectedSocket = listener.EndAccept(result))
                        {
                            // Console.WriteLine("Accepted...");
                            int got;
                            while ((got = connectedSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                            {
                                resultStream.Write(buffer, 0, got);
                            }
                            // Console.WriteLine("Closing connection...");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Receive exception {0}", ex);
                        receiveException = ex;
                    }
                    finally
                    {
                        receiveFinished.Set();
                    }
                }, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites  = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions     = new List <Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                {
                    lock (exceptions)
                    {
                        Console.WriteLine("{0} Write finished {1}", pendingWrites, ex);
                        exceptions.Add(ex);
                        pendingWrites--;
                        if (pendingWrites == 0)
                        {
                            writeCompleted.Set();
                        }
                    }
                };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "messagemessagemessagemessagemessage" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "messagemessagemessagemessagemessage" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(10000, false), "Writes did not complete");
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(10000, false), "Receive did not complete");
                string resultString = Encoding.UTF8.GetString(resultStream.GetBuffer(), 0, (int)resultStream.Length);
                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
                Assert.AreEqual(expectedResult, resultString);
            }
        }
 private static void SetupNetworkTarget(NetworkTarget target, string address)
 {
     target.Address = new SimpleLayout(address);
 }
Esempio n. 29
0
        public void NetworkTargetSendFailureWithoutKeepAliveTests()
        {
            var senderFactory = new MySenderFactory()
            {
                FailCounter = 3, // first 3 sends will fail
            };

            var target = new NetworkTarget();

            target.Address        = "tcp://${logger}.company.lan/";
            target.SenderFactory  = senderFactory;
            target.Layout         = "${message}";
            target.KeepConnection = false;
            target.OnOverflow     = NetworkTargetOverflowAction.Discard;
            target.Initialize(null);

            var exceptions = new List <Exception>();
            var mre        = new ManualResetEvent(false);
            int remaining  = 5;
            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (--remaining == 0)
                    {
                        mre.Set();
                    }
                }
            };

            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
            target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation));

            mre.WaitOne();
            Assert.IsNotNull(exceptions[0]);
            Assert.IsNotNull(exceptions[1]);
            Assert.IsNotNull(exceptions[2]);
            Assert.IsNull(exceptions[3]);
            Assert.IsNull(exceptions[4]);

            target.Close();

            string expectedLog = @"1: connect tcp://logger1.company.lan/
1: send 0 7
1: failed
1: close
2: connect tcp://logger1.company.lan/
2: send 0 7
2: failed
2: close
3: connect tcp://logger1.company.lan/
3: send 0 7
3: failed
3: close
4: connect tcp://logger1.company.lan/
4: send 0 7
4: close
5: connect tcp://logger1.company.lan/
5: send 0 5
5: close
";

            Assert.AreEqual(expectedLog, senderFactory.Log.ToString());
        }
Esempio n. 30
0
 internal static extern void RemoteInvocation(uint entityId, uint targetId, string methodName, object[] args, NetworkTarget target, int channelId);