public static NamespaceManager GetNamespaceManagerWithCustomCredentials(NetworkCredential credential) { Uri httpsUri = ServiceBusHelper.GetLocalHttpsEndpoint(); TokenProvider tokenProvider = TokenProvider.CreateOAuthTokenProvider(new Uri[] { httpsUri }, credential); NamespaceManager nsManager = new NamespaceManager(httpsUri, tokenProvider); return nsManager; }
public void theres_a_namespace_manager_available() { var mf = TestConfigFactory.CreateMessagingFactory(); nm = TestConfigFactory.CreateNamespaceManager(mf); _formatter = new AzureServiceBusMessageNameFormatter(); }
static void Main(string[] args) { GetUserCredentials(); TokenProvider tokenProvider = null; Uri serviceUri = null; CreateTokenProviderAndServiceUri(out tokenProvider, out serviceUri); NamespaceManager namespaceManager = new NamespaceManager(serviceUri, tokenProvider); Console.WriteLine("Creating Topic 'IssueTrackingTopic'..."); if (namespaceManager.TopicExists("IssueTrackingTopic")) namespaceManager.DeleteTopic("IssueTrackingTopic"); MessagingFactory factory = null; TopicDescription myTopic = namespaceManager.CreateTopic(TopicName); // Criar duas Subscrições Console.WriteLine("Creating Subscriptions 'AuditSubscription' and 'AgentSubscription'..."); SubscriptionDescription myAuditSubscription = namespaceManager.CreateSubscription((myTopic.Path, "AuditSubscription"); SubscriptionDescription myAgentSubscription = namespaceManager.CreateSubscription(myTopic.Path, "AgentSubscription"); TopicClient myTopicClient = CreateTopicClient(serviceUri, tokenProvider, myTopic, out factory); List<BrokeredMessage> messageList = new List<BrokeredMessage>(); messageList.Add(CreateIssueMessage("1", "First message information")); messageList.Add(CreateIssueMessage("2", "Second message information")); messageList.Add(CreateIssueMessage("3", "Third message information")); Console.WriteLine("\nSending messages to topic..."); SendListOfMessages(messageList, myTopicClient); Console.WriteLine("\nFinished sending messages, press ENTER to clean up and exit."); myTopicClient.Close(); Console.ReadLine(); namespaceManager.DeleteTopic(TopicName); }
static void Main(string[] args) { try { // Connection String as can be found on the azure portal https://manage.windowsazure.com/microsoft.onmicrosoft.com#Workspaces/ServiceBusExtension/namespaces // // The needed Shared access policy is Manage, this can either be the RootManageSharedAccessKey or one create with Manage priviledges // "Endpoint = sb://NAMESPACE.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=THISISMYKEY"; var policyName = "RootManageSharedAccessKey"; var policySharedAccessKey = "THISISMYKEY"; var serviceBusNamespace = "NAMESPACE"; var credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(policyName, policySharedAccessKey); // access the namespace var serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty); var manager = new NamespaceManager(serviceBusUri, credentials); // Create the eventhub if needed var description = manager.CreateEventHubIfNotExists("MyHub"); Console.WriteLine("AT: " + description.CreatedAt + " EventHub:" + description.Path + " Partitions: " + description.PartitionIds); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.ReadLine(); }
public ServiceBusConnectionContext(ServiceBusScaleoutConfiguration configuration, NamespaceManager namespaceManager, IList<string> topicNames, TraceSource traceSource, Action<int, IEnumerable<BrokeredMessage>> handler, Action<int, Exception> errorHandler, Action<int> openStream) { if (topicNames == null) { throw new ArgumentNullException("topicNames"); } _namespaceManager = namespaceManager; _configuration = configuration; _subscriptions = new SubscriptionContext[topicNames.Count]; _topicClients = new TopicClient[topicNames.Count]; _trace = traceSource; TopicNames = topicNames; Handler = handler; ErrorHandler = errorHandler; OpenStream = openStream; TopicClientsLock = new object(); SubscriptionsLock = new object(); }
public void Initialize() { var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey); var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath); var namespaceManager = new NamespaceManager(serviceUri, tokenProvider); this.settings.Topics.AsParallel().ForAll(topic => { retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic)); topic.Subscriptions.AsParallel().ForAll(subscription => { retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription)); retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topic, subscription)); }); }); // Execute migration support actions only after all the previous ones have been completed. foreach (var topic in this.settings.Topics) { foreach (var action in topic.MigrationSupport) { retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, topic, action)); } } this.initialized = true; }
static void CreateTopicsAndSubscriptions(NamespaceManager namespaceManager) { Console.WriteLine("\nCreating a topic and 3 subscriptions."); // Create a topic and 3 subscriptions. TopicDescription topicDescription = namespaceManager.CreateTopic(Program.TopicName); Console.WriteLine("Topic created."); // Create a subscription for all messages sent to topic. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameAllMessages, new TrueFilter()); Console.WriteLine("Subscription {0} added with filter definition set to TrueFilter.", Program.SubsNameAllMessages); // Create a subscription that'll receive all orders which have color "blue" and quantity 10. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameColorBlueSize10Orders, new SqlFilter("color = 'blue' AND quantity = 10")); Console.WriteLine("Subscription {0} added with filter definition \"color = 'blue' AND quantity = 10\".", Program.SubsNameColorBlueSize10Orders); //var ruleDesc = new RuleDescription(); //ruleDesc.Filter = new CorrelationFilter("high"); //ruleDesc.Action = new SbAction(); // Create a subscription that'll receive all high priority orders. namespaceManager.CreateSubscription(topicDescription.Path, SubsNameHighPriorityOrders, new CorrelationFilter("high")); Console.WriteLine("Subscription {0} added with correlation filter definition \"high\".", Program.SubsNameHighPriorityOrders); Console.WriteLine("Create completed."); }
private async static Task QueueShouldExistAsync(NamespaceManager ns, QueueDescription queueDescription) { if (!await ns.QueueExistsAsync(queueDescription.Path)) { throw new MessagingEntityNotFoundException("Queue: " + queueDescription.Path); } }
public ServiceBusConnection(ServiceBusScaleoutConfiguration configuration, TraceSource traceSource) { _trace = traceSource; _connectionString = configuration.BuildConnectionString(); try { _namespaceManager = NamespaceManager.CreateFromConnectionString(_connectionString); _factory = MessagingFactory.CreateFromConnectionString(_connectionString); if (configuration.RetryPolicy != null) { _factory.RetryPolicy = configuration.RetryPolicy; } else { _factory.RetryPolicy = RetryExponential.Default; } } catch (ConfigurationErrorsException) { _trace.TraceError("The configured Service Bus connection string contains an invalid property. Check the exception details for more information."); throw; } _backoffTime = configuration.BackoffTime; _idleSubscriptionTimeout = configuration.IdleSubscriptionTimeout; _configuration = configuration; }
private async static Task SubscriptionShouldExistAsync(NamespaceManager ns, SubscriptionDescription subscriptionDescription) { if (!await ns.SubscriptionExistsAsync(subscriptionDescription.TopicPath, subscriptionDescription.Name)) { throw new MessagingEntityNotFoundException("Subscription: " + subscriptionDescription.TopicPath + "/" + subscriptionDescription.Name); } }
public EventHubViewModel(string eventHubName, NamespaceManager nsm) { _nsm = nsm; EventHubName = eventHubName; Partitions = new ObservableCollection<PartitionViewModel>(); ConsumerGroups = new ObservableCollection<string>(); }
private async static Task TopicShouldExistAsync(NamespaceManager ns, TopicDescription topicDescription) { if (!await ns.TopicExistsAsync(topicDescription.Path)) { throw new MessagingEntityNotFoundException("Topic: " + topicDescription.Path); } }
public async void Init(MessageReceived messageReceivedHandler) { this.random = new Random(); //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect; // Tcp mode does not work when I run in a VM (VirtualBox) and the host // is using a wireless connection. Hard coding to Http. ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http; string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); this.factory = MessagingFactory.CreateFromConnectionString(connectionString); this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists(topicName)) { namespaceManager.CreateTopic(topicName); } this.subscriptionName = Guid.NewGuid().ToString(); // Not needed really, it's a GUID... if (!namespaceManager.SubscriptionExists(topicName, subscriptionName)) { namespaceManager.CreateSubscription(topicName, subscriptionName); } this.topicClient = factory.CreateTopicClient(topicName); this.subClient = factory.CreateSubscriptionClient(topicName, subscriptionName); while (true) { await ReceiveMessageTaskAsync(messageReceivedHandler); } }
public static void Main(string[] args) { ServiceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"]; // Issuer key sasKeyValue = ConfigurationManager.AppSettings["SASKey"]; // Create management credentials TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue); NamespaceManager namespaceClient = new NamespaceManager( ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), credentials); QueueDescription myQueue; if (!namespaceClient.QueueExists(QUEUE)) { myQueue = namespaceClient.CreateQueue(QUEUE); } MessagingFactory factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), credentials); QueueClient myQueueClient = factory.CreateQueueClient(QUEUE); // Send message Poco poco = new Poco(); poco.Id = "001"; poco.content = "This is some content"; BrokeredMessage message = new BrokeredMessage(); message.Properties.Add("Id", poco.Id); message.Properties.Add("Content", poco.content); myQueueClient.Send(message); }
public static string GetOverrideBordersContent(NamespaceManager manager, string scope) { string temp = ""; switch (scope.ToLower()) { case "none": temp = ""; break; case "namespace": temp = ""; if (manager.GetTopicProperty(manager.DefinitionTopicName.LocalName, "OverrideBorders") != null) if (manager.GetTopicProperty(manager.DefinitionTopicName.LocalName, "OverrideBorders").LastValue != null) { temp = manager.GetTopicProperty(manager.DefinitionTopicName.LocalName, "OverrideBorders").LastValue; } break; case "federation": NamespaceManager mgr = DefaultNamespaceManager(manager.Federation); if (mgr.GetTopicProperty(mgr.DefinitionTopicName.LocalName, "OverrideBorders") != null) if (mgr.GetTopicProperty(mgr.DefinitionTopicName.LocalName, "OverrideBorders").LastValue != null) { temp = mgr.GetTopicProperty(mgr.DefinitionTopicName.LocalName, "OverrideBorders").LastValue; } break; default: temp = ""; break; } return temp; }
public override bool OnStart() { ServicePointManager.DefaultConnectionLimit = 12; var connectionString = CloudConfigurationManager.GetSetting("topicConnectionString"); var topicName = CloudConfigurationManager.GetSetting("topicName"); _nsMgr = NamespaceManager.CreateFromConnectionString(connectionString); if (!_nsMgr.TopicExists(topicName)) { _nsMgr.CreateTopic(topicName); } if (!_nsMgr.SubscriptionExists(topicName, "audit")) { _nsMgr.CreateSubscription(topicName, "audit"); } _client = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, "audit", ReceiveMode.ReceiveAndDelete); var result = base.OnStart(); Trace.TraceInformation("NTM.Auditing has been started"); return result; }
public ServiceBusArgumentsDisplayTestsFixture() : base(cleanStorageAccount: true) { _hostConfiguration = new JobHostConfiguration(StorageAccount.ConnectionString) { TypeLocator = new ExplicitTypeLocator( typeof(ServiceBusArgumentsDisplayFunctions), typeof(DoneNotificationFunction)) }; #if VNEXT_SDK ServiceBusConfiguration serviceBusConfig = new ServiceBusConfiguration(); serviceBusConfig.ConnectionString = ServiceBusAccount; _serviceBusConnectionString = serviceBusConfig.ConnectionString; _hostConfiguration.UseServiceBus(serviceBusConfig); #else _serviceBusConnectionString = ServiceBusAccount; _hostConfiguration.ServiceBusConnectionString = _serviceBusConnectionString; #endif _namespaceManager = NamespaceManager.CreateFromConnectionString(_serviceBusConnectionString); // ensure we're starting in a clean state CleanServiceBusQueues(); // now run the entire end to end scenario, causing all the job functions // to be invoked RunEndToEnd(); }
static void Main() { _servicesBusConnectionString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.ServiceBus); namespaceManager = NamespaceManager.CreateFromConnectionString(_servicesBusConnectionString); if (!namespaceManager.QueueExists(nameof(Step1))) { namespaceManager.CreateQueue(nameof(Step1)); } if (!namespaceManager.QueueExists(nameof(Step2))) { namespaceManager.CreateQueue(nameof(Step2)); } JobHostConfiguration config = new JobHostConfiguration(); config.UseServiceBus(); var host = new JobHost(config); CreateStartMessage(); host.RunAndBlock(); }
public async Task<EventHubDescription> CreateEventHubAsync() { string serviceBusNamespace = "iotmc-ns"; string serviceBusManageKey = "<< Add your SAS here >>"; string eventHubName = "IoTMC"; string eventHubSASKeyName = "Device01"; Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty); TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey); NamespaceManager nameSpaceManager = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider); string eventHubKey = SharedAccessAuthorizationRule.GenerateRandomKey(); EventHubDescription eventHubDescription = new EventHubDescription(eventHubName) { PartitionCount = 8, MessageRetentionInDays = 1 }; SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen }); eventHubDescription.Authorization.Add(eventHubSendRule); eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription); string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey; return eventHubDescription; }
public ReliableClientBase(string sbNamespace, TokenProvider tokenProvider, string path, RetryPolicy<ServiceBusTransientErrorDetectionStrategy> policy) { mRetryPolicy = policy; Uri address = ServiceBusEnvironment.CreateServiceUri("sb", sbNamespace, string.Empty); mNamespaceManager = new NamespaceManager(address, tokenProvider); mMessagingFactory = MessagingFactory.Create(address, tokenProvider); }
/// <summary> /// /// </summary> /// <param name="connectionString"></param> /// <param name="longPollingTimeout"></param> /// Turn it on if you know the limit will not be reached</param> public ServiceBusOperator(string connectionString, TimeSpan longPollingTimeout) { _longPollingTimeout = longPollingTimeout; _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); _clientProvider = new ClientProvider(connectionString, true); }
public HeaterCommunication() { var topicNameSend = "businessrulestofieldgateway"; _topicNameReceive = "fieldgatewaytobusinessrules"; _namespaceMgr = NamespaceManager.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString")); _factory = MessagingFactory.CreateFromConnectionString(CloudConfigurationManager.GetSetting("ServiceBusConnectionString")); _client = _factory.CreateTopicClient(topicNameSend); }
public static NamespaceManager GetNamespaceManagerWithOAuthToken(NetworkCredential credential) { Uri httpsUri = GetLocalHttpsEndpoint(); TokenProvider tokenProvider = CreateOAuthTokenProvider(credential); NamespaceManager nsManager = new NamespaceManager(httpsUri, tokenProvider); return nsManager; }
public ServiceBusQueueListenerFactory(ServiceBusAccount account, string queueName, ITriggeredFunctionExecutor executor, AccessRights accessRights) { _namespaceManager = account.NamespaceManager; _messagingFactory = account.MessagingFactory; _queueName = queueName; _executor = executor; _accessRights = accessRights; }
public static NamespaceManager GetNamespaceManager() { Uri httpsUri = GetLocalHttpsEndpoint(); TokenProvider tokenProvider = TokenProvider.CreateWindowsTokenProvider(new Uri[] { httpsUri }); NamespaceManager nsManager = new NamespaceManager(httpsUri, tokenProvider); return nsManager; }
public SubscriptionDisposer(string topic, string subscription, bool isTransient, NamespaceManager namespaceManager, RetryPolicy retryPolicy) { _topic = topic; _subscription = subscription; _isTransient = isTransient; _namespaceManager = namespaceManager; _retryPolicy = retryPolicy; }
public ServiceBusEndToEndTests() { _serviceBusConfig = new ServiceBusConfiguration(); _nameResolver = new RandomNameResolver(); _namespaceManager = NamespaceManager.CreateFromConnectionString(_serviceBusConfig.ConnectionString); _secondaryConnectionString = AmbientConnectionStringProvider.Instance.GetConnectionString("ServiceBusSecondary"); _secondaryNamespaceManager = NamespaceManager.CreateFromConnectionString(_secondaryConnectionString); }
public ServerQueueAgent(string entityName, string sbCs) { _entityName = entityName; _sbCs = sbCs; _msgFactory = MessagingFactory.CreateFromConnectionString(sbCs); _nsMgr = NamespaceManager.CreateFromConnectionString(sbCs); }
public SubscriptionClientFactory(string topic, string connectionString) { this.topic = topic; this.connectionString = connectionString; this.log = LogProvider.For<SubscriptionClientFactory>(); this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); }
public SBMessageCounter(string ns, string queue, string keyName, string key) { var sb = ServiceBusEnvironment.CreateServiceUri("sb", ns, String.Empty); TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key); NamespaceManager sbus = new NamespaceManager(sb, tokenProvider); var q = sbus.GetQueue(queue); MessageCount = q.MessageCount; }
static NamespaceManager CreateNamespaceManager() { return(NamespaceManager.CreateFromConnectionString(serviceBusConnectionString)); }
public static async Task <ColdStorageCoordinator> CreateAsync( string hostName, string eventHubName, string consumerGroupName, string eventHubConnectionString, string checkpointStorageAccount, int maxBatchSize, int prefetchCount, TimeSpan receiveTimeout, IReadOnlyList <string> blobWriterStorageAccounts, string containerName, int rollSizeMb, string blobPrefix, int warningLevel, int tripLevel, TimeSpan stallInterval, TimeSpan logCooldownInterval, IColdStorageInstrumentationPublisher instrumentationPublisher) { Logger.Info("Initializing event hub listener for {0} ({1})", eventHubName, consumerGroupName); var storageAccounts = blobWriterStorageAccounts .Select(CloudStorageAccount.Parse) .ToList(); Func <string, IBlobWriter> blobWriterFactory = partitionId => new RollingBlobWriter(new PartitionAndDateNamingStrategy(partitionId, blobPrefix), instrumentationPublisher, storageAccounts[Int32.Parse(partitionId) % storageAccounts.Count], containerName, rollSizeMb); var ns = NamespaceManager.CreateFromConnectionString(eventHubConnectionString); try { await ns.GetConsumerGroupAsync(eventHubName, consumerGroupName); } catch (Exception e) { Logger.Error(e, "Invalid consumer group name {0} in event hub {1}", consumerGroupName, eventHubName); throw; } Logger.Info("Found consumer group {1} for {0}", eventHubName, consumerGroupName); var eventHubId = ConfigurationHelper.GetEventHubName(ns.Address, eventHubName); var factory = new ColdStorageEventProcessorFactory( blobWriterFactory, instrumentationPublisher, CancellationToken.None, warningLevel, tripLevel, stallInterval, logCooldownInterval, eventHubId ); var options = new EventProcessorOptions() { MaxBatchSize = maxBatchSize, PrefetchCount = prefetchCount, ReceiveTimeOut = receiveTimeout, InvokeProcessorAfterReceiveTimeout = true }; options.ExceptionReceived += (s, e) => Logger.Error( e.Exception, "Error on message processing, action {0}", e.Action); var host = new EventProcessorHost( hostName, consumerGroupName: consumerGroupName, eventHubPath: eventHubName, eventHubConnectionString: eventHubConnectionString, storageConnectionString: checkpointStorageAccount); await host.RegisterEventProcessorFactoryAsync(factory, options); return(new ColdStorageCoordinator(host)); }
public DisposableTemprorarySubscription(NamespaceManager manager, SubscriptionDescription created) { this.manager = manager; this.created = created; }
public WindowsServiceBusMessageSender(string queueName, string connectionString) { _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); _messagingFactory = MessagingFactory.Create(_namespaceManager.Address, _namespaceManager.Settings.TokenProvider); _client = QueueClient.CreateFromConnectionString(connectionString, queueName); }
protected override bool InitializeBuildElementCollection(System.Reflection.PropertyInfo propertyInfo) { Type elementType = typeof(Filter); BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildElementArrayAttribute)); if (buildElementArrayAttribute == null || propertyInfo.PropertyType != typeof(FilterCollection)) { return(base.InitializeBuildElementCollection(propertyInfo)); } XmlNodeList collectionNodes = ElementXml.ChildNodes; // create new array of the required size - even if size is 0 ArrayList list = new ArrayList(collectionNodes.Count); foreach (XmlNode childNode in collectionNodes) { // skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // remove element from list of remaining items UnprocessedChildNodes.Remove(childNode.Name); // initialize child element (from XML or data type reference) Filter filter = TypeFactory.CreateFilter(childNode, Element); list.Add(filter); } MethodInfo addMethod = null; // get array of public instance methods MethodInfo[] addMethods = propertyInfo.PropertyType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // search for a method called 'Add' which accepts a parameter // to which the element type is assignable foreach (MethodInfo method in addMethods) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; if (parameter.ParameterType.IsAssignableFrom(elementType)) { addMethod = method; break; } } } if (addMethod == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1020"), elementType.FullName, propertyInfo.PropertyType.FullName, propertyInfo.Name, Name), Location); } // if value of property is null, create new instance of collection object collection = propertyInfo.GetValue(Element, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); if (collection == null) { if (!propertyInfo.CanWrite) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1093"), buildElementArrayAttribute.Name, Name), Location); } object instance = Activator.CreateInstance( propertyInfo.PropertyType, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); propertyInfo.SetValue(Element, instance, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } // add each element of the arraylist to collection instance foreach (object childElement in list) { addMethod.Invoke(collection, BindingFlags.Default, null, new object[] { childElement }, CultureInfo.InvariantCulture); } return(true); }
public static NamespaceManager GetNamespaceManager(string connectionString) { return(NamespaceManager.CreateFromConnectionString(connectionString)); }
public static NamespaceManager GetNamespaceManager() { return(NamespaceManager.CreateFromConnectionString(GetServiceBusConnectionString())); }
public AzureServiceBusMessageProducer(string connectionString) { _connectionString = connectionString; _namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); }
/// <summary> /// Receives a notification when a new inter-role communication event occurs. /// </summary> public override void OnNext(TestRunStartEvent msg) { var numInstances = RoleEnvironment.CurrentRoleInstance.Role.Instances.Count - 1; var topicBaseCommunicator = this.interRoleCommunicator as InterRoleCommunicationExtension; if (topicBaseCommunicator != null) { topicBaseCommunicator.Settings.EnableAsyncPublish = msg.EnableAsyncPublish; topicBaseCommunicator.Settings.EnableAsyncDispatch = msg.EnableAsyncDispatch; } if (msg.RequireTopicCleanup) { // Delete the IRC topic first so that instances will have enough time to recreate senders and receivers. var serviceBusSettings = ConfigurationManager.GetSection(ServiceBusConfigurationSettings.SectionName) as ServiceBusConfigurationSettings; var pubsubType = ConfigurationManager.AppSettings[CommonConsts.ConfigSettingPubSubType]; if (pubsubType.Equals(CommonConsts.ConfigSettingPubSubTypeValueTopic)) { var topicEndpoint = serviceBusSettings.Endpoints.Get(CommonConsts.TopicServiceBusEndpointName); var credentials = TokenProvider.CreateSharedSecretTokenProvider(topicEndpoint.IssuerName, topicEndpoint.IssuerSecret); var address = ServiceBusEnvironment.CreateServiceUri("sb", topicEndpoint.ServiceNamespace, String.Empty); var nsManager = new NamespaceManager(address, credentials); if (nsManager.GetTopics().Where(t => String.Compare(t.Path, topicEndpoint.TopicName, true) == 0).Count() > 0) { nsManager.DeleteTopic(topicEndpoint.TopicName); } } } if (msg.PurgeTraceLogTable) { // Purge WADLogsTable. PurgeTraceLogTable(); } // Tell ACK subscriber how many messages it should expect to receive and reset the ACK counter. this.ackSubscriber.SetExpectedAckCount(msg.MessageCount * numInstances); this.ackSubscriber.ResetAckCounter(); var testRun = new TestRunTableEntity() { TestRunID = msg.TestRunID, MessageCount = msg.MessageCount, MessageSize = msg.MessageSize, InstanceCount = numInstances, StartDateTime = DateTime.UtcNow, EndDateTime = new DateTime(1900, 1, 1) }; var testRunsTable = new TestRunEntityTableContext(this.tableClient.BaseUri.ToString(), this.tableClient.Credentials); testRunsTable.TableName = this.testRunsTableName; try { testRunsTable.AddTestRun(testRun); } catch (DataServiceRequestException ex) { if (ex.IsEntityAlreadyExists()) { testRunsTable.UpdateTestRun(testRun); } } using (TraceManager.WorkerRoleComponent.TraceScope("Publishing IRC events", msg.TestRunID, msg.MessageCount, msg.MessageSize)) { for (int i = 1; i <= msg.MessageCount; i++) { DemoPayload payload = new DemoPayload(msg.TestRunID, i, numInstances, DateTime.UtcNow); // Create a data portion of the payload equal to the message size specified in the test run settings. payload.Data = new byte[msg.MessageSize]; (new Random()).NextBytes(payload.Data); InterRoleCommunicationEvent ircEvent = new InterRoleCommunicationEvent(payload); // Update publish time so that it accurately reflects the current time. payload.PublishTickCount = HighResolutionTimer.CurrentTickCount; payload.PublishTime = DateTime.UtcNow; // Publish the IRC event. this.interRoleCommunicator.Publish(ircEvent); } } }
/// <summary> /// Checks if the public topic and subscription name exists as per <see cref="PublicTopicName"/> and <see cref="PublicTopicSubscriptionName"/>. /// </summary> /// <param name="namespaceManager">The <see cref="NamespaceManager"/>.</param> protected virtual void CheckPublicTopicExists(NamespaceManager namespaceManager) { CheckTopicExists(namespaceManager, PublicTopicName = ConfigurationManager.GetSetting(PublicTopicNameConfigurationKey) ?? DefaultPublicTopicName, PublicTopicSubscriptionName = ConfigurationManager.GetSetting(PublicTopicSubscriptionNameConfigurationKey) ?? DefaultPublicTopicSubscriptionName); }
static void Main(string[] args) { Console.Title = "Purchases Publisher"; Console.WriteLine("Verifying existence of Service Bus Topic and Subscriptions"); // Creating the topic if it does not exist already using the service bus connection string stored in the app.config file string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); // Making sure that the topic exists if (!namespaceManager.TopicExists("productsalestopic")) { namespaceManager.CreateTopic("productsalestopic"); } // Making sure that the subscriptions exists if (!namespaceManager.SubscriptionExists("productsalestopic", "AllPurchases")) { // Create a "Audit" subscription namespaceManager.CreateSubscription("productsalestopic", "AllPurchases"); } if (!namespaceManager.SubscriptionExists("productsalestopic", "ExpensivePurchases")) { // Create a "ExpensivePurchases" filtered subscription SqlFilter ExpensivePurchasesFilter = new SqlFilter("ProductPrice > 4000"); namespaceManager.CreateSubscription("productsalestopic", "ExpensivePurchases", ExpensivePurchasesFilter); } if (!namespaceManager.SubscriptionExists("productsalestopic", "CheapPurchases")) { // Create a "CheapPurchases" filtered subscription SqlFilter CheapPurchasesFilter = new SqlFilter("ProductPrice <= 4000"); namespaceManager.CreateSubscription("productsalestopic", "CheapPurchases", CheapPurchasesFilter); } Console.WriteLine("Press any key to start publishing messages."); Console.ReadKey(); Console.WriteLine("Sending four messages"); // Creating four messages for publishing - two with price below 4000$, and two with price above 4000$ var ShoesMessage = new BrokeredMessage(); ShoesMessage.Properties["ProductId"] = 1; ShoesMessage.Properties["ProductName"] = "Shoes"; ShoesMessage.Properties["ProductPrice"] = 2000; var PantsMessage = new BrokeredMessage(); PantsMessage.Properties["ProductId"] = 2; PantsMessage.Properties["ProductName"] = "Pants"; PantsMessage.Properties["ProductPrice"] = 5000; var ShirtMessage = new BrokeredMessage(); ShirtMessage.Properties["ProductId"] = 3; ShirtMessage.Properties["ProductName"] = "Shirt"; ShirtMessage.Properties["ProductPrice"] = 3000; var JacketMessage = new BrokeredMessage(); JacketMessage.Properties["ProductId"] = 4; JacketMessage.Properties["ProductName"] = "Jacket"; JacketMessage.Properties["ProductPrice"] = 6000; TopicClient topicClient = TopicClient.Create("productsalestopic"); // Sending the messages to service bus topicClient.Send(ShoesMessage); topicClient.Send(PantsMessage); topicClient.Send(ShirtMessage); topicClient.Send(JacketMessage); Console.WriteLine("Sending complete"); }
public void ListQueues(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject) { Utilities.ServiceUtilities serviceUtilities = new Utilities.ServiceUtilities(serviceBroker); serviceObject.Properties.InitResultTable(); NamespaceManager namespaceManager = null; System.Data.DataRow dr; try { namespaceManager = serviceUtilities.GetNamespaceManager(inputs.Where(p => p.Name.Equals("requesttimeout")).FirstOrDefault()); IEnumerable <QueueDescription> Qs = namespaceManager.GetQueues(); foreach (QueueDescription Queue in Qs) { dr = serviceBroker.ServicePackage.ResultTable.NewRow(); foreach (Property prop in returns) { switch (prop.Name) { case "defaultmessagetimetolive": dr[prop.Name] = Queue.DefaultMessageTimeToLive.TotalSeconds; break; case "duplicatedetectionhistorytimewindow": dr[prop.Name] = Queue.DuplicateDetectionHistoryTimeWindow.TotalSeconds; break; case "enablebatchedoperations": prop.Value = Queue.EnableBatchedOperations; break; case "enabledeadletteringonmessageexpiration": dr[prop.Name] = Queue.EnableDeadLetteringOnMessageExpiration; break; case "isreadonly": dr[prop.Name] = Queue.IsReadOnly; break; case "lockduration": dr[prop.Name] = Queue.LockDuration.TotalSeconds; break; case "maxdeliverycount": dr[prop.Name] = Queue.MaxDeliveryCount; break; case "maxsizeinmegabytes": dr[prop.Name] = Queue.MaxSizeInMegabytes; break; case "messagecount": dr[prop.Name] = Queue.MessageCount; break; case "queue": dr[prop.Name] = Queue.Path; break; case "requiresduplicatedetection": dr[prop.Name] = Queue.RequiresDuplicateDetection; break; case "requiressession": dr[prop.Name] = Queue.RequiresSession; break; case "sizeinbytes": dr[prop.Name] = Queue.SizeInBytes; break; } } dr["responsestatus"] = ResponseStatus.Success; dr["responsestatusdescription"] = "Queues listed"; serviceBroker.ServicePackage.ResultTable.Rows.Add(dr); } } catch (Exception ex) { dr = serviceBroker.ServicePackage.ResultTable.NewRow(); dr["responsestatus"] = ResponseStatus.Error; dr["responsestatusdescription"] = ex.Message; serviceBroker.ServicePackage.ResultTable.Rows.Add(dr); return; } finally { namespaceManager = null; } }
/// <summary> /// Calls <see cref="AzureServiceBus{TAuthenticationToken}.InstantiateReceiving()"/> /// then uses a <see cref="Task"/> to apply the <see cref="FilterKey"/> as a <see cref="RuleDescription"/> /// to the <see cref="SubscriptionClient"/> instances in <paramref name="serviceBusReceivers"/>. /// </summary> /// <param name="namespaceManager">The <see cref="NamespaceManager"/>.</param> /// <param name="serviceBusReceivers">The receivers collection to place <see cref="SubscriptionClient"/> instances into.</param> /// <param name="topicName">The topic name.</param> /// <param name="topicSubscriptionName">The topic subscription name.</param> protected override void InstantiateReceiving(NamespaceManager namespaceManager, IDictionary <int, SubscriptionClient> serviceBusReceivers, string topicName, string topicSubscriptionName) { base.InstantiateReceiving(namespaceManager, serviceBusReceivers, topicName, topicSubscriptionName); Task.Factory.StartNewSafely (() => { // Because refreshing the rule can take a while, we only want to do this when the value changes string filter; if (!ConfigurationManager.TryGetSetting(FilterKeyConfigurationKey, out filter)) { return; } if (FilterKey == filter) { return; } FilterKey = filter; // https://docs.microsoft.com/en-us/azure/application-insights/app-insights-analytics-reference#summarize-operator // http://www.summa.com/blog/business-blog/everything-you-need-to-know-about-azure-service-bus-brokered-messaging-part-2#rulesfiltersactions // https://github.com/Azure-Samples/azure-servicebus-messaging-samples/tree/master/TopicFilters SubscriptionClient client = serviceBusReceivers[0]; bool reAddRule = false; try { IEnumerable <RuleDescription> rules = namespaceManager.GetRules(client.TopicPath, client.Name).ToList(); RuleDescription ruleDescription = rules.SingleOrDefault(rule => rule.Name == "CqrsConfiguredFilter"); if (ruleDescription != null) { var sqlFilter = ruleDescription.Filter as SqlFilter; if (sqlFilter == null && !string.IsNullOrWhiteSpace(filter)) { reAddRule = true; } else if (sqlFilter != null && sqlFilter.SqlExpression != filter) { reAddRule = true; } if (sqlFilter != null && reAddRule) { client.RemoveRule("CqrsConfiguredFilter"); } } else if (!string.IsNullOrWhiteSpace(filter)) { reAddRule = true; } ruleDescription = rules.SingleOrDefault(rule => rule.Name == "$Default"); // If there is a default rule and we have a rule, it will cause issues if (!string.IsNullOrWhiteSpace(filter) && ruleDescription != null) { client.RemoveRule("$Default"); } // If we don't have a rule and there is no longer a default rule, it will cause issues else if (string.IsNullOrWhiteSpace(filter) && !rules.Any()) { ruleDescription = new RuleDescription ( "$Default", new SqlFilter("1=1") ); client.AddRule(ruleDescription); } } catch (MessagingEntityNotFoundException) { } if (!reAddRule) { return; } int loopCounter = 0; while (loopCounter < 10) { try { RuleDescription ruleDescription = new RuleDescription ( "CqrsConfiguredFilter", new SqlFilter(filter) ); client.AddRule(ruleDescription); break; } catch (MessagingEntityAlreadyExistsException exception) { loopCounter++; // Still waiting for the delete to complete Thread.Sleep(1000); if (loopCounter == 9) { Logger.LogError("Setting the filter failed as it already exists.", exception: exception); TelemetryHelper.TrackException(exception); } } catch (Exception exception) { Logger.LogError("Setting the filter failed.", exception: exception); TelemetryHelper.TrackException(exception); break; } } }); }
public static void CreateEventHubIfNotExists(string eventHubName, int numberOfPartitions, NamespaceManager manager) { try { // Create the Event Hub Trace.WriteLine("Creating Event Hub…"); EventHubDescription ehd = new EventHubDescription(eventHubName); ehd.PartitionCount = numberOfPartitions; manager.CreateEventHubIfNotExistsAsync(ehd).Wait(); } catch (AggregateException agexp) { Trace.WriteLine(agexp.Flatten()); } }
/// <summary> /// Creates and executes the embedded (child XML nodes) elements. /// </summary> /// <remarks> /// Skips any element defined by the host <see cref="Task" /> that has /// a <see cref="BuildElementAttribute" /> defined. /// </remarks> protected virtual void ExecuteChildTasks() { foreach (XmlNode childNode in XmlNode) { //we only care about xmlnodes (elements) that are of the right namespace. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // ignore any private xml elements (by def. this includes any property with a BuildElementAttribute (name). if (IsPrivateXmlElement(childNode)) { continue; } Task task = CreateChildTask(childNode); // for now, we should assume null tasks are because of incomplete metadata about the XML. if (task != null) { task.Parent = this; task.Execute(); } if (BreakTask.Break) { break; } } }
public override void Validate(object state) { base.Validate(state); //if (XPath.IsNull()) // throw new ChoRecordConfigurationException("XPath can't be null or whitespace."); if (XPath.IsNullOrWhiteSpace()) { if (!IsDynamicObject && (RecordType.IsGenericType && RecordType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))) { NodeName = NodeName.IsNullOrWhiteSpace() ? "KeyValuePair" : NodeName; RootName = RootName.IsNullOrWhiteSpace() ? "KeyValuePairs" : RootName; } else if (!IsDynamicObject && !typeof(IChoScalarObject).IsAssignableFrom(RecordType)) { NodeName = NodeName.IsNullOrWhiteSpace() ? RecordType.Name : NodeName; RootName = RootName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : RootName; } } else { RootName = RootName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").FirstOrDefault() : RootName; NodeName = NodeName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").Skip(1).FirstOrDefault() : NodeName; } string rootName = null; string nodeName = null; ChoXmlDocumentRootAttribute da = TypeDescriptor.GetAttributes(RecordType).OfType <ChoXmlDocumentRootAttribute>().FirstOrDefault(); if (da != null) { rootName = da.Name; } else { XmlRootAttribute ra = TypeDescriptor.GetAttributes(RecordType).OfType <XmlRootAttribute>().FirstOrDefault(); if (ra != null) { nodeName = ra.ElementName; } } RootName = RootName.IsNullOrWhiteSpace() && !rootName.IsNullOrWhiteSpace() ? rootName : RootName; NodeName = NodeName.IsNullOrWhiteSpace() && !nodeName.IsNullOrWhiteSpace() ? nodeName : NodeName; RootName = RootName.IsNullOrWhiteSpace() && !NodeName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : RootName; if (!RootName.IsNullOrWhiteSpace() && RootName.ToSingular() != RootName) { NodeName = NodeName.IsNullOrWhiteSpace() && !RootName.IsNullOrWhiteSpace() ? RootName.ToSingular() : NodeName; } if (RootName.IsNullOrWhiteSpace()) { RootName = "Root"; } if (NodeName.IsNullOrWhiteSpace()) { NodeName = "XElement"; } //Encode Root and node names RootName = System.Net.WebUtility.HtmlEncode(RootName); NodeName = System.Net.WebUtility.HtmlEncode(NodeName); string[] fieldNames = null; XElement xpr = null; if (state is Tuple <long, XElement> ) { xpr = ((Tuple <long, XElement>)state).Item2; } else { fieldNames = state as string[]; } if (AutoDiscoverColumns && XmlRecordFieldConfigurations.Count == 0) { if (RecordType != null && !IsDynamicObject && ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()).Any()) { DiscoverRecordFields(RecordType); } else if (xpr != null) { XmlRecordFieldConfigurations.AddRange(DiscoverRecordFieldsFromXElement(xpr)); } else if (!fieldNames.IsNullOrEmpty()) { foreach (string fn in fieldNames) { if (IgnoredFields.Contains(fn)) { continue; } if (fn.StartsWith("_")) { string fn1 = fn.Substring(1); var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}"); obj.FieldName = fn1; obj.IsXmlAttribute = true; XmlRecordFieldConfigurations.Add(obj); } else if (fn.EndsWith("_")) { string fn1 = fn.Substring(0, fn.Length - 1); var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}"); obj.FieldName = fn1; obj.IsXmlCDATA = true; XmlRecordFieldConfigurations.Add(obj); } else { var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn}"); XmlRecordFieldConfigurations.Add(obj); } } } } else { IsComplexXPathUsed = false; foreach (var fc in XmlRecordFieldConfigurations) { if (fc.IsArray == null) { fc.IsArray = typeof(ICollection).IsAssignableFrom(fc.FieldType); } if (fc.FieldName.IsNullOrWhiteSpace()) { fc.FieldName = fc.Name; } if (fc.XPath.IsNullOrWhiteSpace()) { fc.XPath = $"/{fc.FieldName}|/@{fc.FieldName}"; } else { if (fc.XPath == fc.FieldName || fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}" ) { } else { IsComplexXPathUsed = true; fc.UseCache = false; } } } } if (XmlRecordFieldConfigurations.Count <= 0) { throw new ChoRecordConfigurationException("No record fields specified."); } //Validate each record field foreach (var fieldConfig in XmlRecordFieldConfigurations) { fieldConfig.Validate(this); } //Check field position for duplicate string[] dupFields = XmlRecordFieldConfigurations.GroupBy(i => i.Name) .Where(g => g.Count() > 1) .Select(g => g.Key).ToArray(); if (dupFields.Length > 0) { throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields))); } PIDict = new Dictionary <string, System.Reflection.PropertyInfo>(StringComparer.InvariantCultureIgnoreCase); PDDict = new Dictionary <string, PropertyDescriptor>(StringComparer.InvariantCultureIgnoreCase); foreach (var fc in XmlRecordFieldConfigurations) { var pd1 = fc.DeclaringMember.IsNullOrWhiteSpace() ? ChoTypeDescriptor.GetProperty(RecordType, fc.Name) : ChoTypeDescriptor.GetProperty(RecordType, fc.DeclaringMember); if (pd1 != null) { fc.PropertyDescriptor = pd1; } if (fc.PropertyDescriptor == null) { fc.PropertyDescriptor = TypeDescriptor.GetProperties(RecordType).AsTypedEnumerable <PropertyDescriptor>().Where(pd => pd.Name == fc.Name).FirstOrDefault(); } if (fc.PropertyDescriptor == null) { continue; } PIDict.Add(fc.Name, fc.PropertyDescriptor.ComponentType.GetProperty(fc.PropertyDescriptor.Name)); PDDict.Add(fc.Name, fc.PropertyDescriptor); } RecordFieldConfigurationsDict = XmlRecordFieldConfigurations.OrderBy(c => c.IsXmlAttribute).Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name); if (XmlRecordFieldConfigurations.Where(e => e.IsNullable).Any() || NullValueHandling == ChoNullValueHandling.Default) { if (NamespaceManager != null) { if (!NamespaceManager.HasNamespace("xsi")) { NamespaceManager.AddNamespace("xsi", ChoXmlSettings.XmlSchemaInstanceNamespace); } if (!NamespaceManager.HasNamespace("xsd")) { NamespaceManager.AddNamespace("xsd", ChoXmlSettings.XmlSchemaNamespace); } } } LoadNCacheMembers(XmlRecordFieldConfigurations); }
public NamespaceManagerAdapterInternal(NamespaceManager manager) { this.manager = manager; }
static int Main2(string [] args) { bool show_help = false; bool zero_copy = false; string basedir = null; string tmpdir = null; string ns = null; string outfile = null; bool delete_temp = true, debug = false; bool verbose = false; bool unsafef = true; bool external = false; bool public_mode = true; bool nostdlib = false; bool? inline_selectors = null; List <string> sources; var resources = new List <string> (); var linkwith = new List <string> (); var references = new List <string> (); var libs = new List <string> (); var api_sources = new List <string> (); var core_sources = new List <string> (); var extra_sources = new List <string> (); var defines = new List <string> (); string generate_file_list = null; bool process_enums = false; // .NET treats ' as part of the command name when running an app so we must use " on Windows PlatformID pid = Environment.OSVersion.Platform; if (((int)pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX)) { shellQuoteChar = '"'; // Windows } else { shellQuoteChar = '\''; // !Windows } var os = new OptionSet() { { "h|?|help", "Displays the help", v => show_help = true }, { "a", "Include alpha bindings (Obsolete).", v => {}, true }, { "outdir=", "Sets the output directory for the temporary binding files", v => { basedir = v; } }, { "o|out=", "Sets the name of the output library", v => outfile = v }, { "tmpdir=", "Sets the working directory for temp files", v => { tmpdir = v; delete_temp = false; } }, { "debug", "Generates a debugging build of the binding", v => debug = true }, { "sourceonly=", "Only generates the source", v => generate_file_list = v }, { "ns=", "Sets the namespace for storing helper classes", v => ns = v }, { "unsafe", "Sets the unsafe flag for the build", v => unsafef = true }, { "core", "Use this to build product assemblies", v => BindingThirdParty = false }, { "r=", "Adds a reference", v => references.Add(v) }, { "lib=", "Adds the directory to the search path for the compiler", v => libs.Add(Quote(v)) }, { "compiler=", "Sets the compiler to use", v => compiler = v }, { "sdk=", "Sets the .NET SDK to use", v => net_sdk = v }, { "new-style", "Build for Unified (Obsolete).", v => { Console.WriteLine("The --new-style option is obsolete and ignored."); }, true }, { "d=", "Defines a symbol", v => defines.Add(v) }, { "api=", "Adds a API definition source file", v => api_sources.Add(Quote(v)) }, { "s=", "Adds a source file required to build the API", v => core_sources.Add(Quote(v)) }, { "v", "Sets verbose mode", v => verbose = true }, { "x=", "Adds the specified file to the build, used after the core files are compiled", v => extra_sources.Add(Quote(v)) }, { "e", "Generates smaller classes that can not be subclassed (previously called 'external mode')", v => external = true }, { "p", "Sets private mode", v => public_mode = false }, { "baselib=", "Sets the base library", v => baselibdll = v }, { "use-zero-copy", v => zero_copy = true }, { "nostdlib", "Does not reference mscorlib.dll library", l => nostdlib = true }, { "no-mono-path", "Launches compiler with empty MONO_PATH", l => { } }, { "native-exception-marshalling", "Enable the marshalling support for Objective-C exceptions", (v) => { /* no-op */ } }, { "inline-selectors:", "If Selector.GetHandle is inlined and does not need to be cached (enabled by default in Xamarin.iOS, disabled in Xamarin.Mac)", v => inline_selectors = string.Equals("true", v, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(v) }, { "process-enums", "Process enums as bindings, not external, types.", v => process_enums = true }, { "link-with=,", "Link with a native library {0:FILE} to the binding, embedded as a resource named {1:ID}", (path, id) => { if (path == null || path.Length == 0) { throw new Exception("-link-with=FILE,ID requires a filename."); } if (id == null || id.Length == 0) { id = Path.GetFileName(path); } if (linkwith.Contains(id)) { throw new Exception("-link-with=FILE,ID cannot assign the same resource id to multiple libraries."); } resources.Add(string.Format("-res:{0},{1}", path, id)); linkwith.Add(id); } }, { "unified-full-profile", "Launches compiler pointing to XM Full Profile", l => { /* no-op*/ }, true }, { "unified-mobile-profile", "Launches compiler pointing to XM Mobile Profile", l => { /* no-op*/ }, true }, { "target-framework=", "Specify target framework to use. Always required, and the currently supported values are: 'MonoTouch,v1.0', 'Xamarin.iOS,v1.0', 'Xamarin.TVOS,v1.0', 'Xamarin.WatchOS,v1.0', 'XamMac,v1.0', 'Xamarin.Mac,Version=v2.0,Profile=Mobile', 'Xamarin.Mac,Version=v4.5,Profile=Full' and 'Xamarin.Mac,Version=v4.5,Profile=System')", v => SetTargetFramework(v) }, }; try { sources = os.Parse(args); } catch (Exception e) { Console.Error.WriteLine("{0}: {1}", ToolName, e.Message); Console.Error.WriteLine("see {0} --help for more information", ToolName); return(1); } if (show_help) { ShowHelp(os); return(0); } if (!target_framework.HasValue) { throw ErrorHelper.CreateError(86, "A target framework (--target-framework) must be specified."); } switch (target_framework.Value.Identifier.ToLowerInvariant()) { case "monotouch": CurrentPlatform = PlatformName.iOS; Unified = false; if (string.IsNullOrEmpty(baselibdll)) { baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/2.1/monotouch.dll"); } Path.Combine(GetSDKRoot(), "bin/smcs"); break; case "xamarin.ios": CurrentPlatform = PlatformName.iOS; Unified = true; if (string.IsNullOrEmpty(baselibdll)) { baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.iOS/Xamarin.iOS.dll"); } break; case "xamarin.tvos": CurrentPlatform = PlatformName.TvOS; Unified = true; if (string.IsNullOrEmpty(baselibdll)) { baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.TVOS/Xamarin.TVOS.dll"); } break; case "xamarin.watchos": CurrentPlatform = PlatformName.WatchOS; Unified = true; if (string.IsNullOrEmpty(baselibdll)) { baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.WatchOS/Xamarin.WatchOS.dll"); } break; case "xammac": CurrentPlatform = PlatformName.MacOSX; Unified = false; if (string.IsNullOrEmpty(baselibdll)) { baselibdll = Path.Combine(GetSDKRoot(), "lib", "mono", "XamMac.dll"); } net_sdk = "4"; break; case "xamarin.mac": CurrentPlatform = PlatformName.MacOSX; Unified = true; skipSystemDrawing = target_framework == TargetFramework.Xamarin_Mac_4_5_Full; if (string.IsNullOrEmpty(baselibdll)) { if (target_framework == TargetFramework.Xamarin_Mac_2_0_Mobile) { baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "mobile", "Xamarin.Mac.dll"); } else { baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "full", "Xamarin.Mac.dll"); } } net_sdk = "4"; break; default: throw ErrorHelper.CreateError(1043, "Internal error: unknown target framework '{0}'.", target_framework); } if (string.IsNullOrEmpty(compiler)) { compiler = "/Library/Frameworks/Mono.framework/Commands/mcs"; } if (target_framework == TargetFramework.XamMac_1_0 && !references.Any((v) => Path.GetFileNameWithoutExtension(v) == "System.Drawing")) { // If we're targeting XM/Classic ensure we have a reference to System.Drawing.dll. references.Add("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.5/System.Drawing.dll"); } if (sources.Count > 0) { api_sources.Insert(0, Quote(sources [0])); for (int i = 1; i < sources.Count; i++) { core_sources.Insert(i - 1, Quote(sources [i])); } } if (api_sources.Count == 0) { Console.WriteLine("Error: no api file provided"); ShowHelp(os); return(1); } if (tmpdir == null) { tmpdir = GetWorkDir(); } string firstApiDefinitionName = Path.GetFileNameWithoutExtension(Unquote(api_sources [0])); firstApiDefinitionName = firstApiDefinitionName.Replace('-', '_'); // This is not exhaustive, but common. if (outfile == null) { outfile = firstApiDefinitionName + ".dll"; } string refs = string.Empty; foreach (var r in references) { if (refs != string.Empty) { refs += " "; } refs += "-r:" + Quote(r); } string paths = (libs.Count > 0 ? "-lib:" + String.Join(" -lib:", libs.ToArray()) : ""); try { var tmpass = Path.Combine(tmpdir, "temp.dll"); // -nowarn:436 is to avoid conflicts in definitions between core.dll and the sources // Keep source files at the end of the command line - csc will create TWO assemblies if any sources preceed the -out parameter var cargs = new StringBuilder(); if (CurrentPlatform == PlatformName.MacOSX) { if (!string.IsNullOrEmpty(net_sdk) && net_sdk != "mobile") { cargs.Append("-sdk:").Append(net_sdk).Append(' '); } } else { if (!string.IsNullOrEmpty(net_sdk)) { cargs.Append("-sdk:").Append(net_sdk).Append(' '); } } cargs.Append("-debug -unsafe -target:library -nowarn:436").Append(' '); cargs.Append("-out:").Append(Quote(tmpass)).Append(' '); cargs.Append("-r:").Append(Environment.GetCommandLineArgs()[0]).Append(' '); cargs.Append(refs).Append(' '); if (unsafef) { cargs.Append("-unsafe "); } cargs.Append("-r:").Append(Quote(baselibdll)).Append(' '); foreach (var def in defines) { cargs.Append("-define:").Append(def).Append(' '); } cargs.Append(paths).Append(' '); if (nostdlib) { cargs.Append("-nostdlib "); } foreach (var qs in api_sources) { cargs.Append(qs).Append(' '); } foreach (var cs in core_sources) { cargs.Append(cs).Append(' '); } if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll))) { cargs.Append("-lib:").Append(Path.GetDirectoryName(baselibdll)).Append(' '); } var si = new ProcessStartInfo(compiler, cargs.ToString()) { UseShellExecute = false, }; // HACK: We are calling btouch with forced 2.1 path but we need working mono for compiler si.EnvironmentVariables.Remove("MONO_PATH"); if (verbose) { Console.WriteLine("{0} {1}", si.FileName, si.Arguments); } var p = Process.Start(si); p.WaitForExit(); if (p.ExitCode != 0) { Console.WriteLine("{0}: API binding contains errors.", ToolName); return(1); } Assembly api; try { api = Assembly.LoadFrom(tmpass); } catch (Exception e) { if (verbose) { Console.WriteLine(e); } Console.Error.WriteLine("Error loading API definition from {0}", tmpass); return(1); } Assembly baselib; try { baselib = Assembly.LoadFrom(baselibdll); } catch (Exception e) { if (verbose) { Console.WriteLine(e); } Console.Error.WriteLine("Error loading base library {0}", baselibdll); return(1); } GC.KeepAlive(baselib); // Fixes a compiler warning (unused variable). TypeManager.Initialize(api); foreach (var linkWith in AttributeManager.GetCustomAttributes <LinkWithAttribute> (api)) { if (!linkwith.Contains(linkWith.LibraryName)) { Console.Error.WriteLine("Missing native library {0}, please use `--link-with' to specify the path to this library.", linkWith.LibraryName); return(1); } } foreach (var r in references) { if (File.Exists(r)) { try { Assembly.LoadFrom(r); } catch (Exception ex) { ErrorHelper.Show(new BindingException(1104, false, "Could not load the referenced library '{0}': {1}.", r, ex.Message)); } } } var types = new List <Type> (); var strong_dictionaries = new List <Type> (); foreach (var t in api.GetTypes()) { if ((process_enums && t.IsEnum) || AttributeManager.HasAttribute <BaseTypeAttribute> (t) || AttributeManager.HasAttribute <ProtocolAttribute> (t) || AttributeManager.HasAttribute <StaticAttribute> (t) || AttributeManager.HasAttribute <PartialAttribute> (t)) { types.Add(t); } if (AttributeManager.HasAttribute <StrongDictionaryAttribute> (t)) { strong_dictionaries.Add(t); } } var nsManager = new NamespaceManager( NamespacePlatformPrefix, ns == null ? firstApiDefinitionName : ns, skipSystemDrawing ); var g = new Generator(nsManager, public_mode, external, debug, types.ToArray(), strong_dictionaries.ToArray()) { BindThirdPartyLibrary = BindingThirdParty, BaseDir = basedir != null ? basedir : tmpdir, ZeroCopyStrings = zero_copy, InlineSelectors = inline_selectors ?? (Unified && CurrentPlatform != PlatformName.MacOSX), }; if (!Unified && !BindingThirdParty) { foreach (var mi in baselib.GetType(nsManager.CoreObjCRuntime + ".Messaging").GetMethods()) { if (mi.Name.IndexOf("_objc_msgSend", StringComparison.Ordinal) != -1) { g.RegisterMethodName(mi.Name); } } } g.Go(); if (generate_file_list != null) { using (var f = File.CreateText(generate_file_list)){ foreach (var x in g.GeneratedFiles.OrderBy((v) => v)) { f.WriteLine(x); } } return(0); } cargs.Clear(); if (unsafef) { cargs.Append("-unsafe "); } cargs.Append("-target:library "); cargs.Append("-out:").Append(Quote(outfile)).Append(' '); foreach (var def in defines) { cargs.Append("-define:").Append(def).Append(' '); } foreach (var gf in g.GeneratedFiles) { cargs.Append(gf).Append(' '); } foreach (var cs in core_sources) { cargs.Append(cs).Append(' '); } foreach (var es in extra_sources) { cargs.Append(es).Append(' '); } cargs.Append(refs).Append(' '); cargs.Append("-r:").Append(Quote(baselibdll)).Append(' '); foreach (var res in resources) { cargs.Append(res).Append(' '); } if (nostdlib) { cargs.Append("-nostdlib "); } if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll))) { cargs.Append("-lib:").Append(Path.GetDirectoryName(baselibdll)).Append(' '); } si = new ProcessStartInfo(compiler, cargs.ToString()) { UseShellExecute = false, }; // HACK: We are calling btouch with forced 2.1 path but we need working mono for compiler si.EnvironmentVariables.Remove("MONO_PATH"); if (verbose) { Console.WriteLine("{0} {1}", si.FileName, si.Arguments); } p = Process.Start(si); p.WaitForExit(); if (p.ExitCode != 0) { Console.WriteLine("{0}: API binding contains errors.", ToolName); return(1); } } finally { if (delete_temp) { Directory.Delete(tmpdir, true); } } return(0); }
protected virtual void CheckPrivateEventHubExists(NamespaceManager namespaceManager) { CheckHubExists(namespaceManager, PrivateEventHubName = ConfigurationManager.GetSetting(PrivateEventHubNameConfigurationKey) ?? DefaultPrivateEventHubName, PrivateEventHubConsumerGroupName = ConfigurationManager.GetSetting(PrivateEventHubConsumerGroupNameConfigurationKey) ?? DefaultPrivateEventHubConsumerGroupName); }
public SubscriptionService(string serviceBusConnectionString) { nameSpaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString); }
public Manager() { Client = NamespaceManager.Create(); Address = Client.Address; }
/// <summary> /// Generates an NDoc project and builds the documentation. /// </summary> protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Assemblies.BaseDirectory == null) { Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Summaries.BaseDirectory == null) { Summaries.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (ReferencePaths.BaseDirectory == null) { ReferencePaths.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // Make sure there is at least one included assembly. This can't // be done in the Initialize() method because the files might // not have been built at startup time. if (Assemblies.FileNames.Count == 0) { throw new BuildException(ResourceUtils.GetString("NA2020"), Location); } // create NDoc Project NDoc.Core.Project project = null; try { project = new NDoc.Core.Project(); } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2021"), Location, ex); } // set-up probe path, meaning list of directories where NDoc searches // for documenters // by default, NDoc scans the startup path of the app, so we do not // need to add this explicitly string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null) { // have NDoc also probe for documenters in the privatebinpath foreach (string relativePath in privateBinPath.Split(Path.PathSeparator)) { project.AppendProbePath(Path.Combine( AppDomain.CurrentDomain.BaseDirectory, relativePath)); } } // check for valid documenters (any other validation can be done by NDoc itself at project load time) foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; CheckAndGetDocumenter(project, documenterName); } // write documenter project settings to temp file string projectFileName = Path.GetTempFileName(); Log(Level.Verbose, ResourceUtils.GetString("String_WritingProjectSettings"), projectFileName); XmlTextWriter writer = new XmlTextWriter(projectFileName, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("project"); // write assemblies section writer.WriteStartElement("assemblies"); foreach (string assemblyPath in Assemblies.FileNames) { string docPath = Path.ChangeExtension(assemblyPath, ".xml"); writer.WriteStartElement("assembly"); writer.WriteAttributeString("location", assemblyPath); if (File.Exists(docPath)) { writer.WriteAttributeString("documentation", docPath); } writer.WriteEndElement(); } writer.WriteEndElement(); // write summaries section StringBuilder sb = new StringBuilder(); foreach (string summaryPath in Summaries.FileNames) { // write out the namespace summary nodes try { XmlTextReader tr = new XmlTextReader(summaryPath); tr.MoveToContent(); // skip XmlDeclaration and Processing Instructions sb.Append(tr.ReadOuterXml()); tr.Close(); } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2022"), summaryPath), Location, ex); } } writer.WriteRaw(sb.ToString()); // write out the documenters section writer.WriteStartElement("documenters"); foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } writer.WriteRaw(node.OuterXml); } writer.WriteEndElement(); // end project element writer.WriteEndElement(); writer.Close(); try { // read NDoc project file Log(Level.Verbose, ResourceUtils.GetString("String_NDocProjectFile"), Path.GetFullPath(projectFileName)); project.Read(projectFileName); // add additional directories to search for referenced assemblies if (ReferencePaths.DirectoryNames.Count > 0) { foreach (string directory in ReferencePaths.DirectoryNames) { project.ReferencePaths.Add(new ReferencePath(directory)); } } foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; IDocumenter documenter = CheckAndGetDocumenter(project, documenterName); // hook up events for feedback during the build documenter.DocBuildingStep += new DocBuildingEventHandler(OnDocBuildingStep); documenter.DocBuildingProgress += new DocBuildingEventHandler(OnDocBuildingProgress); // build documentation documenter.Build(project); } } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2023"), Location, ex); } }
public void TopicCleanUp() { var namespaceManager = new NamespaceManagerAdapter(NamespaceManager.CreateFromConnectionString(AzureServiceBusConnectionString.Value)); namespaceManager.DeleteTopic(topicPath).Wait(); }
static void Main(string[] args) { GetUserCredentials(); MessagingFactory factory = null; try { //***************************************************************************************************** // Management Operations //***************************************************************************************************** NamespaceManager namespaceClient = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString); Console.WriteLine("\nCreating Queue '{0}'...", QueueName); // Delete if exists if (namespaceClient.QueueExists(AsyncSender.QueueName)) { namespaceClient.DeleteQueue(AsyncSender.QueueName); } namespaceClient.CreateQueue(QueueName); //***************************************************************************************************** // Runtime Operations //***************************************************************************************************** factory = MessagingFactory.CreateFromConnectionString(ServiceBusConnectionString); QueueClient myQueueClient = factory.CreateQueueClient(AsyncSender.QueueName); //***************************************************************************************************** // Sending messages to a Queue //***************************************************************************************************** List <BrokeredMessage> messageList = new List <BrokeredMessage>(); messageList.Add(CreateIssueMessage("1", "First Package")); messageList.Add(CreateIssueMessage("2", "Second Package")); messageList.Add(CreateIssueMessage("3", "Third Package")); Console.WriteLine("\nSending messages to Queue..."); foreach (BrokeredMessage message in messageList) { // Initiate the asynchronous send myQueueClient.BeginSend(message, OnSendComplete, new Tuple <QueueClient, string>(myQueueClient, message.MessageId)); Console.WriteLine(string.Format("Asynchronous Message Send Begin: Id = {0}, Body = {1}", message.MessageId, message.GetBody <string>())); } Console.WriteLine("\nAfter all messages are sent, press ENTER to clean up and exit.\n"); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("Unexpected exception {0}", e.ToString()); throw; } finally { // Closing factory close all entities created from the factory. if (factory != null) { factory.Close(); } } }
public async Task <bool> SubscriptionExistsAsync(string connectionString, string topic, string subscription) { NamespaceManager namespaceManager = ServiceBusConnectionsFactory.GetNamespaceManager(connectionString); return(await namespaceManager.SubscriptionExistsAsync(topic, subscription)); }
public async Task <SubscriptionDescription> CreateSubscription(string connectionString, string topic, string subscription) { NamespaceManager namespaceManager = ServiceBusConnectionsFactory.GetNamespaceManager(connectionString); return(await namespaceManager.CreateSubscriptionAsync(topic, subscription)); }
public void CreateQueues(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject) { Utilities.ServiceUtilities serviceUtilities = new Utilities.ServiceUtilities(serviceBroker); serviceObject.Properties.InitResultTable(); NamespaceManager namespaceManager = null; QueueDescription ReturnQueue = null; try { string queuepath = string.Empty; if (inputs.Length == 0) { queuepath = serviceObject.MetaData.DisplayName; } else { queuepath = inputs.Where(p => p.Name.Equals("queue")).First().Value.ToString(); } namespaceManager = serviceUtilities.GetNamespaceManager(inputs.Where(p => p.Name.Equals("requesttimeout")).FirstOrDefault()); if (serviceObject.Methods[0].Name.Equals("createqueuefulldetails")) { QueueDescription Queue = new QueueDescription(queuepath); foreach (Property prop in inputs) { if (prop.Value != null) { switch (prop.Name) { case "queue": Queue.Path = queuepath; break; case "defaultmessagetimetolive": Queue.DefaultMessageTimeToLive = new TimeSpan(long.Parse(prop.Value.ToString()) * TimeSpan.TicksPerSecond); break; case "duplicatedetectionhistorytimewindow": Queue.DuplicateDetectionHistoryTimeWindow = new TimeSpan(long.Parse(prop.Value.ToString()) * TimeSpan.TicksPerSecond); break; case "lockduration": Queue.LockDuration = new TimeSpan(long.Parse(prop.Value.ToString()) * TimeSpan.TicksPerSecond); break; case "maxsizeinmegabytes": Queue.MaxSizeInMegabytes = long.Parse(prop.Value.ToString()); break; case "enabledeadletteringonmessageexpiration": Queue.EnableDeadLetteringOnMessageExpiration = bool.Parse(prop.Value.ToString()); break; case "requiresduplicatedetection": Queue.RequiresDuplicateDetection = bool.Parse(prop.Value.ToString()); break; case "requiressession": Queue.RequiresSession = bool.Parse(prop.Value.ToString()); break; } } } ReturnQueue = namespaceManager.CreateQueue(Queue); } else { // create with defaults ReturnQueue = namespaceManager.CreateQueue(queuepath); } foreach (Property prop in returns) { switch (prop.Name) { case "defaultmessagetimetolive": prop.Value = ReturnQueue.DefaultMessageTimeToLive.TotalSeconds; break; case "duplicatedetectionhistorytimewindow": prop.Value = ReturnQueue.DuplicateDetectionHistoryTimeWindow.TotalSeconds; break; case "enablebatchedoperations": prop.Value = ReturnQueue.EnableBatchedOperations; break; case "enabledeadletteringonmessageexpiration": prop.Value = ReturnQueue.EnableDeadLetteringOnMessageExpiration; break; case "isreadonly": prop.Value = ReturnQueue.IsReadOnly; break; case "lockduration": prop.Value = ReturnQueue.LockDuration.TotalSeconds; break; case "maxdeliverycount": prop.Value = ReturnQueue.MaxDeliveryCount; break; case "maxsizeinmegabytes": prop.Value = ReturnQueue.MaxSizeInMegabytes; break; case "messagecount": prop.Value = ReturnQueue.MessageCount; break; case "queue": prop.Value = ReturnQueue.Path; break; case "requiresduplicatedetection": prop.Value = ReturnQueue.RequiresDuplicateDetection; break; case "requiressession": prop.Value = ReturnQueue.RequiresSession; break; case "sizeinbytes": prop.Value = ReturnQueue.SizeInBytes; break; } } returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Success; returns.Where(p => p.Name.Equals("responsestatusdescription")).First().Value = "Queue created"; } catch (Exception ex) { returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Error; returns.Where(p => p.Name.Equals("responsestatusdescription")).First().Value = ex.Message; } finally { namespaceManager = null; } serviceObject.Properties.BindPropertiesToResultTable(); }
public async Task <bool> TopicExistsAsync(string connectionString, string topic) { NamespaceManager namespaceManager = ServiceBusConnectionsFactory.GetNamespaceManager(connectionString); return(await namespaceManager.TopicExistsAsync(topic)); }
public async Task Should_be_configured_and_working() { var settings = new TestAzureServiceBusAccountSettings(); var provider = new SharedAccessKeyTokenProvider(settings); var tokenProvider = provider.GetTokenProvider(); var namespaceSettings = new NamespaceManagerSettings { TokenProvider = tokenProvider }; var serviceUri = AzureServiceBusEndpointUriCreator.Create( Configuration.ServiceNamespace, "MassTransit.Azure.ServiceBus.Core.Tests" ); var namespaceManager = new NamespaceManager(serviceUri, namespaceSettings); await CreateQueue(namespaceManager, serviceUri, "TestClient"); await CreateHostQueue(tokenProvider); var mfs = new MessagingFactorySettings { TokenProvider = tokenProvider, OperationTimeout = TimeSpan.FromSeconds(30), TransportType = TransportType.Amqp }; var factory = MessagingFactory.Create(serviceUri, mfs); var receiver = factory.CreateQueueClient("Control"); receiver.PrefetchCount = 100; var done = TaskUtil.GetTask <bool>(); var count = 0; const int limit = 1000; receiver.RegisterMessageHandler(async(message, cancellationToken) => { await receiver.CompleteAsync(message.SystemProperties.LockToken); var received = Interlocked.Increment(ref count); if (received == limit) { done.TrySetResult(true); } }, new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false, MaxConcurrentCalls = 100, MaxAutoRenewDuration = TimeSpan.FromSeconds(60) }); var client = factory.CreateMessageSender("Control"); var stopwatch = Stopwatch.StartNew(); var tasks = new Task[limit]; for (var i = 0; i < limit; i++) { tasks[i] = SendAMessage(client); } await done.Task; stopwatch.Stop(); await Task.WhenAll(tasks); await receiver.CloseAsync(); Console.WriteLine("Performance: {0:F2}/s", limit * 1000 / stopwatch.ElapsedMilliseconds); }
public ServiceBusEndpoint(IServiceBusConfiguration configuration) { _factory = MessagingFactory.CreateFromConnectionString(configuration.ConnectionString); _namespaceManager = NamespaceManager.CreateFromConnectionString(configuration.ConnectionString); }