public void Subscribe(Address subscriber, IEnumerable<MessageType> messageTypes) { Action subscribeAction = () => { using (var client = GetClient()) { using (var tran = client.CreateTransaction()) { foreach (var messageType in messageTypes) { tran.QueueCommand(c => c.Sets[GetSetName(messageType)].Add(subscriber.ToString())); } tran.Commit(); } } }; if (Transaction.Current != null) { Transaction.Current.EnlistVolatile(new ActionResourceManager(subscribeAction, null), EnlistmentOptions.None); } else { subscribeAction(); } }
/// <summary> /// Sets the public return address of this endpoint. /// </summary> /// <param name="address">The public address.</param> public static void OverridePublicReturnAddress(Address address) { PublicReturnAddress = address; if (preventChanges) throw new InvalidOperationException("Overwriting a previously set public return address is a very dangerous operation. If you think that your scenario warrants it, you can catch this exception and continue."); }
public void Send(TransportMessage message, Address address) { using(var redisClient = new RedisClient()) { redisClient.Add(string.Format("{0}:{1}", address.Machine, address.Queue), message); } }
/// <summary> /// Sets the address of this endpoint. /// </summary> /// <param name="queue">The queue name.</param> public static void InitializeLocalAddress(string queue) { Local = Parse(queue); PublicReturnAddress = Local; if (preventChanges) throw new InvalidOperationException("Overwriting a previously set local address is a very dangerous operation. If you think that your scenario warrants it, you can catch this exception and continue."); }
static void Main(string[] args) { cmdLine = args; var timeOfMigration = DateTime.UtcNow; var storage = GetSetting("-storageQueue"); var inputStorageQueue = Address.Parse(storage); var destination = GetSetting("-destination"); newTimeoutManagerAddress = Address.Parse(destination); var minAge = GetSetting("-migrateOlderThan"); var minAgeOfTimeouts = TimeSpan.MinValue; if (!string.IsNullOrEmpty(minAge)) minAgeOfTimeouts = TimeSpan.Parse(minAge); bus = Configure.With() .DefaultBuilder() .XmlSerializer() .MsmqTransport() .UnicastBus() .SendOnly(); var path = MsmqUtilities.GetFullPath(inputStorageQueue); storageQueue = new MessageQueue(path) { MessageReadPropertyFilter = { LookupId = true } }; if (!storageQueue.Transactional) throw new Exception(inputStorageQueue + " must be transactional."); storageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(TimeoutData) }); Console.WriteLine(string.Format("Parsing {0} to find timeouts to migrate", inputStorageQueue)); storageQueue.GetAllMessages().ToList().ForEach( m => { var timeoutData = m.Body as TimeoutData; if (timeoutData == null) //get rid of message throw new InvalidOperationException("Failed to parse timeout data with id " + m.Id); if (minAgeOfTimeouts != TimeSpan.MinValue && timeoutData.Time < (timeOfMigration + minAgeOfTimeouts)) { Console.WriteLine(string.Format("Timeout {0} has a expiry ({1}) less than the configured min age of {2} and will be ignored", m.Id, timeoutData.Time, minAgeOfTimeouts)); return; } timeoutsToBeMigrated.Add(new Tuple<TimeoutData, string>(timeoutData, m.Id)); }); Console.WriteLine(string.Format("{0} parsed, {1} timeouts found that will be migrated", inputStorageQueue, timeoutsToBeMigrated.Count())); timeoutsToBeMigrated.ForEach(t => MigrateMessage(t.Item1, t.Item2)); Console.WriteLine(string.Format("Migration completed successfully")); }
static Settings() { AuditQueue = GetAuditQueue(); ErrorQueue = GetErrorQueue(); ErrorLogQueue = GetErrorLogQueue(); AuditLogQueue = GetAuditLogQueue(); DbPath = GetDbPath(); TransportType = SettingsReader<string>.Read("TransportType", typeof(Msmq).AssemblyQualifiedName); }
/// <summary> /// Turns a '@' separated value into a full path. /// Format is 'queue@machine', or 'queue@ipaddress' /// </summary> public static string GetFullPath(Address value) { IPAddress ipAddress; if (IPAddress.TryParse(value.Machine, out ipAddress)) { return PREFIX_TCP + MsmqQueueCreator.GetFullPathWithoutPrefix(value); } return PREFIX + MsmqQueueCreator.GetFullPathWithoutPrefix(value); }
public void Init() { var error = ConfigurationManager.AppSettings["watchr.errorqueue"]; if (string.IsNullOrEmpty(error)) error = "WatchR.Error"; errorQueue = Address.Parse(error); NServiceBus.Utils.MsmqUtilities.CreateQueueIfNecessary(errorQueue, Thread.CurrentPrincipal.Identity.Name); }
public void Send(TransportMessage message, Address address) { Inner.Send(message,address); if (BlowUpAfterDispatch && PipelineExecutor.CurrentContext.Get<bool>("Outbox_StartDispatching")) { BlowUpAfterDispatch = false; Console.Out.WriteLine("Monkey: Message {0} dispatched, blowing up now like you asked me to!",message.Id); throw new Exception("BlowUpAfterDispatch"); } }
private static void SetLocalAddress(Address applicativeInputQueue) { try { Address.InitializeLocalAddress(applicativeInputQueue.Queue); } catch (Exception) { //intentionally swallow } }
/// <summary> /// Forward messages that have repeatedly failed to another endpoint. /// </summary> /// <param name="config"></param> /// <returns></returns> public static Configure MessageForwardingInCaseOfFault(this Configure config) { if (ErrorQueue != null) { return config; } if (SettingsHolder.Get<bool>("Endpoint.SendOnly")) { return config; } ErrorQueue = Address.Undefined; var section = Configure.GetConfigSection<MessageForwardingInCaseOfFaultConfig>(); if (section != null) { if (string.IsNullOrWhiteSpace(section.ErrorQueue)) { throw new ConfigurationErrorsException( "'MessageForwardingInCaseOfFaultConfig' configuration section is found but 'ErrorQueue' value is missing." + "\n The following is an example for adding such a value to your app config: " + "\n <MessageForwardingInCaseOfFaultConfig ErrorQueue=\"error\"/> \n"); } Logger.Debug("Error queue retrieved from <MessageForwardingInCaseOfFaultConfig> element in config file."); ErrorQueue = Address.Parse(section.ErrorQueue); config.Configurer.ConfigureComponent<FaultManager>(DependencyLifecycle.InstancePerCall) .ConfigureProperty(fm => fm.ErrorQueue, ErrorQueue); return config; } var errorQueue = RegistryReader<string>.Read("ErrorQueue"); if (!string.IsNullOrWhiteSpace(errorQueue)) { Logger.Debug("Error queue retrieved from registry settings."); ErrorQueue = Address.Parse(errorQueue); config.Configurer.ConfigureComponent<FaultManager>(DependencyLifecycle.InstancePerCall) .ConfigureProperty(fm => fm.ErrorQueue, ErrorQueue); } if (ErrorQueue == Address.Undefined) { throw new ConfigurationErrorsException("Faults forwarding requires an error queue to be specified. Please add a 'MessageForwardingInCaseOfFaultConfig' section to your app.config" + "\n or configure a global one using the powershell command: Set-NServiceBusLocalMachineSettings -ErrorQueue {address of error queue}"); } return config; }
public void Init() { var audit = ConfigurationManager.AppSettings["watchr.audit.input"]; if (string.IsNullOrEmpty(audit)) { logger.Warn("No audit input queue defined, audit feed won't start"); return; } auditQueueAddress = Address.Parse(audit); includeMessageBody = false; }
static void ConfigureStartup(Address gatewayInputAddress) { Configure.ConfigurationComplete += () => { Configure.Instance.Builder.Build<IStartableBus>() .Started += (sender, eventargs) => { Configure.Instance.Builder.Build<GatewayReceiver>().Start(gatewayInputAddress); Configure.Instance.Builder.Build<GatewaySender>().Start(gatewayInputAddress); }; }; }
/// <summary> /// Stores subscription data using MSMQ. /// If multiple machines need to share the same list of subscribers, /// you should not choose this option - prefer the DbSubscriptionStorage /// in that case. /// </summary> /// <param name="config"></param> /// <returns></returns> public static Configure MsmqSubscriptionStorage(this Configure config) { var cfg = Configure.GetConfigSection<MsmqSubscriptionStorageConfig>(); if (cfg == null) Logger.Warn("Could not find configuration section for Msmq Subscription Storage."); Queue = (cfg != null ? cfg.Queue : "NServiceBus_Subscriptions"); var storageConfig = config.Configurer.ConfigureComponent<MsmqSubscriptionStorage>(DependencyLifecycle.SingleInstance); storageConfig.ConfigureProperty(s => s.Queue, Queue); return config; }
public void Init() { var error = ConfigurationManager.AppSettings["watchr.errors.input"]; if (string.IsNullOrEmpty(error)) { logger.Warn("No error input queue defined, error feed won't start"); return; } var errorLog = ConfigurationManager.AppSettings["watchr.errors.log"]; if (string.IsNullOrEmpty(errorLog)) errorLog = error + "_log"; errorQueueAddress = Address.Parse(error); errorLogAddress = Address.Parse(errorLog); }
/// <summary> /// Stores subscription data using MSMQ. /// If multiple machines need to share the same list of subscribers, /// you should not choose this option - prefer the DbSubscriptionStorage /// in that case. /// </summary> /// <param name="config"></param> /// <param name="endpointName"></param> /// <returns></returns> public static Configure MsmqSubscriptionStorage(this Configure config, string endpointName) { var cfg = Configure.GetConfigSection<MsmqSubscriptionStorageConfig>(); if (cfg == null && string.IsNullOrEmpty(endpointName)) Logger.Warn("Could not find configuration section for Msmq Subscription Storage and no name was specified for this endpoint. Going to default the subscription queue"); if (string.IsNullOrEmpty(endpointName)) endpointName = "NServiceBus"; Queue = cfg != null ? Address.Parse(cfg.Queue): Address.Parse(endpointName).SubScope("subscriptions"); var storageConfig = config.Configurer.ConfigureComponent<MsmqSubscriptionStorage>(DependencyLifecycle.SingleInstance); storageConfig.ConfigureProperty(s => s.Queue, Queue); return config; }
/// <summary> /// Gets the name of the return address from the provided value. /// If the target includes a machine name, uses the local machine name in the returned value /// otherwise uses the local IP address in the returned value. /// </summary> public static string GetReturnAddress(Address value, Address target) { var machine = target.Machine; IPAddress targetIpAddress; //see if the target is an IP address, if so, get our own local ip address if (IPAddress.TryParse(machine, out targetIpAddress)) { if (string.IsNullOrEmpty(localIp)) { localIp = LocalIpAddress(targetIpAddress); } return PREFIX_TCP + localIp + PRIVATE + value.Queue; } return PREFIX + MsmqQueueCreator.GetFullPathWithoutPrefix(value); }
public static void SetExceptionHeaders(this TransportMessage message,Exception e, Address failedQueue, string reason = null) { if (!string.IsNullOrWhiteSpace(reason)) { message.Headers["NServiceBus.ExceptionInfo.Reason"] = reason; } message.Headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName; if (e.InnerException != null) { message.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName; } message.Headers["NServiceBus.ExceptionInfo.HelpLink"] = e.HelpLink; message.Headers["NServiceBus.ExceptionInfo.Message"] = e.GetMessage(); message.Headers["NServiceBus.ExceptionInfo.Source"] = e.Source; message.Headers["NServiceBus.ExceptionInfo.StackTrace"] = e.StackTrace; message.Headers[FaultsHeaderKeys.FailedQ] = failedQueue.ToString(); message.Headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow); }
internal static void SetExceptionHeaders(Dictionary<string, string> headers, Exception e, Address failedQueue, string reason, bool legacyStackTrace) { if (!string.IsNullOrWhiteSpace(reason)) { headers["NServiceBus.ExceptionInfo.Reason"] = reason; } headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName; if (e.InnerException != null) { headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName; } headers["NServiceBus.ExceptionInfo.HelpLink"] = e.HelpLink; headers["NServiceBus.ExceptionInfo.Message"] = e.GetMessage(); headers["NServiceBus.ExceptionInfo.Source"] = e.Source; if (legacyStackTrace) { headers["NServiceBus.ExceptionInfo.StackTrace"] = e.StackTrace; } else { headers["NServiceBus.ExceptionInfo.StackTrace"] = e.ToString(); } headers[FaultsHeaderKeys.FailedQ] = failedQueue.ToString(); headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if(e.Data == null) // ReSharper disable once HeuristicUnreachableCode return; foreach (DictionaryEntry entry in e.Data) { if (entry.Value == null) continue; headers["NServiceBus.ExceptionInfo.Data." + entry.Key] = entry.Value.ToString(); } }
private void Init(Address queue) { var path = MsmqUtilities.GetFullPath(queue); var mq = new MessageQueue(path); if (!mq.Transactional) throw new Exception("Queue must be transactional."); storageQueue = mq; storageQueue.Formatter = new XmlMessageFormatter(new[] {typeof (TimeoutData)}); storageQueue.GetAllMessages().ToList().ForEach( m => { var td = m.Body as TimeoutData; if (td == null) //get rid of message storageQueue.ReceiveById(m.Id, MessageQueueTransactionType.Single); else //put into lookup sagaToMessageIdLookup[td.SagaId] = m.Id; }); }
/// <summary> /// Forward messages that have repeatedly failed to another endpoint. /// </summary> /// <param name="config"></param> /// <returns></returns> public static Configure MessageForwardingInCaseOfFault(this Configure config) { var section = Configure.GetConfigSection<MessageForwardingInCaseOfFaultConfig>(); if (section == null) { Logger.Warn("Could not find configuration section 'MessageForwardingInCaseOfFaultConfig'. Going to try to find the error queue defined in 'MsmqTransportConfig'."); var msmq = Configure.GetConfigSection<MsmqTransportConfig>(); if (msmq == null) throw new ConfigurationErrorsException("Could not find backup configuration section 'MsmqTransportConfig' in order to locate the error queue."); ErrorQueue = Address.Parse(msmq.ErrorQueue); } else ErrorQueue = Address.Parse(section.ErrorQueue); if(ErrorQueue == Address.Undefined) throw new ConfigurationErrorsException("Faults forwarding requires a error queue to be specified. Please add a 'MessageForwardingInCaseOfFaultConfig' section to your app.config"); config.Configurer.ConfigureComponent<FaultManager>(DependencyLifecycle.InstancePerCall) .ConfigureProperty(fm => fm.ErrorQueue, ErrorQueue); return config; }
// ReSharper disable once UnusedParameter.Global public static void OverridePublicReturnAddress(Address address) { throw new InvalidOperationException(); }
public void Unsubscribe(NServiceBus.Address client, IEnumerable <NServiceBus.Unicast.Subscriptions.MessageType> messageTypes) { throw new NotImplementedException(); }
/// <summary> /// Check this is equal to other Address /// </summary> /// <param name="other">reference addressed to be checked with this</param> /// <returns>true if this is equal to other</returns> private bool Equals(Address other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreMachineName && !other.machineLowerCased.Equals(machineLowerCased)) return false; return other.queueLowerCased.Equals(queueLowerCased); }
protected string GetClaimedMessageIdListName(Address address) { return _keyNameProvider.GetClaimedMessageIdListName(address); //return GetBaseQueueName(address) + ":claimed"; }
protected string GetMessageHashName(Address address) { return _keyNameProvider.GetMessageHashName(address); //return GetBaseQueueName(address) + ":messages"; }
public void Init(Address address) { }
public void CreateQueueIfNecessary(Address address, string account) { // create the queues here }
public void CreateQueueIfNecessary(Address address, string account) { }
static Configure SetupGateway(this Configure config) { GatewayInputAddress = Address.Parse(Configure.EndpointName).SubScope("gateway"); ConfigureChannels(config); ConfigureReceiver(config); ConfigureSender(config); return config; }
public NServiceBus_MSMQ_Audit_Queue_Listener(IBus bus, Address queueName) { Bus = bus; var path = NServiceBus.Utils.MsmqUtilities.GetFullPath(queueName); Queue = new MessageQueue(path, QueueAccessMode.ReceiveAndAdmin); var mpf = new MessagePropertyFilter(); mpf.SetAll(); Queue.MessageReadPropertyFilter = mpf; Queue.PeekCompleted += queue_PeekCompleted; }