Exemplo n.º 1
0
        static async Task AsyncMain()
        {
            var configuration = new BusConfiguration();
            configuration.EndpointName("Gru");
            configuration.UseSerialization<JsonSerializer>();
            configuration.UsePersistence<InMemoryPersistence>();
            configuration.EnableInstallers();
            configuration.SendFailedMessagesTo("error");


            var minionEndpoint = new EndpointName("Minion");
            configuration.Routing().UnicastRoutingTable.AddStatic(typeof(DoSomethingNaughty), minionEndpoint);
            configuration.Routing().UseFileBasedEndpointInstanceLists().LookForFilesIn(@".\");

            var endpoint = await Endpoint.Start(configuration);
            var busContext = endpoint.CreateBusContext();

            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    await endpoint.Stop();
                    return;
                }

                Console.WriteLine("Commanding to do something naughty.");
                await busContext.Send<DoSomethingNaughty>(m => m.Data = "Go minion, go!");
            }
        }
Exemplo n.º 2
0
        private static async Task MainAsync()
        {
            var factory = LogManager.Use<DefaultFactory>();
            factory.Level(LogLevel.Debug);

            var configuration = new EndpointConfiguration();
            configuration.EndpointName("Sender");
            configuration.EnableInstallers();
            configuration.UseSerialization<JsonSerializer>();
            configuration.UsePersistence<InMemoryPersistence>();

            configuration.SendFailedMessagesTo("error");
           
            var transportConfiguration = configuration.UseTransport<AzureServiceBusTransport>();

            transportConfiguration.ConnectionString(Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString"));


            // define routing (what used to be message endpoint mapping)
            var endpointName = new EndpointName("Receiver");
           // configuration.Routing().SetMessageDistributionStrategy(new SingleInstanceRoundRobinDistributionStrategy(), t => true);
            configuration.Routing().UnicastRoutingTable.RouteToEndpoint(typeof(TestCommand), endpointName);
            configuration.Routing().EndpointInstances.AddStatic(endpointName, new EndpointInstance(endpointName, null, null));

            var endpoint = await Endpoint.Start(configuration);

            Console.WriteLine("Press ESC to exit, any other key to send a message");
            Console.WriteLine("Press any other key to send a message");
            while (Console.ReadKey().Key != ConsoleKey.Escape)
            {
                await endpoint.Send<TestCommand>(m => m.Data = "Testing ASB send");
                Console.WriteLine("message sent");
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Adds a named endpoint to the collection
 /// </summary>
 /// <param name="endpointName">The name of the endpoint</param>
 /// <param name="endpoint">The endpoint</param>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="endpointName"/>
 /// or <paramref name="endpoint"/> are <c>null</c></exception>
 /// <exception cref="EndpointAlreadyExistsException">Thrown if there is already an
 /// endpoint with the specified <paramref name="endpointName"/></exception>
 public void Add(EndpointName endpointName, IEndpoint endpoint)
 {
     if (endpointName == null) throw new ArgumentNullException("endpointName");
     if (endpoint == null) throw new ArgumentNullException("endpoint");
     if (_endpoints.ContainsKey(endpointName)) throw new EndpointAlreadyExistsException(endpointName);
     _endpoints[endpointName] = endpoint;
 }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a serialized <see cref="EndpointNotFoundException"/> from
 /// a streaming context
 /// </summary>
 /// <param name="info">The serialization info</param>
 /// <param name="context">The streaming context</param>
 public EndpointNotFoundException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     _endpoint = info.GetString("Endpoint");
     var addressStr = info.GetString("Address");
     _address = string.IsNullOrWhiteSpace(addressStr) ? null : new Uri(addressStr);
 }
Exemplo n.º 5
0
 public void StaticEndpointMappingWithDiscriminators()
 {
     var busConfig = new BusConfiguration();
     #region Routing-StaticEndpointMappingWithDiscriminators
     EndpointName sales = new EndpointName("Sales");
     busConfig.Routing().EndpointInstances.AddStaticUsingTransportDiscriminators(sales, "MachineA", "MachineB");
     #endregion
 }
Exemplo n.º 6
0
 public void StaticEndpointMapping()
 {
     var busConfig = new BusConfiguration();
     #region Routing-StaticEndpointMapping
     EndpointName sales = new EndpointName("Sales");
     busConfig.Routing().EndpointInstances.AddStatic(sales, new EndpointInstanceName(sales, "1", null), new EndpointInstanceName(sales, "2", null));
     #endregion
 }
        public void StaticEndpointMapping()
        {
            BusConfiguration busConfiguration = new BusConfiguration();

            #region Routing-StaticEndpointMapping
            EndpointName sales = new EndpointName("Sales");
            busConfiguration.Routing().EndpointInstances
            .AddStatic(sales, new EndpointInstance(sales, "1", null), new EndpointInstance(sales, "2", null));
            #endregion
        }
Exemplo n.º 8
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (EndpointName != null ? EndpointName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (InstanceId != null ? InstanceId.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (InstanceName != null ? InstanceName.GetHashCode() : 0);
         return(hashCode);
     }
 }
 /// <summary>
 /// Updates entities in TSheets via an HTTP PUT call to the API endpoint, with retries.
 /// </summary>
 /// <param name="endpointName">The name of the endpoint, <see cref="EndpointName"/></param>
 /// <param name="jsonData">The content to be sent in the body of the request.</param>
 /// <param name="logContext">Call-specific contextual information for logging purposes.</param>
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 /// <returns>The serialized response of the API method call.</returns>
 public async Task <string> UpdateAsync(
     EndpointName endpointName,
     string jsonData,
     LogContext logContext,
     CancellationToken cancellationToken)
 {
     return(await ExecutePolicyAsync(
                logContext,
                () => this.restClient.UpdateAsync(endpointName, jsonData, logContext, cancellationToken))
            .ConfigureAwait(false));
 }
 /// <summary>Snippet for GetEndpoint</summary>
 public void GetEndpointResourceNames()
 {
     // Snippet: GetEndpoint(EndpointName, CallSettings)
     // Create client
     IDSClient iDSClient = IDSClient.Create();
     // Initialize request argument(s)
     EndpointName name = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
     // Make the request
     Endpoint response = iDSClient.GetEndpoint(name);
     // End snippet
 }
 /// <summary>
 /// Removes entities in TSheets via an HTTP DELETE call to the API endpoint, with retries.
 /// </summary>
 /// <param name="endpointName">The name of the endpoint, <see cref="EndpointName"/></param>
 /// <param name="ids">The ids of the entities to be deleted.</param>
 /// <param name="logContext">Call-specific contextual information for logging purposes.</param>
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 /// <returns>The serialized response of the API method call.</returns>
 public async Task <string> DeleteAsync(
     EndpointName endpointName,
     IEnumerable <long> ids,
     LogContext logContext,
     CancellationToken cancellationToken)
 {
     return(await ExecutePolicyAsync(
                logContext,
                () => this.restClient.DeleteAsync(endpointName, ids, logContext, cancellationToken))
            .ConfigureAwait(false));
 }
 /// <summary>
 /// Downloads binary data from TSheets via an HTTP POST call to the API endpoint, with retries.
 /// </summary>
 /// <param name="endpointName">The name of the endpoint, <see cref="EndpointName"/></param>
 /// <param name="filters">The key-value pairs to be sent as URL request parameters.</param>
 /// <param name="logContext">Call-specific contextual information for logging purposes.</param>
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 /// <returns>The serialized response of the API method call.</returns>
 public async Task <byte[]> DownloadAsync(
     EndpointName endpointName,
     Dictionary <string, string> filters,
     LogContext logContext,
     CancellationToken cancellationToken)
 {
     return(await ExecutePolicyAsync(
                logContext,
                () => this.restClient.DownloadAsync(endpointName, filters, logContext, cancellationToken))
            .ConfigureAwait(false));
 }
 /// <summary>Snippet for RawPredict</summary>
 public void RawPredictResourceNames()
 {
     // Snippet: RawPredict(EndpointName, HttpBody, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     EndpointName endpoint = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
     HttpBody     httpBody = new HttpBody();
     // Make the request
     HttpBody response = predictionServiceClient.RawPredict(endpoint, httpBody);
     // End snippet
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new <see cref="DiagnosticEvent"/>
 /// </summary>
 /// <param name="source">The object that emitted the event</param>
 /// <param name="type">The type of event</param>
 /// <param name="detail">Specific details regarding this instance of the event</param>
 /// <param name="exception">The exception related to the event, if applicable</param>
 /// <param name="message">The message to which the event pertains, if applicable</param>
 /// <param name="endpoint">The name of the endpoint, if applicable</param>
 /// <param name="queue">The queue to which the event pertains, if applicable</param>
 /// <param name="topic">The topic to which the message pertains, if applicable</param>
 public DiagnosticEvent(object source, DiagnosticEventType type, string detail = null, Exception exception = null, Message message = null, EndpointName endpoint = null, QueueName queue = null, TopicName topic = null)
 {
     Timestamp = DateTime.UtcNow;
     Source    = source;
     Type      = type ?? throw new ArgumentNullException(nameof(type));
     Detail    = detail;
     Exception = exception;
     Message   = message;
     Endpoint  = endpoint;
     Queue     = queue;
     Topic     = topic;
 }
Exemplo n.º 15
0
        private Uri CreateRequestUri(EndpointName endpointName, Dictionary <string, string> filters = null)
        {
            string endpointSegment = EndpointMapper.GetEndpoint(endpointName);
            Uri    fullUri         = new Uri($"{this.context.ConnectionInfo.BaseUri}/{endpointSegment}");

            return(filters?.Count > 0
                ? new UriBuilder(fullUri)
            {
                Query = filters.ToUrlQueryString()
            }.Uri
                : fullUri);
        }
Exemplo n.º 16
0
        private void SetupAsyncMocks <TEntity, TContext>(EndpointName endpoint, Params expect)
            where TEntity : new()
            where TContext : PipelineContext <TEntity>
        {
            this.mockPipeline
            .Setup(f => f.ProcessAsync(It.IsAny <TContext>(), It.IsAny <ILogger>(), It.IsAny <CancellationToken>()))
            .Callback((PipelineContext <TEntity> context, ILogger log, CancellationToken cancellationToken) =>
                      Process(context, endpoint, expect))
            .Returns(Task.CompletedTask);

            SetupPipelineFactoryMock <TEntity>();
        }
Exemplo n.º 17
0
        void StaticEndpointMapping(EndpointConfiguration endpointConfiguration)
        {
            #region Routing-StaticEndpointMapping

            EndpointName sales = new EndpointName("Sales");
            endpointConfiguration.UnicastRouting().Mapping.Physical
                .Add(sales,
                    new EndpointInstance(sales, "1", null),
                    new EndpointInstance(sales, "2", null));

            #endregion
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeleteContext{T}"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint with which to interact.</param>
        /// <param name="ids">The set of ids corresponding to the data entities to be deleted.</param>
        internal DeleteContext(EndpointName endpoint, IEnumerable <int> ids)
            : base(MethodType.Delete, endpoint)
        {
            List <int> listIds = ids?.ToList();

            if (listIds == null || !listIds.Any())
            {
                throw new BadRequestException("Request cannot contain a null or empty set of ids.");
            }

            Ids = listIds;
        }
Exemplo n.º 19
0
 /// <summary>
 /// Returns the endpoint with the specified name
 /// </summary>
 /// <param name="endpointName">The name of the endpoint</param>
 /// <returns>Returns the endpoint</returns>
 /// <exception cref="EndpointNotFoundException">Thrown if there
 /// is no endpoint with the specified name</exception>
 public IEndpoint this[EndpointName endpointName]
 {
     get
     {
         IEndpoint endpoint;
         if (!_endpoints.TryGetValue(endpointName, out endpoint))
         {
             throw new EndpointNotFoundException(endpointName);
         }
         return endpoint;
     }
 }
Exemplo n.º 20
0
        void StaticEndpointMapping(EndpointConfiguration endpointConfiguration)
        {
            #region Routing-StaticEndpointMapping

            EndpointName sales = new EndpointName("Sales");
            endpointConfiguration.Routing().EndpointInstances
            .AddStatic(sales,
                       new EndpointInstance(sales, "1", null),
                       new EndpointInstance(sales, "2", null));

            #endregion
        }
Exemplo n.º 21
0
        void StaticEndpointMapping(EndpointConfiguration endpointConfiguration)
        {
            #region Routing-StaticEndpointMapping

            EndpointName sales = new EndpointName("Sales");
            endpointConfiguration.UnicastRouting().Mapping.Physical
            .Add(sales,
                 new EndpointInstance(sales, "1", null),
                 new EndpointInstance(sales, "2", null));

            #endregion
        }
Exemplo n.º 22
0
 /// <summary>
 /// Adds a named endpoint to the configuration
 /// </summary>
 /// <param name="name">The name of the endpoint</param>
 /// <param name="endpoint">The endpoint</param>
 /// <remarks>
 /// Named endpoints must be added before messages can be sent or
 /// subscriptions can be created
 /// </remarks>
 /// <exception cref="ArgumentNullException">Thrown if either argument
 /// is <c>null</c></exception>
 public virtual void AddEndpoint(EndpointName name, IEndpoint endpoint)
 {
     if (name == null)
     {
         throw new ArgumentNullException(nameof(name));
     }
     if (endpoint == null)
     {
         throw new ArgumentNullException(nameof(endpoint));
     }
     _endpoints.Add(name, endpoint);
 }
        public static EndpointMetaAttribute GetAttribute(EndpointName enumValue)
        {
#if NETSTANDARD1_3
            Type   type = enumValue.GetType();
            string name = Enum.GetName(type, enumValue);
            return(type.GetRuntimeField(name).GetCustomAttribute <EndpointMetaAttribute>());
#else
            Type   type = enumValue.GetType();
            string name = Enum.GetName(type, enumValue);
            return(type.GetField(name).GetCustomAttribute <EndpointMetaAttribute>());
#endif
        }
Exemplo n.º 24
0
        public async stt::Task UpdateEndpointAsync()
        {
            moq::Mock <EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock <EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            UpdateEndpointRequest request = new UpdateEndpointRequest
            {
                Endpoint   = new Endpoint(),
                UpdateMask = new wkt::FieldMask(),
            };
            Endpoint expectedResponse = new Endpoint
            {
                EndpointName   = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
                DisplayName    = "display_name137f65c2",
                Description    = "description2cf9da67",
                DeployedModels =
                {
                    new DeployedModel(),
                },
                TrafficSplit =
                {
                    {
                        "key8a0b6e3c",
                        1623286560
                    },
                },
                Etag   = "etage8ad7218",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime           = new wkt::Timestamp(),
                UpdateTime           = new wkt::Timestamp(),
                EncryptionSpec       = new EncryptionSpec(),
                NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
                ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
                EnablePrivateServiceConnect = false,
            };

            mockGrpcClient.Setup(x => x.UpdateEndpointAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            EndpointServiceClient client  = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
            Endpoint responseCallSettings = await client.UpdateEndpointAsync(request.Endpoint, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Endpoint responseCancellationToken = await client.UpdateEndpointAsync(request.Endpoint, request.UpdateMask, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 25
0
 /// <summary>Snippet for Predict</summary>
 public void PredictResourceNames()
 {
     // Snippet: Predict(EndpointName, IEnumerable<Value>, Value, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     EndpointName        endpoint  = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
     IEnumerable <Value> instances = new Value[] { new Value(), };
     Value parameters = new Value();
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(endpoint, instances, parameters);
     // End snippet
 }
        public void JsonPaths_ReturnsExpectedResults()
        {
            foreach (KeyValuePair <EndpointName, string> mapping in ExpectedJsonPaths)
            {
                EndpointName endpointName     = mapping.Key;
                string       expectedJsonPath = mapping.Value;

                var    pipelineContext = new GetContext <TestEntity>(mapping.Key, null);
                string actualJsonPath  = pipelineContext.JsonPath();

                Assert.AreEqual(expectedJsonPath, actualJsonPath);
            }
        }
        /// <summary>Snippet for GetEndpointAsync</summary>
        public async Task GetEndpointResourceNamesAsync()
        {
            // Snippet: GetEndpointAsync(EndpointName, CallSettings)
            // Additional: GetEndpointAsync(EndpointName, CancellationToken)
            // Create client
            IDSClient iDSClient = await IDSClient.CreateAsync();

            // Initialize request argument(s)
            EndpointName name = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
            // Make the request
            Endpoint response = await iDSClient.GetEndpointAsync(name);

            // End snippet
        }
Exemplo n.º 28
0
    public void DeleteEndpoint(
        string projectId   = "my-project",
        string locationId  = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId   = "test-service",
        string endpointId  = "test-endpoint")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var endpointName = EndpointName.FromProjectLocationNamespaceServiceEndpoint(projectId, locationId, namespaceId, serviceId, endpointId);

        registrationServiceClient.DeleteEndpoint(endpointName);
    }
 /// <summary>Snippet for GetEndpoint</summary>
 public void GetEndpointRequestObject()
 {
     // Snippet: GetEndpoint(GetEndpointRequest, CallSettings)
     // Create client
     IDSClient iDSClient = IDSClient.Create();
     // Initialize request argument(s)
     GetEndpointRequest request = new GetEndpointRequest
     {
         EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
     };
     // Make the request
     Endpoint response = iDSClient.GetEndpoint(request);
     // End snippet
 }
Exemplo n.º 30
0
        /// <summary>
        /// Retrieves entities from TSheets via an HTTP GET call to the API endpoint.
        /// </summary>
        /// <param name="endpointName">The name of the endpoint, <see cref="EndpointName"/></param>
        /// <param name="filters">The key-value pairs to be sent as URL request parameters.</param>
        /// <param name="logContext">Call-specific contextual information for logging purposes.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>The serialized response of the API method call.</returns>
        public async Task <string> GetAsync(
            EndpointName endpointName,
            Dictionary <string, string> filters,
            LogContext logContext,
            CancellationToken cancellationToken)
        {
            Uri requestUri = CreateRequestUri(endpointName, filters);

            LogMethodCall(MethodType.Get, requestUri, logContext);

            HttpResponseMessage response = await this.httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);

            return(ProcessResponse(response, logContext, MethodType.Get));
        }
 /// <summary>Snippet for RawPredict</summary>
 public void RawPredictRequestObject()
 {
     // Snippet: RawPredict(RawPredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     RawPredictRequest request = new RawPredictRequest
     {
         EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
         HttpBody = new HttpBody(),
     };
     // Make the request
     HttpBody response = predictionServiceClient.RawPredict(request);
     // End snippet
 }
        /// <summary>Snippet for RawPredictAsync</summary>
        public async Task RawPredictResourceNamesAsync()
        {
            // Snippet: RawPredictAsync(EndpointName, HttpBody, CallSettings)
            // Additional: RawPredictAsync(EndpointName, HttpBody, CancellationToken)
            // Create client
            PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync();

            // Initialize request argument(s)
            EndpointName endpoint = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
            HttpBody     httpBody = new HttpBody();
            // Make the request
            HttpBody response = await predictionServiceClient.RawPredictAsync(endpoint, httpBody);

            // End snippet
        }
Exemplo n.º 33
0
        /// <summary>
        /// Updates entities in TSheets via an HTTP PUT call to the API endpoint.
        /// </summary>
        /// <param name="endpointName">The name of the endpoint, <see cref="EndpointName"/></param>
        /// <param name="requestData">The content to be sent in the body of the request.</param>
        /// <param name="logContext">Call-specific contextual information for logging purposes.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>The serialized response of the API method call.</returns>
        public async Task <string> UpdateAsync(
            EndpointName endpointName,
            string requestData,
            LogContext logContext,
            CancellationToken cancellationToken)
        {
            Uri requestUri = CreateRequestUri(endpointName);

            LogMethodCall(MethodType.Put, requestUri, logContext, requestData);

            HttpContent         content  = new StringContent(requestData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await this.httpClient.PutAsync(requestUri, content, cancellationToken).ConfigureAwait(false);

            return(ProcessResponse(response, logContext, MethodType.Put));
        }
        public override void Initialize()
        {
            base.Initialize();

            this.endpointName = EndpointName.Tests;
            this.inputData    = "{ \"input\": \"data\" }";
            this.inputFilter  = new Dictionary <string, string> {
                { "ids", "1,2,3" }
            };
            this.deleteIds = new List <int> {
                1, 2, 3
            };
            this.logContext     = new LogContext();
            this.mockRestClient = new Mock <IRestClient>();
        }
Exemplo n.º 35
0
        public void GetEndpointResourceNames()
        {
            moq::Mock <EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock <EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetEndpointRequest request = new GetEndpointRequest
            {
                EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
            };
            Endpoint expectedResponse = new Endpoint
            {
                EndpointName   = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
                DisplayName    = "display_name137f65c2",
                Description    = "description2cf9da67",
                DeployedModels =
                {
                    new DeployedModel(),
                },
                TrafficSplit =
                {
                    {
                        "key8a0b6e3c",
                        1623286560
                    },
                },
                Etag   = "etage8ad7218",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime           = new wkt::Timestamp(),
                UpdateTime           = new wkt::Timestamp(),
                EncryptionSpec       = new EncryptionSpec(),
                NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
                ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
                EnablePrivateServiceConnect = false,
            };

            mockGrpcClient.Setup(x => x.GetEndpoint(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
            Endpoint response            = client.GetEndpoint(request.EndpointName);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public async stt::Task GetEndpointRequestObjectAsync()
        {
            moq::Mock <EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock <EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetEndpointRequest request = new GetEndpointRequest
            {
                EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
            };
            Endpoint expectedResponse = new Endpoint
            {
                EndpointName   = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
                DisplayName    = "display_name137f65c2",
                Description    = "description2cf9da67",
                DeployedModels =
                {
                    new DeployedModel(),
                },
                TrafficSplit =
                {
                    {
                        "key8a0b6e3c",
                        1623286560
                    },
                },
                Etag   = "etage8ad7218",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime     = new wkt::Timestamp(),
                UpdateTime     = new wkt::Timestamp(),
                EncryptionSpec = new EncryptionSpec(),
            };

            mockGrpcClient.Setup(x => x.GetEndpointAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            EndpointServiceClient client  = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
            Endpoint responseCallSettings = await client.GetEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Endpoint responseCancellationToken = await client.GetEndpointAsync(request, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
        /// <summary>Snippet for ListConnectionsAsync</summary>
        public async Task ListConnectionsRequestObjectAsync()
        {
            // Snippet: ListConnectionsAsync(ListConnectionsRequest, CallSettings)
            // Create client
            ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync();

            // Initialize request argument(s)
            ListConnectionsRequest request = new ListConnectionsRequest
            {
                ParentAsEndpointName = EndpointName.FromProjectEndpoint("[PROJECT]", "[ENDPOINT]"),
            };
            // Make the request
            PagedAsyncEnumerable <ListConnectionsResponse, Connection> response = connectionServiceClient.ListConnectionsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Connection item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListConnectionsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Connection item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <Connection> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Connection item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Exemplo n.º 38
0
 /// <summary>Snippet for Predict</summary>
 public void PredictRequestObject()
 {
     // Snippet: Predict(PredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
         Instances  = { new Value(), },
         Parameters = new Value(),
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
     // End snippet
 }
Exemplo n.º 39
0
 public void DynamicEndpointMapping()
 {
     var busConfig = new BusConfiguration();
     #region Routing-DynamicEndpointMapping
     EndpointName sales = new EndpointName("Sales");
     busConfig.Routing().EndpointInstances.AddDynamic(e =>
     {
         if (e.ToString().StartsWith("Sales"))
         {
             return new[]
             {
                 new EndpointInstanceName(e, "1", "MachineA"),
                 new EndpointInstanceName(e, "2", "MachineB")
             };
         }
         return null;
     });
     #endregion
 }
        private IEndpoint GetEndpoint(EndpointName endpointName, HttpContext context)
        {
            if (_options.Endpoints.IsEndpointEnabled(endpointName))
            {
                var mapping = _mappings.Where(x => x.Endpoint == endpointName).LastOrDefault();
                if (mapping != null)
                {
                    _logger.LogDebug("Mapping found for endpoint: {0}, creating handler: {1}", endpointName, mapping.Handler.FullName);
                    return context.RequestServices.GetService(mapping.Handler) as IEndpoint;
                }
                else
                {
                    _logger.LogError("No mapping found for endpoint: {0}", endpointName);
                }
            }
            else
            {
                _logger.LogWarning("{0} endpoint requested, but is diabled in endpoint options.", endpointName);
            }

            return null;
        }
 public static bool IsEndpointEnabled(this EndpointsOptions options, EndpointName endpointName)
 {
     switch (endpointName)
     {
         case EndpointName.Authorize:
             return options.EnableAuthorizeEndpoint;
         case EndpointName.CheckSession:
             return options.EnableCheckSessionEndpoint;
         case EndpointName.Discovery:
             return options.EnableDiscoveryEndpoint;
         case EndpointName.EndSession:
             return options.EnableEndSessionEndpoint;
         case EndpointName.Introspection:
             return options.EnableIntrospectionEndpoint;
         case EndpointName.Revocation:
             return options.EnableTokenRevocationEndpoint;
         case EndpointName.Token:
             return options.EnableTokenEndpoint;
         case EndpointName.UserInfo:
             return options.EnableUserInfoEndpoint;
         default:
             return false;
     }
 }
 /// <summary>
 /// Initializes a serialized <see cref="EndpointAlreadyExistsException"/>
 /// from a streaming context.
 /// </summary>
 /// <param name="info">The serialization info</param>
 /// <param name="context">The streaming context</param>
 public EndpointAlreadyExistsException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     _endpoint = info.GetString("Endpoint");
 }
Exemplo n.º 43
0
 /// <summary>
 /// Adds a named endpoint to the configuration
 /// </summary>
 /// <param name="name">The name of the endpoint</param>
 /// <param name="endpoint">The endpoint</param>
 /// <remarks>
 /// Named endpoints must be added before messages can be sent or
 /// subscriptions can be created
 /// </remarks>
 /// <exception cref="ArgumentNullException">Thrown if either argument
 /// is <c>null</c></exception>
 public void AddEndpoint(EndpointName name, IEndpoint endpoint)
 {
     if (name == null) throw new ArgumentNullException("name");
     if (endpoint == null) throw new ArgumentNullException("endpoint");
     _endpoints.Add(name, endpoint);
 }
Exemplo n.º 44
0
        /// <summary>
        ///     Sends <paramref name="content" /> to a single caller-specified
        ///     <paramref name="endpointName" />.
        /// </summary>
        /// <param name="content">The message to send.</param>
        /// <param name="endpointName">The name of the endpoint to which the message should be sent.</param>
        /// <param name="options">Optional settings that influence how the message is sent.</param>
        /// <param name="cancellationToken">An optional cancellation token</param>
        public async Task<ISentMessage> Send(object content, EndpointName endpointName,
            SendOptions options = default(SendOptions), CancellationToken cancellationToken = default(CancellationToken))
        {
            CheckDisposed();

            if (content == null) throw new ArgumentNullException("content");
            if (endpointName == null) throw new ArgumentNullException("endpointName");

            var endpoint = _endpoints[endpointName];
            var credentials = endpoint.Credentials;
            var headers = new MessageHeaders
            {
                Destination = endpoint.Address
            };
            var message = BuildMessage(content, headers, options);

            Log.DebugFormat("Sending message ID {0} to endpoint \"{1}\" ({2})...",
                message.Headers.MessageId, endpointName, endpoint.Address);

            // Create the sent message before transporting it in order to ensure that the
            // reply stream is cached before any replies arrive.
            var sentMessage = _replyHub.CreateSentMessage(message);
            await _transportService.SendMessage(message, credentials, cancellationToken);
            return sentMessage;
        }
 private Dictionary<EndpointName, HashSet<EndpointInstanceName>> BuildNewInstanceMap(EndpointName endpointName, EndpointInstanceName instanceName)
 {
     var newInstanceMap = new Dictionary<EndpointName, HashSet<EndpointInstanceName>>();
     foreach (var pair in instanceMap)
     {
         var otherInstances = pair.Value.Where(x => x != instanceName);
         newInstanceMap[pair.Key] = new HashSet<EndpointInstanceName>(otherInstances);
     }
     HashSet<EndpointInstanceName> endpointEntry;
     if (!newInstanceMap.TryGetValue(endpointName, out endpointEntry))
     {
         endpointEntry = new HashSet<EndpointInstanceName>();
         newInstanceMap[endpointName] = endpointEntry;
     }
     endpointEntry.Add(instanceName);
     return newInstanceMap;
 }
 private Task UpdateCaches(EndpointName endpointName, EndpointInstanceName instanceName, Type[] types)
 {
     instanceMap = BuildNewInstanceMap(endpointName, instanceName);
     endpointMap = BuildNewEndpointMap(endpointName, types);
     return Task.FromResult(0);
 }
        private Dictionary<Type, HashSet<EndpointName>> BuildNewEndpointMap(EndpointName endpointName, Type[] types)
        {
            var newEndpointMap = new Dictionary<Type, HashSet<EndpointName>>();
            foreach (var pair in endpointMap)
            {
                var otherEndpoints = pair.Value.Where(x => x != endpointName);
                newEndpointMap[pair.Key] = new HashSet<EndpointName>(otherEndpoints);
            }

            foreach (var type in types)
            {
                HashSet<EndpointName> typeEntry;
                if (!newEndpointMap.TryGetValue(type, out typeEntry))
                {
                    typeEntry = new HashSet<EndpointName>();
                    newEndpointMap[type] = typeEntry;
                }
                typeEntry.Add(endpointName);
            }
            return newEndpointMap;
        }
Exemplo n.º 48
0
 /// <summary>
 /// Initializes a new <see cref="EndpointNotFoundException"/> for the
 /// specified <paramref name="endpoint"/> name
 /// </summary>
 /// <param name="endpoint">The name of the endpoint that could not be
 /// found</param>
 public EndpointNotFoundException(EndpointName endpoint) : base(endpoint)
 {
     _endpoint = endpoint;
 }
 private IEnumerable<EndpointInstanceName> FindInstances(EndpointName endpointName)
 {
     HashSet<EndpointInstanceName> instances;
     if (instanceMap.TryGetValue(endpointName, out instances))
     {
         var activeInstances =
             instances.Where(i => instanceInformation[i].State == InstanceState.Active).ToArray();
         if (activeInstances.Any())
         {
             return activeInstances;
         }
         Logger.InfoFormat("No active instances of endpoint {0} detected. Trying to route to the inactive ones.", endpointName);
         return instances;
     }
     return Enumerable.Empty<EndpointInstanceName>();
 }
 /// <summary>
 /// Initializes a new <see cref="EndpointAlreadyExistsException"/> with
 /// the specified <paramref name="endpoint"/>
 /// </summary>
 /// <param name="endpoint">The endpoint name that already exists</param>
 public EndpointAlreadyExistsException(EndpointName endpoint)
 {
     _endpoint = endpoint;
 }
Exemplo n.º 51
0
 // ReSharper disable once ConvertClosureToMethodGroup
 public void TransportAddressRules()
 {
     var busConfig = new BusConfiguration();
     #region Routing-TransportAddressRule
     EndpointName sales = new EndpointName("Sales");
     busConfig.Routing().TransportAddresses.AddRule(i => CustomTranslationRule(i));
     #endregion
 }
Exemplo n.º 52
0
 public void SpecialCaseTransportAddress()
 {
     var busConfig = new BusConfiguration();
     #region Routing-SpecialCaseTransportAddress
     EndpointName sales = new EndpointName("Sales");
     busConfig.Routing().TransportAddresses.AddException(new EndpointInstanceName(sales, "1", null), "Sales-One@MachineA");
     #endregion
 }
        protected override async Task OnStart(IBusContext context)
        {
            var routingTable = settings.Get<UnicastRoutingTable>();
            var endpointInstances = settings.Get<EndpointInstances>();

            routingTable.AddDynamic((list, bag) => FindDestination(list));
            endpointInstances.AddDynamic(FindInstances);
           
            subscription = await dataBackplane.GetAllAndSubscribeToChanges("NServiceBus.HandledMessages",
                async e =>
                {
                    var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data);
                    var endpointName = new EndpointName(deserializedData.EndpointName);
                    var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator, deserializedData.TransportDiscriminator);

                    var types =
                        deserializedData.HandledMessageTypes.Select(x => Type.GetType(x, false))
                            .Where(x => x != null)
                            .ToArray();

                    EndpointInstanceInfo instanceInfo;
                    if (!instanceInformation.TryGetValue(instanceName, out instanceInfo))
                    {
                        var newInstanceInformation = new Dictionary<EndpointInstanceName, EndpointInstanceInfo>(instanceInformation);
                        instanceInfo = new EndpointInstanceInfo();
                        newInstanceInformation[instanceName] = instanceInfo;
                        instanceInformation = newInstanceInformation;
                    }
                    if (deserializedData.Active)
                    {
                        instanceInfo.Activate(deserializedData.Timestamp);
                        Logger.InfoFormat("Instance {0} active (heartbeat).", instanceName);
                    }
                    else
                    {
                        instanceInfo.Deactivate();
                        Logger.InfoFormat("Instance {0} deactivated.", instanceName);
                    }
                    await UpdateCaches(endpointName, instanceName, types);
                }, 
                async e =>
                {

                    var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data);
                    var endpointName = new EndpointName(deserializedData.EndpointName);
                    var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator,
                        deserializedData.TransportDiscriminator);

                    Logger.InfoFormat("Instance {0} removed from routing tables.", instanceName);

                    await UpdateCaches(endpointName, instanceName, new Type[0]);

                    instanceInformation.Remove(instanceName);
                });
            sweepTimer = new Timer(state =>
            {
                foreach (var info in instanceInformation)
                {
                    if (!info.Value.Sweep(DateTime.UtcNow, heartbeatTimeout))
                    {
                        Logger.InfoFormat("Instance {0} deactivated (heartbeat timeout).", info.Key);
                    }
                }
            }, null, sweepPeriod, sweepPeriod);
        }