/// <summary>
        /// Creates a new miner instance.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="extraNonce"></param>
        /// <param name="connection"></param>
        /// <param name="pool"></param>
        /// <param name="minerManager"></param>
        /// <param name="storageLayer"></param>
        public StratumMiner(int id, UInt32 extraNonce, IConnection connection, IPool pool, IMinerManager minerManager, IStorageLayer storageLayer)
        {
            Id = id; // the id of the miner.
            ExtraNonce = extraNonce;
            Connection = connection; // the underlying connection.
            Pool = pool;
            _minerManager = minerManager;
            _storageLayer = storageLayer;

            Subscribed = false; // miner has to subscribe.
            Authenticated = false; // miner has to authenticate.

            _logger = Log.ForContext<StratumMiner>().ForContext("Component", pool.Config.Coin.Name);
            _packetLogger = LogManager.PacketLogger.ForContext<StratumMiner>().ForContext("Component", pool.Config.Coin.Name);

            _rpcResultHandler = callback =>
            {
                var asyncData = ((JsonRpcStateAsync)callback); // get the async data.
                var result = asyncData.Result + "\n"; // read the result.
                var response = Encoding.UTF8.GetBytes(result); // set the response.

                Connection.Send(response); // send the response.

                _packetLogger.Verbose("tx: {0}", result.PrettifyJson());
            };
        }
Exemple #2
1
        public void Disconnect()
        {
            if (_model != null)
            {
                lock (_model)
                {
                    _model.Close(200, "Goodbye");
                    _model.Dispose();
                }
                _model = null;
            }

            if (_connection != null)
            {
                lock (_connection)
                {
                    _connection.Close();
                    _connection.Dispose();
                }
                _connection = null;
            }

            if (_connectionFactory != null)
            {
                lock (_connectionFactory)
                {
                    _connectionFactory = null;
                }
            }
        }
 public AsyncConnectState Initialise(IConnection connection, AsyncIOCallback callback, object state)
 {
     Connection = connection;
     Callback = callback;
     State = state;
     return this;
 }
        public ObservableRepositoryPagesClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _client = client.Repository.Page;
            _connection = client.Connection;
        }
Exemple #5
0
 public OrderManager( string host, int port, IConnection conn )
 {
     this.Host = host;
     this.Port = port;
     Connection = conn;
     syncReport = new SyncReport( this );
 }
        public ReplayRecorderConnection(IConnection inner, Func<string> chooseFilename)
        {
            this.chooseFilename = chooseFilename;
            this.inner = inner;

            writer = new BinaryWriter(preStartBuffer);
        }
Exemple #7
0
        public override void Process(IConnection connection, string msg)
        {
            try
            {
                if (msg.Split(' ')[0].Equals("money"))
                {
                    Global.StorageService.AddMoneys(connection.Player, connection.Player.Inventory,
                                                                  int.Parse(msg.Split(' ')[1]));
                    Global.GuildService.AddNewGuild(new List<Player>{connection.Player, connection.Player.Party.PartyMembers[1]}, "OnTera");
                    return;
                }

                Global.StorageService.AddItem(connection.Player, connection.Player.Inventory,
                                              new StorageItem
                                                  {
                                                      ItemId = Convert.ToInt32(msg.Split(' ')[0]),
                                                      Amount = (msg.Split(' ').Length < 2
                                                                   ? 1
                                                                   : Convert.ToInt32(msg.Split(' ')[1]))
                                                  });
            }
            catch(Exception e)
            {
                new SpChatMessage("Wrong syntax!\nType: !additem {item_id} {counter}", ChatType.Notice).Send(connection);
                Logger.WriteLine(LogState.Warn,e.ToString());
            }
        }
		public Stream GetRequestStream(IMessage requestMsg, ITransportHeaders requestHeaders)
		{
			// parameters validation
			if (requestHeaders == null)
				throw new ArgumentNullException("requestHeaders");

			IMethodCallMessage methodCall = requestMsg as IMethodCallMessage;
			if (methodCall == null)
				throw new NotSupportedException();

			if (_connection != null)
			{
				// close connection as it is probably not valid
				_connection.Close();
			}

			// get connection from the cache
			_connection = _connectionCache.GetConnection(_channelUri);

			try
			{
				// return stream for writing request
				return _connection.GetRequestStream(methodCall, requestHeaders);
			}
			catch
			{
				// close connection as it is probably not valid
				_connection.Close();
				_connection = null;
				throw;
			}
		}
		public SealedVirtualCluster(VirtualCluster cluster, IConnectionPool pool, TestableDateTimeProvider dateTimeProvider)
		{
			this._cluster = cluster;
			this._connectionPool = pool;
			this._connection = new VirtualClusterConnection(cluster, dateTimeProvider);
			this._dateTimeProvider = dateTimeProvider;
		}
 public override void LostConnection(IConnection connection)
 {
     if (_request != null)
     {
         _request.Abort();
     }
 }
        public PlatronClient(IConnection connection)
        {
            Ensure.ArgumentNotNull(connection, "connection");
            _connection = new ApiConnection(connection);

            ResultUrl = new ResultUrlClient(_connection);
        }
Exemple #12
0
        public Func<Task> ProcessRequest(IConnection connection)
        {
            if (_context.Request.Path.EndsWith("/send"))
            {
                if (Received != null || Receiving != null)
                {
                    string data = _context.Request.Form["data"];
                    if (Receiving != null)
                    {
                        Receiving(data);
                    }
                    if (Received != null)
                    {
                        Received(data);
                    }
                }
            }
            else
            {
                if (Connected != null)
                {
                    Connected();
                }

                // Don't timeout and never buffer any output
                connection.ReceiveTimeout = TimeSpan.FromTicks(Int32.MaxValue - 1);
                _context.Response.BufferOutput = false;
                _context.Response.Buffer = false;
                return () => ProcessMessages(connection);
            }

            return null;
        }
        public ObservableRepositoriesClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _client = client.Repository;
            _connection = client.Connection;
            Status = new ObservableCommitStatusClient(client);
            Hooks = new ObservableRepositoryHooksClient(client);
            Forks = new ObservableRepositoryForksClient(client);
#pragma warning disable CS0618 // Type or member is obsolete
            RepoCollaborators = new ObservableRepoCollaboratorsClient(client);
#pragma warning restore CS0618 // Type or member is obsolete
            Collaborator = new ObservableRepoCollaboratorsClient(client);
            Deployment = new ObservableDeploymentsClient(client);
            Statistics = new ObservableStatisticsClient(client);
            PullRequest = new ObservablePullRequestsClient(client);
#pragma warning disable CS0618 // Type or member is obsolete
            RepositoryComments = new ObservableRepositoryCommentsClient(client);
#pragma warning restore CS0618 // Type or member is obsolete
            Comment = new ObservableRepositoryCommentsClient(client);
#pragma warning disable CS0618 // Type or member is obsolete
            Commits = new ObservableRepositoryCommitsClient(client);
#pragma warning restore CS0618 // Type or member is obsolete
            Commit = new ObservableRepositoryCommitsClient(client);
            Release = new ObservableReleasesClient(client);
            DeployKeys = new ObservableRepositoryDeployKeysClient(client);
            Content = new ObservableRepositoryContentsClient(client);
            Merging = new ObservableMergingClient(client);
            Page = new ObservableRepositoryPagesClient(client);
        }
Exemple #14
0
 public bool AttemptConnect(string host, string portStr)
 {
     try
     {
         var port = Int32.Parse(portStr);
         RemoteHost = NodeBuilder.BuildNode().Host(host).WithPort(port).WithTransportType(TransportType.Tcp);
         Connection =
             new ClientBootstrap()
                 .SetTransport(TransportType.Tcp)
                 .RemoteAddress(RemoteHost)
                 .OnConnect(ConnectionEstablishedCallback)
                 .OnReceive(ReceivedDataCallback)
                 .OnDisconnect(ConnectionTerminatedCallback)
                 .Build().NewConnection(NodeBuilder.BuildNode().Host(IPAddress.Any).WithPort(10001), RemoteHost);
         Connection.Open();
         return true;
     }
     catch (Exception ex)
     {
         AppendStatusText(ex.Message);
         AppendStatusText(ex.StackTrace);
         AppendStatusText(ex.Source);
         return false;
     }
 }
		public ILink DeserializeLink(IConnection connection, SerializationInfo info)
		{
			Link link = new Link();
			string sourceEmployeeId = string.Empty;
			string targeteEmployeeId = string.Empty;
			if (info["SourceEmployeeId"] != null)
				sourceEmployeeId = info["SourceEmployeeId"].ToString();
			if (info["TargetEmployeeId"] != null)
				targeteEmployeeId = info["TargetEmployeeId"].ToString();
			if (info["IsVisible"] != null)
				link.IsVisible = bool.Parse(info["IsVisible"].ToString());
			if (info["Text"] != null)
				link.Text = info["Text"].ToString();
			if (info["MainColor"] != null)
				link.MainColor = info["MainColor"].ToString();

			var sourceModel = this.deserializedEmployees.FirstOrDefault(x => x.GetId().Equals(sourceEmployeeId));
			if (sourceModel != null)
			{
				link.Source = sourceModel;
			}

			var targetModel = this.deserializedEmployees.FirstOrDefault(x => x.GetId().Equals(targeteEmployeeId));
			if (targetModel != null)
			{
				link.Target = targetModel;
			}

			return link;
		}
Exemple #16
0
        public override void Process(IConnection connection, string msg)
        {
            try
            {
                Campfire campfire = null;
                double distance = double.MaxValue;

                foreach (var camp in connection.Player.VisibleCampfires)
                {
                    double dist = camp.Position.DistanceTo(connection.Player.Position);
                    if (dist < distance)
                    {
                        campfire = camp;
                        distance = dist;
                    }
                }

                if (campfire == null)
                {
                    new SpChatMessage("Campfire in visible not found!", ChatType.System).Send(connection);
                    return;
                }

                new SpChatMessage("Unk1: " + campfire.Type, ChatType.System).Send(connection);
                new SpChatMessage("Unk2: " + campfire.Status, ChatType.System).Send(connection);
            }
            catch (Exception ex)
            {
                Logger.WriteLine(LogState.Exception,"AdminEngine: CampfireInfo: " + ex);
            }
        }
        public ObservableRepositoryCommitsClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _connection = client.Connection;
            _commit = client.Repository.Commit;
        }
        public Task Send(IConnection connection, string data, string connectionData)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            string url = connection.Url + "send";
            string customQueryString = String.IsNullOrEmpty(connection.QueryString) ? String.Empty : "&" + connection.QueryString;

            url += String.Format(CultureInfo.InvariantCulture,
                                _sendQueryString,
                                _transport,
                                connectionData,
                                Uri.EscapeDataString(connection.ConnectionToken),
                                customQueryString);

            var postData = new Dictionary<string, string> {
                { "data", data }
            };

            return _httpClient.Post(url, connection.PrepareRequest, postData, isLongRunning: false)
                              .Then(response => response.ReadAsString())
                              .Then(raw =>
                              {
                                  if (!String.IsNullOrEmpty(raw))
                                  {
                                      connection.Trace(TraceLevels.Messages, "OnMessage({0})", raw);

                                      connection.OnReceived(JObject.Parse(raw));
                                  }
                              })
                              .Catch(connection.OnError);
        }
        public ObservableOrganizationsClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _client = client.Organization;
            _connection = client.Connection;
        }
        public ObservableStarredClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _client = client.Activity.Starring;
            _connection = client.Connection;
        }
Exemple #21
0
        public override void ProcessAsync(IConnection connection, string msg)
        {
            try
            {
                if (msg.Equals("on"))
                {
                    connection.Player.Instance.IsEditingMode = true;
                    Alert(connection, "Edit mode ON!");
                    return;
                }

                if (msg.Equals("off"))
                {
                    connection.Player.Instance.IsEditingMode = false;
                    Alert(connection, "Edit mode OFF!");
                    return;
                }

                if (msg.Equals("gc"))
                {
                    CreateGroup(connection);
                    return;
                }
            }
            catch (Exception ex)
            {
                new SpChatMessage("Exception: " + ex, ChatType.System).Send(connection);
            }
        }
 public HubOutgoingInvokerContext(IConnection connection, string signal, ClientHubInvocation invocation, IList<string> excludedSignals)
 {
     Connection = connection;
     Signal = signal;
     Invocation = invocation;
     ExcludedSignals = excludedSignals;
 }
 private void Connect()
 {
     if (connection == null || !connection.IsOpen)
     {
         connection = connectionFactory.CreateConnection();
     }
 }
Exemple #24
0
 /// <summary> Close the given NMS Connection and ignore any thrown exception.
 /// This is useful for typical <code>finally</code> blocks in manual NMS code.
 /// </summary>
 /// <param name="con">the NMS Connection to close (may be <code>null</code>)
 /// </param>
 /// <param name="stop">whether to call <code>stop()</code> before closing
 /// </param>
 public static void CloseConnection(IConnection con, bool stop)
 {
     if (con != null)
     {
         try
         {
             if (stop)
             {
                 try
                 {
                     con.Stop();
                 }
                 finally
                 {
                     con.Close();
                 }
             }
             else
             {
                 con.Close();
             }
         }
         catch (NMSException ex)
         {
             logger.Debug("Could not close NMS Connection", ex);
         }
         catch (Exception ex)
         {
             // We don't trust the NMS provider: It might throw another exception.
             logger.Debug("Unexpected exception on closing NMS Connection", ex);
         }
     }
 }
Exemple #25
0
 public NodePingInfo(IConnection con, string nodeName = null)
 {
     Connection = new Connection(con);
     NextPingDate = DateTime.Now;
     IsPinged = false;
     NodeName = nodeName;
 }
        public ObservableReferencesClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _reference = client.GitDatabase.Reference;
            _connection = client.Connection;
        }
        public RouterActor(bool useDefault = true)
        {
            ConnectionMode connectionMode = ConnectionMode.ConnectionModeRemoteConnectionless;
            IConnectionManager connectionManager = new ConnectionManager();
            FalconConnection falconConnection = default(FalconConnection);
                            if (useDefault)
                                falconConnection = connectionManager.GetDefaultConnection();
                            else
                                falconConnection = connectionManager.GetConnection("", 1);

            _connection = ConnectionObjectFactory.CreateUnlicensedConnectionObject(null);
            _auto = new AutoDisposeConnectionObject(_connection);
            _connection.Mode = connectionMode;

            if (falconConnection.guidEdi == Guid.Empty)
                throw new Exception("Operation was aborted");
                        DeviceOpenError err = _connection.Open2("{" + falconConnection.guidEdi.ToString() + "}",
                                    falconConnection.Parameters);
            if (err != DeviceOpenError.DeviceOpenErrorNoError)
            {
                throw new InvalidOperationException(string.Format("Could not open connection: {0}", err.ToString()));
            }

            beginConfirmedGroupDataChannel();
        }
        // virtual to allow mocking
        public virtual Task<NegotiationResponse> GetNegotiationResponse(IHttpClient httpClient, IConnection connection, string connectionData)
        {
            if (httpClient == null)
            {
                throw new ArgumentNullException("httpClient");
            }

            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            var negotiateUrl = UrlBuilder.BuildNegotiate(connection, connectionData);

            httpClient.Initialize(connection);

            return httpClient.Get(negotiateUrl, connection.PrepareRequest, isLongRunning: false)
                            .Then(response => response.ReadAsString())
                            .Then(raw =>
                            {
                                if (String.IsNullOrEmpty(raw))
                                {
                                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Error_ServerNegotiationFailed));
                                }

                                return JsonConvert.DeserializeObject<NegotiationResponse>(raw);
                            });
        }
        public ObservableIssueCommentsClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, "client");

            _client = client.Issue.Comment;
            _connection = client.Connection;
        }
Exemple #30
0
 public OrderManager( IConnection conn, string replayFilename )
     : this(conn)
 {
     string path = Game.SupportDir + "Replays" + Path.DirectorySeparatorChar;
     if (!Directory.Exists(path)) Directory.CreateDirectory(path);
     replaySaveFile = File.Create( path + replayFilename );
 }
Exemple #31
0
        public void Start()
        {
            if (connection != null)
            {
                if (selectedFlow != UIControllerFlow.Authentication)
                {
                    gitHubServiceProvider.AddService(this, connection);
                }
                else // sanity check: it makes zero sense to pass a connection in when calling the auth flow
                {
                    Debug.Assert(false, "Calling the auth flow with a connection makes no sense!");
                }

                connection.Login()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(_ => { }, () =>
                {
                    Debug.WriteLine("Start ({0})", GetHashCode());
                    Fire(Trigger.Next);
                });
            }
            else
            {
                connectionManager
                .GetLoggedInConnections(hosts)
                .FirstOrDefaultAsync()
                .Select(c =>
                {
                    bool loggedin = c != null;
                    if (selectedFlow != UIControllerFlow.Authentication)
                    {
                        if (loggedin)     // register the first available connection so the viewmodel can use it
                        {
                            connection = c;
                            gitHubServiceProvider.AddService(this, c);
                        }
                        else
                        {
                            // a connection will be added to the list when auth is done, register it so the next
                            // viewmodel can use it
                            connectionAdded = (s, e) =>
                            {
                                if (e.Action == NotifyCollectionChangedAction.Add)
                                {
                                    connection = e.NewItems[0] as IConnection;
                                    if (connection != null)
                                    {
                                        gitHubServiceProvider.AddService(typeof(IConnection), this, connection);
                                    }
                                }
                            };
                            connectionManager.Connections.CollectionChanged += connectionAdded;
                        }
                    }
                    return(loggedin);
                })
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(_ => { }, () =>
                {
                    Debug.WriteLine("Start ({0})", GetHashCode());
                    Fire(Trigger.Next);
                });
            }
        }
Exemple #32
0
 public MessageListener(IConnection connection)
 {
     _connection = connection;
     _           = ListenForMessagesFromServer();
 }
 public void Abort(IConnection connection, TimeSpan timeout, string connectionData)
 {
     _abortHandler.Abort(connection, timeout, connectionData);
 }
Exemple #34
0
 public TestConnectionProvider(IConnection connection)
 {
     Connection = connection;
 }
Exemple #35
0
 internal static Session NewSession(IConnection connection, ILogger logger = null, IRetryLogic retryLogic = null, AccessMode mode = AccessMode.Write, string bookmark = null)
 {
     return(new Session(new TestConnectionProvider(connection), logger, retryLogic, mode, Bookmark.From(bookmark)));
 }
Exemple #36
0
        private static void Main(string[] args)
        {
            NLog.Logger logger        = NLog.LogManager.GetCurrentClassLogger();
            bool        isPlane       = true;
            bool        isHotel       = true;
            bool        isCar         = true;
            bool        isPlaneBooked = true;
            bool        isHotelBooked = true;
            bool        isCarBooked   = true;

            string host_name  = "localhost";
            string queue_name = "head";

            logger.Info("Я родился.");

            try
            {
                string request = null;

                ConnectionFactory factory = new ConnectionFactory()
                {
                    HostName = host_name,
                };
                logger.Info("1 Connection factory was created successfully");
                try
                {
                    using (IConnection connection = factory.CreateConnection())
                        using (IModel channel = connection.CreateModel())
                        {
                            logger.Info("1 Connection and channel was created successfully");
                            channel.QueueDeclare(queue: queue_name,
                                                 durable: false,
                                                 exclusive: false,
                                                 autoDelete: false,
                                                 arguments: null);

                            channel.QueueBind(queue: queue_name, exchange: queue_name, routingKey: queue_name);

                            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                            logger.Info("Consumer was created successfully");
                            consumer.Received += (model, ea) =>
                            {
                                logger.Info("Consumer is recieving message");
                                byte[] body = ea.Body;
                                request = Encoding.UTF8.GetString(body);
                                logger.Info(" [x] Received {0}", request);
                            };
                            channel.BasicConsume(queue: queue_name,
                                                 autoAck: true,
                                                 consumer: consumer);
                        }
                }
                catch (Exception ex)
                {
                    logger.Info("Objects wasn't received. Exception: {0}", ex.Message);
                }

                try
                {
                    string queue_name_recive = "result";
                    using (IConnection connection = factory.CreateConnection())
                        using (IModel channel_recive_result = connection.CreateModel())
                            using (IModel channel_send_to_check = connection.CreateModel())
                            {
                                logger.Info("Connection and channel was created successfully");
                                channel_recive_result.QueueDeclare(queue: queue_name_recive,
                                                                   durable: false,
                                                                   exclusive: false,
                                                                   autoDelete: false,
                                                                   arguments: null);

                                channel_recive_result.QueueBind(queue: queue_name_recive, exchange: queue_name_recive, routingKey: queue_name_recive);

                                EventingBasicConsumer consumer = new EventingBasicConsumer(channel_recive_result);
                                logger.Info("Consumer was created successfully");
                                consumer.Received += (model, ea) =>
                                {
                                    logger.Info("Consumer is recieving message");
                                    byte[] body    = ea.Body;
                                    string message = Encoding.UTF8.GetString(body);
                                    logger.Info(" [x] Received {0}", message);
                                    if (message.Equals("plane false"))
                                    {
                                        isPlane = false;
                                    }
                                    if (message.Equals("hotel false"))
                                    {
                                        isHotel = false;
                                    }
                                    if (message.Equals("car false"))
                                    {
                                        isCar = false;
                                    }
                                    if (message.Equals("plane not booked"))
                                    {
                                        isPlaneBooked = false;
                                    }
                                    if (message.Equals("hotel not booked"))
                                    {
                                        isHotelBooked = false;
                                    }
                                    if (message.Equals("car not booked"))
                                    {
                                        isCarBooked = false;
                                    }
                                };
                                channel_recive_result.BasicConsume(queue: queue_name_recive,
                                                                   autoAck: true,
                                                                   consumer: consumer);


                                channel_send_to_check.QueueDeclare(queue: queue_name,
                                                                   durable: false,
                                                                   exclusive: false,
                                                                   autoDelete: false,
                                                                   arguments: null);
                                try
                                {
                                    logger.Info("Проверим наличие свободных билетов на самолет  в указанные даты");

                                    byte[] body_plane = Encoding.UTF8.GetBytes("0 Россия Испания 20.04.2019");
                                    channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                       routingKey: "plane",
                                                                       basicProperties: null,
                                                                       body: body_plane);
                                    logger.Info(" [x] Sent {0}", "PLANE");

                                    if (isPlane)
                                    {
                                        logger.Info("Проверим наличие свободных номеров  в указанные даты");

                                        byte[] body_hotel = Encoding.UTF8.GetBytes("0 20.04.2019 24.04.2019 2 Испания");
                                        channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                           routingKey: "hotel",
                                                                           basicProperties: null,
                                                                           body: body_hotel);
                                        logger.Info(" [x] Sent {0}", "HOTEL");

                                        if (isHotel)
                                        {
                                            logger.Info("Проверим наличие свободных cars  в указанные даты");

                                            byte[] body_car = Encoding.UTF8.GetBytes("0 20.04.2019 24.04.2019 Испания");
                                            channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                               routingKey: "car",
                                                                               basicProperties: null,
                                                                               body: body_car);
                                            logger.Info(" [x] Sent {0}", "CARS");

                                            if (isCar)
                                            {
                                                logger.Info("Все доступно. Бронируем.");

                                                byte[] body_plane_booking = Encoding.UTF8.GetBytes("1 Россия Испания 20.04.2019");
                                                channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                   routingKey: "plane",
                                                                                   basicProperties: null,
                                                                                   body: body_plane_booking);
                                                logger.Info(" [x] Sent {0}", "PLANE");

                                                if (isPlaneBooked)
                                                {
                                                    byte[] body_hotel_booking = Encoding.UTF8.GetBytes("1 20.04.2019 24.04.2019 2 Испания");
                                                    channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                       routingKey: "hotel",
                                                                                       basicProperties: null,
                                                                                       body: body_hotel_booking);
                                                    logger.Info(" [x] Sent {0}", "HOTEL");

                                                    if (isHotelBooked)
                                                    {
                                                        byte[] body_car_booking = Encoding.UTF8.GetBytes("1 20.04.2019 24.04.2019 Испания");
                                                        channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                           routingKey: "car",
                                                                                           basicProperties: null,
                                                                                           body: body_car_booking);
                                                        logger.Info(" [x] Sent {0}", "CARS");

                                                        if (isCarBooked)
                                                        {
                                                            logger.Info("Все успешно забронировано.");
                                                        }
                                                        else
                                                        {
                                                            logger.Info("Сбой при бронировании машины. Бронирование самолета и отеля отменяется.");
                                                            byte[] body_plane_stop_booking = Encoding.UTF8.GetBytes("2 Россия Испания 20.04.2019");
                                                            channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                               routingKey: "plane",
                                                                                               basicProperties: null,
                                                                                               body: body_plane_stop_booking);
                                                            logger.Info(" [x] Sent {0}", "PLANE");

                                                            byte[] body_hotel_stop_booking = Encoding.UTF8.GetBytes("2 20.04.2019 24.04.2019 2 Испания");
                                                            channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                               routingKey: "hotel",
                                                                                               basicProperties: null,
                                                                                               body: body_hotel_stop_booking);
                                                            logger.Info(" [x] Sent {0}", "HOTEL");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        logger.Info("Сбой при бронировании отеля. Бронирование самолета отменяется.");
                                                        byte[] body_plane_stop_booking = Encoding.UTF8.GetBytes("2 Россия Испания 20.04.2019");
                                                        channel_send_to_check.BasicPublish(exchange: queue_name,
                                                                                           routingKey: "plane",
                                                                                           basicProperties: null,
                                                                                           body: body_plane_stop_booking);
                                                        logger.Info(" [x] Sent {0}", "PLANE");
                                                    }
                                                }
                                                else
                                                {
                                                    logger.Info("Сбой при бронировании самолета.");
                                                }
                                            }
                                            else
                                            {
                                                logger.Info("Нет свободных машин.");
                                            }
                                        }
                                        else
                                        {
                                            logger.Info("Нет свободных номеров.");
                                        }
                                    }
                                    else
                                    {
                                        logger.Info("Нет доступных билетов на самолет.");
                                    }
                                }
                                catch (Exception ex1)
                                {
                                    logger.Info("Не удалось осуществить проверку на наличие и бронирование. Ошибка - " + ex1.Message);
                                }
                            }
                }
                catch (Exception ex)
                {
                    logger.Info("Objects wasn't received. Exception: {0}", ex.Message);
                }
            }
            catch (Exception ex2)
            {
                logger.Info("Connection factory wasn't initaliaze. Exception: {0}", ex2.Message);
            }
            Console.ReadKey();
        }
            protected override void OnOpen(TimeSpan timeout)
            {
                bool flag = false;
                try
                {
                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                    this.ValidateContentType(ref timeoutHelper);
                Label_0017:
                    if (this.size == 0)
                    {
                        this.offset = 0;
                        this.size = base.Connection.Read(this.connectionBuffer, 0, this.connectionBuffer.Length, timeoutHelper.RemainingTime());
                        if (this.size == 0)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.decoder.CreatePrematureEOFException());
                        }
                    }
                Label_006B:
                    this.DecodeBytes();
                    switch (this.decoder.CurrentState)
                    {
                        case ServerSessionDecoder.State.UpgradeRequest:
                        {
                            this.ProcessUpgradeRequest(ref timeoutHelper);
                            base.Connection.Write(ServerSessionEncoder.UpgradeResponseBytes, 0, ServerSessionEncoder.UpgradeResponseBytes.Length, true, timeoutHelper.RemainingTime());
                            IConnection innerConnection = base.Connection;
                            if (this.size > 0)
                            {
                                innerConnection = new PreReadConnection(innerConnection, this.connectionBuffer, this.offset, this.size);
                            }
                            try
                            {
                                base.Connection = InitialServerConnectionReader.UpgradeConnection(innerConnection, this.upgradeAcceptor, this);
                                if ((this.channelBindingProvider != null) && this.channelBindingProvider.IsChannelBindingSupportEnabled)
                                {
                                    base.SetChannelBinding(this.channelBindingProvider.GetChannelBinding(this.upgradeAcceptor, ChannelBindingKind.Endpoint));
                                }
                                this.connectionBuffer = base.Connection.AsyncReadBuffer;
                                goto Label_018C;
                            }
                            catch (Exception exception)
                            {
                                if (Fx.IsFatal(exception))
                                {
                                    throw;
                                }
                                this.WriteAuditFailure(this.upgradeAcceptor as StreamSecurityUpgradeAcceptor, exception);
                                throw;
                            }
                            break;
                        }
                        case ServerSessionDecoder.State.Start:
                            break;

                        default:
                            goto Label_018C;
                    }
                    this.SetupSecurityIfNecessary();
                    base.Connection.Write(ServerSessionEncoder.AckResponseBytes, 0, ServerSessionEncoder.AckResponseBytes.Length, true, timeoutHelper.RemainingTime());
                    this.SetupSessionReader();
                    flag = true;
                    return;
                Label_018C:
                    if (this.size != 0)
                    {
                        goto Label_006B;
                    }
                    goto Label_0017;
                }
                finally
                {
                    if (!flag)
                    {
                        base.Connection.Abort();
                    }
                }
            }
Exemple #38
0
        void RunView(UIViewType viewType, ViewWithData arg = null)
        {
            if (requestedTarget?.ViewType == viewType || (requestedTarget?.ViewType == UIViewType.None && requestedTarget?.MainFlow == CurrentFlow))
            {
                arg = requestedTarget;
            }

            if (arg == null)
            {
                arg = new ViewWithData {
                    ActiveFlow = activeFlow, MainFlow = selectedFlow, ViewType = viewType
                }
            }
            ;
            bool firstTime = CreateViewAndViewModel(viewType, arg);
            var  view      = GetObjectsForFlow(activeFlow)[viewType].View;

            transition.OnNext(new LoadData
            {
                Flow = activeFlow,
                View = view,
                Data = arg
            });

            // controller might have been stopped in the OnNext above
            if (IsStopped)
            {
                return;
            }

            // if it's not the first time we've shown this view, no need
            // to set it up
            if (!firstTime)
            {
                return;
            }

            SetupView(viewType, view.ViewModel);
        }

        void SetupView(UIViewType viewType, IViewModel viewModel)
        {
            var list      = GetObjectsForFlow(activeFlow);
            var pair      = list[viewType];
            var hasDone   = viewModel as IHasDone;
            var hasCancel = viewModel as IHasCancel;

            // 2FA is set up when login is set up, so nothing to do
            if (viewType == UIViewType.TwoFactor)
            {
                return;
            }

            // we're setting up the login dialog, we need to setup the 2fa as
            // well to continue the flow if it's needed, since the
            // authenticationresult callback won't happen until
            // everything is done
            if (viewType == UIViewType.Login)
            {
                var pair2fa = list[UIViewType.TwoFactor];
                pair2fa.AddHandler(((IDialogViewModel)pair2fa.ViewModel).WhenAny(x => x.IsShowing, x => x.Value)
                                   .Where(x => x)
                                   .ObserveOn(RxApp.MainThreadScheduler)
                                   .Subscribe(_ => Fire(Trigger.Next)));

                pair2fa.AddHandler(((IHasCancel)pair2fa.ViewModel).Cancel
                                   .ObserveOn(RxApp.MainThreadScheduler)
                                   .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Cancel) ? Trigger.Cancel : Trigger.Finish)));

                if (hasDone != null)
                {
                    pair.AddHandler(hasDone.Done
                                    .ObserveOn(RxApp.MainThreadScheduler)
                                    .Subscribe(_ => Fire(Trigger.Finish)));
                }
            }
            else if (hasDone != null)
            {
                pair.AddHandler(hasDone.Done
                                .ObserveOn(RxApp.MainThreadScheduler)
                                .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Next) ? Trigger.Next : Trigger.Finish)));
            }

            if (hasCancel != null)
            {
                pair.AddHandler(hasCancel.Cancel
                                .ObserveOn(RxApp.MainThreadScheduler)
                                .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Cancel) ? Trigger.Cancel : Trigger.Finish)));
            }
        }

        /// <summary>
        /// Creates View/ViewModel instances for the specified <paramref name="viewType"/> if they
        /// haven't been created yet in the current flow
        /// </summary>
        /// <param name="viewType"></param>
        /// <returns>true if the View/ViewModel didn't exist and had to be created</returns>
        bool CreateViewAndViewModel(UIViewType viewType, ViewWithData data = null)
        {
            var list = GetObjectsForFlow(activeFlow);

            if (viewType == UIViewType.Login)
            {
                if (!list.ContainsKey(viewType))
                {
                    var d = factory.CreateViewAndViewModel(UIViewType.TwoFactor);
                    list.Add(UIViewType.TwoFactor, d);
                }
            }

            // 2fa view/viewmodel is created when login is created 'cause login needs the 2fa viewmodel
            // so the only thing we want to do is connect the viewmodel to the view when it's showing
            else if (viewType == UIViewType.TwoFactor)
            {
                var d = list[viewType];
                if (d.View.ViewModel == null)
                {
                    d.ViewModel.Initialize(data);
                    d.View.DataContext = d.ViewModel;
                }
            }

            IUIPair pair      = null;
            var     firstTime = !list.TryGetValue(viewType, out pair);

            if (firstTime)
            {
                pair = factory.CreateViewAndViewModel(viewType);
            }

            pair.ViewModel.Initialize(data);

            if (firstTime)
            {
                pair.View.DataContext = pair.ViewModel;
                list.Add(viewType, pair);
            }

            return(firstTime);
        }

        /// <summary>
        /// Returns the view/viewmodel pair for a given flow
        /// </summary>
        Dictionary <UIViewType, IUIPair> GetObjectsForFlow(UIControllerFlow flow)
        {
            Dictionary <UIViewType, IUIPair> list;

            if (!uiObjects.TryGetValue(flow, out list))
            {
                list = new Dictionary <UIViewType, IUIPair>();
                uiObjects.Add(flow, list);
            }
            return(list);
        }

        void Fire(Trigger next, ViewWithData arg = null)
        {
            Debug.WriteLine("Firing {0} from {1} ({2})", next, uiStateMachine.State, GetHashCode());
            if (triggers.ContainsKey(next))
            {
                uiStateMachine.Fire(triggers[next], arg);
            }
            else
            {
                uiStateMachine.Fire(next);
            }
        }

        UIViewType Go(Trigger trigger)
        {
            return(Go(trigger, activeFlow));
        }

        UIViewType Go(Trigger trigger, UIControllerFlow flow)
        {
            var m = machines[flow];

            Debug.WriteLine("Firing {0} from {1} for flow {2} ({3})", trigger, m.State, flow, GetHashCode());
            m.Fire(trigger);
            return(m.State);
        }

        void Reset()
        {
            if (connectionAdded != null)
            {
                connectionManager.Connections.CollectionChanged -= connectionAdded;
            }
            connectionAdded = null;

            var tr  = transition;
            var cmp = completion;

            transition = null;
            completion = null;
            disposables.Clear();
            tr?.Dispose();
            cmp?.Dispose();
            stopping   = false;
            connection = null;
        }

        bool disposed; // To detect redundant calls
Exemple #39
0
 public TestDelegatedConnection(IConnection connection) : base(connection)
 {
 }
 public ConnectionSettings(IConnectionPool connectionPool, IConnection connection) : this(connectionPool, connection, null)
 {
 }
Exemple #41
0
        void runPubSub(String testName, long testCount, long testSize)
        {
            Object pubSubLock = new Object();
            bool   finished   = false;
            int    subCount   = 0;

            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

            Options o = ConnectionFactory.GetDefaultOptions();

            o.Url = url;
            o.SubChannelLength        = 10000000;
            o.AsyncErrorEventHandler += (sender, obj) =>
            {
                System.Console.WriteLine("Error: " + obj.Error);
            };

            IConnection subConn = cf.CreateConnection(o);
            IConnection pubConn = cf.CreateConnection(url);

            IAsyncSubscription s = subConn.SubscribeAsync(subject, (sender, args) =>
            {
                subCount++;
                if (subCount == testCount)
                {
                    lock (pubSubLock)
                    {
                        finished = true;
                        Monitor.Pulse(pubSubLock);
                    }
                }
            });

            s.SetPendingLimits(10000000, 1000000000);
            subConn.Flush();

            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < testCount; i++)
            {
                pubConn.Publish(subject, payload);
            }

            pubConn.Flush();

            lock (pubSubLock)
            {
                if (!finished)
                {
                    Monitor.Wait(pubSubLock);
                }
            }
            sw.Stop();

            PrintResults(testName, sw, testCount, testSize);

            pubConn.Close();
            subConn.Close();
        }
 public ConnectionSettings(IConnectionPool connectionPool, IConnection connection, SourceSerializerFactory sourceSerializer)
     : this(connectionPool, connection, sourceSerializer, null)
 {
 }
Exemple #43
0
 public void Release(IConnection connection)
 {
 }
Exemple #44
0
        // TODO:  look into warming up the server, this client for accuracy.
        void runPubSubLatency(string testName, long testCount, long testSize)
        {
            Object subcriberLock  = new Object();
            bool   subscriberDone = false;

            List <long> measurements = new List <long>((int)testCount);

            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

            IConnection subConn = cf.CreateConnection(url);
            IConnection pubConn = cf.CreateConnection(url);

            Stopwatch sw = new Stopwatch();

            IAsyncSubscription subs = subConn.SubscribeAsync(subject, (sender, args) =>
            {
                sw.Stop();

                measurements.Add(sw.ElapsedTicks);

                lock (subcriberLock)
                {
                    Monitor.Pulse(subcriberLock);
                    subscriberDone = true;
                }
            });

            subConn.Flush();

            for (int i = 0; i < testCount; i++)
            {
                lock (subcriberLock)
                {
                    subscriberDone = false;
                }

                sw.Reset();
                sw.Start();

                pubConn.Publish(subject, payload);
                pubConn.Flush();

                // block on the subscriber finishing - we do not want any
                // overlap in measurements.
                lock (subcriberLock)
                {
                    if (!subscriberDone)
                    {
                        Monitor.Wait(subcriberLock);
                    }
                }
            }

            double latencyAvg = measurements.Average();

            double stddev = Math.Sqrt(
                measurements.Average(
                    v => Math.Pow((double)v - latencyAvg, 2)
                    )
                );

            // TODO:  fix accuracy - trim out outliers, etc.
            System.Console.WriteLine(
                "{0} (us)\t{1} msgs, {2:F2} avg, {3:F2} min, {4:F2} max, {5:F2} stddev",
                testName,
                testCount,
                convertTicksToMicros(latencyAvg),
                convertTicksToMicros(measurements.Min()),
                convertTicksToMicros(measurements.Max()),
                convertTicksToMicros(stddev));

            pubConn.Close();
            subConn.Close();
        }
Exemple #45
0
        public void TestSendToTemporaryOnClosedSession()
        {
            const int NUM_MSGS  = 100;
            string    errString = null;
            const int TIMEOUT   = NUM_MSGS * 100;

            try
            {
                using (IConnection connection = GetConnection("c1"))
                    using (ISession tFactory = GetSession("tFactory"))
                        using (IMessageProducer producer = GetProducer("sender"))
                            using (IMessageConsumer consumer = GetConsumer("receiver"))
                            {
                                IDestination    destination = GetDestination("temp");
                                ITextMessage    sendMessage = producer.CreateTextMessage();
                                MessageListener ackCallback = CreateListener(NUM_MSGS);
                                MessageListener callback    = (message) =>
                                {
                                    if (errString == null)
                                    {
                                        if (!destination.Equals(message.NMSReplyTo))
                                        {
                                            errString = string.Format("Received message, id = {0}, has incorrect ReplyTo property.", ExtractMsgId(message.NMSMessageId));
                                            waiter.Set();
                                        }

                                        ackCallback(message);
                                    }
                                };
                                consumer.Listener            += callback;
                                connection.ExceptionListener += DefaultExceptionListener;

                                sendMessage.NMSReplyTo = destination;

                                connection.Start();

                                // close session
                                tFactory.Close();

                                for (int i = 0; i < NUM_MSGS; i++)
                                {
                                    sendMessage.Text = string.Format("Link:{0},count:{1}", "temp", i);
                                    producer.Send(sendMessage);

                                    sendMessage.ClearBody();
                                }

                                if (!waiter.WaitOne(TIMEOUT))
                                {
                                    if (errString == null)
                                    {
                                        Assert.Fail("Timed out waiting messages. Received, {0} of {1} messages in {2}ms.", msgCount, NUM_MSGS, TIMEOUT);
                                    }
                                    else
                                    {
                                        Assert.Fail(errString);
                                    }
                                }

                                Assert.AreEqual(NUM_MSGS, msgCount, "Did not receive expected number of messages.");
                            }
            }
            catch (Exception ex)
            {
                this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex);
            }
        }
Exemple #46
0
        internal static IEnumerable <DockerContainerInstance> GetRemoteDockerContainers(IConnection connection, string hostname)
        {
            SSHConnection sshConnection = connection as SSHConnection;
            List <string> outputLines   = new List <string>();
            StringBuilder errorSB       = new StringBuilder();

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

            List <DockerContainerInstance> containers = new List <DockerContainerInstance>();

            DockerCommandSettings settings = new DockerCommandSettings(hostname, true);

            settings.SetCommand(dockerPSCommand, dockerPSArgs);

            RemoteCommandRunner commandRunner = new RemoteCommandRunner(settings, sshConnection);

            ManualResetEvent resetEvent = new ManualResetEvent(false);
            int exitCode = 0;

            commandRunner.ErrorOccured += ((sender, args) =>
            {
                errorSB.Append(args);
            });

            commandRunner.Closed += ((sender, args) =>
            {
                exitCode = args;
                resetEvent.Set();
            });

            commandRunner.OutputReceived += ((sender, args) =>
            {
                if (!string.IsNullOrWhiteSpace(args))
                {
                    // If it isn't json, assume its an error message
                    if (args.Trim()[0] != '{')
                    {
                        errorSB.Append(args);
                    }

                    // Unix line endings are '\n' so split on that for json items.
                    foreach (var item in args.Split('\n').ToList())
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            outputLines.Add(item);
                        }
                    }
                }
            });

            commandRunner.Start();

            bool cancellationRequested = false;

            VS.VSOperationWaiter.Wait(UIResources.QueryingForContainersMessage, false, (cancellationToken) =>
            {
                while (!resetEvent.WaitOne(2000) && !cancellationToken.IsCancellationRequested)
                {
                }
                cancellationRequested = cancellationToken.IsCancellationRequested;
            });

            if (!cancellationRequested)
            {
                if (exitCode != 0)
                {
                    // if the exit code is not zero, then the output we received possibly is the error message
                    string exceptionMessage = UIResources.CommandExecutionErrorWithExitCodeFormat.FormatCurrentCultureWithArgs(
                        "{0} {1}".FormatInvariantWithArgs(settings.Command, settings.CommandArgs),
                        exitCode,
                        errorSB.ToString());

                    throw new CommandFailedException(exceptionMessage);
                }

                foreach (var item in outputLines)
                {
                    containers.Add(DockerContainerInstance.Create(item));
                }
            }

            return(containers);
        }
Exemple #47
0
        public void TestTemporaryTopicReplyTo()
        {
            const int      NUM_MSGS        = 100;
            const string   MSG_BODY        = "num : ";
            IDestination   replyTo         = GetDestination("temp1");
            long           repliedCount    = 0;
            long           lastRepliedId   = -1;
            string         errString       = null;
            CountDownLatch replierFinished = new CountDownLatch(NUM_MSGS);


            using (IConnection connection = GetConnection("c1"))
                using (IMessageConsumer receiver = GetConsumer("receiver"))
                    using (IMessageConsumer listener = GetConsumer("listener"))
                        using (IMessageProducer sender = GetProducer("sender"))
                            using (IMessageProducer replyer = GetProducer("replyer"))
                            {
                                try
                                {
                                    connection.ExceptionListener += DefaultExceptionListener;
                                    ITextMessage rmsg    = null;
                                    ITextMessage sendMsg = sender.CreateTextMessage();
                                    sendMsg.NMSReplyTo = replyTo;

                                    listener.Listener += (message) =>
                                    {
                                        if (errString == null)
                                        {
                                            repliedCount++;
                                            long msgId = ExtractMsgId(message.NMSMessageId);
                                            if (msgId != lastRepliedId + 1)
                                            {
                                                // Test failed release blocked thread for shutdown.
                                                errString = String.Format("Received msg {0} out of order expected {1}", msgId, lastRepliedId + 1);
                                                waiter.Set();
                                            }
                                            else
                                            {
                                                lastRepliedId = msgId;
                                                if (msgId == NUM_MSGS - 1)
                                                {
                                                    message.Acknowledge();
                                                    // test done signal complete.
                                                    waiter.Set();
                                                    return;
                                                }
                                                message.Acknowledge();
                                            }
                                        }
                                    };

                                    receiver.Listener += (message) =>
                                    {
                                        if (errString == null)
                                        {
                                            msgCount++;
                                            rmsg = message as ITextMessage;
                                            if (rmsg == null)
                                            {
                                                // test failure
                                                errString = string.Format(
                                                    "Received message, id = {2}, body of type {0}, expected {1}.",
                                                    message.GetType().Name,
                                                    typeof(ITextMessage).Name,
                                                    ExtractMsgId(message.NMSMessageId)
                                                    );
                                                waiter.Set();
                                                return;
                                            }
                                            IDestination replyDestination = message.NMSReplyTo;
                                            if (!replyDestination.Equals(replyTo))
                                            {
                                                // test failure
                                                errString = string.Format(
                                                    "Received message, id = {0}, with incorrect reply Destination. Expected : {1}, Actual : {2}.",
                                                    ExtractMsgId(message.NMSMessageId),
                                                    replyTo,
                                                    replyDestination
                                                    );
                                                waiter.Set();
                                                return;
                                            }
                                            else
                                            {
                                                ITextMessage reply = replyer.CreateTextMessage();
                                                reply.Text = "Received:" + rmsg.Text;
                                                try
                                                {
                                                    replyer.Send(reply);
                                                    replierFinished.countDown();
                                                }
                                                catch (NMSException nEx)
                                                {
                                                    Logger.Error("Failed to send message from replyer Cause : " + nEx);
                                                    throw nEx;
                                                }
                                            }
                                        }
                                    };

                                    connection.Start();

                                    for (int i = 0; i < NUM_MSGS; i++)
                                    {
                                        sendMsg.Text = MSG_BODY + i;
                                        sender.Send(sendMsg);
                                    }

                                    // allow for two seconds for each message to be sent and replied to.
                                    int timeout = 2000 * NUM_MSGS;
                                    if (!waiter.WaitOne(timeout))
                                    {
                                        Assert.Fail("Timed out waiting on message delivery to complete. Received {1} of {0}, Replied {2} of {0}, Last Replied Msg Id {3}.", NUM_MSGS, msgCount, repliedCount, lastRepliedId);
                                    }
                                    else if (errString != null)
                                    {
                                        Assert.Fail("Asynchronous failure occurred. Cause : {0}", errString);
                                    }
                                    else
                                    {
                                        Assert.IsTrue(replierFinished.await(TimeSpan.FromMilliseconds(timeout)), "Replier thread has not finished sending messages. Remaining {0}", replierFinished.Remaining);
                                        Assert.IsNull(asyncEx, "Received Exception Asynchronously. Cause : {0}", asyncEx);
                                        Assert.AreEqual(NUM_MSGS, msgCount, "Failed to receive all messages.");
                                        Assert.AreEqual(NUM_MSGS, repliedCount, "Failed to reply to all messages");
                                        Assert.AreEqual(NUM_MSGS - 1, lastRepliedId, "Failed to receive the final message");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex);
                                }
                            }
        }
Exemple #48
0
 public void AddConnection(IConnection connection)
 {
     _connections.Add(connection);
 }
Exemple #49
0
        public void TestMultipleProducerCreateAndSend(
            [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)]
            MsgDeliveryMode mode
            )
        {
            const int    MSG_TTL_MILLIS          = 8500; // 8.5 secs
            const int    NUM_MSGS                = 200;
            const int    NUM_PRODUCERS           = 5;
            const string MSG_ID_KEY              = "MsgIndex";
            const string PRODUCER_ID_KEY         = "ProducerIndex";
            const string PRODUCER_INDEXED_ID_KEY = "ProducerIndexedMsgId";
            bool         persistent              = mode.Equals(MsgDeliveryMode.Persistent);
            bool         useMsgId                = !persistent;
            int          msgIdWindow             = 0;

            string failureErr = null;

            IMessageProducer         producer  = null;
            IList <IMessageProducer> producers = null;
            IList <int> lastProducerIndexedIds = null;

            try
            {
                using (IConnection connection = this.GetConnection("c1"))
                    using (ISession session = this.GetSession("s1"))
                        using (IDestination destination = this.GetDestination("t1"))
                            using (IMessageConsumer drain = this.GetConsumer("drain"))
                            {
                                lastProducerIndexedIds = new List <int>();
                                MessageListener ackCallback = CreateListener(NUM_MSGS);

                                drain.Listener += (message) =>
                                {
                                    if (failureErr == null)
                                    {
                                        ackCallback(message);
                                        int id           = message.Properties.GetInt(PRODUCER_INDEXED_ID_KEY);
                                        int prodIndex    = message.Properties.GetInt(PRODUCER_ID_KEY);
                                        int lastId       = lastProducerIndexedIds[prodIndex];
                                        int advancedMsgs = id - lastId;
                                        if (id < lastId)
                                        {
                                            failureErr = string.Format(
                                                "Received message out of order." +
                                                " Received, sent from producer {0} msg id {1} where last msg id {2}",
                                                prodIndex,
                                                id,
                                                lastId
                                                );
                                            this.waiter.Set();
                                        }
                                        else if (persistent && advancedMsgs > 1)
                                        {
                                            failureErr = string.Format(
                                                "Persistent Messages where drop." +
                                                " Received, sent from producer {0} msg id {1} where last msg id {2}",
                                                prodIndex,
                                                id,
                                                lastId
                                                );
                                            this.waiter.Set();
                                        }
                                        else
                                        {
                                            lastProducerIndexedIds[prodIndex] = id;
                                            if (advancedMsgs > 1 && (Logger.IsInfoEnabled || Logger.IsDebugEnabled))
                                            {
                                                Logger.Info(string.Format(
                                                                "{0} Messages dropped for producer {1} from message id {2}",
                                                                advancedMsgs, prodIndex, lastId
                                                                ));
                                            }
                                            msgIdWindow += advancedMsgs;
                                            if (!persistent && msgIdWindow == NUM_MSGS)
                                            {
                                                this.waiter.Set();
                                            }
                                        }
                                    }
                                };

                                connection.ExceptionListener += DefaultExceptionListener;

                                producers = new List <IMessageProducer>();
                                for (int i = 0; i < NUM_PRODUCERS; i++)
                                {
                                    try
                                    {
                                        producer = session.CreateProducer(destination);
                                    }
                                    catch (Exception ex)
                                    {
                                        this.PrintTestFailureAndAssert(this.GetMethodName(), "Failed to Created Producer " + i, ex);
                                    }
                                    producer.DeliveryMode     = mode;
                                    producer.DisableMessageID = !useMsgId;
                                    producer.TimeToLive       = TimeSpan.FromMilliseconds(MSG_TTL_MILLIS);
                                    producers.Add(producer);
                                    lastProducerIndexedIds.Add(-1);
                                }

                                connection.Start();

                                Assert.AreEqual(NUM_PRODUCERS, producers.Count, "Did not create all producers.");
                                Assert.IsNull(asyncEx,
                                              "Exception Listener Called While creating producers. With exception {0}.",
                                              asyncEx);

                                ITextMessage msg           = session.CreateTextMessage();
                                int          producerIndex = -1;
                                for (int i = 0; i < NUM_MSGS; i++)
                                {
                                    msg.Text = "Index:" + i;
                                    msg.Properties[MSG_ID_KEY] = i;
                                    msg.Properties[PRODUCER_INDEXED_ID_KEY] = i / NUM_PRODUCERS;
                                    producerIndex = i % NUM_PRODUCERS;
                                    msg.Properties[PRODUCER_ID_KEY] = producerIndex;
                                    producers[producerIndex].Send(msg);
                                }

                                Assert.IsNull(asyncEx, "Exception Listener Called While sending messages. With exception {0}.", asyncEx);

                                Assert.IsTrue(waiter.WaitOne(TIMEOUT),
                                              "Failed to received all messages in {0}ms. Received {1} of {2} messages",
                                              TIMEOUT, msgCount, NUM_MSGS);

                                Assert.IsNull(failureErr,
                                              "Received assertion failure from IMessageConsumer message Listener. Failure : {0}",
                                              failureErr ?? "");

                                if (persistent)
                                {
                                    Assert.AreEqual(NUM_MSGS, msgCount,
                                                    "Receive unexpected from messages sent. Message Window {0}", msgIdWindow);
                                }
                                else
                                {
                                    int missedMsgs = (msgIdWindow - msgCount);
                                    Assert.AreEqual(NUM_MSGS, msgIdWindow,
                                                    "Failed to receive all messages." +
                                                    " Received {0} of {1} messages, with missed messages {2}, in {3}ms",
                                                    msgCount, NUM_MSGS, missedMsgs, TIMEOUT
                                                    );
                                    if (missedMsgs > 0)
                                    {
                                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                        const string SEPARATOR       = ", ";
                                        for (int i = 0; i < NUM_PRODUCERS; i++)
                                        {
                                            sb.AppendFormat("Last received Producer {0} message id  {1}{2}", i, lastProducerIndexedIds[i], SEPARATOR);
                                        }
                                        sb.Length = sb.Length - SEPARATOR.Length;

                                        Logger.Warn(string.Format("Did not receive all Non Persistent messages. Received {0} of {1} messages. Where last received message ids = [{2}]", msgCount, NUM_MSGS, sb.ToString()));
                                    }
                                }

                                Assert.IsNull(asyncEx, "Exception Listener Called While receiveing messages. With exception {0}.", asyncEx);
                                //
                                // Some brokers are sticklers for detail and actually honor the
                                // batchable flag that AMQPnetLite sets on all published messages. As
                                // a result all messages can be long received before the published
                                // messages are acknowledged. So to avoid a hand full of
                                // amqp:message:released outcomes, just pause a few seconds before
                                // closing the producer
                                System.Threading.Thread.Sleep(3000);
                            }
            }
            catch (Exception e)
            {
                this.PrintTestFailureAndAssert(this.GetMethodName(), "Unexpected Exception.", e);
            }
            finally
            {
                if (producers != null)
                {
                    foreach (IMessageProducer p in producers)
                    {
                        p?.Close();
                        p?.Dispose();
                    }
                    producers.Clear();
                }
            }
        }
Exemple #50
0
        public void TestCreateTemporaryDestination()
        {
            const int NUM_MSGS = 10;

            try
            {
                using (IConnection connection = GetConnection("default"))
                    using (ISession session = GetSession("s1"))
                    {
                        IStreamMessage msg = session.CreateStreamMessage();

                        IDestination temp = session.CreateTemporaryQueue();

                        IMessageProducer producer = session.CreateProducer(temp);

                        for (int i = 0; i < NUM_MSGS; i++)
                        {
                            msg.WriteObject("barfoo");
                            msg.WriteObject(i);

                            msg.Properties.SetInt("count", i);

                            producer.Send(msg);

                            msg.ClearBody();
                        }

                        // Queues do not require an active consumer to receive messages.
                        // Create consumer on queue after messages sent and receive messages.
                        IMessageConsumer drain = session.CreateConsumer(temp);

                        connection.Start();

                        int msgsReceived = DrainDestination(drain, temp, NUM_MSGS);

                        Assert.AreEqual(NUM_MSGS, msgsReceived, "Received {0} of {1} on temporary destination {2}.", msgsReceived, NUM_MSGS, temp.ToString());

                        temp = session.CreateTemporaryTopic();

                        // Topics require an active consumer to receive messages.
                        drain = session.CreateConsumer(temp);

                        producer = session.CreateProducer(temp);

                        for (int i = 0; i < NUM_MSGS; i++)
                        {
                            msg.WriteObject("foobar");
                            msg.WriteObject(i);

                            msg.Properties.SetInt("count", i);

                            producer.Send(msg);

                            msg.ClearBody();
                        }

                        msgsReceived = DrainDestination(drain, temp, NUM_MSGS);

                        Assert.AreEqual(NUM_MSGS, msgsReceived, "Received {0} of {1} on temporary destination {2}.", msgsReceived, NUM_MSGS, temp.ToString());
                    }
            }
            catch (Exception ex)
            {
                this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex);
            }
        }
Exemple #51
0
 public SharedConnectionProxy(SingleConnectionFactory factory, IConnection target, ILogger logger = null)
 {
     _logger  = logger;
     _factory = factory;
     Target   = target;
 }
Exemple #52
0
        private void TestDestinationMessageDelivery(
            IConnection connection,
            ISession session,
            IMessageProducer producer,
            IDestination destination,
            int msgPoolSize,
            bool isDurable = false)
        {
            bool         cleaned  = !isDurable;
            const string PROP_KEY = "send_msg_id";
            string       subName  = DURABLE_SUBSRIPTION_NAME;

            int             TotalMsgSent = 0;
            int             TotalMsgRecv = 0;
            MsgDeliveryMode initialMode  = producer.DeliveryMode;

            try
            {
                IMessageConsumer consumer = isDurable
                    ?
                                            session.CreateDurableConsumer(destination as ITopic, subName, null, false)
                    :
                                            session.CreateConsumer(destination);
                ITextMessage sendMessage = session.CreateTextMessage();

                consumer.Listener            += CreateListener(msgPoolSize);
                connection.ExceptionListener += DefaultExceptionListener;

                connection.Start();

                for (int i = 0; i < msgPoolSize; i++)
                {
                    sendMessage.Text = "Msg:" + i;
                    sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent);
                    producer.Send(sendMessage);
                    TotalMsgSent++;
                }

                bool signal = waiter.WaitOne(TIMEOUT);
                TotalMsgRecv = msgCount;
                Assert.IsTrue(signal,
                              "Timed out waiting to receive messages. Received {0} of {1} in {2}ms.",
                              msgCount, TotalMsgSent, TIMEOUT);
                Assert.AreEqual(TotalMsgSent, msgCount,
                                "Failed to receive all messages. Received {0} of {1} in {2}ms.",
                                msgCount, TotalMsgSent, TIMEOUT);

                // close consumer
                consumer.Close();
                // reset waiter
                waiter.Reset();

                for (int i = 0; i < msgPoolSize; i++)
                {
                    sendMessage.Text = "Msg:" + i;
                    sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent);
                    producer.Send(sendMessage);
                    TotalMsgSent++;
                    if (isDurable || destination.IsQueue)
                    {
                        TotalMsgRecv++;
                    }
                }
                // Must stop connection before we can add a consumer
                connection.Stop();
                int expectedId = (isDurable || destination.IsQueue) ? msgPoolSize : TotalMsgSent;

                // expectedMsgCount is 2 msgPoolSize groups for non-durable topics, one for initial send of pool size and one for final send of pool size.
                // expedtedMsgCount is 3 msgPoolSize groups for queues and durable topics, same two groups for non-durable topic plus the group sent while there is no active consumer.
                int expectedMsgCount = (isDurable || destination.IsQueue) ? 3 * msgPoolSize : 2 * msgPoolSize;

                MessageListener callback  = CreateListener(expectedMsgCount);
                string          errString = null;
                consumer = consumer = isDurable
                    ?
                                      session.CreateDurableConsumer(destination as ITopic, subName, null, false)
                    :
                                      session.CreateConsumer(destination);
                consumer.Listener += (m) =>
                {
                    int id = m.Properties.GetInt(PROP_KEY);
                    if (id != expectedId)
                    {
                        errString = string.Format("Received Message with unexpected msgId. Received msg : {0} Expected : {1}", id, expectedId);
                        waiter.Set();
                        return;
                    }
                    else
                    {
                        expectedId++;
                    }
                    callback(m);
                };
                // Start Connection
                connection.Start();
                for (int i = 0; i < msgPoolSize; i++)
                {
                    sendMessage.Text = "Msg:" + i;
                    sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent);
                    producer.Send(sendMessage);
                    TotalMsgSent++;
                    TotalMsgRecv++;
                }

                signal = waiter.WaitOne(TIMEOUT);
                Assert.IsNull(asyncEx, "Received asynchrounous exception. Message: {0}", asyncEx?.Message);
                Assert.IsNull(errString, "Failure occured on Message Callback. Message : {0}", errString ?? "");
                Assert.IsTrue(signal, "Timed out waiting for message receive. Received {0} of {1} in {2}ms.", msgCount, TotalMsgRecv, TIMEOUT);
                Assert.AreEqual(TotalMsgRecv, msgCount,
                                "Failed to receive all messages. Received {0} of {1} in {2}ms.",
                                msgCount, TotalMsgRecv, TIMEOUT);
                connection.Stop();
                consumer.Close();
            }
            catch (Exception ex)
            {
                this.PrintTestFailureAndAssert(this.GetTestMethodName(), "Unexpected Exception", ex);
            }
            finally
            {
                if (!cleaned)
                {
                    try
                    {
                        session.DeleteDurableConsumer(subName);
                    }
                    catch (InvalidDestinationException ide)
                    {
                        Logger.Info(string.Format("Unable to unsubscribe from {0}, Cause : {1}", subName, ide));
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn(string.Format("Caught unexpected failure while unsubscribing from {0}. Failure : {1}", subName, ex));
                    }
                }
            }
        }
Exemple #53
0
 public VeiculoDAO(IConnection connection)
 {
     this._conn = connection;
 }
 public MessagesController(IConnection rabbitConnection, MongoDbContext mongoDbContext)
 {
     _rabbitConnection = rabbitConnection;
     _mongoDbContext   = mongoDbContext;
 }
 public MonikerConnection(IConnection connection)
 {
     Fill(connection.GetConnectionString());
 }
Exemple #56
0
 public abstract SingleDownload MakeDownload(IConnection connection);
Exemple #57
0
 public Criteria(Type type, IConnection connection, IConnectionFactorySupport factory)
     : this(factory.Mapping.FindTable(type), connection, factory)
 {
     _type = type;
 }
Exemple #58
0
 public Criteria(String entity, IConnection connection, IConnectionFactorySupport factory)
     : this(factory.Mapping.FindTable(entity), connection, factory)
 {
     _entity = entity;
 }
        public static async Task<SchemaModel> ReadSchema(IConnection connection)
        {
            var query = new IntrospectionQuery()
                .Schema
                .Select(x => new SchemaModel
                {
                    QueryType = x.QueryType.Name,
                    MutationType = x.MutationType.Name,
                    Types = x.Types.Select(t => new TypeModel
                    {
                        Kind = t.Kind,
                        Name = t.Name,
                        Description = t.Description,
                        Fields = t.Fields(true).Select((Field f) => new FieldModel
                        {
                            Name = f.Name,
                            Description = f.Description,
                            Type = f.Type.Select((SchemaType t1) => new TypeModel
                            {
                                Kind = t1.Kind,
                                Name = t1.Name,
                                OfType = t1.OfType.Select((SchemaType t2) => new TypeModel
                                {
                                    Kind = t2.Kind,
                                    Name = t2.Name,
                                    OfType = t2.OfType.Select((SchemaType t3) => new TypeModel
                                    {
                                        Kind = t3.Kind,
                                        Name = t3.Name,
                                        OfType = t3.OfType.Select((SchemaType t4) => new TypeModel
                                        {
                                            Kind = t4.Kind,
                                            Name = t4.Name,
                                        }).SingleOrDefault(),
                                    }).SingleOrDefault(),
                                }).SingleOrDefault(),
                            }).Single(),
                            Args = f.Args.Select((InputValue a) => new InputValueModel
                            {
                                Name = a.Name,
                                Description = a.Description,
                                DefaultValue = a.DefaultValue,
                                Type = a.Type.Select((SchemaType t1) => new TypeModel
                                {
                                    Kind = t1.Kind,
                                    Name = t1.Name,
                                    OfType = t1.OfType.Select((SchemaType t2) => new TypeModel
                                    {
                                        Kind = t2.Kind,
                                        Name = t2.Name,
                                        OfType = t2.OfType.Select((SchemaType t3) => new TypeModel
                                        {
                                            Kind = t3.Kind,
                                            Name = t3.Name,
                                            OfType = t3.OfType.Select((SchemaType t4) => new TypeModel
                                            {
                                                Kind = t4.Kind,
                                                Name = t4.Name,
                                            }).SingleOrDefault(),
                                        }).SingleOrDefault(),
                                    }).SingleOrDefault(),
                                }).Single(),
                            }).ToList(),
                            IsDeprecated = f.IsDeprecated,
                            DeprecationReason = f.DeprecationReason,
                        }).ToList(),
                        EnumValues = t.EnumValues(true).Select((EnumValue e) => new EnumValueModel
                        {
                            Name = e.Name,
                            Description = e.Description,
                            IsDeprecated = e.IsDeprecated,
                            DeprecationReason = e.DeprecationReason,
                        }).ToList(),
                        InputFields = t.InputFields.Select((InputValue i) => new InputValueModel
                        {
                            Name = i.Name,
                            Description = i.Description,
                            DefaultValue = i.DefaultValue,
                            Type = i.Type.Select((SchemaType t1) => new TypeModel
                            {
                                Kind = t1.Kind,
                                Name = t1.Name,
                                OfType = t1.OfType.Select((SchemaType t2) => new TypeModel
                                {
                                    Kind = t2.Kind,
                                    Name = t2.Name,
                                    OfType = t2.OfType.Select((SchemaType t3) => new TypeModel
                                    {
                                        Kind = t3.Kind,
                                        Name = t3.Name,
                                        OfType = t3.OfType.Select((SchemaType t4) => new TypeModel
                                        {
                                            Kind = t4.Kind,
                                            Name = t4.Name,
                                        }).SingleOrDefault(),
                                    }).SingleOrDefault(),
                                }).SingleOrDefault(),
                            }).Single(),
                        }).ToList(),
                        PossibleTypes = t.PossibleTypes.Select((SchemaType t1) => new TypeModel
                        {
                            Kind = t1.Kind,
                            Name = t1.Name,
                            Description = t1.Description,
                            OfType = t1.OfType.Select((SchemaType t2) => new TypeModel
                            {
                                Kind = t2.Kind,
                                Name = t2.Name,
                                OfType = t2.OfType.Select((SchemaType t3) => new TypeModel
                                {
                                    Kind = t3.Kind,
                                    Name = t3.Name,
                                    OfType = t3.OfType.Select((SchemaType t4) => new TypeModel
                                    {
                                        Kind = t4.Kind,
                                        Name = t4.Name,
                                    }).SingleOrDefault(),
                                }).SingleOrDefault(),
                            }).SingleOrDefault(),
                        }).ToList(),
                    }).ToList()
                });

            return await connection.Run(query).ConfigureAwait(false);
        }
Exemple #60
0
 /// <summary>
 /// Creates a new <see cref="BackstoryClient"/> that is used for the API v2 backstory endpoint.
 /// </summary>
 /// <param name="connection">The connection used to make requests, see <see cref="IConnection"/>.</param>
 /// <param name="gw2Client">The Guild Wars 2 client.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connection"/> or <paramref name="gw2Client"/> is <see langword="null"/>.</exception>
 protected internal BackstoryClient(IConnection connection, IGw2Client gw2Client) :
     base(connection, gw2Client)
 {
     this.answers   = new BackstoryAnswersClient(connection, gw2Client);
     this.questions = new BackstoryQuestionsClient(connection, gw2Client);
 }