Пример #1
0
 internal static RequestDelegate ShareMyData(RequestDelegate next)
 {
     return(async ctx =>
     {
         var navigations = NavigationApiMiddleWare.GetNavigationsFromAssembly <Navigation>().ToList();
         if (navigations.HasAny())
         {
             try
             {
                 var url = Microservice.Of("Hub").Url("local-setup");
                 navigations.Do(r => r.Define());
                 new WebClient().UploadString(url, Newtonsoft.Json.JsonConvert.SerializeObject(new
                 {
                     Service = GetService(),
                     BoardSources = GetBoardSources(navigations),
                     Features = GetFeatures(navigations),
                     GlobalySearchable = GetControllerFromAssembly <Olive.GlobalSearch.SearchSource>().HasAny()
                 }));
                 Shared = true;
             }
             catch (Exception ex)
             {
                 Log.For(typeof(DevelopmentShareInfo)).Error("With URL: " + Microservice.Of("Hub").Url("local-setup") + "\nCould not reach local hub.\n" + ex);
             }
         }
         await next(ctx);
     });
 }
Пример #2
0
 public void Constructor_WithEmptyFeatureInstances_ThrowsException()
 {
     Assert.Throws <ArgumentException>(() =>
     {
         var sot = new Microservice(Enumerable.Empty <FeatureInstance>());
     });
 }
Пример #3
0
        public void OpenAndStartServiceHostTestWithSB()
        {
            var host = getMicroserviceHostWithTableStorage();

            Microservice service = new Microservice();

            service.InputArgument = new Daenet.DurableTaskMicroservices.Tests.TestOrchestrationInput()
            {
                Counter = 2,
                Delay   = 1000,
            };

            service.OrchestrationQName = typeof(CounterOrchestration).AssemblyQualifiedName;

            service.ActivityQNames = new string[] {
                typeof(Task1).AssemblyQualifiedName, typeof(Task2).AssemblyQualifiedName,
            };

            host.LoadService(service);

            host.OpenAsync().Wait();

            // This is client side code.
            var instance = host.StartServiceAsync(service.OrchestrationQName, service.InputArgument).Result;

            Debug.WriteLine($"Microservice instance {instance.OrchestrationInstance.InstanceId} started");

            host.WaitOnInstanceAsync(instance).Wait();
        }
        private void lstItemsMicroservice_SelectedIndexChanged(object sender, EventArgs e)
        {
            Microservice microservice = (Microservice)lstItemsMicroservice.SelectedItem;

            _selectedMicroserviceId = microservice != null ? microservice.Id : 0;
            lblDescricao.Text       = microservice != null ? microservice.Description : "";
        }
Пример #5
0
        public void Initialise()
        {
            mService = new Microservice();

            //mService.
            mService.Start();
        }
        private void waitOnInstance(ServiceHost host, Microservice service, MicroserviceInstance instance)
        {
            ManualResetEvent mEvent = new ManualResetEvent(false);

            new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(1000);

                        var cnt = host.GetNumOfRunningInstances(service);

                        if (cnt == 0)
                        {
                            mEvent.Set();
                            Debug.WriteLine($"Microservice instance {instance.OrchestrationInstance.InstanceId} completed.");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        mEvent.Set();
                        Assert.Fail(ex.Message);
                    }
                }
            }).Start();


            mEvent.WaitOne();
        }
Пример #7
0
        /// <summary>
        /// Tries to decompose an event identifier <see cref="string"/> to its components.
        /// </summary>
        /// <param name="eventIdentifier">The event identifier <see cref="string"/>.</param>
        /// <param name="microservice">When this method returns, the <see cref="Microservice"/> that committed the event.</param>
        /// <param name="tenant">When this method returns, the <see cref="TenantId"/> that committed the event.</param>
        /// <param name="sequenceNumber">When this method returns, the <see cref="EventLogSequenceNumber"/> of the event that was committed.</param>
        /// <returns><c>true</c> if the deomposition was successful; otherwise, <c>false</c>.</returns>
        public static bool TryDecompose(string eventIdentifier, out Microservice microservice, out TenantId tenant, out EventLogSequenceNumber sequenceNumber)
        {
            var decoded = new Span <byte>(new byte[40]);

            if (Convert.TryFromBase64String(eventIdentifier, decoded, out var read) && read == 40)
            {
                var microserviceBytes   = decoded.Slice(0, 16);
                var tenantBytes         = decoded.Slice(16, 16);
                var sequenceNumberBytes = decoded.Slice(32, 8);

                if (!BitConverter.IsLittleEndian)
                {
                    sequenceNumberBytes.Reverse();
                }

                microservice   = new Guid(microserviceBytes);
                tenant         = new Guid(tenantBytes);
                sequenceNumber = BitConverter.ToUInt64(sequenceNumberBytes);

                return(true);
            }

            microservice   = null;
            tenant         = null;
            sequenceNumber = 0;
            return(false);
        }
        public void OpenAndStartServiceHostTest()
        {
            var host = createMicroserviceHost();

            Microservice service = new Microservice();

            service.InputArgument = new TestOrchestrationInput()
            {
                Counter = 3,
                Delay   = 1000,
            };

            service.OrchestrationQName = typeof(CounterOrchestration).AssemblyQualifiedName;

            service.ActivityQNames = new string[] {
                typeof(Task1).AssemblyQualifiedName, typeof(Task2).AssemblyQualifiedName,
            };

            host.LoadService(service);

            host.Open();

            // This is client side code.
            var instance = host.StartService(service.OrchestrationQName, service.InputArgument);

            Debug.WriteLine($"Microservice instance {instance.OrchestrationInstance.InstanceId} started");

            waitOnInstance(host, service, instance);
        }
Пример #9
0
        private static void runSample1()
        {
            ServiceHost host = new ServiceHost(m_ServiceBusConnectionString, m_StorageConnectionString, nameof(runSample1));

            Microservice microSvc = new Microservice();

            #region How to create Config automatically?
            //microSvc.InputArgument = new CounterOrchestrationInput() { Counter = 1, Delay = 2 };

            //xmlSerializeService(microSvc, "c:\\temp\\aaa.xml");
            #endregion

            var instances = host.LoadServiceFromXml("counterorchestration.config.xml",
                                                    new List <Type>()
            {
                typeof(CounterOrchestrationInput)
            }, out microSvc);

            host.Open();

            var instance = host.StartService(microSvc.OrchestrationQName, microSvc.InputArgument);

            Debug.WriteLine($"Microservice instance {instance.OrchestrationInstance.InstanceId} started");

            waitOnInstance(host, microSvc, instance);
        }
Пример #10
0
 public MicroserviceTests()
 {
     _instances        = new Dictionary <Uri, IMicroserviceInstance>();
     _metricDictionary = new Dictionary <MetricType, IInstanceMetric>();
     _servicesNames    = new List <string>();
     _sut = new Microservice(MicroserviceName, _servicesNames, _instances);
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExecutionContextManager"/> class.
 /// </summary>
 /// <param name="logger"><see cref="ILogger"/> for logging.</param>
 public ExecutionContextManager(ILogger logger)
 {
     _logger       = logger;
     _microservice = Microservice.NotSet;
     _version      = Version.NotSet;
     _environment  = Environment.Undetermined;
 }
Пример #12
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(x => x.AddPolicy("AllowHubOrigin",
                                              f => f.WithOrigins(Microservice.Of("Hub").Url().TrimEnd("/"), HubDevUrl)
                                              .AllowAnyHeader().AllowAnyMethod().AllowCredentials()));

            base.ConfigureServices(services);
        }
 private JObject WriteMicroservice(Microservice microservice)
 {
     return(new JObject(
                new JProperty("id", new JValue(microservice.Id.ToString())),
                new JProperty("name", new JValue(microservice.Id.ToString())),
                new JProperty("features", new JArray(microservice.Select(WriteFeature)))
                ));
 }
Пример #14
0
        public void SerializeJsonConfigTest(string fileName)
        {
            Microservice service = getMicroService();

            string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(service);

            File.WriteAllText(GetPathForFile(fileName), jsonString);
        }
Пример #15
0
        public void When_passed_name_to_constructor_then_instances_should_be_empty()
        {
            // Act
            _sut = new Microservice(MicroserviceName);

            // Assert
            Assert.NotNull(_sut.GetInstances());
            Assert.Empty(_sut.GetInstances());
        }
Пример #16
0
        public void ServiceUrlWithoutPortTest()
        {
            var service = new Microservice()
            {
                DomainName = "http://localhost"
            };

            Assert.AreEqual("http://localhost", service.ServiceUrl);
        }
Пример #17
0
        public void GatewayBaseUrlTest()
        {
            var service = new Microservice()
            {
                Prefix = "Authentication"
            };

            Assert.IsTrue(service.GatewayBaseUrl.EndsWith("Authentication", StringComparison.Ordinal));
        }
Пример #18
0
 /// <inheritdoc/>
 public void SetConstants(
     Microservice microservice,
     Version version,
     Environment environment)
 {
     _microservice = microservice;
     _version      = version;
     _environment  = environment;
 }
Пример #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SubscriptionId"/> class.
 /// </summary>
 /// <param name="consumerTenant">The consumer <see cref="TenantId" />.</param>
 /// <param name="producerMicroservice">The producer <see cref="Microservice" />.</param>
 /// <param name="producerTenant">The producer <see cref="TenantId" />.</param>
 /// <param name="scope">The <see cref="Events.Store.ScopeId" />.</param>
 /// <param name="stream">The public <see cref="Events.Store.Streams.StreamId" /> to subscribe to.</param>
 /// <param name="partition">The <see cref="Events.Store.Streams.PartitionId" /> in the stream to subscribe to.</param>
 public SubscriptionId(TenantId consumerTenant, Microservice producerMicroservice, TenantId producerTenant, ScopeId scope, StreamId stream, PartitionId partition)
 {
     ConsumerTenantId       = consumerTenant;
     ProducerMicroserviceId = producerMicroservice;
     ProducerTenantId       = producerTenant;
     ScopeId     = scope;
     StreamId    = stream;
     PartitionId = partition;
 }
Пример #20
0
        public override void ConfigureServices(IServiceCollection services)
        {
            Configuration.MergeEnvironmentVariables();
            services.AddCors(x => x.AddPolicy("AllowHubOrigin",
                                              f => f.WithOrigins(Microservice.Of("Hub").Url().TrimEnd("/"), HubDevUrl)
                                              .SetIsOriginAllowed(x => true)
                                              .AllowAnyHeader().AllowAnyMethod().AllowCredentials()));

            base.ConfigureServices(services);
        }
Пример #21
0
        static void Main(string[] args)
        {
            Serilog.Log.Logger = LoggerConfiguration.ConfigureLogger();

            AppDomain.CurrentDomain.ProcessExit += ProcessExit;

            Microservice.StartAsync <Startup>(cancellationTokenSource.Token).Wait();

            Serilog.Log.Logger.Information("Process Exited");
        }
Пример #22
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         Container?.Dispose();
         Microservice?.Dispose();
         FirstChanceExceptionListener?.Dispose();
         UnhandledExceptionListener?.Dispose();
     }
 }
Пример #23
0
        public void Delete(int microserviceId)
        {
            CustomerMicroserviceService customerMicroserviceService = new CustomerMicroserviceService();

            customerMicroserviceService.DeleteMicroservicesByMicroserviceId(microserviceId);

            Microservice microservice = GetById(microserviceId);

            _microserviceRepository.Delete(microservice);
        }
        public static async Task StartServiceAsync(this ServiceHost host, string orchestrationQualifiedName,
                                                   OrchestrationInput inputArgs, string activityId)
        {
            var tp = Type.GetType(orchestrationQualifiedName);

            if (tp == null)
            {
                throw new ArgumentException(String.Format("Cannot lookup type '{0} ", orchestrationQualifiedName));
            }

            Microservice config = ServiceHost.GetServiceConfiguration(String.Empty, tp);

            var svcCfg = config.ServiceConfiguration as OrchestrationConfig;

            if (svcCfg == null)
            {
                throw new ArgumentException(String.Format("Specified orchestration configuration is not of type 'OrchestrationConfig'. Failed by starting of '{1}' - Specified (invalid) configuration type: '{2}'.", orchestrationQualifiedName, config));
            }

            if (!String.IsNullOrEmpty(svcCfg.LogTraceSourceName))
            {
                foreach (var item in config.ActivityConfiguration)
                {
                    TaskConfig cfg = item.Value as TaskConfig;

                    //
                    // We can have configuration, which is not of type of TaskConfig.
                    if (cfg != null)
                    {
                        if (String.IsNullOrEmpty(cfg.LogTraceSourceName))
                        {
                            cfg.LogTraceSourceName = svcCfg.LogTraceSourceName;
                        }
                    }
                }
            }

            //
            // Generate new Guid if not set
            if (String.IsNullOrEmpty(activityId))
            {
                activityId = Guid.NewGuid().ToString();
            }

            inputArgs.Context = new Dictionary <string, object>();
            var logCtx = new LoggingContext();

            logCtx.LoggingScopes = new Dictionary <string, string>();
            logCtx.LoggingScopes.Add("ActivityId", activityId);
            inputArgs.Context.Add("Orchestration", config.Type.FullName);
            inputArgs.Context.Add("ParentLoggingContext", logCtx);


            await host.StartServiceAsync(orchestrationQualifiedName, inputArgs);
        }
Пример #25
0
        public void MicroserviceValidationTest()
        {
            var service = new Microservice()
            {
                Endpoints = null
            };

            var result = service.Validate();

            Assert.IsFalse(result);
        }
Пример #26
0
        public void MicroserviceWithoutEndpointsTest()
        {
            var service = new Microservice()
            {
                Endpoints = new List <Endpoint>()
            };

            var result = service.Validate();

            Assert.IsFalse(result);
        }
Пример #27
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var permittedUrls = Config.Get("PermittedDomains").Split(",").Union(Microservice.Of("Hub").Url()).Select(d => d.TrimEnd("/")).Union(HubDevUrl).ToArray();

            Configuration.MergeEnvironmentVariables();
            services.AddCors(x => x.AddPolicy("AllowHubOrigin",
                                              f => f.WithOrigins(permittedUrls)
                                              .SetIsOriginAllowed(x => true)
                                              .AllowAnyHeader().AllowAnyMethod().AllowCredentials()));

            base.ConfigureServices(services);
        }
Пример #28
0
        public ActionResult <IList <Microservice> > Add(Microservice service)
        {
            var result = this.serviceManager.Register(service);

            if (result)
            {
                return(Ok(service));
            }
            else
            {
                return(BadRequest());
            }
        }
Пример #29
0
        public void ToString_Returns_NonEmptyString()
        {
            var aProperties      = new[] { new Property(new PropertyIdentifier("p1"), "p1") };
            var bProperties      = new[] { new Property(new PropertyIdentifier("p2"), "p2") };
            var featureInstances = new[]
            {
                new FeatureInstance(new Feature(new FeatureIdentifier("a"), "a", aProperties), aProperties.Select(p => p.Id)),
                new FeatureInstance(new Feature(new FeatureIdentifier("b"), "b", bProperties), bProperties.Select(p => p.Id))
            };
            var microservice = new Microservice(featureInstances);

            Assert.False(string.IsNullOrEmpty(microservice.ToString()));
        }
 private static void serializeService(Microservice svc)
 {
     using (XmlWriter writer = XmlWriter.Create("abc.xml", new XmlWriterSettings()
     {
         Indent = true
     }))
     {
         DataContractSerializerSettings sett = new DataContractSerializerSettings();
         DataContractSerializer         ser  = new DataContractSerializer(typeof(Microservice),
                                                                          loadKnownTypes());
         ser.WriteObject(writer, (Microservice)svc);
     }
 }