public void Should_be_able_to_configure_request()
        {
            var client = new ManagementClient(hostUrl, username, password, configureRequest: 
                req => req.Headers.Add("x-not-used", "some_value"));

            client.GetOverview();
        }
		public void Should_get_vHost_OK()
		{
			var client = new ManagementClient (hostUrl, username, password, port, true);

			var vHost = client.GetVhost ("/");

			Console.WriteLine ("Got vHost with name '{0}'.", vHost.Name);
		}
        private static void DeleteQueue(string queueToDelete)
        {
            var management = new ManagementClient("http://localhost", "guest", "guest");

            var vhost = management.GetVhost("/");
            var queue = management.GetQueue(queueToDelete, vhost);
            management.DeleteQueue(queue);
        }
 public Jsr262MBeanServerConnection(int enumerationMaxElements, string serverUri)
 {
     _enumerationMaxElements = enumerationMaxElements;
     _soapClient = new SOAPClient(serverUri);
     _manClient = new ManagementClient(serverUri);
     _enumClient = new EnumerationClient(true, serverUri);
     _eventingClient = new EventingClient(serverUri);
 }
Beispiel #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            var initial = new ManagementClient("http://192.169.164.138", "guest", "guest");

            var queues = initial.GetQueues();
               foreach (var queue in queues)
            {
                if(queue.Name.Contains("error") || queue.MessagesReady >=25)
                    initial.DeleteQueue(queue);
                Console.WriteLine(queue.Name + ": " + queue.IdleSince);
            }
        }
Beispiel #6
0
        void _t_Tick(object sender, EventArgs e)
        {
            var initial = new ManagementClient("http://192.169.164.138", "guest", "guest");
            var nodes = initial.GetNodes();
            grdMain.DataSource = nodes;
            grdMain.RefreshDataSource();
            var queues = initial.GetQueues();
            grd.DataSource = queues;

            grd.RefreshDataSource();
            Application.DoEvents();
        }
		public void Should_get_Channel_OK()
		{
            var managementClient2 = new ManagementClient(hostUrl, username, password, port, true);

			var channels = managementClient2.GetChannels ();

			foreach (var channel in channels) {
				Console.WriteLine ("Channel: {0}", channel.Name);
				var detail = managementClient2.GetChannel (channel.Name);

				foreach (var consumer in detail.ConsumerDetails) {
					Console.WriteLine ("\tConsumer for: {0}", consumer.Queue.Name);
				}
			}
		}
Beispiel #8
0
        public static void PerformTest()
        {
            var client = new ManagementClient("http://localhost:12345/Management");

            Console.WriteLine("Client: requesting fragment {0} of resource {1} with selector [{2}/{3}]", Program.ResourceUri, "a", "name", "value");
            Console.WriteLine();
            var o = client.Get<XmlFragment<SampleData>>(Program.ResourceUri, "a", new[] { new Selector("name", "value"), });

            Console.WriteLine("Client: putting fragment {0} of resource {1}: {2}", Program.ResourceUri, "fragment", o.Value);
            Console.WriteLine();
            var a = client.Put<SampleData>(Program.ResourceUri, "fragment", o.Value);

            Console.WriteLine("Client: deleting resource {0} with selector [{1}/{2}]", Program.ResourceUri, "name", "http://tempuri.org");
            Console.WriteLine();
            client.Delete(Program.ResourceUri, new[] { new Selector("name", new EndpointReference("http://tempuri.org")) });
        }
        public void PurgeQueues(string hostUrl, string username, string password)
        {
            lock (lockObject)
            {

                string lookupString = "QuoteServer.On";
                var management = new ManagementClient(hostUrl, username, password);
                var queues = management.GetQueues();

                foreach (var queue in queues)
                {
                    if (queue.Name.StartsWith(lookupString, StringComparison.InvariantCultureIgnoreCase))
                    {
                        management.Purge(queue);
                    }
                }

            }
        }
Beispiel #10
0
		public Guid CreateSession (string connection, string username, string password, int authMechanism, int protocolVersion)
		{
			ChannelFactory<IWSTransferContract> cf = new ChannelFactory<IWSTransferContract>(new WSManBinding());
			cf.Credentials.UserName.UserName = username;
			cf.Credentials.UserName.Password = password;
			if (connection.IndexOf ("://") == -1) {
				//Default to http connection
				connection = "http://" + connection;
			}
			UriBuilder builder = new UriBuilder (connection);
			if (builder.Port == 80 || builder.Port == 443) {
				builder.Port = 5985;
			}

			ManagementClient client = new ManagementClient(builder.Uri, cf, MessageVersion.Soap12WSAddressing10);
			var sessionData = client.Get<XmlFragment<SessionData>>(PowerShellNamespaces.Namespace, "CreateSession", new Selector("ProtocolVersion", protocolVersion.ToString()));
			_services.Add (sessionData.Value.Id, client);
			return sessionData.Value.Id;
		}
        public void InitializeQueues(string hostUrl, string username, string password, string queueNamePattern)
        {
            lock (lockObject)
            {

                var management = new ManagementClient(hostUrl, username, password);
                var queues = management.GetQueues();

                foreach (var queue in queues)
                {
                    if (queue.Name.IndexOf(queueNamePattern, StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        management.Purge(queue);
                        management.DeleteQueue(queue);
                    }
                }

            }
        }
Beispiel #12
0
        public void Dispose()
        {
            var managementClient = new ManagementClient(AsbTestConfig.ConnectionString);

            AsyncHelpers.RunSync(async() =>
            {
                try
                {
                    var topicDescription = await managementClient.GetQueueAsync(_queueName);

                    await managementClient.DeleteQueueAsync(topicDescription.Path);

                    Console.WriteLine($"Deleted queue '{_queueName}'");
                }
                catch (MessagingEntityNotFoundException)
                {
                    // it's ok
                }
            });
        }
Beispiel #13
0
        private async Task <TopicDescription> CreateTopic()
        {
            ManagementClient managementClient = new ManagementClient(_ManagementConnectionString);

            try
            {
                TopicDescription topicDescription = new TopicDescription(_Topic)
                {
                    AutoDeleteOnIdle         = TimeSpan.FromMinutes(30),
                    DefaultMessageTimeToLive = TimeSpan.FromMinutes(5),
                    MaxSizeInMB = 1024
                };

                return(await managementClient.CreateTopicAsync(topicDescription));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Beispiel #14
0
        public static async Task EnsureSubscriptionRuleExistsAsync(string topicName, string subscriptionName, RuleDescription ruleDescription)
        {
            var sbManagement = new ManagementClient(Configs.SbFailoverConnectionString);

            var rules = await sbManagement.GetRulesAsync(topicName, subscriptionName);

            var defaultRule = rules.SingleOrDefault(x => x.Name.Equals(RuleDescription.DefaultRuleName));

            if (defaultRule != null)
            {
                Console.WriteLine($"Removing subscription rule: {defaultRule.Name}");
                await sbManagement.DeleteRuleAsync(topicName, subscriptionName, defaultRule.Name);
            }

            if (!rules.Any(x => x.Name.Equals(ruleDescription.Name)))
            {
                Console.WriteLine($"Creating subscription rule: {ruleDescription.Name}");
                await sbManagement.CreateRuleAsync(topicName, subscriptionName, ruleDescription);
            }
        }
 private static void Init()
 {
     try
     {
         _managementClient = new ManagementClient(_connectionString);
         if (!_managementClient.TopicExistsAsync(_topicName).Result)
         {
             _managementClient.CreateTopicAsync(new TopicDescription(_topicName)
             {
                 AutoDeleteOnIdle        = TimeSpan.FromMinutes(60),
                 EnableBatchedOperations = true
             });
         }
         _topicClient = new TopicClient(_connectionString, _topicName);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
        static async Task DeleteAllTopics()
        {
            var managementClient = new ManagementClient(AsbTestConfig.ConnectionString);

            while (true)
            {
                var topics = await managementClient.GetTopicsAsync();

                if (!topics.Any())
                {
                    return;
                }

                await Task.WhenAll(topics.Select(async topic =>
                {
                    Console.WriteLine($"Deleting topic '{topic.Path}'");
                    await managementClient.DeleteTopicAsync(topic.Path);
                }));
            }
        }
 static void Init()
 {
     try
     {
         _managementClient = new ManagementClient(_connectionString);
         if (!_managementClient.QueueExistsAsync(_queueName).Result)
         {
             _managementClient.CreateQueueAsync(new QueueDescription(_queueName)
             {
                 AutoDeleteOnIdle = TimeSpan.FromHours(1),
                 EnableDeadLetteringOnMessageExpiration = true
             }).Wait();
         }
         _queueClient = new QueueClient(_connectionString, _queueName);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Beispiel #18
0
        private static void EnsureQueueAndSubscription(ManagementClient managementClient, string queue, Type messageType = null)
        {
            try
            {
                EnsureQueue(managementClient, queue);

                if (messageType == null)
                {
                    return;
                }

                EnsureSubscription(managementClient, queue, messageType);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error ensuring Ensure Queue And Subscription: {e.Message}.");
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #19
0
        public void TryActiavateTest()
        {
            var managementClient = new ManagementClient(ManagementApi);

            var email = Guid.NewGuid() + "@test.hu";

            managementClient.User.Register(new Register {
                Email = email, Name = "test user", Password = "******"
            });
            var user = managementClient.User.Get();

            managementClient.User.Logoff();

            // will return with HTTP status code forbidden because activation is not required
            managementClient.User.Activate(new Activate
            {
                UserId         = user.Id,
                ActivationCode = "12345678901234567890123456789012"
            });
        }
 private void InitializeServiceBus()
 {
     _managementClient = new ManagementClient(_connectionString);
     if (!_managementClient.QueueExistsAsync(_queueClientName).Result)
     {
         _managementClient.CreateQueueAsync(new QueueDescription(_queueClientName)
         {
             AutoDeleteOnIdle = TimeSpan.FromHours(1)
         }).GetAwaiter().GetResult();
     }
     if (!_managementClient.QueueExistsAsync(_queueServerName).Result)
     {
         _managementClient.CreateQueueAsync(new QueueDescription(_queueServerName)
         {
             AutoDeleteOnIdle = TimeSpan.FromHours(1),
             RequiresSession  = true
         }).GetAwaiter().GetResult();
     }
     _queueClient = new QueueClient(_connectionString, _queueClientName);
 }
Beispiel #21
0
        public async Task Unsubscribe(Type eventType, ContextBag context)
        {
            await CheckForManagePermissions().ConfigureAwait(false);

            var ruleName = ruleNameFactory(eventType);

            var client = new ManagementClient(connectionStringBuilder, tokenProvider);

            try
            {
                await client.DeleteRuleAsync(topicPath, subscriptionName, ruleName).ConfigureAwait(false);
            }
            catch (MessagingEntityNotFoundException)
            {
            }
            finally
            {
                await client.CloseAsync().ConfigureAwait(false);
            }
        }
Beispiel #22
0
        public async Task <bool> UpdateTeamAsync(Team TeamToUpdate)
        {
            bool success = false;

            //Get a Kontent Management API client for v1 of the API
            ManagementClient client = _managementService.GetManagementClient();

            //Create identifiers for working with our item
            var ids = KontentManagementHelper.GetIdentifiers(TeamToUpdate.CodeName);

            //Specify fields we want to update in our content item
            Models.Generated.TeamForScore updateModel = new Models.Generated.TeamForScore()
            {
                TeamScore      = new Decimal(TeamToUpdate.TeamScore),
                TeamFramesleft = new Decimal(TeamToUpdate.TeamFramesLeft)
            };

            try
            {
                //Create a new version of the content item in Kontent
                success = await _managementBetaService.CreateContentItemNewVersion(TeamToUpdate.CodeName);

                //Commit the update to Kontent
                await client.UpsertContentItemVariantAsync(ids.Item3, updateModel);

                //Publish the version of the content item in Kontent
                success = await _managementBetaService.PublishContentItem(TeamToUpdate.CodeName);

                //Update the local memory object
                var localTeam = _allTeams.Find(t => t.CodeName == TeamToUpdate.CodeName);
                localTeam.TeamScore      = (int)updateModel.TeamScore;
                localTeam.TeamFramesLeft = (int)updateModel.TeamFramesleft;
            }
            catch (Exception ex)
            {
                //TODO: log the update error
                string message = ex.Message;
            }

            return(success);
        }
        public async Task Should_be_able_to_provision_a_virtual_host()
        {
            var initial = new ManagementClient(rabbitMqUrl, Configuration.RabbitMqUser,
                                               Configuration.RabbitMqPassword, Configuration.RabbitMqManagementPort);

            // first create a new virtual host
            var vhost = await initial.CreateVhostAsync("my_virtual_host").ConfigureAwait(false);

            // next create a user for that virutal host
            var user = await initial.CreateUserAsync(new UserInfo("mike", "topSecret").AddTag("administrator")).ConfigureAwait(false);

            // give the new user all permissions on the virtual host
            await initial.CreatePermissionAsync(new PermissionInfo(user, vhost)).ConfigureAwait(false);

            // now log in again as the new user
            var management = new ManagementClient(rabbitMqUrl, user.Name, "topSecret",
                                                  Configuration.RabbitMqManagementPort);

            // test that everything's OK
            await management.IsAliveAsync(vhost).ConfigureAwait(false);

            // create an exchange
            var exchange = await management.CreateExchangeAsync(new ExchangeInfo("my_exchagne", "direct"), vhost).ConfigureAwait(false);

            // create a queue
            var queue = await management.CreateQueueAsync(new QueueInfo("my_queue"), vhost).ConfigureAwait(false);

            // bind the exchange to the queue
            await management.CreateBindingAsync(exchange, queue, new BindingInfo("my_routing_key")).ConfigureAwait(false);

            // publish a test message
            await management.PublishAsync(exchange, new PublishInfo("my_routing_key", "Hello World!")).ConfigureAwait(false);

            // get any messages on the queue
            var messages = await management.GetMessagesFromQueueAsync(queue, new GetMessagesCriteria(1, Ackmodes.ack_requeue_false)).ConfigureAwait(false);

            foreach (var message in messages)
            {
                Console.Out.WriteLine("message.payload = {0}", message.Payload);
            }
        }
Beispiel #24
0
        public async Task Go()
        {
            _TopicClient = new TopicClient(_ConnectionString, TOPIC_NAME);

            _ManagementClient = new ManagementClient(_ConnectionString);

            var subscriptionId          = Guid.NewGuid().ToString();
            var subscriptionDescription = new SubscriptionDescription(TOPIC_NAME, subscriptionId)
            {
                AutoDeleteOnIdle = TimeSpan.FromMinutes(30)
            };
            await _ManagementClient.CreateSubscriptionAsync(subscriptionDescription);

            _SubscriptionClient = new SubscriptionClient(_ConnectionString, TOPIC_NAME, subscriptionId);

            var messageHandlerOptions = new MessageHandlerOptions(OnExceptionReceived)
            {
                MaxConcurrentCalls = 20,
                AutoComplete       = false
            };

            _SubscriptionClient.RegisterMessageHandler(OnMessageReveived, messageHandlerOptions);

            var random = new Random();

            while (true)
            {
                Console.WriteLine("Press enter to send a some messages to the topic");
                Console.ReadLine();

                var count = random.Next(1, 5);
                for (int i = 0; i < count; i++)
                {
                    var message = $"Random {random.Next(0, 1000)}";
                    Console.WriteLine($"Sending: {message}");

                    var messageBytes = Encoding.UTF8.GetBytes(message);
                    await _TopicClient.SendAsync(new Message(messageBytes));
                }
            }
        }
Beispiel #25
0
        public void CreateGetUpdateGetDeleteGetServiceTest()
        {
            var managementClient = new ManagementClient(ManagementApi);

            managementClient.User.Register(new Register
            {
                Email    = Guid.NewGuid() + "@test.hu",
                Name     = "test user",
                Password = "******"
            });

            var companyId = managementClient.Company.Create(new Company {
                Name = "company"
            });

            var serviceId = managementClient.Service.Create(new Service {
                CompanyId = companyId, Name = "árvíztűrő tükörfúrógép"
            });

            Assert.IsNotNull(serviceId);

            var service = managementClient.Service.Get(serviceId);

            Assert.AreEqual("árvíztűrő tükörfúrógép", service.Name);
            Assert.IsNotNull(service.ApiKey);
            Assert.AreEqual(companyId, service.CompanyId);

            service.Name  += "mod";
            service.ApiKey = "aaa";

            managementClient.Service.Update(service);

            service = managementClient.Service.Get(serviceId);

            Assert.AreEqual("árvíztűrő tükörfúrógépmod", service.Name);
            Assert.AreEqual(32, service.ApiKey.Length);

            managementClient.Service.Delete(serviceId);

            managementClient.Service.Get(serviceId);
        }
        /// <summary>
        /// Create subscription client
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private async Task <ISubscriptionClient> NewSubscriptionClientAsync(
            string topic, string name)
        {
            var managementClient = new ManagementClient(_config.ServiceBusConnString);
            var exists           = await managementClient.TopicExistsAsync(topic);

            if (!exists)
            {
                await Try.Async(() =>
                                managementClient.CreateTopicAsync(new TopicDescription(topic)));
            }
            exists = await managementClient.SubscriptionExistsAsync(topic, name);

            if (!exists)
            {
                await managementClient.CreateSubscriptionAsync(
                    new SubscriptionDescription(topic, name));
            }
            return(new SubscriptionClient(_config.ServiceBusConnString, topic, name,
                                          ReceiveMode.PeekLock, RetryPolicy.Default));
        }
Beispiel #27
0
        public int?GetConnectedAlgServersCountSync()
        {
            if (!_bus.IsConnected)
            {
                return(null);
            }
            var client = new ManagementClient(_brokerOptions.Value.Hostname, _brokerOptions.Value.Username, _brokerOptions.Value.Password);

            try
            {
                return(client
                       .GetConnections()
                       .Count(c => c.ClientProperties.Application == "CVaS.AlgServer.dll"));
            }
            catch (Exception exc)
            {
                _logger.LogWarning("Exception when getting connected Alg Servers Count", exc);
            }

            return(null);
        }
Beispiel #28
0
        private async Task <string> GetOrCreateSubscriptionAsync(CancellationToken cancellationToken)
        {
            var    managementClient = new ManagementClient(_options.ConnectionString);
            string subscriptionName = $"sub-{_nodeIdProvider.NodeId}";

            try
            {
                await managementClient.GetSubscriptionAsync(_options.TopicName, subscriptionName, cancellationToken);
            }
            catch (MessagingEntityNotFoundException)
            {
                var subscription = new SubscriptionDescription(_options.TopicName, subscriptionName)
                {
                    AutoDeleteOnIdle         = _options.AutoDeleteSubscriptionOnIdle,
                    DefaultMessageTimeToLive = _options.MessageTimeToLive
                };
                await managementClient.CreateSubscriptionAsync(subscription, cancellationToken);
            }

            return(subscriptionName);
        }
Beispiel #29
0
        public OpenVpnConnection(
            ILogger logger,
            INetworkInterfaceLoader networkInterfaceLoader,
            OpenVpnProcess process,
            ManagementClient managementClient)
        {
            _logger = logger;
            _networkInterfaceLoader = networkInterfaceLoader;
            _process          = process;
            _managementClient = managementClient;

            _managementClient.VpnStateChanged       += ManagementClient_StateChanged;
            _managementClient.TransportStatsChanged += ManagementClient_TransportStatsChanged;

            _managementPorts             = new OpenVpnManagementPorts();
            _randomStrings               = new RandomStrings();
            _connectAction               = new SingleAction(ConnectAction);
            _connectAction.Completed    += ConnectAction_Completed;
            _disconnectAction            = new SingleAction(DisconnectAction);
            _disconnectAction.Completed += DisconnectAction_Completed;
        }
 public void Instantiate(string className)
 {
     try
     {
         using (UndoContext context = UndoContext.Current)
         {
             context.Start(className, "FixtureSetup");
             this.managementClient = this.GetManagementClient();
             this.DefaultLocation  = managementClient.GetDefaultLocation("Compute", "Storage");
         }
     }
     catch (Exception)
     {
         Cleanup();
         throw;
     }
     finally
     {
         TestUtilities.EndTest();
     }
 }
Beispiel #31
0
 private static async Task Init()
 {
     try
     {
         _managementClient = new ManagementClient(_connectionString);
         if (!await _managementClient.TopicExistsAsync(_topicName))
         {
             await _managementClient.CreateTopicAsync(new TopicDescription(_topicName)
             {
                 AutoDeleteOnIdle = TimeSpan.FromHours(1),
                 DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2),
                 RequiresDuplicateDetection          = true
             });
         }
         _topicClient = new TopicClient(_connectionString, _topicName);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Beispiel #32
0
 //- $StopInstance -//
 private void StopInstance()
 {
     using (ManagementClient client = new ManagementClient())
     {
         String   name     = this.Instance.Name;
         Instance instance = client.StopInstance(this.Instance.Id);
         //+
         this.Instance.State             = instance.State;
         this.Instance.OperationStatus   = instance.OperationStatus;
         this.Instance.LastActionMessage = instance.LastActionMessage;
         //+
         if (this.Instance.OperationStatus == Instance.InstanceStatus.OperationSuccess)
         {
             this.TabControl.Window.ReportActionMessage(String.Format("Instance {0} ({1}) successfully stopped.", this.Instance.Name, this.Instance.Id), String.Empty);
         }
         else
         {
             this.TabControl.Window.ReportActionMessage(String.Format("Unable to stop instance {0} ({1}) (see message log for details).", this.Instance.Name, this.Instance.Id), this.Instance.LastActionMessage);
         }
     }
 }
Beispiel #33
0
        private static async Task CreateOrUpdateSubscriptionAsync <TPayload>(
            string connectionString,
            string channelName,
            string subscriptionName,
            string topicPath,
            IMessageFactory <TPayload> messageFactory)
            where TPayload : class, IReceivedServiceBusMessage
        {
            var managementClient = new ManagementClient(connectionString);
            var ruleDescription  = GetRuleDescriptionFromTypeMap(subscriptionName, topicPath, messageFactory);

            try
            {
                var subscriptionDescription = new SubscriptionDescription(channelName, subscriptionName);
                await managementClient.CreateSubscriptionAsync(subscriptionDescription, ruleDescription);
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                await UpdateSubscriptionRules(managementClient, channelName, subscriptionName, ruleDescription, messageFactory);
            }
        }
Beispiel #34
0
        public QueueConnector(string connectionString, string queueName)
        {
            asyncClient = new Lazy <Task <QueueClient> >(async() =>
            {
                var managementClient = new ManagementClient(connectionString);

                var allQueues = await managementClient.GetQueuesAsync();

                var foundQueue = allQueues.Where(q => q.Path == queueName.ToLower()).SingleOrDefault();

                if (foundQueue == null)
                {
                    await managementClient.CreateQueueAsync(queueName);//add queue desciption properties
                }


                return(new QueueClient(connectionString, queueName));
            });

            queueClient = asyncClient.Value.Result;
        }
        /// <summary>
        /// Determines whether a particular topic or subscription is disabled.
        /// </summary>
        /// <param name="manager">The manager.</param>
        /// <param name="topicName">Name of the topic.</param>
        /// <param name="subscriptionName">Name of the subscription.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        public static async Task <bool> IsTopicOrSubscriptionDisabled(this ManagementClient manager, string topicName, string subscriptionName = null)
        {
            var topic = await manager.GetTopicAsync(topicName);

            // If topic is disabled, return true here.
            if (topic.Status == EntityStatus.Disabled || topic.Status == EntityStatus.ReceiveDisabled)
            {
                return(true);
            }

            // If no subscription was requested, then return false as the topic is enabled.
            if (subscriptionName == null)
            {
                return(false);
            }

            // Otherwise, carry on and check subscription.
            var subscription = await manager.GetSubscriptionAsync(topicName, subscriptionName);

            return(subscription.Status == EntityStatus.Disabled || subscription.Status == EntityStatus.ReceiveDisabled);
        }
Beispiel #36
0
        private void Initialise()
        {
            s_logger.LogDebug("Initialising new management client wrapper...");

            try
            {
                if (_configuration == null)
                {
                    throw new ArgumentNullException(nameof(_configuration), "Configuration is null, ensure this is set in the constructor.");
                }

                _managementClient = new ManagementClient(_configuration.ConnectionString);
            }
            catch (Exception e)
            {
                s_logger.LogError(e, "Failed to initialise new management client wrapper.");
                throw;
            }

            s_logger.LogDebug("New management client wrapper initialised.");
        }
Beispiel #37
0
        public void MultiCreateListCompanyTest()
        {
            var managementClient = new ManagementClient(ManagementApi);

            managementClient.User.Register(new Register {
                Email = Guid.NewGuid() + "@test.hu", Name = "test user", Password = "******"
            });

            managementClient.Company.Create(new Company {
                Name = "company1"
            });
            managementClient.Company.Create(new Company {
                Name = "company2"
            });

            var companies = managementClient.Company.List();

            Assert.AreEqual(2, companies.Count());
            Assert.IsTrue(companies.Any(c => c.Name == "company1"));
            Assert.IsTrue(companies.Any(c => c.Name == "company2"));
        }
Beispiel #38
0
        private void CheckRabbitQueueWarningLimit(ManagementClient managementClient, IRabbitMqHostConfiguration rabbitConfiguration)
        {
            try
            {
                var rabbitQueues = managementClient.GetQueues();

                foreach (var rabbitQueue in rabbitQueues)
                {
                    if (rabbitQueue.Messages > rabbitConfiguration.QueueWarningLimit)
                    {
                        _logger.Warn(
                            "Queue '{0}' on node '{1}' has exceeded the queue item limit threshold of {2} and currrently has {3} messages queued, please check queue is processing as expected",
                            rabbitQueue.Name, rabbitQueue.Node, rabbitConfiguration.QueueWarningLimit, rabbitQueue.Messages);
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(managementClient.HostUrl, ex);
            }
        }
 private static void Init()
 {
     try
     {
         _managementClient = new ManagementClient(_connectionString);
         if (!_managementClient.QueueExistsAsync(_queueName).Result)
         {
             _managementClient.CreateQueueAsync(new QueueDescription(_queueName)
             {
                 EnablePartitioning                  = true,
                 RequiresDuplicateDetection          = true,
                 DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2)
             }).Wait();
         }
         _queueClient = new QueueClient(_connectionString, _queueName);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
        public void Setup()
        {
            managementClient = new ManagementClient("59f86b4832eb28071bdd9214", "4b880fff06b080f154ee48c9e689a541")
            {
                Host      = "http://192.168.50.64:3000",
                PublicKey = @"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4xKeUgQ+Aoz7TLfAfs9+paePb
5KIofVthEopwrXFkp8OCeocaTHt9ICjTT2QeJh6cZaDaArfZ873GPUn00eOIZ7Ae
+TiA2BKHbCvloW3w5Lnqm70iSsUi5Fmu9/2+68GZRH9L7Mlh8cFksCicW2Y2W2uM
GKl64GDcIq3au+aqJQIDAQAB
-----END PUBLIC KEY-----",
            };

            email    = RandomString() + "@gmail.com";
            password = "******";
            user     = managementClient.Users.Create(new CreateUserInput()
            {
                Email    = email,
                Password = password,
            }).Result;
        }
Beispiel #41
0
        public void ResetPasswordTest()
        {
            var managementClient = new ManagementClient(ManagementApi);

            var email = Guid.NewGuid() + "@test.hu";

            managementClient.User.Register(new Register {
                Email = email, Name = "test user", Password = "******"
            });
            var user = managementClient.User.Get();

            managementClient.User.Logoff();

            // invalid confirmation code results forbidden
            managementClient.User.ResetPassword(new ResetPassword
            {
                UserId           = user.Id,
                ConfirmationCode = "12345678901234567890123456789012",
                Password         = "******"
            });
        }
Beispiel #42
0
        public void Should_be_able_to_provision_a_virtual_host()
        {
            var initial = new ManagementClient("http://localhost", "guest", "guest");

            // first create a new virtual host
            var vhost = initial.CreateVirtualHost("my_virtual_host");

            // next create a user for that virutal host
            var user = initial.CreateUser(new UserInfo("mike", "topSecret"));

            // give the new user all permissions on the virtual host
            initial.CreatePermission(new PermissionInfo(user, vhost));

            // now log in again as the new user
            var management = new ManagementClient("http://localhost", user.name, "topSecret");

            // test that everything's OK
            management.IsAlive(vhost);

            // create an exchange
            var exchange = management.CreateExchange(new ExchangeInfo("my_exchagne", "direct"), vhost);

            // create a queue
            var queue = management.CreateQueue(new QueueInfo("my_queue"), vhost);

            // bind the exchange to the queue
            management.CreateBinding(exchange, queue, new BindingInfo("my_routing_key"));

            // publish a test message
            management.Publish(exchange, new PublishInfo("my_routing_key", "Hello World!"));

            // get any messages on the queue
            var messages = management.GetMessagesFromQueue(queue, new GetMessagesCriteria(1, false));

            foreach (var message in messages)
            {
                Console.Out.WriteLine("message.payload = {0}", message.payload);
            }
        }
        public void Queue_should_not_be_deleted_if_expires_is_not_set()
        {
            var bus = RabbitHutch.CreateBus("host=localhost");

            var subscriptionId = "TestSubscriptionWithoutExpires";
            var conventions = new Conventions(new TypeNameSerializer());
            var queueName = conventions.QueueNamingConvention(typeof(MyMessage), subscriptionId);
            var client = new ManagementClient("http://localhost", "guest", "guest");
            var vhost = new Vhost { Name = "/" };

            bus.Subscribe<MyMessage>(subscriptionId, message => { });

            var queue = client.GetQueue(queueName, vhost);
            queue.ShouldNotBeNull();

            // this will abandon the queue... poor queue!
            bus.Dispose();

            Thread.Sleep(1500);

            queue = client.GetQueue(queueName, vhost);
            queue.ShouldNotBeNull();
        }
        public void Should_get_overview_on_mono()
        {
            var managementClient2 = new ManagementClient(hostUrl, username, password, port, true);

            var overview = managementClient2.GetOverview();

            Console.Out.WriteLine("overview.ManagementVersion = {0}", overview.ManagementVersion);
            foreach (var exchangeType in overview.ExchangeTypes)
            {
                Console.Out.WriteLine("exchangeType.Name = {0}", exchangeType.Name);
            }
            foreach (var listener in overview.Listeners)
            {
                Console.Out.WriteLine("listener.IpAddress = {0}", listener.IpAddress);
            }

            Console.Out.WriteLine("overview.Messages = {0}", overview.QueueTotals != null ? overview.QueueTotals.Messages : 0);

            foreach (var context in overview.Contexts)
            {
                Console.Out.WriteLine("context.Description = {0}", context.Description);
            }
        }
 public void SetUp()
 {
     _restClient = MockRepository.GenerateStub<IRestClient>();
     _client = new ManagementClient(_restClient);
 }
        private void IntermittentDisconnection()
        {
            const int secondsBetweenDisconnection = 2;

            Task.Factory.StartNew(() =>
                {
                    var client = new ManagementClient("http://localhost", "guest", "guest", 15672);
                    while (true)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(secondsBetweenDisconnection)); 
                        var connections = client.GetConnections();
                        foreach (var connection in connections)
                        {
                            client.CloseConnection(connection);
                        }
                    }
                }, TaskCreationOptions.LongRunning);
        }
        internal CloudServiceClient(
            WindowsAzureSubscription subscription,
            ManagementClient managementClient,
            StorageManagementClient storageManagementClient,
            ComputeManagementClient computeManagementClient)
            : this((string)null, null, null, null)
        {
            Subscription = subscription;
            CurrentDirectory = null;
            DebugStream = null;
            VerboseStream = null;
            WarningStream = null;

            CloudBlobUtility = new CloudBlobUtility();
            ManagementClient = managementClient;
            StorageClient = storageManagementClient;
            ComputeClient = computeManagementClient;
        }
		public void Should_get_queue_OK()
		{
			var client = new ManagementClient (hostUrl, username, password, port, true);
			var queue = client.GetQueue ("queuespy.commands", new EasyNetQ.Management.Client.Model.Vhost { Name = "/" });
			Console.WriteLine ("Got queue: {0}", queue.Name);
		}