Example #1
0
        public async Task PublishToNonExistentQueueAsync()
        {
            var options = new RabbitOptions();

            options.FactoryOptions.Uri = new Uri("amqp://*****:*****@localhost:5672/");

            var pub = new Publisher(
                _fixture.ChannelPool,
                _fixture.SerializationProvider,
                _fixture.EncryptionProvider,
                _fixture.CompressionProvider);

            var letter = MessageExtensions.CreateSimpleRandomLetter("TestQueue", 2000);

            await pub.PublishAsync(letter, false);

            var tokenSource = new CancellationTokenSource(delay: TimeSpan.FromSeconds(1));

            async Task ReadReceiptAsync(CancellationToken cancellationToken)
            {
                var receiptBuffer = pub.GetReceiptBufferReader();
                await receiptBuffer.WaitToReadAsync(cancellationToken);

                var receipt = receiptBuffer.ReadAsync(cancellationToken);
            }

            await Assert
            .ThrowsAnyAsync <OperationCanceledException>(() => ReadReceiptAsync(tokenSource.Token));
        }
Example #2
0
        void Send(Header h)
        {
            gotAck  = false;
            gotNack = false;
            gui.ShowMessage("Command " + Enum.GetName(typeof(OPCODE), h.Opcode) + " sent");
            log.Debug("Command " + Enum.GetName(typeof(OPCODE), h.Opcode) + " sent");
            switch (h.Opcode)
            {
            case OPCODE.RequestMonitoringReport:
            case OPCODE.IdentifyAndSeparate:
                monitorReportReceived = false;
                break;

            case OPCODE.ConfigureHwfe:
                hwStateReceived  = false;
                feStatusEeceived = false;
                break;

            case OPCODE.ConfigureSwfe:
                swStateReceived  = false;
                feStatusEeceived = false;
                break;

            case OPCODE.StartFe:
                feStatusEeceived = false;
                break;
            }
            client.Send(MessageExtensions.ToByteArray(h));
        }
Example #3
0
        public void StartThread(Uri input1_url, Uri input2_url, Uri output1_url, Uri output2_url)
        {
            try
            {
                if (Connect() == false)
                {
                    log.Warn("Cannot connect to the Mediation server");
                    return;
                }

                log.Debug("Starting Mediation");
                lastCommand = "Start Command";
                AutomaticStartCommand asc = new AutomaticStartCommand
                {
                    Input1Url  = input1_url.ToString(),
                    Input2Url  = input2_url.ToString(),
                    Output1Url = output1_url.ToString(),
                    Output2Url = output2_url.ToString()
                };

                Header h = new Header {
                    Sequence = 0, Opcode = OPCODE.AutoStartCmd, MessageData = MessageExtensions.ToByteString(asc)
                };
                Send(h);
                log.Debug("Mediation started");
                isRunning = true;
            }
            catch (Exception e)
            {
                log.Error("Mediation error during auto start", e);
                isRunning = false;
            }
        }
Example #4
0
        public async Task <GamestreamSession> StartGamestreamAsync()
        {
            var startMessage = new GamestreamStartMessage()
            {
                Configuration        = GamestreamConfiguration.GetStandardConfig(),
                ReQueryPreviewStatus = false
            };

            var startedMessageTask = MessageExtensions.WaitForMessageAsync <GamestreamStateStartedMessage, BroadcastErrorMessage, BroadcastBaseMessage>(
                _transport,
                TimeSpan.FromSeconds(2),
                () => _transport.SendAsync(startMessage));

            var initializingMessageTask = MessageExtensions.WaitForMessageAsync
                                          <GamestreamStateInitializingMessage, BroadcastErrorMessage, BroadcastBaseMessage>(_transport, TimeSpan.FromSeconds(10));

            await Task.WhenAll(initializingMessageTask, startedMessageTask);

            var initializingMessage = initializingMessageTask.Result;
            var startedMessage      = startedMessageTask.Result;

            if (initializingMessage.SessionId != startedMessage.SessionId)
            {
                throw new GamestreamException("Invalid session received.", GamestreamError.General);
            }

            return(new GamestreamSession(initializingMessage.TcpPort, initializingMessage.UdpPort));
        }
Example #5
0
        public void SendMsg(AFCoreEx.AFIDENTID xID, AFMsg.EGameMsgID unMsgID, IMessage xData)
        {
            MemoryStream stream = new MemoryStream();

            MessageExtensions.WriteTo(xData, stream);
            SendMsg(xID, unMsgID, stream);
        }
        public void GlobalSetup()
        {
            var marshaller = Marshallers.Create((arg) => MessageExtensions.ToByteArray(arg), bytes => new ChatMessage());
            var method     = new Method <ChatMessage, ChatMessage>(MethodType.Unary, typeof(TestService).FullName, nameof(TestService.SayHello), marshaller, marshaller);

            _callHandler = new UnaryServerCallHandler <ChatMessage, ChatMessage, TestService>(method);

            _trailers = new HeaderDictionary();

            var messageData = new ChatMessage
            {
                Name = "Joe"
            }.ToByteArray();

            _requestStream = new MemoryStream();
            MessageHelpers.WriteMessage(_requestStream, messageData);

            var services = new ServiceCollection();

            services.TryAddSingleton <IGrpcServiceActivator <TestService> >(new TestGrpcServiceActivator <TestService>(new TestService()));
            _requestServices = services.BuildServiceProvider();

            _httpContext = new DefaultHttpContext();
            _httpContext.RequestServices = _requestServices;
            _httpContext.Request.Body    = _requestStream;

            _httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
            {
                Trailers = _trailers
            });
        }
Example #7
0
        public async Task CreateAutoPublisherByConfigQueueAndConcurrentPublish()
        {
            var pub = new Publisher(
                _fixture.Options,
                _fixture.SerializationProvider,
                _fixture.EncryptionProvider,
                _fixture.CompressionProvider);

            await pub.StartAutoPublishAsync().ConfigureAwait(false);

            var         finished = false;
            const ulong count    = 10000;

            await Task.Run(
                async() =>
            {
                for (ulong i = 0; i < count; i++)
                {
                    var letter       = MessageExtensions.CreateSimpleRandomLetter("AutoPublisherTestQueue");
                    letter.MessageId = Guid.NewGuid().ToString();
                    await pub.QueueMessageAsync(letter).ConfigureAwait(false);
                }

                finished = true;
            }).ConfigureAwait(false);

            while (!finished)
            {
                await Task.Delay(1).ConfigureAwait(false);
            }

            await pub.StopAutoPublishAsync().ConfigureAwait(false);
        }
Example #8
0
        public void TestDeserialise()
        {
            const string sender          = "ftp://127.0.0.1:22/";
            const string recipient       = "ftp://127.0.0.1/";
            const string messageProperty = "Something";
            var          messageCreated  = DateTime.Now;

            const string messageTemplate = @"{{""Sender"":{{""PeerAddress"":""{0}""}},""Recipient"":{{""PeerAddress"":""{1}""}},""Message"":{{""MessageType"":""{2}"",""MessageProperty"":""{3}""}},""MessageCreated"":""{4}""}}";

            var serialiser = new JsonMessageSerialiser(this._messageTypeDictionary);

            var messageContent = string.Format(
                messageTemplate,
                sender,
                recipient,
                MessageExtensions.MessageTypeSignature <DummyMessage>(),
                messageProperty,
                messageCreated.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK"));

            var deserialised = serialiser.Deserialise(messageContent);

            Assert.IsInstanceOfType(deserialised, typeof(Envelope <DummyMessage>));
            Assert.AreEqual(sender, deserialised.Sender.PeerAddress.AbsoluteUri);
            Assert.AreEqual(recipient, deserialised.Recipient.PeerAddress.AbsoluteUri);
            Assert.AreEqual(messageCreated, deserialised.MessageCreated);
            Assert.AreEqual(messageProperty, (deserialised.Message as DummyMessage).MessageProperty);
        }
Example #9
0
        public bool StartThread(Uri Orion_url, Uri input1_url, Uri input2_url, int Port1, int Port2)
        {
            log.Debug("Cygnus started");
            if (Connect() == false)
            {
                log.Warn("Cannot connect to the Cygnus server");
                return(false);
            }

            try
            {
                lastCommand = "Start Command";
                StartCommand sc = new StartCommand
                {
                    BoxUrl    = Orion_url.ToString(),
                    E1Port1   = Port1,
                    E1Port2   = Port2,
                    Input1Url = input1_url.ToString(),
                    Input2Url = input2_url.ToString()
                };
                Header h = new Header {
                    Sequence = 0, Opcode = OPCODE.StartCmd, MessageData = MessageExtensions.ToByteString(sc)
                };
                Send(h);
                log.Debug("Cygnus started");
                isRunning = true;
            }
            catch (Exception e)
            {
                log.Error("Cygnus error during auto start", e);
                isRunning = false;
            }
            return(isRunning);
        }
Example #10
0
        private static async Task PublishLettersAsync(Publisher apub, string queueName, int count)
        {
            var sw = Stopwatch.StartNew();

            for (int i = 0; i < count; i++)
            {
                var letter = MessageExtensions.CreateSimpleRandomLetter(queueName, MessageSize);
                letter.Envelope.RoutingOptions.DeliveryMode = 1;
                letter.MessageId = Guid.NewGuid().ToString();

                await apub.QueueMessageAsync(letter).ConfigureAwait(false);

                if (i % 10_000 == 0)
                {
                    await Console
                    .Out
                    .WriteLineAsync($"- QueueName ({queueName}) is publishing letter {letter.MessageId}")
                    .ConfigureAwait(false);
                }
            }
            sw.Stop();

            await Console
            .Out
            .WriteLineAsync($"- Finished queueing all letters in {sw.ElapsedMilliseconds / 60_000.0} minutes.")
            .ConfigureAwait(false);
        }
Example #11
0
        // 位置数据,为了加载数据的时候不用全部加载(按需加载)
        // 自定义选择 如果需要自己编写 .proto文件
        // 作为优化的备选,SerializePos里面的逻辑都可以删除
        // 思路为:
        // 一、修改序列化方法(Serialize),对xxxconfig类里面的datas遍历序列化后依次写进文件
        // 二、对datas里每一个对象进行相应的计算,例如:index、pos、length
        private static void SerializePos(object obj, string sheetName)
        {
            string       fileName     = sheetName + "Pos.bytes";
            object       configIns    = assembly.CreateInstance("clientDataPosConfig"); // 创建数据容器类
            PropertyInfo propertyInfo = configIns.GetType().GetProperty("Datas");       // 取到容器字段
            object       DatasVal     = propertyInfo.GetValue(configIns);               // 取到容器

            PropertyInfo objPInfo = obj.GetType().GetProperty("Datas");                 // 取到容器字段
            IList        datas    = objPInfo.GetValue(obj) as IList;
            int          pos      = 0;

            for (int i = 0; i < datas.Count; i++)
            {
                object     dataIns   = assembly.CreateInstance("clientDataPos");                                                 // 创建数据类
                MethodInfo addMethod = propertyInfo.PropertyType.GetMethod("Add", new Type[] { dataIns.GetType() });
                addMethod?.Invoke(DatasVal, new[] { dataIns });                                                                  // 往容器中添加数据

                int length = (datas[i] as IMessage).ToByteArray().Length;                                                        // 使用Pb自带的转字节数组
                dataIns.GetType().GetField("index_", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(dataIns, i);       // 数据在第几行
                dataIns.GetType().GetField("length_", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(dataIns, length); // 当前行数据长度
                dataIns.GetType().GetField("pos_", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(dataIns, pos);       // 当前行数据开始位置
                pos += length;
            }
            // 数据写进文件
            using (FileStream fs = new FileStream(Path.Combine(Common.dataFileDirPath, fileName), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                MessageExtensions.WriteTo(configIns as IMessage, fs);
            }
        }
Example #12
0
        //public Guid? VetId
        //{
        //    get { return _VetId; }
        //    set { _VetId = value; }
        //}
        //private Guid? _VetId = null;

        public int ExecuteNonQuery()
        {
            //CacheHelper.AddUpdateItem<ProviderGroup, Pet>(this.ProviderGroupId.ToString(), this, (cache) => cache.PetCollection.Where(x => x.Id == this.Id).SingleOrDefault());

            int result = MessageExtensions.ExecuteNonQuery <Pet>(this);

            return(result);
        }
        public async Task <IActionResult> ReIndexCalculationResults(string correlationId, Reference user)
        {
            IDictionary <string, string> properties = MessageExtensions.BuildMessageProperties(correlationId, user);

            await _messengerService.SendToQueue(ServiceBusConstants.QueueNames.ReIndexCalculationResultsIndex, "", properties);

            return(new NoContentResult());
        }
Example #14
0
        public void AddMessageWithNullTextAndNullArguments_Should_Ignore()
        {
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);

            MessageExtensions.Msg(logEvent, null, null).Should().BeSameAs(logEvent);

            var message = logEvent.Details.OfType <Message>().Should().BeEmpty();
        }
Example #15
0
 void Send(Header h)
 {
     gui.ShowMessage("Command " + Enum.GetName(typeof(OPCODE), h.Opcode) + " sent");
     log.Debug("Command " + Enum.GetName(typeof(OPCODE), h.Opcode) + " sent");
     gotAck  = false;
     gotNack = false;
     client.Send(MessageExtensions.ToByteArray(h));
 }
Example #16
0
    public void SendMessageSync(MSG_CS msgId, IMessage request)
    {
        requestStream.SetLength(0);
        MessageExtensions.WriteTo(request, requestStream);
        ByteBuffer buffer = createByteBuffer((ushort)msgId, requestStream);

        client.WriteMessage(buffer.ToBytes());
        buffer.Close();
    }
Example #17
0
        // 序列化后二进制文件
        private static void Serialize(object obj, string sheetName)
        {
            string fileName = sheetName + ".bytes";

            using (FileStream fs = new FileStream(Path.Combine(Common.dataFileDirPath, fileName), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                MessageExtensions.WriteTo(obj as IMessage, fs);
            }
        }
Example #18
0
        void Serialize(object obj)
        {
            var type = obj.GetType();
            var path = Settings.Export_Folder + Settings.dat_folder + "/" + type.Name + ".bytes";

            using (var output = File.Create(path))
            {
                MessageExtensions.WriteTo((IMessage)obj, output);
            }
        }
Example #19
0
        public async Task CreateAutoPublisherAndPublish()
        {
            var pub = new Publisher(
                _fixture.ChannelPool,
                _fixture.SerializationProvider,
                _fixture.EncryptionProvider,
                _fixture.CompressionProvider);

            var letter = MessageExtensions.CreateSimpleRandomLetter("AutoPublisherTestQueue");
            await Assert.ThrowsAsync <InvalidOperationException>(async() => await pub.QueueMessageAsync(letter));
        }
Example #20
0
    void OnConnectSucc()
    {
        UnityEngine.Debug.Log("connect success ");
        PBLoginReq req = new PBLoginReq();

        req.Token  = token;
        req.UserId = userId;
        Packet packet = new Packet(PACKET_TYPE.PACKET_CLLogin, MessageExtensions.ToByteArray(req));

        NetClient.Instance.PushPacket(packet);
    }
Example #21
0
        public void GlobalSetup()
        {
            var marshaller = Marshallers.Create((arg) => MessageExtensions.ToByteArray(arg), bytes => new ChatMessage());
            var method     = new Method <ChatMessage, ChatMessage>(MethodType.Unary, typeof(TestService).FullName, nameof(TestService.SayHello), marshaller, marshaller);

            _callHandler = new UnaryServerCallHandler <ChatMessage, ChatMessage, TestService>(method);

            var services = new ServiceCollection();

            services.TryAddSingleton <IGrpcServiceActivator <TestService> >(new TestGrpcServiceActivator <TestService>(new TestService()));
            _requestServices = services.BuildServiceProvider();
        }
Example #22
0
        public async Task CreateAutoPublisherByConfigAndPublish()
        {
            var pub = new Publisher(
                _fixture.Options,
                _fixture.SerializationProvider,
                _fixture.EncryptionProvider,
                _fixture.CompressionProvider);

            await pub.StartAutoPublishAsync().ConfigureAwait(false);

            var letter = MessageExtensions.CreateSimpleRandomLetter("AutoPublisherTestQueue");
            await pub.QueueMessageAsync(letter).ConfigureAwait(false);
        }
Example #23
0
        public void AddMessageWithFormatStringTextAndNullArguments_Should_SucceedWithoutArguments()
        {
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);
            var text     = "Message text with arg #1 ({0}) and arg #2 ({1}).";

            MessageExtensions.Msg(logEvent, text).Should().BeSameAs(logEvent);

            var message = logEvent.Details.OfType <Message>().Single();

            message.Text.Should().Be(text);
            message.StringArguments.Should().BeEmpty();
            message.ToString().Should().Be("Message text with arg #1 ({0}) and arg #2 ({1}).");
        }
Example #24
0
   static void __Helper_SerializeMessage(IMessage message, grpc.SerializationContext context)
   {
 #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
       if (message is IBufferMessage)
       {
           context.SetPayloadLength(message.CalculateSize());
           MessageExtensions.WriteTo(message, context.GetBufferWriter());
           context.Complete();
           return;
       }
 #endif
       context.Complete(MessageExtensions.ToByteArray(message));
   }
Example #25
0
        // Get a message and write it to a file
        public static void writeToFile(IMessage message, string fileName)
        {
            // Create out generic class that holds any other classes
            GenericClass genericClass = new GenericClass
            {
                MyObject = Any.Pack(message)
            };

            // Serialize the class and write it to a file
            using (Stream output = File.Open(fileName, FileMode.Append))
            {
                MessageExtensions.WriteDelimitedTo(genericClass, output);
            }
        }
Example #26
0
        private async Task PublishLettersAsync(Publisher pub, ulong count)
        {
            var sw = Stopwatch.StartNew();

            for (ulong i = 0; i < count; i++)
            {
                var letter = MessageExtensions.CreateSimpleRandomLetter("AutoPublisherTestQueue");
                letter.MessageId = Guid.NewGuid().ToString();
                await pub.QueueMessageAsync(letter).ConfigureAwait(false);
            }
            sw.Stop();

            _fixture.Output.WriteLine($"Finished queueing all letters in {sw.ElapsedMilliseconds} ms.");
        }
Example #27
0
        public async Task PublishManyAsync()
        {
            var options = new RabbitOptions();

            options.FactoryOptions.Uri = new Uri("amqp://*****:*****@localhost:5672/");
            const int letterCount = 10_000;
            const int byteCount   = 500;

            var pub = new Publisher(
                _fixture.ChannelPool,
                _fixture.SerializationProvider,
                _fixture.EncryptionProvider,
                _fixture.CompressionProvider);

            await pub
            .StartAutoPublishAsync()
            .ConfigureAwait(false);

            var queueNames = new List <string>
            {
                "TestQueue0",
                "TestQueue1",
                "TestQueue2",
                "TestQueue3",
                "TestQueue4",
                "TestQueue5",
                "TestQueue6",
                "TestQueue7",
                "TestQueue8",
                "TestQueue9",
            };

            var letters = MessageExtensions.CreateManySimpleRandomLetters(queueNames, letterCount, byteCount);

            var sw = Stopwatch.StartNew();
            await pub
            .PublishManyAsync(letters, false)
            .ConfigureAwait(false);

            sw.Stop();

            const double kiloByteCount = byteCount / 1000.0;

            _fixture.Output.WriteLine($"Published {letterCount} letters, {kiloByteCount} KB each, in {sw.ElapsedMilliseconds} ms.");

            var rate     = letterCount / (sw.ElapsedMilliseconds / 1000.0);
            var dataRate = rate * kiloByteCount;

            _fixture.Output.WriteLine($"Message Rate: {rate.ToString("0.###")} letters / sec, or {(dataRate / 1000.0).ToString("0.###")} MB/s");
        }
Example #28
0
        public void GlobalSetup()
        {
            var message = new ChatMessage
            {
                Name =
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ligula nec orci placerat mollis. " +
                    "Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut aliquet non nunc id lobortis. " +
                    "In tincidunt ac sapien sit amet consequat. Interdum et malesuada fames ac ante ipsum primis in faucibus. " +
                    "Duis vel tristique ipsum, eget hendrerit justo. Donec accumsan, purus quis cursus auctor, sapien nisi " +
                    "lacinia ligula, ut vehicula lorem augue vel est. Vestibulum finibus ornare vulputate."
            };

            var services = new ServiceCollection();

            services.TryAddSingleton <IGrpcInterceptorActivator <UnaryAwaitInterceptor> >(new TestGrpcInterceptorActivator <UnaryAwaitInterceptor>(new UnaryAwaitInterceptor()));
            var serviceProvider = services.BuildServiceProvider();

            var marshaller = Marshallers.Create((arg) => MessageExtensions.ToByteArray(arg), bytes => new ChatMessage());
            var method     = new Method <ChatMessage, ChatMessage>(MethodType.Unary, typeof(TestService).FullName, nameof(TestService.SayHello), marshaller, marshaller);
            var result     = Task.FromResult(new ChatMessage());

            _callHandler = new UnaryServerCallHandler <TestService, ChatMessage, ChatMessage>(
                method,
                (service, request, context) => result,
                ServiceOptions,
                NullLoggerFactory.Instance,
                new TestGrpcServiceActivator <TestService>(new TestService()),
                serviceProvider);

            _trailers = new HeaderDictionary();

            _requestMessage = GetMessageData(message);

            _requestPipe = new TestPipeReader();

            _requestServices = serviceProvider;

            _httpContext = new DefaultHttpContext();
            _httpContext.RequestServices     = _requestServices;
            _httpContext.Request.ContentType = GrpcProtocolConstants.GrpcContentType;
            _httpContext.Request.Protocol    = GrpcProtocolConstants.Http2Protocol;

            _httpContext.Features.Set <IRequestBodyPipeFeature>(new TestRequestBodyPipeFeature(_requestPipe));
            _httpContext.Features.Set <IHttpResponseBodyFeature>(new TestResponseBodyFeature(new TestPipeWriter()));
            _httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
            {
                Trailers = _trailers
            });
            SetupHttpContext(_httpContext);
        }
Example #29
0
        public void MessageToStringWithFormatStringTextAndTooFewArguments_Should_FillInAvailableArgumentsAndLeaveOtherPlaceholdersUntouched()
        {
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);
            var text     = "Message text with arg #1 ({0}) and arg #2 ({1}).";
            var arg1     = 1;

            MessageExtensions.Msg(logEvent, text, arg1).Should().BeSameAs(logEvent);

            var message = logEvent.Details.OfType <Message>().Single();

            message.Text.Should().Be(text);
            message.StringArguments.Count().Should().Be(1);
            message.StringArguments.Should().Contain(arg1.ToString());
            message.ToString().Should().Be("Message text with arg #1 ({0}) and arg #2 ({1}). {\"1\"}");
        }
Example #30
0
        static void Main(string[] args)
        {
            Con c = new Con();

            c.connect("127.0.0.1:6667");

            while (true)
            {
                Package.ChatMessage cm = new Package.ChatMessage {
                    Txt = Console.ReadLine(),
                    Tag = DateTime.Now.Ticks
                };
                c.sendPackage(MessageExtensions.ToByteArray(cm));
            }
        }