public IEndpointConfiguration Bootstrap(EndpointDefinition endpointDefinition)
    {
        if (endpointDefinition.MachineName != null)
        {
            RuntimeEnvironment.MachineNameAction = () => endpointDefinition.MachineName;
        }

        busConfiguration = new BusConfiguration();

        busConfiguration.Conventions()
        .DefiningMessagesAs(
            t => t.Namespace != null && t.Namespace.EndsWith(".Messages") && t != typeof(TestEvent));
        busConfiguration.Conventions().DefiningEventsAs(t => t == typeof(TestEvent));

        busConfiguration.EndpointName(endpointDefinition.Name);
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        busConfiguration.UseTransport <SqlServerTransport>();

        customConfiguration = new CustomConfiguration();
        busConfiguration.CustomConfigurationSource(customConfiguration);

        messageStore        = new MessageStore();
        subscriptionStore   = new SubscriptionStore();
        callbackResultStore = new CallbackResultStore();

        busConfiguration.RegisterComponents(c => c.RegisterSingleton(messageStore));
        busConfiguration.RegisterComponents(c => c.RegisterSingleton(subscriptionStore));

        busConfiguration.Pipeline.Register <SubscriptionBehavior.Registration>();

        return(this);
    }
예제 #2
0
        public static bool Create(string subscriptionKey, string hostURI, string name, string description,
                                  string local, Guid projectId, Guid modelId, bool wait = true)
        {
            var properties = new Dictionary <string, string>();

            properties.Add("PortalAPIVersion", "3");

            System.Net.Http.HttpResponseMessage response;


            var endpointDefinition = EndpointDefinition.Create(
                name,
                description,
                local,
                new Identity(projectId),
                new List <Identity> {
                new Identity(modelId)
            },
                properties);
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(endpointDefinition);

            response = APIHelper.Submit(subscriptionKey, hostURI + API_V3.VoiceEndpoints_Create, jsonString);

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                APIHelper.PrintErrorMessage(response);
                return(false);
            }

            Console.WriteLine("endpoint created: " + response.Headers.Location.ToString());

            return(true);
        }
예제 #3
0
        public async Task<Guid> RegisterEndpointAsync(EndpointDefinition definition, CancellationToken cancellationToken)
        {
            _logger.Info($"Registering endpoint Group={definition.GroupName}, Name={definition.EndpointName} in Health Monitor: {_healthMonitorUrl}");
            try
            {
                using (var client = new HttpClient())
                {
                    var response = await PostAsync(client, "/api/endpoints/register", new
                    {
                        Name = definition.EndpointName,
                        Group = definition.GroupName,
                        Address = definition.Address,
                        MonitorType = PushMonitorType,
                        Tags = definition.Tags,
                        Password = definition.Password
                    }, cancellationToken);

                    return await DeserializeJsonAsync<Guid>(response);
                }
            }
            catch (Exception e)
            {
                _logger.Error("Endpoint registration failed.", e);
                throw;
            }
        }
 public DefaultEndpointCircuitBreaker(IPipelineTransport transport, ISerializer serializer, EndpointDefinition definitioin)
 {
     this.ErrorStrategy = new EndpointPostConsumeStrategy.ErrorEndpointPerEndpoint(transport, serializer, definitioin);
     this.RetryStrategy = new EndpointPostConsumeStrategy.RetryEndpointPerEndpoint(transport, serializer, definitioin);
     this.SuccessStrategy = new EndpointPostConsumeStrategy.NoSuccessStrategy();
     this.MaximumMessageAge = 5;
 }
예제 #5
0
 public static RequestHandler GetRequestHandler(
     EndpointDefinition endpointDefinition,
     RequestDbConnection requestDbConnection,
     RequestParameterValues parameterValues)
 {
     return(new RequestHandler(endpointDefinition, requestDbConnection, parameterValues));
 }
예제 #6
0
        public Endpoint LoadEndpointFromDefinition(EndpointDefinition definition)
        {
            var clientDomain = CreateAppDomain(definition.ConfigPath, definition.AssemblyPath);

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

            var clientAssembly = Assembly.Load(new AssemblyName()
            {
                CodeBase = definition.AssemblyPath
            });

            var endpoint = new Endpoint(definition, Guid.NewGuid().ToString())
            {
                ClientDomain   = clientDomain,
                ClientAssembly = clientAssembly
            };

            var contractType = clientAssembly.GetType(endpoint.Definition.Contract);

            if (contractType == null)
            {
                return(endpoint);
            }

            endpoint.ContractTypeName = clientAssembly.GetTypes().FirstOrDefault(x => !x.IsInterface && contractType.IsAssignableFrom(x))?.FullName;
            endpoint.Methods          = GetContractMethods(clientAssembly, contractType).ToList();

            return(endpoint);
        }
    public IEndpointConfiguration Bootstrap(EndpointDefinition endpointDefinition)
    {
        if (endpointDefinition.MachineName != null)
        {
            RuntimeEnvironment.MachineNameAction = () => endpointDefinition.MachineName;
        }

        configure = Configure.With();
        configure.DefaultBuilder();

        configure.DefineEndpointName(endpointDefinition.Name);
        Address.InitializeLocalAddress(endpointDefinition.Name);

        configure.DefiningMessagesAs(t => t.Namespace != null && t.Namespace.EndsWith(".Messages") && t != typeof(TestEvent));
        configure.DefiningEventsAs(t => t == typeof(TestEvent));

        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();

        customConfiguration = new CustomConfiguration();
        configure.CustomConfigurationSource(customConfiguration);

        Feature.Enable <MessageDrivenSubscriptions>();

        configure.Configurer.ConfigureComponent <MessageStore>(DependencyLifecycle.SingleInstance);

        return(this);
    }
        public static IObservable <bool> ObserveStartServer(
            [NotNull] this IServer server,
            EndpointDefinition endpoint,
            IScheduler scheduler = null)
        {
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            IObservable <bool> bindObservable = Observable.Create(
                async(IObserver <bool> o) =>
            {
                Observer.Synchronize(o);
                try
                {
                    await server.StopAsync();
                    await server.StartAsync(endpoint);

                    o.OnCompleted();
                }
                catch (Exception ex)
                {
                    o.OnError(ex);
                }

                return(Disposable.Empty);
            }).ObserveOn(scheduler ?? Scheduler.Default);

            return(bindObservable);
        }
            int OnExecute(CommandLineApplication app)
            {
                List <ModelIdentity> modelProperty;

                if (string.IsNullOrWhiteSpace(AcousticModel))
                {
                    modelProperty = new List <ModelIdentity>()
                    {
                        new ModelIdentity(Guid.Parse(LanguageModel))
                    };
                }
                else
                {
                    modelProperty = new List <ModelIdentity>()
                    {
                        new ModelIdentity(Guid.Parse(AcousticModel)), new ModelIdentity(Guid.Parse(LanguageModel))
                    };
                }

                var endpointDefinition = new EndpointDefinition()
                {
                    Name                   = Name,
                    Description            = Description,
                    Locale                 = Locale ?? "en-us",
                    ModelsProperty         = modelProperty,
                    ConcurrentRecognitions = ConcurrentRecognitions ?? 1,
                    ContentLoggingEnabled  = ContentLogging ?? true,
                    Properties             = SplitProperties(Properties),
                };

                _console.WriteLine("Creating endpoint...");
                var res = CreateAndWait(() => _speechApi.CreateEndpoint(endpointDefinition), Wait, _speechApi.GetEndpoint);

                return(res);
            }
예제 #10
0
        public void Start(EndpointDefinition smtpEndpoint)
        {
            ServicePointManager.ServerCertificateValidationCallback = IgnoreCertificateValidationFailureForTestingOnly;

            _currentEndpoint = smtpEndpoint;

            var options = new SmtpServerOptionsBuilder()
                          .ServerName(_applicationMetaData.AppName)
                          .UserAuthenticator(new SimpleAuthentication())
                          .MailboxFilter(new DelegatingMailboxFilter(CanAcceptMailbox))
                          .Logger(_bridgeLogger)
                          .MessageStore(_messageStore);

            options = options.Endpoint(new EndpointDefinitionBuilder()
                                       .Endpoint(smtpEndpoint.ToIPEndPoint())
                                       .IsSecure(false)
                                       .AllowUnsecureAuthentication(false)
                                       .Build());

            var server = new SmtpServer(options.Build());

            server.SessionCreated   += OnSessionCreated;
            server.SessionCompleted += OnSessionCompleted;

            _logger.Information("Starting Smtp Server on {IP}:{Port}...", ListenIpAddress, ListenPort);

            _tokenSource    = new CancellationTokenSource();
            _smtpServerTask = server.StartAsync(_tokenSource.Token);
        }
예제 #11
0
        public async Task Notifier_should_register_endpoint_with_all_details_and_specified_host()
        {
            EndpointDefinition captured = null;
            var countdown  = new AsyncCountdown("register", 1);
            var endpointId = Guid.NewGuid();

            _mockClient
            .Setup(c => c.RegisterEndpointAsync(It.IsAny <EndpointDefinition>(), It.IsAny <CancellationToken>()))
            .Returns((EndpointDefinition def, CancellationToken token) => _awaitableFactory
                     .Execute(() => { captured = def; return(endpointId); })
                     .WithCountdown(countdown)
                     .RunAsync());

            SetupHealthCheckInterval(TimeSpan.FromMilliseconds(1));

            Action <IEndpointDefintionBuilder> builder = b => b.DefineName("endpointName")
                                                         .DefineGroup("endpointGroup")
                                                         .DefineTags("t1")
                                                         .DefineAddress("host", "uniqueName")
                                                         .DefinePassword(AuthenticationToken);

            using (CreateNotifier(builder, token => Task.FromResult(new EndpointHealth(HealthStatus.Offline))))
                await countdown.WaitAsync(TestMaxTime);

            Assert.NotNull(captured);
            Assert.Equal("endpointName", captured.EndpointName);
            Assert.Equal("endpointGroup", captured.GroupName);
            Assert.Equal(new[] { "t1" }, captured.Tags);
            Assert.Equal("host:uniqueName", captured.Address);
        }
예제 #12
0
        public async Task StartAsync(EndpointDefinition endpoint)
        {
            await Task.CompletedTask;

            if (this.IsActive)
            {
                return;
            }

            this._currentEndpoint = endpoint;

            try
            {
                // Set it as starting
                this.IsActive = true;

                // Create and start new listener socket
                this.CreateListener();
            }
            catch
            {
                this.IsActive = false;
                throw;
            }
        }
예제 #13
0
    public IEndpointConfiguration Bootstrap(EndpointDefinition endpointDefinition)
    {
        if (endpointDefinition.MachineName != null)
        {
            RuntimeEnvironment.MachineNameAction = () => endpointDefinition.MachineName;
        }

        endpointConfiguration = new EndpointConfiguration(endpointDefinition.Name);

        endpointConfiguration.Conventions().DefiningMessagesAs(t => t.Namespace != null && t.Namespace.EndsWith(".Messages") && t != typeof(TestEvent));
        endpointConfiguration.Conventions().DefiningEventsAs(t => t == typeof(TestEvent));

        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        endpointConfiguration.Recoverability().Immediate(i => i.NumberOfRetries(0));
        endpointConfiguration.Recoverability().Delayed(d => d.NumberOfRetries(0));

        endpointConfiguration.AuditProcessedMessagesTo("audit");

        messageStore        = new MessageStore();
        callbackResultStore = new CallbackResultStore();
        subscriptionStore   = new SubscriptionStore();

        endpointConfiguration.RegisterComponents(c => c.RegisterSingleton(messageStore));
        endpointConfiguration.RegisterComponents(c => c.RegisterSingleton(subscriptionStore));

        endpointConfiguration.Pipeline.Register <SubscriptionMonitoringBehavior.Registration>();

        return(this);
    }
        /// <summary>
        /// Build the endpoint definition.
        /// </summary>
        /// <returns>The endpoint definition that was built.</returns>
        public IEndpointDefinition Build()
        {
            var definition = new EndpointDefinition();

            _setters.ForEach(setter => setter(definition));

            return(definition);
        }
예제 #15
0
 /// <summary>
 ///     The contstructor for IWrite endpoints
 /// </summary>
 /// <param name="endpointDefinition"> The EndpointDefinition for this endpoint. </param>
 /// <param name="serviceEndpoint"> TThe ServiceEndpoint definition for this endpoint. </param>
 /// <param name="receiveTimeout">
 ///     The inactivity time interval to be used by the server to timeout this endpoint when no
 ///     requests are received from the client.
 /// </param>
 /// <param name="sendTimeout"> The length of time WCF will wait for a response before throwing an exception. </param>
 /// <param name="maxItemsInObjectGraph"> The number of objects the server will serialize into a single response. </param>
 internal XiWriteEndpoint(EndpointDefinition endpointDefinition,
                          ServiceEndpoint serviceEndpoint, TimeSpan receiveTimeout, TimeSpan sendTimeout,
                          int maxItemsInObjectGraph)
     : base(
         endpointDefinition, serviceEndpoint, receiveTimeout, sendTimeout,
         maxItemsInObjectGraph)
 {
     CreateChannel();
 }
예제 #16
0
 private RequestHandler(
     EndpointDefinition endpointDefinition,
     RequestDbConnection requestDbConnection,
     RequestParameterValues parameterValues)
 {
     _endpointDefinition  = endpointDefinition;
     _requestDbConnection = requestDbConnection;
     _parameterValues     = parameterValues;
 }
 public ErrorEndpointPerEndpoint(IPipelineTransport transport, ISerializer serializer, EndpointDefinition endpointDefinition)
 {
     this.serializer = serializer;
     this.transport = transport;
     endpointWhereErrorOccured = endpointDefinition.EndpointName;
     errorPipelineName = endpointDefinition.PipelineName + ".Errors";
     EndpointDefinition errorEndpoint = new EndpointDefinition(errorPipelineName, endpointWhereErrorOccured + ".Errors", null, endpointWhereErrorOccured);
     transport.EndpointFactory.CreateTopicEndpoint(errorEndpoint);
 }
 public RabbitMqEndpoint(EndpointDefinition endpointDefinition, RabbitMqSession session)
 {
     RoutingHeaders = new Dictionary<string, object>(endpointDefinition.RoutingHeaders);
     AutoDelete = false;
     Exclusive = false;
     Durable = true;
     this.session = session;
     RoutingKey = endpointDefinition.RoutingKey;
     Name = endpointDefinition.EndpointName;
 }
        public IEndpoint CreateTopicEndpoint(EndpointDefinition definition)
        {
            var endpoint = new RabbitMqEndpoint(definition, session);
            endpoint.Declare();

            var pipeLine = new RabbitMqPipeline(definition.PipelineName, session, PipelineType.Topics);
            pipeLine.Declare();
            pipeLine.Bind(endpoint);
            return endpoint;
        }
예제 #20
0
        /// <summary>
        ///     The contstructor for IRegisterForCallback/ICallback endpoints
        /// </summary>
        /// <param name="endpointDefinition"> The EndpointDefinition for this endpoint. </param>
        /// <param name="serviceEndpoint"> TThe ServiceEndpoint definition for this endpoint. </param>
        /// <param name="receiveTimeout">
        ///     The inactivity time interval to be used by the server to timeout this endpoint when no
        ///     requests are received from the client.
        /// </param>
        /// <param name="sendTimeout"> The length of time WCF will wait for a response before throwing an exception. </param>
        /// <param name="maxItemsInObjectGraph"> The number of objects the server will serialize into a single response. </param>
        /// <param name="xiCallbackDoer"></param>
        internal XiCallbackEndpoint(EndpointDefinition endpointDefinition,
                                    ServiceEndpoint serviceEndpoint, TimeSpan receiveTimeout, TimeSpan sendTimeout,
                                    int maxItemsInObjectGraph, IDispatcher xiCallbackDoer)
            : base(
                endpointDefinition, serviceEndpoint, receiveTimeout, sendTimeout,
                maxItemsInObjectGraph)
        {
            _xiCallbackDoer = xiCallbackDoer;

            CreateChannel();
        }
예제 #21
0
 //Create Endpoint
 public void CreateEndpoint(string name, string description, string locale, List <ModelIdentity> ModelIds)
 {
     var endpointDefinition = new EndpointDefinition(name,
                                                     description,
                                                     locale,
                                                     ModelIds,
                                                     null,
                                                     0,
                                                     false);
     var submitResponse = VoiceAPIHelper.Submit <EndpointDefinition>(endpointDefinition, CreateEndpointUrl, this.subscriptionKey);
 }
예제 #22
0
        /// <summary>
        /// Build the endpoint definition.
        /// </summary>
        /// <returns>The endpoint definition that was built.</returns>
        public IEndpointDefinition Build()
        {
            var definition = new EndpointDefinition
            {
                ReadTimeout = TimeSpan.FromMinutes(2)
            };

            _setters.ForEach(setter => setter(definition));

            return(definition);
        }
예제 #23
0
 /// <summary>
 ///     The constructor for endpoints
 /// </summary>
 /// <param name="endpointDefinition"> The EndpointDefinition for this endpoint. </param>
 /// <param name="serviceEndpoint"> TThe ServiceEndpoint definition for this endpoint. </param>
 /// <param name="receiveTimeout">
 ///     The inactivity time interval to be used by the server to timeout this endpoint when no
 ///     requests are received from the client.
 /// </param>
 /// <param name="sendTimeout"> The length of time WCF will wait for a response before throwing an exception. </param>
 /// <param name="maxItemsInObjectGraph"> The number of objects the server will serialize into a single response. </param>
 protected XiEndpointRoot(EndpointDefinition endpointDefinition,
                          ServiceEndpoint serviceEndpoint, TimeSpan receiveTimeout, TimeSpan sendTimeout,
                          int maxItemsInObjectGraph)
 {
     _endpointDefinition = endpointDefinition;
     ServiceEndpoint     = serviceEndpoint;
     ServiceEndpoint.Binding.ReceiveTimeout = receiveTimeout;
     ServiceEndpoint.Binding.SendTimeout    = sendTimeout;
     MaxItemsInObjectGraph = maxItemsInObjectGraph;
     LastCallUtc           = DateTime.UtcNow;
 }
        public IEndpoint CreateEndpoint(EndpointDefinition definition)
        {
            var endpoint = new RabbitMqEndpoint(definition, session);
            endpoint.RoutingHeaders.Add("x-match", "any");
            endpoint.Declare();

            var pipeLine = new UberPipeline(definition.PipelineName, session, PipelineType.Headers);
            pipeLine.Declare();
            pipeLine.Bind(endpoint);
            return endpoint;
        }
        public IEndpoint GetOrAddEndpoint(EndpointDefinition endpointDefinition)
        {
            var       pipeline = GetOrAddPipeline(endpointDefinition.PipelineName);
            IEndpoint endpoint;

            if (!TryGetEndpoint(endpointDefinition.EndpointName, out endpoint))
            {
                endpoint = new InMemoryEndpoint(this, endpointDefinition.EndpointName, endpointDefinition.RoutingHeaders);
                Bind(pipeline, endpoint);
            }
            return(endpoint);
        }
예제 #26
0
        public HealthMonitorPushClient DefineEndpoint(Action <IEndpointDefintionBuilder> definitionBuilder)
        {
            if (_definition != null)
            {
                throw new InvalidOperationException("Endpoint already defined.");
            }
            var builder = new EndpointDefintionBuilder();

            definitionBuilder.Invoke(builder);
            _definition = builder.Build();
            return(this);
        }
예제 #27
0
        /// <summary>
        /// Build the endpoint definition.
        /// </summary>
        /// <returns>The endpoint definition that was built.</returns>
        public IEndpointDefinition Build()
        {
            var definition = new EndpointDefinition
            {
                ReadTimeout           = TimeSpan.FromMinutes(2),
                SupportedSslProtocols = SslProtocols.Tls12,
            };

            _setters.ForEach(setter => setter(definition));

            return(definition);
        }
예제 #28
0
 public void SetUp()
 {
     sourceEndpoint = new EndpointDefinition("Source")
     {
         MachineName = Environment.MachineName + "_A"
     };
     competingEndpoint = new EndpointDefinition("Source")
     {
         MachineName = Environment.MachineName + "_B"
     };
     destinationEndpoint = new EndpointDefinition("Destination");
 }
            public RetryEndpointPerEndpoint(IPipelineTransport transport, ISerializer serializer, EndpointDefinition endpointDefinition)
            {
                this.serializer = serializer;
                this.transport = transport;

                endpointWhereErrorOccured = endpointDefinition.EndpointName;
                retryPipelineName = endpointDefinition.PipelineName + ".RetryScheduler";
                Dictionary<string, object> headers = new Dictionary<string, object>();
                headers.Add("x-dead-letter-exchange", endpointDefinition.PipelineName);
                headers.Add("x-message-ttl", 500);

                EndpointDefinition retryEndpoint = new EndpointDefinition(retryPipelineName, endpointWhereErrorOccured + ".Retry", headers, endpointWhereErrorOccured);
                transport.EndpointFactory.CreateTopicEndpoint(retryEndpoint);
            }
예제 #30
0
 public EndpointHealthNotifier(IHealthMonitorClient client, ITimeCoordinator timeCoordinator, EndpointDefinition definition, IHealthChecker healthChecker)
 {
     _client                 = client;
     _timeCoordinator        = timeCoordinator;
     _definition             = definition;
     _healthChecker          = healthChecker;
     _cancelationTokenSource = new CancellationTokenSource();
     _healthCheckInterval    = new CachedValue <TimeSpan>(HealthCheckIntervalCacheDuration, GetHealthCheckIntervalAsync);
     _thread                 = new Thread(HealthLoop)
     {
         IsBackground = true, Name = "Health Check loop"
     };
     _thread.Start();
 }
        public override IEnumerable<EndpointDefinition> GetEndpointDefinition(IEndpointConsumer consumer, SubscriptionMiddleware subscriptionMiddleware)
        {
            var pipeLine = subscriptionMiddleware.Subscribers.Select(x => pipelineNameConvention.GetPipelineName(x.MessageTypes.First())).Distinct();
            if (pipeLine.Count() == 0)
                throw new ArgumentException("Cannot find pipeline to subscribe to.");
            else if (pipeLine.Count() > 1)
                throw new ArgumentException("Cannot subscribe to more than one pipeline. Probably you have mixed ICommand and IEvent messages within a single handler.");

            var routingHeaders = subscriptionMiddleware.Subscribers.SelectMany(x => x.MessageTypes)
                                                        .Distinct()
                                                        .ToDictionary<Type, string, object>(key => key.GetContractId(), val => String.Empty);

            EndpointDefinition endpointDefinition = new EndpointDefinition(pipeLine.Single(), consumer.Name, routingHeaders);
            yield return endpointDefinition;
        }
        /// <summary>
        ///     Returns collection of routes that will be used to populate
        ///     <see cref="MessageFilterTable&lt;ServiceEndpoint&gt;" /> of the routing service.
        /// </summary>
        /// <param name="backendEndpoints">
        ///     All available endpoints in the outbound endpoint group that this
        ///     router instance is bound to.
        /// </param>
        /// <returns>
        ///     Collection of routes that will be used to populate
        ///     <see cref="MessageFilterTable&lt;ServiceEndpoint&gt;" /> of the routing service.
        /// </returns>
        public IEnumerable <Route> GetRoutes(IEnumerable <EndpointDefinition> backendEndpoints)
        {
            if (backendEndpoints == null)
            {
                throw new ArgumentNullException("backendEndpoints");
            }

            // Validate router configuration
            if (!Validate())
            {
                throw new ValidationException(ErrorMessage);
            }

            var routes         = new Collection <Route>();
            var routeEndpoints = new Collection <EndpointDefinition>();
            var priority       = Byte.MaxValue;

            foreach (RoutingRule routingRule in RoutingRules)
            {
                // Collection can be reused as endpoints are copied in Route() constructor
                routeEndpoints.Clear();

                // collection of the backend endpoint per routingRule
                foreach (string endpointUri in routingRule.Endpoints)
                {
                    // Find outbound endpoint by its AbsoluteURI
                    EndpointDefinition endpoint = backendEndpoints.FirstOrDefault(e => String.Equals(e.LogicalAddress.AbsoluteUri, endpointUri, StringComparison.OrdinalIgnoreCase));
                    if (endpoint == null)
                    {
                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, InvalidRouterConfiguration, endpointUri));
                    }
                    routeEndpoints.Add(endpoint);
                }

                // build a route for each routingRule
                var filter = new ContextPropertyMessageFilter
                {
                    PropertyName  = routingRule.Name,
                    PropertyValue = routingRule.Value
                };
                // endpoint Fallback scenario
                routes.Add(new Route(filter, routeEndpoints, priority));
                priority--;
            }

            return(routes);
        }
예제 #33
0
        public Task StartAsync(EndpointDefinition smtpEndpoint)
        {
            if (this.IsActive)
            {
                return(Task.CompletedTask);
            }

            ServicePointManager.ServerCertificateValidationCallback = this.IgnoreCertificateValidationFailureForTestingOnly;

            this._currentEndpoint = smtpEndpoint;

            var options = new SmtpServerOptionsBuilder()
                          .ServerName(this._applicationMetaData.AppName)
                          .Endpoint(
                new EndpointDefinitionBuilder()
                .Endpoint(smtpEndpoint.ToIPEndPoint())
                .IsSecure(false)
                .AllowUnsecureAuthentication(false)
                .Build());

            this._server = this._smtpServerFactory(options.Build());

            this._server.SessionCreated   += this.OnSessionCreated;
            this._server.SessionCompleted += this.OnSessionCompleted;

            this._logger.Information("Starting Smtp Server on {IP}:{Port}...", this.ListenIpAddress, this.ListenPort);
            this._tokenSource = new CancellationTokenSource();

#pragma warning disable 4014
            // server will block -- just let it run
            Task.Run(
                async() =>
            {
                try
                {
                    await this._server.StartAsync(this._tokenSource.Token);
                }
                catch (Exception ex)
                {
                    this._logger.Error(ex, "Smtp Server Error");
                }
            },
                this._tokenSource.Token);
#pragma warning restore 4014

            return(Task.CompletedTask);
        }
예제 #34
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Func <ILogger <Startup>, string, string> helloApi = (logger, name) =>
            {
                logger.LogInformation("Running the API using parameter {Name}", name);
                return($"Hello {name}!");
            };

            services.AddControllers();

            services.AddApiFrameworkStarterKit()
            .AddApi(helloApi)
            .AddApi <CalculatorApi>()
            .AddSqlServer()
            .AddOpenApi()
            .AddEndpoint <CalculatorApi>("/mycal", 15)
            .AddEndpoint <CalculatorApi>("/second", 100)
            .AddEndpoint <CalculatorApi>("/third", 0)
            .AddEndpoint("/sqlserver", ("Weikio.ApiFramework.Plugins.SqlServer", Version.Parse("1.1.0.0")), new SqlServerOptions()
            {
                ConnectionString =
                    "Server=tcp:adafydevtestdb001.database.windows.net,1433;User ID=docs;Password=3h1@*6PXrldU4F95;Integrated Security=false;Initial Catalog=adafyweikiodevtestdb001;"
            })
            .AddEndpoint("/sqlserver_products", ("Weikio.ApiFramework.Plugins.SqlServer", Version.Parse("1.1.0.0")), new SqlServerOptions()
            {
                ConnectionString =
                    "Server=tcp:adafydevtestdb001.database.windows.net,1433;User ID=docs;Password=3h1@*6PXrldU4F95;Integrated Security=false;Initial Catalog=adafyweikiodevtestdb001;",
                Tables = new[] { "Product*" },
            })
            .AddEndpoint("/pets", "Weikio.ApiFramework.Plugins.OpenApi",
                         new ApiOptions()
            {
                SpecificationUrl = "https://petstore.swagger.io/v2/swagger.json", IncludeHttpMethods = new[] { "GET" }
            });

            var endpointDefinition = new EndpointDefinition("/pets_writeonly", "Weikio.ApiFramework.Plugins.OpenApi",
                                                            new ApiOptions()
            {
                SpecificationUrl = "https://petstore.swagger.io/v2/swagger.json", ExcludeHttpMethods = new[] { "GET" }
            });

            services.AddSingleton(endpointDefinition);
        }
예제 #35
0
        public override IEnumerable <EndpointDefinition> GetEndpointDefinition(IEndpointConsumer consumer, SubscriptionMiddleware subscriptionMiddleware)
        {
            var pipeLine = subscriptionMiddleware.Subscribers.Select(x => pipelineNameConvention.GetPipelineName(x.MessageTypes.First())).Distinct();

            if (pipeLine.Count() == 0)
            {
                throw new ArgumentException("Cannot find pipeline to subscribe to.");
            }
            else if (pipeLine.Count() > 1)
            {
                throw new ArgumentException("Cannot subscribe to more than one pipeline. Probably you have mixed ICommand and IEvent messages within a single handler.");
            }

            var watchMessageTypes = subscriptionMiddleware.Subscribers.SelectMany(x => x.MessageTypes).Distinct().Select(x => x.GetContractId()).ToList();

            EndpointDefinition endpointDefinition = new EndpointDefinition(pipeLine.Single(), consumer.Name, watchMessageTypes);

            yield return(endpointDefinition);
        }
예제 #36
0
파일: Startup.cs 프로젝트: Vake93/QuickAPI
        private async Task HandleRequestAsync(HttpContext context, EndpointDefinition endpointDefinition, ILogger logger)
        {
            try
            {
                var credentials     = AuthEnabled ? Credentials.Authenticate(context, AuthConfig !) : null;
                var parameterValues = RequestParameterValues.ResolveParameters(context, endpointDefinition);

                using var requestDbConnection = RequestDbConnection.GetRequestDbConnection(EndpointConfiguration, credentials);
                using var requestHandler      = RequestHandler.GetRequestHandler(endpointDefinition, requestDbConnection, parameterValues);

                var items = await requestHandler.HandleRequestAsync();

                await context.WriteResponseAsync(new { Items = items }, HttpStatusCode.OK);
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                await context.WriteErrorResponseAsync(e);
            }
        }
예제 #37
0
        public static bool Create(string subscriptionKey, string hostURI, string name, string description,
                                  string local, Guid projectId, Guid modelId)
        {
            var endpointDefinition = EndpointDefinition.Create(
                name,
                description,
                local,
                new Identity(projectId),
                new List <Identity> {
                new Identity(modelId)
            },
                null);
            var response = APIHelper.Submit <EndpointDefinition>(subscriptionKey, hostURI + API_V3.VoiceEndpoints_Create, endpointDefinition);

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                APIHelper.PrintErrorMessage(response);
                return(false);
            }
            return(true);
        }
예제 #38
0
 public IEndpoint CreateTopicEndpoint(EndpointDefinition definition)
 {
     return transport.GetOrAddEndpoint(definition);
 }
 public void Initialize(IEndpointFactory endpointFactory, EndpointDefinition endpointDefinition) { }
 public IEndpointCircuitBreaker Create(Transport.IPipelineTransport transport, Serializer.ISerializer serializer, EndpointDefinition definitioin)
 {
     return new DefaultEndpointCircuitBreaker(transport, serializer, definitioin);
 }