Exemple #1
0
        internal UnicastBus()
        {
            EnableByDefault();

            Defaults(s =>
            {
/*
 *              string fullPathToStartingExe;
 *              s.SetDefault("NServiceBus.HostInformation.HostId", GenerateDefaultHostId(out fullPathToStartingExe));
 */
                var HostIdSettingsKey     = "NServiceBus.HostInformation.HostId";
                var fullPathToStartingExe = PathUtilities.SanitizedPath(Environment.CommandLine);

                if (!s.HasExplicitValue(HostIdSettingsKey))
                {
                    s.SetDefault(HostIdSettingsKey, DeterministicGuid.Create(fullPathToStartingExe, RuntimeEnvironment.MachineName));
                }

                s.SetDefault("NServiceBus.HostInformation.DisplayName", RuntimeEnvironment.MachineName);
                s.SetDefault("NServiceBus.HostInformation.Properties", new Dictionary <string, string>
                {
                    { "Machine", RuntimeEnvironment.MachineName },
                    { "ProcessID", Process.GetCurrentProcess().Id.ToString() },
                    { "UserName", Environment.UserName },
                    { "PathToExecutable", fullPathToStartingExe }
                });
            });
        }
        public void SameProducesSameGuid(KeyValuePair <string, int> testObject)
        {
            var first  = DeterministicGuid.Create(testObject);
            var second = DeterministicGuid.Create(testObject);

            first.Should().Be(second);
        }
        public void DifferntProduceDifferentGuids(KeyValuePair <string, int> firstObject, KeyValuePair <string, int> secondObject)
        {
            var first  = DeterministicGuid.Create(firstObject);
            var second = DeterministicGuid.Create(secondObject);

            first.Should().NotBe(second);
        }
Exemple #4
0
        public static async Task <string> GetOrCreateEssence(DemographicsDocument document, IDatabaseAsync database)
        {
            var keys = GetKeys(document);

            var results = await Task.WhenAll(keys.Select(key => database.StringGetAsync(key)).ToArray());

            var maybeMatches = results
                               .Zip(keys, (value, key) => new { Key = key, Value = value })
                               .ToLookup(x => x.Value.HasValue);

            var essenceId = maybeMatches[true]
                            .Select(redisValue => (string)redisValue.Value)
                            .GroupBy(_ => _)
                            .OrderByDescending(valueGroup => valueGroup.Count())
                            .Select(valueGroup => valueGroup.Key)
                            .FirstOrDefault();

            essenceId = essenceId ?? EssenceId.Create(document.DocumentId).ToString("N");

            var unmatchedKeys = maybeMatches[false].Select(x => x.Key).ToArray();

            await Task.WhenAll(unmatchedKeys.Select(key => database.StringSetAsync(key, essenceId)));

            return(essenceId);
        }
        public void Customize(BusConfiguration configuration)
        {
            var endpointName = "Case00030984";                                                                          //Hard coded

            var resourceManagerId = DeterministicGuid.Create(endpointName + "-NServiceBus@" + Environment.MachineName); //replaced with copy of version used by NServiceBus

            var programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            var txRecoveryPath  = Path.Combine(programDataPath, "NServiceBus.RavenDB", resourceManagerId.ToString());

            var store = new DocumentStore()
            {
                ConnectionStringName       = "ravendb", //hard coded
                DefaultDatabase            = endpointName,
                ResourceManagerId          = resourceManagerId,
                TransactionRecoveryStorage = new LocalDirectoryTransactionRecoveryStorage(txRecoveryPath)
            };

            store.Initialize();

            var logger = LogManager.GetLogger(endpointName);

            logger.InfoFormat("Recovery path for NServiceBBus raven store: '{0}' set to: '{1}'", store.ResourceManagerId, txRecoveryPath);

            configuration.EndpointName(endpointName);
            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <XmlSerializer>();

            var persistence = configuration.UsePersistence <RavenDBPersistence>().DoNotSetupDatabasePermissions();

            persistence.SetDefaultDocumentStore(store);
        }
Exemple #6
0
        private IEnumerable <object> ScopedHandle(Envelope <MessageContext, object> mainEnvelope)
        {
            var tenantId = mainEnvelope.Header.MetadataLookup["tenantId"].First() as string;

            if (tenantId == null)
            {
                return new[] { new NotHandled(mainEnvelope) }
            }
            ;

            var scopedDispatcher = new Dispatcher();

            scopedDispatcher.Register <WriteToStream>(writeToStream =>
            {
                var envelope = Envelope.Create(mainEnvelope.Header, writeToStream);
                Task.WhenAll(EventStoreHandlers.WriteAsync(envelope, _eventStoreConnection)).Wait();
                return(Enumerable.Empty <object>());
            });

            scopedDispatcher.Register <Envelope <MessageContext, ItemPurchased> >(envelope =>
            {
                var eventId = EventId.Create(mainEnvelope.Header.EventId);
                return(InventoryProjectionHandlers.Project(envelope.Body, eventId, envelope.Header.StreamContext.EventNumber));
            });

            var connectionSettingsFactory = new MultitenantSqlConnectionSettingsFactory(tenantId);
            var connectionStringSettings  = connectionSettingsFactory.GetSettings("Projections");
            var connectionString          = connectionStringSettings.ConnectionString;

            _hasInitialized.GetOrAdd(tenantId, _ =>
            {
                var executor = new SqlCommandExecutor(connectionStringSettings);
                executor.ExecuteNonQuery(InventoryProjectionHandlers.CreateSchema());
                return(Nothing.Value);
            });

            var sqlConnection = new SqlConnection(connectionString);

            sqlConnection.Open();

            using (sqlConnection)
                using (var transaction = sqlConnection.BeginTransaction())
                {
                    var sqlExecutor = new ConnectedTransactionalSqlCommandExecutor(transaction);

                    scopedDispatcher.Register <SqlNonQueryCommand>(command =>
                    {
                        sqlExecutor.ExecuteNonQuery(command);
                        return(Enumerable.Empty <object>());
                    });

                    var typedMainEnvelope = Envelope.CreateGeneric(mainEnvelope.Header, mainEnvelope.Body);
                    var unhandled         = scopedDispatcher.DispatchExhaustive(typedMainEnvelope);

                    transaction.Commit();

                    return(unhandled);
                }
        }
        /// <summary>
        /// The format id.
        /// </summary>
        /// <param name="messageType">
        /// The message type.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string FormatId(MessageType messageType)
        {
            Contract.Requires <ArgumentNullException>(messageType != null, "messageType != null");
            Contract.Ensures(Contract.Result <string>() != null);

            var id = DeterministicGuid.Create(messageType.TypeName, "/", messageType.Version.Major);

            return(string.Format("Subscriptions/{0}", id));
        }
Exemple #8
0
        public void It_allows_to_generate_a_deterministic_id_using_instance_and_host_names()
        {
            var busConfig = new EndpointConfiguration("myendpoint");

            busConfig.UniquelyIdentifyRunningInstance().UsingNames("Instance", "Host");

            var configuredId = busConfig.Settings.Get <HostingComponent.Settings>().HostId;

            Assert.AreEqual(DeterministicGuid.Create("Instance", "Host"), configuredId);
        }
Exemple #9
0
        public static HostInformation CreateDefault()
        {
            var commandLine = Environment.CommandLine;

            var fullPathToStartingExe = commandLine.Split('"')[1];

            var hostId = DeterministicGuid.Create(fullPathToStartingExe, Environment.MachineName);

            return(new HostInformation(hostId, Environment.MachineName, String.Format("{0}", fullPathToStartingExe)));
        }
        static async Task Main(string[] args)
        {
            var instanceName = args.FirstOrDefault();

            if (string.IsNullOrEmpty(instanceName))
            {
                Console.Title = "Destination1";

                instanceName = "destination1";
            }
            else
            {
                Console.Title = $"{instanceName}";
            }

            var instanceId = DeterministicGuid.Create(instanceName);

            var endpointConfiguration = new EndpointConfiguration(instanceName);

            endpointConfiguration.UseTransport <LearningTransport>();
            endpointConfiguration.UsePersistence <LearningPersistence>();
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.UseSerialization <NewtonsoftSerializer>();
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.AuditProcessedMessagesTo("audit");

            // just to show the flexibility
            var recoverability = endpointConfiguration.Recoverability();

            recoverability.Immediate(c => c.NumberOfRetries(3));
            recoverability.Delayed(c => c.NumberOfRetries(2).TimeIncrease(new TimeSpan(2)));

            // this is just here to make it possible to retry a message that went into the error queue
            endpointConfiguration.Notifications.Errors.MessageSentToErrorQueue += (sender, message) =>
            {
                Handler.messageIds.TryAdd(message.MessageId, message.MessageId);
            };

            endpointConfiguration.UniquelyIdentifyRunningInstance()
            .UsingCustomDisplayName(instanceName)
            .UsingCustomIdentifier(instanceId);

            var metrics = endpointConfiguration.EnableMetrics();

            metrics.SendMetricDataToServiceControl(
                "Particular.Monitoring",
                TimeSpan.FromMilliseconds(500)
                );

            var endpoint = await Endpoint.Start(endpointConfiguration);

            Console.WriteLine($"Started {instanceName}");
            Console.ReadLine();
            await endpoint.Stop();
        }
        public void UsingNames()
        {
            var context = new Context();

            Scenario.Define(context)
            .WithEndpoint <UsingNames_Endpoint>(e => e.Given(b => b.SendLocal(new MyMessage())))
            .Done(c => c.HostId != Guid.Empty)
            .Run();

            Assert.AreEqual(DeterministicGuid.Create(instanceName, hostName), context.HostId);
        }
        public DefaultHostIdGenerator(string commandLine, string machineName)
        {
            if (commandLine.StartsWith("\""))
            {
                FullPathToStartingExe = (from Match match in Regex.Matches(commandLine, "\"([^\"]*)\"")
                    select match.ToString()).First().Trim('"');
            }
            else
            {
                FullPathToStartingExe = commandLine.Split(' ').First();
            }

            HostId = DeterministicGuid.Create(FullPathToStartingExe, machineName);
        }
        public Task Configure()
        {
            SagaIdGenerator = new LearningSagaIdGenerator();
            SagaStorage     = new LearningSagaPersister();

            var sagaManifests = new SagaManifestCollection(SagaMetadataCollection,
                                                           Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".sagas"),
                                                           name => DeterministicGuid.Create(name).ToString());

            SynchronizedStorage = new LearningSynchronizedStorage(sagaManifests);

            SynchronizedStorageAdapter = new LearningStorageAdapter();

            return(Task.CompletedTask);
        }
Exemple #14
0
        private async Task <IEnumerable <object> > IndexAndQueryBestMatch(Envelope <MessageContext, DemographicsDocument> envelope)
        {
            var database    = _redisConnection.GetDatabase();
            var transaction = database.CreateTransaction();

            var document = envelope.Body;

            var essenceId = await MatchingHandlers.GetOrCreateEssence(document, transaction);

            var matchedEvent = new DemographicsMatched(document.DocumentId, essenceId);
            var eventId      = EventId.Create(envelope.Header.EventId);
            var writeEvent   = new WriteToStream(eventId, "matched", matchedEvent);

            return(new[] { writeEvent });
        }
Exemple #15
0
        internal static HostInformation CreateHostInformation(string commandLine, string machineName)
        {
            string fullPathToStartingExe;

            if (commandLine.StartsWith("\""))
            {
                fullPathToStartingExe = (from Match match in Regex.Matches(commandLine, "\"([^\"]*)\"")
                                         select match.ToString()).First().Trim('"');
            }
            else
            {
                fullPathToStartingExe = commandLine.Split(' ').First();
            }

            var hostId = DeterministicGuid.Create(fullPathToStartingExe, machineName);

            return(new HostInformation(hostId, machineName, String.Format("{0}", fullPathToStartingExe)));
        }
        public static HostInformation CreateDefault()
        {
            var commandLine = Environment.CommandLine;

            var commandLineParts = commandLine.Split('"');

            var fullPathToStartingExe = "";

            if (commandLineParts.Length > 1)
            {
                fullPathToStartingExe = commandLineParts[1];
            }
            else if (commandLineParts.Length == 1)
            {
                fullPathToStartingExe = commandLineParts[0];
            }

            var hostId = DeterministicGuid.Create(fullPathToStartingExe, Environment.MachineName);

            return(new HostInformation(hostId, Environment.MachineName, String.Format("{0}", fullPathToStartingExe)));
        }
        public HostInformationFeature()
        {
            EnableByDefault();
            Defaults(s =>
            {
                var fullPathToStartingExe = PathUtilities.SanitizedPath(Environment.CommandLine);

                if (!s.HasExplicitValue(HostIdSettingsKey))
                {
                    s.SetDefault(HostIdSettingsKey, DeterministicGuid.Create(fullPathToStartingExe, RuntimeEnvironment.MachineName));
                }
                s.SetDefault("NServiceBus.HostInformation.DisplayName", RuntimeEnvironment.MachineName);
                s.SetDefault("NServiceBus.HostInformation.Properties", new Dictionary <string, string>
                {
                    { "Machine", RuntimeEnvironment.MachineName },
#pragma warning disable PC001
                    { "ProcessID", Process.GetCurrentProcess().Id.ToString() },
#pragma warning restore PC001
                    { "UserName", Environment.UserName },
                    { "PathToExecutable", fullPathToStartingExe }
                });
            });
        }
Exemple #18
0
        static async Task Main(string[] args)
        {
            Console.WriteLine(Environment.CommandLine);
            var id        = DeterministicGuid.Create(args[0]);
            var mutexName = id.ToString("N");

            using var appSingleton = new System.Threading.Mutex(false, mutexName, out var createdNew);

            if (!createdNew)
            {
                Console.WriteLine("Single instance!");
                return;
            }

            Configuration.ConnectionString = args[0];

            TelemetryClient telemetryClient = null;

            if (Configuration.AppInsightKey != null)
            {
                var configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey = Configuration.AppInsightKey;
                telemetryClient = new TelemetryClient(configuration);
            }

            if (args.Contains("--reset"))
            {
                Console.WriteLine("Cleaning wait_time stats ...");
                await ClearWaitTimeStats();
            }

            telemetryClient?.TrackTrace("Monitor started");

            Console.WriteLine("Monitor started");

            DateTime RoundUp(DateTime dt, TimeSpan d)
            {
                return(new DateTime((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Kind));
            }

            var interval = TimeSpan.FromSeconds(30); // Report granulatity is 1 minute, must be reporting more often to ensure every minute has atleast one sample.
            var now      = DateTime.UtcNow;
            var next     = RoundUp(now, interval);
            var delay    = next - now;
            await Task.Delay(delay); // Align clock

            while (true)
            {
                try
                {
                    async Task Invoke()
                    {
                        var pageLatchMetrics = await GetPageLatchStats();

                        if (telemetryClient != null)
                        {
                            pageLatchMetrics.ToList().ForEach(m => telemetryClient.TrackMetric(m));
                            await foreach (var item in GetQueueLengthsMetric())
                            {
                                telemetryClient.TrackMetric(item);
                            }
                            telemetryClient.Flush();
                        }
                    }
                    now   = DateTime.UtcNow; // Keeps invocation spot on the interval
                    next += interval;
                    delay = next - now;
                    await Task.WhenAll(
                        Task.Delay(delay),
                        Invoke()
                        );
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(ex);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.BackgroundColor = ConsoleColor.Black;
                }
            }
        }
        public void DeterministicGuid_Version5()
        {
            var actual = DeterministicGuid.Create(DeterministicGuid.DnsNamespace, "www.example.com", DeterministicGuidVersion.Version5);

            Assert.Equal(Guid.Parse("2ed6657d-e927-568b-95e1-2665a8aea6a2"), actual);
        }
        public void DeterministicGuid_Version3_Dns(string name, string expectedGuid)
        {
            var actual = DeterministicGuid.Create(DeterministicGuid.DnsNamespace, name, DeterministicGuidVersion.Version3);

            Assert.Equal(Guid.Parse(expectedGuid), actual);
        }
Exemple #21
0
        public static string FormatId(MessageType messageType)
        {
            var id = DeterministicGuid.Create(messageType.TypeName, "/", messageType.Version.Major);

            return(string.Format("Subscriptions/{0}", id));
        }
 public Guid NewGuid()
 {
     return(DeterministicGuid.Create(_orchestrationGuidNamespace, $"{ExecutionId}/{++_count}"));
 }