Exemplo n.º 1
0
    async Task <Position?> GetPositionAsync(Type projection, CancellationToken ct)
    {
        using var session = _connectionFactory.Connect();
        var state = await session.LoadAsync <ProjectionState>(projection.Name, ct);

        if (state == null)
        {
            return(null);
        }

        return(new Position(state.CommitPosition, state.PreparePosition));
    }
    public PatientDemographicProjection(ConnectionFactory connectionFactory)
    {
        When <PatientAdmitted>(async(e, ct) =>
        {
            var rangeLookup = RangeLookup.Get(e.AgeInYears);

            using var session = connectionFactory.Connect();
            var range         = await session.LoadAsync <Range>(rangeLookup.Name, ct);

            if (range == null)
            {
                await session.StoreAsync(new Range {
                    Id = rangeLookup.Name, Count = 1
                }, ct);
                Console.WriteLine($"{rangeLookup.Name}: 1");
            }
            else
            {
                range.Count++;
                Console.WriteLine($"{rangeLookup.Name}: {range.Count}");
            }

            await session.SaveChangesAsync(ct);
        });
    }
Exemplo n.º 3
0
        private static async Task <IDisposable> StartRpcReplyThread()
        {
            var conn =             // (RecoveryEnabledConnection)
                       await ConnectionFactory
                       .Connect(_host, _vhost,
                                _username, _password,
                                recoverySettings : AutoRecoverySettings.All,
                                connectionName : "replier");

            var channel = await conn.CreateChannel();

            await channel.QueueDeclare("qrpc1", false, true, false, false, null, waitConfirmation : true);

            await channel.BasicConsume(ConsumeMode.ParallelWithBufferCopy, (delivery) =>
            {
                var prop = channel.RentBasicProperties();

                prop.CorrelationId = delivery.properties.CorrelationId;
                var buffer         = new byte[4];
                delivery.stream.Read(buffer, 0, 4);

                Console.WriteLine("Got rpc request " + BitConverter.ToInt32(buffer, 0) + ". Sending rpc reply");

                channel.BasicPublishFast("", delivery.properties.ReplyTo, false, prop, Encoding.UTF8.GetBytes("Reply"));

                return(Task.CompletedTask);
            }, "qrpc1", "", true, false, null, true);

            return((IDisposable)conn);
        }
Exemplo n.º 4
0
        private static async Task <bool> StartConsumer()
        {
            IConnection conn1 = null;

            conn1 = await ConnectionFactory.Connect(_targetHost, vhost : _vhost, username : _username, password : _password);

            var newChannel = await conn1.CreateChannel();

            Console.WriteLine("[channel created] " + newChannel.ChannelNumber);
            await newChannel.BasicQos(0, 5, false);

            await newChannel.ExchangeDeclare("test_ex", "direct", true, false, null, true);

            var qInfo = await newChannel.QueueDeclare("perf1", false, true, false, false, null, true);

            Console.WriteLine("[qInfo] " + qInfo);

            await newChannel.QueueBind("perf1", "test_ex", "perf1", null, true);

            Console.WriteLine("Starting consumer...");

            int count = 0;

            await newChannel.BasicConsume(ConsumeMode.ParallelWithBufferCopy, (delivery) =>
            {
                var buffer = new byte[delivery.bodySize];
                try
                {
                    delivery.stream.Read(buffer, 0, buffer.Length);

                    var msg = (Messages1)
                              ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(new MemoryStream(buffer),
                                                                                 null, typeof(Messages1), buffer.Length);

//					Console.WriteLine("   OK Received " + ToStr(buffer) +
//						" Count " + Interlocked.Increment(ref count) + " seq " + msg.Seq + " __ " + delivery.stream);
                }
                catch (Exception e)
                {
                    lock (Console.Out)
                    {
                        var prev = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("!! ER Received " + ToStr(buffer) + " __ " + delivery.stream);
//						Console.WriteLine(e.Message);
                        Console.ForegroundColor = prev;
                    }
                }

                return(Task.CompletedTask);
            }, "perf1", "", true, false, null, true);

            await Task.Delay(TimeSpan.FromMinutes(10));

            await newChannel.Close();

            conn1.Dispose();

            return(true);
        }
Exemplo n.º 5
0
        internal Response SubmitRequest(Uri uri, Request req)
        {
            var reqEvent = new RequestSendingEventArgs(uri, req);

            OnRequestSending(reqEvent);
            //Trace.TraceInformation("{0:HH:mm:ss.fff} [{1:d2}] Sending {2} to {3}",
            //    DateTime.Now, Thread.CurrentThread.ManagedThreadId, reqEvent.Request.ApiKey, reqEvent.Uri.AbsoluteUri);
            using (var connection = _connectionFactory.Connect(reqEvent.Uri)) {
                var resp = connection.Submit(reqEvent.Request);
                //Trace.TraceInformation("{0:HH:mm:ss.fff} [{1:d2}] Received {2} from {3}",
                //    DateTime.Now, Thread.CurrentThread.ManagedThreadId, resp.GetType().Name, reqEvent.Uri.AbsoluteUri);
                var respEvent = new ResponseReceivedEventArg(resp);
                OnResponseReceived(respEvent);
                return(respEvent.Response);
            }
        }
Exemplo n.º 6
0
    public void Connect()
    {
        var         game       = GameObject.FindGameObjectWithTag("GameController").GetComponent <Game>();
        IConnection connection =
            ConnectionFactory.Connect(ip,
                                      game.port,
                                      game.connectionType);

        lobby.Connection = connection;
        menus.SetActivePanel(lobby.gameObject);
    }
Exemplo n.º 7
0
        public async Task <IConnection> StartConnection(bool autoRecovery = false)
        {
            using (var console = new RestConsole(_host, _username, _password))
            {
                var vhosts = await console.GetVHosts();

                var users = await console.GetUsers();

                Console.WriteLine("vhosts: " + vhosts.Aggregate(" ", (agg, vhst) => agg + " " + vhst.Name));
                Console.WriteLine("users: " + users.Aggregate(" ", (agg, u) => agg + " " + u.Name + "[" + u.Tags + "]"));

                if (!vhosts.Any(v => v.Name == _vhost))
                {
                    await console.CreateVHost(_vhost);

                    await console.SetUserVHostPermission(_username, _vhost);
                }
            }

            LogAdapter.LogDebugFn = (cat, msg, exc) =>
            {
                Console.WriteLine("DEBUG [{0}] : {1} - {2}", cat, msg, exc);
            };
            LogAdapter.LogErrorFn = (cat, msg, exc) =>
            {
                var color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("ERROR [{0}] : {1} - {2}", cat, msg, exc);
                Console.ForegroundColor = color;
            };
            LogAdapter.LogWarnFn = (cat, msg, exc) =>
            {
                var color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("WARN  [{0}] : {1} - {2}", cat, msg, exc);
                Console.ForegroundColor = color;
            };

            var conn = await ConnectionFactory.Connect(_host, _vhost, _username, _password, autoRecovery : autoRecovery);

            if (conn is Connection)
            {
                _io = (conn as Connection)._io;
            }
            else if (conn is RecoveryEnabledConnection)
            {
                _io = (conn as RecoveryEnabledConnection)._connection._io;
            }

            _conn = conn;
            return(conn);
        }
    public WardViewProjection(ConnectionFactory connectionFactory)
    {
        When <PatientAdmitted>(async(e, ct) =>
        {
            using var session = connectionFactory.Connect();
            await session.StoreAsync(new Patient
            {
                Id          = e.PatientId.ToString(),
                WardNumber  = e.WardNumber,
                PatientName = e.PatientName,
                AgeInYears  = e.AgeInYears
            }, ct);

            await session.SaveChangesAsync(ct);

            Console.WriteLine($"Recording Patient Admission: {e.PatientName}");
        });

        When <PatientTransfered>(async(e, ct) =>
        {
            using var session  = connectionFactory.Connect();
            var patient        = await session.LoadAsync <Patient>(e.PatientId.ToString(), ct);
            patient.WardNumber = e.WardNumber;
            await session.SaveChangesAsync(ct);

            Console.WriteLine($"Recording Patient Transfer: {e.PatientId}");
        });

        When <PatientDischarged>(async(e, ct) =>
        {
            using var session = connectionFactory.Connect();
            var patient       = await session.LoadAsync <Patient>(e.PatientId.ToString(), ct);
            session.Delete(patient);

            await session.SaveChangesAsync(ct);

            Console.WriteLine($"Recording Patient Discharged: {e.PatientId}");
        });
    }
        public async Task ConnectWithListOfHosts()
        {
            Console.WriteLine("ConnectWithListOfHosts");

            var badHostsWithGoodAsLast = new []
            {
                "192.168.0.23",
                _host
            };

            var conn = await ConnectionFactory.Connect(badHostsWithGoodAsLast, _vhost, _username, _password);

            conn.Dispose();
        }
Exemplo n.º 10
0
        private static async Task <bool> StartProducing()
        {
            IConnection conn1 = null;

            conn1 = await ConnectionFactory.Connect(_targetHost, vhost : _vhost, username : _username, password : _password);

            var newChannel = await conn1.CreateChannel();

            Console.WriteLine("[channel created] " + newChannel.ChannelNumber);

            await newChannel.ExchangeDeclare("test_ex", "direct", true, false, null, true);

            var qInfo = await newChannel.QueueDeclare("perf1", false, true, false, false, null, true);

            Console.WriteLine("[qInfo] " + qInfo);

            await newChannel.QueueBind("perf1", "test_ex", "perf1", null, true);

            Console.WriteLine("Starting producer...");

            for (int i = 0; i < TotalPublish; i++)
            {
                var msg = new Messages1
                          //{Seq = i, Ticks = Stopwatch.GetTimestamp()};
                {
                    Seq = i,
                    // Ticks = 1,
                    Something = "something _" + i + "_"
                };

                var stream = new MemoryStream();
                ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, msg);
                var buffer = stream.GetBuffer();
                var len    = (int)stream.Position;

                newChannel.BasicPublishFast("test_ex", "perf1", false,
                                            new BasicProperties {
                    Type = typeof(Messages1).FullName
                },
                                            new ArraySegment <byte>(buffer, 0, len));
            }

            await Task.Delay(TimeSpan.FromMinutes(1));

            await newChannel.Close();

            conn1.Dispose();

            return(true);
        }
        protected override void ProcessRecord()
        {
            ISession session = null;

            if (!String.IsNullOrEmpty(Name))
            {
                session = ConnectionFactory.Connect(ConnectionParameters, Name);
            }
            else
            {
                ConnectionParameters[SessionParameter.RepositoryId] = Id;
                session = ConnectionFactory.Connect(ConnectionParameters);
            }
            SetCmisSession(session);
        }
Exemplo n.º 12
0
        protected override void ProcessRecord()
        {
            // first make sure to reset existing data
            ConnectionParameters = null;
            SetCmisSession(null);

            // set the connection parameters
            if (Parameters == null)
            {
                ConnectionParameters = ConnectionFactory.CreateAtomPubParams(Url, UserName, Password);
            }
            else
            {
                ConnectionParameters = Utilities.HashtableToStringDict(Parameters);
            }

            // check if insecure SSLs should be used anyway
            if (Insecure)
            {
                // TODO: improve unsecure SLL handling
                ServicePointManager.ServerCertificateValidationCallback +=
                    _acceptInsecureSSLCallback;
            }
            else
            {
                ServicePointManager.ServerCertificateValidationCallback -=
                    _acceptInsecureSSLCallback;
            }

            // check if we should directly connect to a specified repository
            if (!String.IsNullOrEmpty(Repository))
            {
                // either by optional name
                SetCmisSession(ConnectionFactory.Connect(ConnectionParameters, Repository));
            }
            else if (ConnectionParameters.ContainsKey(SessionParameter.RepositoryId))
            {
                // or by provided parameters
                SetCmisSession(ConnectionFactory.Connect(ConnectionParameters));
            }
        }
Exemplo n.º 13
0
    public async Task EndToEndTest()
    {
        var ct                = new CancellationTokenSource().Token;
        var eventStore        = GetEventStore();
        var dispatcher        = SetupDispatcher(eventStore);
        var connectionFactory = new ConnectionFactory("PatientManagement");
        await connectionFactory.EnsureDatabaseExistsAsync(ct);

        var projections = new List <IProjection>
        {
            new WardViewProjection(connectionFactory),
            new PatientDemographicProjection(connectionFactory)
        };

        var projectionManager = new ProjectionManager.ProjectionManager(
            eventStore,
            connectionFactory,
            projections);

        await projectionManager.StartAsync(ct);

        var patientId = Guid.NewGuid();

        var admitPatient = new AdmitPatient(patientId, "Tony Ferguson", 32, DateTime.UtcNow, 10);
        await dispatcher.Dispatch(admitPatient, ct);

        await retryPolicy.ExecuteAsync(async token =>
        {
            using var session = connectionFactory.Connect();
            var patient       = await session.LoadAsync <Patient>(patientId.ToString(), token);

            Assert.NotNull(patient);
            Assert.Equal(patientId.ToString(), patient.Id);
            Assert.Equal(admitPatient.PatientName, patient.PatientName);
            Assert.Equal(admitPatient.AgeInYears, patient.AgeInYears);
            Assert.Equal(admitPatient.WardNumber, patient.WardNumber);
        }, ct);

        var transferPatientOne = new TransferPatient(patientId, 76);
        await dispatcher.Dispatch(transferPatientOne, ct);

        await retryPolicy.ExecuteAsync(async token =>
        {
            using var session = connectionFactory.Connect();
            var patient       = await session.LoadAsync <Patient>(patientId.ToString(), token);

            Assert.NotNull(patient);
            Assert.Equal(transferPatientOne.WardNumber, patient.WardNumber);
        }, ct);

        var transferPatientTwo = new TransferPatient(patientId, 34);
        await dispatcher.Dispatch(transferPatientTwo, ct);

        await retryPolicy.ExecuteAsync(async token =>
        {
            using var session = connectionFactory.Connect();
            var patient       = await session.LoadAsync <Patient>(patientId.ToString(), token);

            Assert.NotNull(patient);
            Assert.Equal(transferPatientTwo.WardNumber, patient.WardNumber);
        }, ct);

        var dischargePatient = new DischargePatient(patientId);
        await dispatcher.Dispatch(dischargePatient, ct);

        await retryPolicy.ExecuteAsync(async token =>
        {
            using var session = connectionFactory.Connect();
            var patient       = await session.LoadAsync <Patient>(patientId.ToString(), token);

            Assert.Null(patient);
        }, ct);
    }
Exemplo n.º 14
0
        private static async Task <bool> StartRpcServer()
        {
            IConnection conn1 = null;

            try
            {
                conn1 = await ConnectionFactory.Connect(TargetHost,
                                                        vhost : VHost, username : _username, password : _password);

                Console.WriteLine("[Connected]");

                var newChannel = await conn1.CreateChannel();

                Console.WriteLine("[channel created] " + newChannel.ChannelNumber);
                await newChannel.BasicQos(0, Prefetch, false);

                await newChannel.ExchangeDeclare("test_ex", "direct", true, false, null, true);

                var qInfo = await newChannel.QueueDeclare("rpc1", false, true, false, false, null, true);

                Console.WriteLine("[qInfo] " + qInfo);

                await newChannel.QueueBind("rpc1", "test_ex", "rpc1", null, true);

                // when
                // ConsumeMode.SingleThreaded -> invoked from the readframeloop thread
                // ConsumeMode.Parallel* -> invoked from the threadpool

                // var temp = new byte[100];

                Console.WriteLine("Starting Rpc channel Parallel consumer...");
                await newChannel.BasicConsume(ConsumeMode.SingleThreaded, delivery =>
                {
                    var temp = new byte[4];

                    if (delivery.stream != null)
                    {
                        delivery.stream.Read(temp, 0, (int)delivery.bodySize);
                    }

                    var x = BitConverter.ToInt32(temp, 0);
//					Console.WriteLine("Got request " + x);
//					Thread.SpinWait(100);

//					var replyProp = new BasicProperties()
//					{
//						CorrelationId = delivery.properties.CorrelationId
//					};
                    var replyProp = newChannel.RentBasicProperties();

                    // send reply
                    newChannel.BasicPublish("",
                                            delivery.properties.ReplyTo, true,
                                            replyProp, new ArraySegment <byte>(temp, 0, 4));

                    return(Task.CompletedTask);
                }, "rpc1", "", true, false, null, waitConfirmation : true);

                await Task.Delay(TimeSpan.FromMinutes(12));

//				var ev = new AutoResetEvent(false);

//				Console.CancelKeyPress += (sender, args) =>
//				{
//					Console.WriteLine("Exiting...");
//					ev.Set();
//				};
//				Console.WriteLine("Waiting...");
//				ev.WaitOne();


                await newChannel.Close();
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("[Captured error] " + ex.Flatten().Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[Captured error 2] " + ex.Message);
            }

            if (conn1 != null)
            {
                conn1.Dispose();
            }

            return(true);
        }
Exemplo n.º 15
0
        private static async Task <bool> Start()
        {
            var replier = await StartRpcReplyThread();


            var conn =             // (RecoveryEnabledConnection)
                       await ConnectionFactory
                       .Connect(_host, _vhost,
                                _username, _password,
                                recoverySettings : AutoRecoverySettings.All,
                                connectionName : "main", heartbeat : 60);

//			conn.RecoveryCompleted += () =>
//			{
//				Console.WriteLine("Recovery completed!!");
//			};

            var channel1 = await conn.CreateChannel();

            await channel1.ExchangeDeclare("exchange_rec_1", "direct", false, autoDelete : true, arguments : null, waitConfirmation : true);

//			await channel1.QueueDeclare("qrpc1", false, durable: true, exclusive: false, autoDelete: false, arguments: null, waitConfirmation: true);
            await channel1.QueueDeclare("queue_rec_1", false, durable : true, exclusive : false, autoDelete : true, arguments : null, waitConfirmation : true);

            await channel1.QueueBind("queue_rec_1", "exchange_rec_1", "routing1", null, waitConfirmation : true);

            var rpcHelper = await channel1.CreateRpcHelper(ConsumeMode.ParallelWithBufferCopy, 1000);

            var channel2 = await conn.CreateChannel();

            await channel2.ExchangeDeclare("exchange_rec_2", "direct", false, autoDelete : true, arguments : null, waitConfirmation : true);

            await channel2.QueueDeclare("queue_rec_2", false, durable : true, exclusive : false, autoDelete : true, arguments : null, waitConfirmation : true);

            await channel2.QueueBind("queue_rec_2", "exchange_rec_2", "routing2", null, waitConfirmation : true);

            int counter = 0;

            _timer = new Timer(async state =>
            {
                Console.WriteLine("Sending message ..");

                try
                {
                    var reply = await rpcHelper.Call("", "qrpc1", BasicProperties.Empty, BitConverter.GetBytes(counter++));
                    Console.WriteLine("rpc reply received. size " + reply.bodySize);
                    await channel1.BasicPublish("exchange_rec_1", "routing1", false, BasicProperties.Empty, Buffer1);
                    await channel2.BasicPublish("exchange_rec_2", "routing2", false, BasicProperties.Empty, Buffer2);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("Error sending message " + ex.Message);
                }
            }, null, TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(1));


            var channel3 = await conn.CreateChannel();

            await channel3.BasicConsume(ConsumeMode.ParallelWithBufferCopy, new Consumer("1"), "queue_rec_1", "", true, false, null, true);

            await channel3.BasicConsume(ConsumeMode.ParallelWithBufferCopy, new Consumer("2"), "queue_rec_2", "", true, false, null, true);



            Console.WriteLine("Do stop rabbitmq service");



            await Task.Delay(TimeSpan.FromMinutes(10));



            _timer.Dispose();

            Console.WriteLine("Done. Disposing...");

            conn.Dispose();

            replier.Dispose();

            return(true);
        }