Exemplo n.º 1
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            ParameterInfo       parameter           = context.Parameter;
            ServiceBusAttribute serviceBusAttribute = parameter.GetCustomAttribute <ServiceBusAttribute>(inherit: false);

            if (serviceBusAttribute == null)
            {
                return(Task.FromResult <IBinding>(null));
            }

            string queueOrTopicName      = Resolve(serviceBusAttribute.QueueOrTopicName);
            IBindableServiceBusPath path = BindableServiceBusPath.Create(queueOrTopicName);

            path.ValidateContractCompatibility(context.BindingDataContract);

            IArgumentBinding <ServiceBusEntity> argumentBinding = _innerProvider.TryCreate(parameter);

            if (argumentBinding == null)
            {
                throw new InvalidOperationException("Can't bind ServiceBus to type '" + parameter.ParameterType + "'.");
            }

            string            connectionString = _accountProvider.ConnectionString;
            ServiceBusAccount account          = ServiceBusAccount.CreateFromConnectionString(connectionString);

            IBinding binding = new ServiceBusBinding(parameter.Name, argumentBinding, account, path);

            return(Task.FromResult(binding));
        }
        public override async Task BindAsync(BindingContext context)
        {
            string boundQueueName = QueueOrTopicName;

            if (context.BindingData != null)
            {
                boundQueueName = _queueOrTopicNameBindingTemplate.Bind(context.BindingData);
            }

            boundQueueName = Resolve(boundQueueName);

            var attribute = new ServiceBusAttribute(boundQueueName);

            Attribute[] additionalAttributes = null;
            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                additionalAttributes = new Attribute[]
                {
                    new ServiceBusAccountAttribute(Metadata.Connection)
                };
            }
            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute, additionalAttributes);

            await BindAsyncCollectorAsync <string>(context.Value, context.Binder, runtimeContext);
        }
Exemplo n.º 3
0
        public Task <IBinding> TryCreateAsync(BindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo       parameter = context.Parameter;
            ServiceBusAttribute attribute = parameter.GetCustomAttribute <ServiceBusAttribute>(inherit: false);

            if (attribute == null)
            {
                return(Task.FromResult <IBinding>(null));
            }

            string queueOrTopicName      = Resolve(attribute.QueueOrTopicName);
            IBindableServiceBusPath path = BindableServiceBusPath.Create(queueOrTopicName);

            ValidateContractCompatibility(path, context.BindingDataContract);

            IArgumentBinding <ServiceBusEntity> argumentBinding = InnerProvider.TryCreate(parameter);

            if (argumentBinding == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can't bind ServiceBus to type '{0}'.", parameter.ParameterType));
            }

            ServiceBusAccount account = ServiceBusAccount.CreateFromConnectionString(_config.ConnectionString);

            IBinding binding = new ServiceBusBinding(parameter.Name, argumentBinding, account, path, attribute.Access);

            return(Task.FromResult(binding));
        }
Exemplo n.º 4
0
        public void Constructor_AccessSpecified_SetsExpectedValues()
        {
            ServiceBusAttribute attribute = new ServiceBusAttribute("testqueue", AccessRights.Listen);

            Assert.Equal("testqueue", attribute.QueueOrTopicName);
            Assert.Equal(AccessRights.Listen, attribute.Access);
        }
Exemplo n.º 5
0
 public StringToServiceBusEntityConverter(ServiceBusAttribute attribute, IBindableServiceBusPath defaultPath, MessagingProvider messagingProvider, ServiceBusClientFactory clientFactory)
 {
     _attribute         = attribute;
     _defaultPath       = defaultPath;
     _entityType        = _attribute.EntityType;
     _messagingProvider = messagingProvider;
     _clientFactory     = clientFactory;
 }
Exemplo n.º 6
0
        private static async Task <HttpResponseMessage> Run(string type, HttpRequestMessage req, TraceWriter log, IBinder binder)
        {
            try
            {
                log.Info($"{type} WebHook Received");

                var queryParams = req.GetQueryNameValuePairs().ToList();
                var tenant      = queryParams.FirstOrDefault(x => string.Equals(x.Key, "tenant", StringComparison.OrdinalIgnoreCase)).Value;

                if (string.IsNullOrWhiteSpace(tenant))
                {
                    log.Error($"{type} - Missing tenant parameter");
                    return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide tenant parameter"));
                }

                var validTenants = Environment.GetEnvironmentVariable("ValidTenants")?.Split(';');

                if (validTenants == null || !validTenants.Any(x => string.Equals(x, tenant, StringComparison.InvariantCultureIgnoreCase)))
                {
                    log.Error($"{type} - Tenant {tenant} is not allowed");
                    return(req.CreateErrorResponse(HttpStatusCode.Forbidden, "Please provide valid tenant parameter"));
                }

                var subType = queryParams.FirstOrDefault(x => string.Equals(x.Key, "subType", StringComparison.OrdinalIgnoreCase)).Value;

                if (string.IsNullOrWhiteSpace(subType))
                {
                    log.Error($"{type} - Missing subType parameter");
                    return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide subType parameter"));
                }

                log.Info($"{type} WebHook (tenant: {tenant} | subType: {subType})");

                var jsonData = await req.Content.ReadAsStringAsync();

                var hookInformation = new HookInformation {
                    Type = type, SubType = subType, JsonData = jsonData, RequestHeaders = req.Headers.ToList()
                };

                var serviceBusQueueAttribute = new ServiceBusAttribute($"hooks_{tenant}", AccessRights.Manage)
                {
                    Connection = "AzureServiceBus"
                };

                var queueMessageJson = JsonConvert.SerializeObject(hookInformation);
                var outputMessages   = await binder.BindAsync <IAsyncCollector <string> >(serviceBusQueueAttribute);

                await outputMessages.AddAsync(queueMessageJson);

                return(req.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                log.Error($"Error Processing {type} Hook", e);
                return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
Exemplo n.º 7
0
        public void ServiceBusShouldHaveStringEnumForAccessRights()
        {
            var attribute = new ServiceBusAttribute("queue1", AccessRights.Manage);

            var jObject = attribute.ToJObject();

            jObject.Should().HaveElement("accessRights");
            jObject["accessRights"].Should().Be("manage");
        }
Exemplo n.º 8
0
        public void ServiceBusShouldHaveCorrectQueueName()
        {
            var attribute = new ServiceBusAttribute("queue1")
            {
                EntityType = EntityType.Queue
            };

            var jObject = attribute.ToJObject();

            jObject.Should().HaveElement("queueName");
            jObject["queueName"].Should().Be("queue1");
        }
 public ServiceBusBinding(
     string parameterName,
     IArgumentBinding <ServiceBusEntity> argumentBinding,
     IBindableServiceBusPath path,
     ServiceBusAttribute attribute,
     MessagingProvider messagingProvider,
     ServiceBusClientFactory clientFactory)
 {
     _parameterName     = parameterName;
     _argumentBinding   = argumentBinding;
     _path              = path;
     _messagingProvider = messagingProvider;
     _clientFactory     = clientFactory;
     _attribute         = attribute;
     _converter         = new OutputConverter <string>(new StringToServiceBusEntityConverter(_attribute, _path, _messagingProvider, _clientFactory));
 }
Exemplo n.º 10
0
            public static void ServiceBusBinderTest(
                string message,
                int numMessages,
                Binder binder)
            {
                var attribute = new ServiceBusAttribute(_firstQueueScope.QueueName)
                {
                    EntityType = ServiceBusEntityType.Queue
                };

                var collector = binder.Bind <ICollector <string> >(attribute);

                for (int i = 0; i < numMessages; i++)
                {
                    collector.Add(message + i);
                }
            }
Exemplo n.º 11
0
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string queueName        = Context.GetMetadataValue <string>("queueName");
                string topicName        = Context.GetMetadataValue <string>("topicName");
                string subscriptionName = Context.GetMetadataValue <string>("subscriptionName");
                var    accessRights     = Context.GetMetadataEnumValue <Microsoft.ServiceBus.Messaging.AccessRights>("accessRights");

                Attribute attribute = null;

                if (Context.IsTrigger)
                {
                    if (!string.IsNullOrEmpty(topicName) && !string.IsNullOrEmpty(subscriptionName))
                    {
                        attribute = new ServiceBusTriggerAttribute(topicName, subscriptionName, accessRights);
                    }
                    else if (!string.IsNullOrEmpty(queueName))
                    {
                        attribute = new ServiceBusTriggerAttribute(queueName, accessRights);
                    }
                }
                else
                {
                    attribute = new ServiceBusAttribute(queueName ?? topicName, accessRights)
                    {
                        EntityType = string.IsNullOrEmpty(topicName) ? EntityType.Queue : EntityType.Topic
                    };
                }

                if (attribute == null)
                {
                    throw new InvalidOperationException("Invalid ServiceBus trigger configuration.");
                }
                attributes.Add(attribute);

                var    connectionProvider = (IConnectionProvider)attribute;
                string connection         = Context.GetMetadataValue <string>("connection");

                if (!string.IsNullOrEmpty(connection))
                {
                    connectionProvider.Connection = connection;
                }

                return(attributes);
            }
Exemplo n.º 12
0
        public async Task <ISendTransport> GetSendTransport(Uri address)
        {
            var queueOrTopicName = address.AbsolutePath.Trim('/');

            var serviceBusQueue = new ServiceBusAttribute(queueOrTopicName, EntityType.Queue);

            IAsyncCollector <Message> collector = await _binder.BindAsync <IAsyncCollector <Message> >(serviceBusQueue, _cancellationToken).ConfigureAwait(false);

            LogContext.Debug?.Log("Creating Send Transport: {Queue}", queueOrTopicName);

            var sendEndpointContext = new CollectorMessageSendEndpointContext(queueOrTopicName, collector, _cancellationToken);

            var source = new CollectorSendEndpointContextSupervisor(sendEndpointContext);

            var transportContext = new HostServiceBusSendTransportContext(address, source, LogContext.Current.CreateLogContext(LogCategoryName.Transport.Send));

            return(new ServiceBusSendTransport(transportContext));
        }
Exemplo n.º 13
0
            public static async Task ServiceBusBinderTest(
                string message,
                int numMessages,
                Binder binder)
            {
                var attribute = new ServiceBusAttribute(BinderQueueName)
                {
                    EntityType = EntityType.Queue
                };
                var collector = await binder.BindAsync <IAsyncCollector <string> >(attribute);

                for (int i = 0; i < numMessages; i++)
                {
                    await collector.AddAsync(message + i);
                }

                await collector.FlushAsync();
            }
Exemplo n.º 14
0
        public async Task <ISendTransport> GetSendTransport(Uri address)
        {
            var queueOrTopicName = address.AbsolutePath.Trim('/');

            var serviceBusQueue = new ServiceBusAttribute(queueOrTopicName, EntityType.Queue);

            IAsyncCollector <Message> collector = await _binder.BindAsync <IAsyncCollector <Message> >(serviceBusQueue, _cancellationToken).ConfigureAwait(false);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Creating Send Transport: {0}", queueOrTopicName);
            }

            var sendEndpointContext = new CollectorMessageSendEndpointContext(queueOrTopicName, _log, collector, _cancellationToken);

            var source = new CollectorSendEndpointContextSource(sendEndpointContext);

            return(new ServiceBusSendTransport(source, address));
        }
Exemplo n.º 15
0
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            //[ServiceBus("emails", AccessRights.Manage, Connection = "ServiceBusConnection")] IAsyncCollector<string> collector,
            TraceWriter log, IBinder binder)
        {
            log.Info("C# HTTP trigger function processed a request.");
            var qs = req.GetQueryNameValuePairs();
            var valValue = qs.FirstOrDefault(x => x.Key.Equals(validationKey, StringComparison.CurrentCultureIgnoreCase));
            if (!string.IsNullOrEmpty(valValue.Value))
                return req.CreateResponse(HttpStatusCode.OK, valValue.Value);
            else
            {
                var serviceBusQueueAttribute = new ServiceBusAttribute("emails", AccessRights.Manage)
                {
                    Connection = "ServiceBusConnection"
                };
                var outputMessages = await binder.BindAsync<IAsyncCollector<string>>(serviceBusQueueAttribute);


                var body = await req.Content.ReadAsStringAsync();
                await outputMessages.AddAsync(body);
                return req.CreateResponse(HttpStatusCode.Accepted);
            }
        }
        async Task <ISendTransport> GetSendTransport(Uri address)
        {
            var queueOrTopicName = address.AbsolutePath.Trim('/');

            var serviceBusTopic = new ServiceBusAttribute(queueOrTopicName, AccessRights.Manage);

            serviceBusTopic.EntityType = EntityType.Topic;

            IAsyncCollector <BrokeredMessage> collector = await _binder.BindAsync <IAsyncCollector <BrokeredMessage> >(serviceBusTopic, _cancellationToken).ConfigureAwait(false);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Creating Publish Transport: {0}", queueOrTopicName);
            }

            var client = new CollectorSendEndpointContext(queueOrTopicName, _log, collector, _cancellationToken);

            var source = new CollectorSendEndpointContextSource(client);

            var transport = new ServiceBusSendTransport(source, address);

            return(transport);
        }
        public override async Task BindAsync(BindingContext context)
        {
            string boundQueueName = QueueOrTopicName;
            if (context.BindingData != null)
            {
                boundQueueName = _queueOrTopicNameBindingTemplate.Bind(context.BindingData);
            }

            boundQueueName = Resolve(boundQueueName);

            var attribute = new ServiceBusAttribute(boundQueueName);
            Attribute[] additionalAttributes = null;
            if (!string.IsNullOrEmpty(Metadata.Connection))
            {
                additionalAttributes = new Attribute[]
                {
                    new ServiceBusAccountAttribute(Metadata.Connection)
                };
            }
            RuntimeBindingContext runtimeContext = new RuntimeBindingContext(attribute, additionalAttributes);

            await BindAsyncCollectorAsync<string>(context.Value, context.Binder, runtimeContext);
        }
Exemplo n.º 18
0
        public static async Task <ActivityResponse> QueryOutputToServiceBusActivity(
            [ActivityTrigger] DurableActivityContext context,
            Binder outputBinder,
            ILogger log)
        {
            ActivityResponse ret = new ActivityResponse()
            {
                FunctionName = "QueryOutputToServiceBusActivity"
            };

            #region Logging
            if (null != log)
            {
                log.LogDebug($"Output  in {ret.FunctionName} ");
            }
            #endregion

            // Read the results
            QueryOutputRecord <object> results = context.GetInput <QueryOutputRecord <object> >();
            if (null != results)
            {
                var queueAttribute = new ServiceBusAttribute(results.Target);

                var payloadAsJSON = JsonConvert.SerializeObject(results.Results);

                using (var writer = outputBinder.Bind <TextWriter>(queueAttribute))
                {
                    await writer.WriteAsync(payloadAsJSON);
                }
            }
            else
            {
                ret.Message = $"Unable to get query output record to send to Service Bus";
            }

            return(ret);
        }
Exemplo n.º 19
0
 public ServiceBusBinding(string parameterName, IArgumentBinding <ServiceBusEntity> argumentBinding, ServiceBusAccount account, IBindableServiceBusPath path, ServiceBusAttribute attr, MessagingProvider messagingProvider)
 {
     _parameterName     = parameterName;
     _argumentBinding   = argumentBinding;
     _account           = account;
     _path              = path;
     _entityType        = attr.EntityType;
     _messagingProvider = messagingProvider;
     _converter         = new OutputConverter <string>(new StringToServiceBusEntityConverter(account, _path, _entityType, _messagingProvider));
 }
 public void Constructor_AccessSpecified_SetsExpectedValues()
 {
     ServiceBusAttribute attribute = new ServiceBusAttribute("testqueue", AccessRights.Listen);
     Assert.Equal("testqueue", attribute.QueueOrTopicName);
     Assert.Equal(AccessRights.Listen, attribute.Access);
 }
        public void Constructor_Success()
        {
            ServiceBusAttribute attribute = new ServiceBusAttribute("testqueue");

            Assert.AreEqual("testqueue", attribute.QueueOrTopicName);
        }
Exemplo n.º 22
0
 public ServiceBusBinding(string parameterName, IArgumentBinding <ServiceBusEntity> argumentBinding, ServiceBusAccount account, IBindableServiceBusPath path, ServiceBusAttribute attr)
 {
     _parameterName   = parameterName;
     _argumentBinding = argumentBinding;
     _account         = account;
     _namespaceName   = ServiceBusClient.GetNamespaceName(account);
     _path            = path;
     _accessRights    = attr.Access;
     _entityType      = attr.EntityType;
     _converter       = new OutputConverter <string>(
         new StringToServiceBusEntityConverter(account, _path, _accessRights, _entityType));
 }