Exemplo n.º 1
0
        public void Setup()
        {
            _busMock = new Mock<IBus>();
            _context = MessageContext.CreateTest("u.name");

            _bus = new MessageContextAwareBus(_busMock.Object, _context);
        }
Exemplo n.º 2
0
 public PipeInvocation(IMessageHandlerInvoker invoker, IMessage message, MessageContext messageContext, IEnumerable<IPipe> pipes)
 {
     _invoker = invoker;
     _message = message;
     _messageContext = messageContext;
     _pipes = pipes.AsList();
 }
Exemplo n.º 3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="command"></param>
 protected ExecutingEventArgs(
     MessageContext command)
 {
     this.Id = Guid.NewGuid();
     this.ExecutingOn = DateTime.Now;
     this.Command = command;
 }
 public MessageProcessedEventArgs(MessageContext currentMessageContext, DateTime startTimestamp, DateTime endTimestamp, double duration)
 {
     this.MessageContext = currentMessageContext;
     this.StartProcessingTimestamp = startTimestamp;
     this.EndProcessingTimestamp = endTimestamp;
     this.ProcessingDuration = duration;
 }
        public async Task Invoke(MessageContext context)
        {
            var timeoutId = context.Headers["Timeout.Id"];

            var timeoutData = await persister.Peek(timeoutId, context.Context).ConfigureAwait(false);

            if (timeoutData == null)
            {
                return;
            }

            timeoutData.Headers[Headers.TimeSent] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            timeoutData.Headers["NServiceBus.RelatedToTimeoutId"] = timeoutData.Id;

            var outgoingMessage = new OutgoingMessage(context.MessageId, timeoutData.Headers, timeoutData.State);
            var transportOperation = new TransportOperation(outgoingMessage, new UnicastAddressTag(timeoutData.Destination), dispatchConsistency);
            await dispatcher.Dispatch(new TransportOperations(transportOperation), context.TransportTransaction, context.Context).ConfigureAwait(false);

            var timeoutRemoved = await persister.TryRemove(timeoutId, context.Context).ConfigureAwait(false);
            if (!timeoutRemoved)
            {
                // timeout was concurrently removed between Peek and TryRemove. Throw an exception to rollback the dispatched message if possible.
                throw new Exception($"timeout '{timeoutId}' was concurrently processed.");
            }
        }
Exemplo n.º 6
0
 public NewMessageViewModel()
 {
     _usersContext = ContextFactory.GetUserContext();
     _messageContext = ContextFactory.GetMessageContext();
     _saveMessageCommand = new RelayCommand(OnSaveMessage);
     UpdateForUsersRole();
     LoadData();
 }
Exemplo n.º 7
0
 /// <summary>
 /// Declares a CURIE->URI prefix mapping for prefix message sender.
 /// </summary>
 /// <param name="messageContext">Context wrapper object for incoming WAMP message</param>
 public virtual void Handle(MessageContext messageContext)
 {
     var message = messageContext.Message as PrefixMessage;
     if (message != null)
     {
         messageContext.SenderSession.Prefixes.SetPrefix(message.Prefix, message.Uri);
     }
 }
        public void Handle(MessageContext context)
        {
            var senders = _messageBrokerManager.GetSendersFor(context.MessageEnvelop.MessageType);

            // Should be just one receiver because we send a message as a command
            var sender = senders.Single();
            sender.Send(context.MessageEnvelop.Message);
        }
Exemplo n.º 9
0
        public MessageDispatch(MessageContext context, IMessage message, Action<MessageDispatch, DispatchResult> continuation, bool shouldRunSynchronously = false)
        {
            _continuation = continuation;

            ShouldRunSynchronously = shouldRunSynchronously;
            Context = context;
            Message = message;
        }
Exemplo n.º 10
0
        public async Task Invoke(MessageContext context)
        {
            var sagaId = Guid.Empty;

            string sagaIdString;
            if (context.Headers.TryGetValue(Headers.SagaId, out sagaIdString))
            {
                sagaId = Guid.Parse(sagaIdString);
            }

            if (context.Headers.ContainsKey(TimeoutManagerHeaders.ClearTimeouts))
            {
                if (sagaId == Guid.Empty)
                {
                    throw new InvalidOperationException("Invalid saga id specified, clear timeouts is only supported for saga instances");
                }

                await persister.RemoveTimeoutBy(sagaId, context.Context).ConfigureAwait(false);
            }
            else
            {
                string expire;
                if (!context.Headers.TryGetValue(TimeoutManagerHeaders.Expire, out expire))
                {
                    throw new InvalidOperationException("Non timeout message arrived at the timeout manager, id:" + context.MessageId);
                }

                var destination = GetReplyToAddress(context);

                string routeExpiredTimeoutTo;
                if (context.Headers.TryGetValue(TimeoutManagerHeaders.RouteExpiredTimeoutTo, out routeExpiredTimeoutTo))
                {
                    destination = routeExpiredTimeoutTo;
                }

                var data = new TimeoutData
                {
                    Destination = destination,
                    SagaId = sagaId,
                    State = context.Body,
                    Time = DateTimeExtensions.ToUtcDateTime(expire),
                    Headers = context.Headers,
                    OwningTimeoutManager = owningTimeoutManager
                };

                if (data.Time.AddSeconds(-1) <= DateTime.UtcNow)
                {
                    var outgoingMessage = new OutgoingMessage(context.MessageId, data.Headers, data.State);
                    var transportOperation = new TransportOperation(outgoingMessage, new UnicastAddressTag(data.Destination));
                    await dispatcher.Dispatch(new TransportOperations(transportOperation), context.TransportTransaction, context.Context).ConfigureAwait(false);
                    return;
                }

                await persister.Add(data, context.Context).ConfigureAwait(false);

                poller.NewTimeoutRegistered(data.Time);
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Handles incoming WAMP <see cref="SubscribeMessage"/>,
 /// subscribing message sender to target WAMP topic, or creating one if topic didn't exists yet.
 /// </summary>
 /// <param name="messageContext">Context wrapper object for incoming WAMP message</param>
 public virtual void Handle(MessageContext messageContext)
 {
     var message = messageContext.Message as SubscribeMessage;
     if (message != null)
     {
         var topic = messageContext.Topics.AddTopic(message.TopicUri);
         topic.Subscribers.Add(messageContext.SenderSession.SessionId);
     }
 }
Exemplo n.º 12
0
        public static MessageExecutionCompleted Create(MessageContext messageContext, DispatchResult dispatchResult, IMessageSerializer serializer)
        {
            if (dispatchResult.Errors.Any())
                return Failure(messageContext.MessageId, dispatchResult.Errors);

            if (messageContext.ReplyResponse != null)
                return Success(messageContext.MessageId, messageContext.ReplyResponse, serializer);

            return new MessageExecutionCompleted(messageContext.MessageId, messageContext.ReplyCode, messageContext.ReplyMessage);
        }
 public async Task Process_GivenSetSettingsWithSpaceBrackets_ShouldResondWithSetSettingsContext()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Set("monitor_channel_jenkins", "http://therig:9999"));
     var messageContext = new MessageContext("set setting monitor_channel_jenkins <http://therig:9999>");
     // action
     await _chatBot.Process(messageContext);
     // assert
 }
 protected override void Invoke(MessageContext context, Action next)
 {
     // GetDispatchersForMessageType simply returns a enumerable of all
     // handlers which can accept the message as a parameter in which ever order they exist internally
     foreach (var dispatcher in context.ServiceLocator.Resolve<MessageHandlerCollection>().GetDispatchersForMessageType(context.CurrentMessage.GetType()))
     {
         dispatcher.Execute(ResolveParameters(dispatcher, context.CurrentMessage, context.ServiceLocator));
     }
     next(); // it's best practice to call next, even though this is likely the most inner behavior to execute
 }
 public async Task Process_GivenWhereAreYou_ShouldResondWithAboutContext()
 {
     // arrange
     Setup();
     var messageContext = new MessageContext("where are you?");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().Contain(x => x.Contains("working from home today"));
 }
Exemplo n.º 16
0
 public MessagesViewModel()
 {
     _context = ContextFactory.GetMessageContext();
     _usersContext = ContextFactory.GetUserContext();
     AppMessages.MailDeletedMessage.Register(this, OnMessageDeleted);
     AppMessages.MailSentMessage.Register(this, OnMessageSent);
     IsLoggedIn = true;
     //Load all messages for current user sorted
     LoadData();
 }
Exemplo n.º 17
0
        /// <summary>
        /// Handles incoming WAMP <see cref="WelcomeMessage"/>,
        /// initializing a new WAMP session on the client side.
        /// </summary>
        /// <param name="messageContext">Context wrapper object for incoming WAMP message</param>
        public void Handle(MessageContext messageContext)
        {
            var message = messageContext.Message as WelcomeMessage;
            if (message != null)
            {
                EnsureProtocolVersion(message);

                messageContext.SenderSession.SessionId = message.SessionId;
            }
        }
 public async Task Process_GivenMessage_ShouldRespond()
 {
     // arrange
     Setup();
     // action
     var sampleMessage = new MessageContext("help me out");
     await _chatBot.Process(sampleMessage);
     // assert
     sampleMessage.LastMessages.Should().Contain(x => x.Contains("help"));
 }
 public async Task Process_GivenSetSettingsContext_ShouldResondWithSetSettingsContext()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Set("monitor_channel_jenkins", "#builds"));
     var messageContext = new MessageContext("set setting monitor_channel_jenkins #builds");
     // action
     await _chatBot.Process(messageContext);
     // assert
 }
 public async Task Process_GivenGetSettingsContext_ShouldResondWithGetSettingsContext()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Get("monitor_channel_jenkins", null)).Returns("#builds");
     var messageContext = new MessageContext("get setting monitor_channel_jenkins");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Last().Should().Be("#builds");
 }
        public async Task Process_GivenSaySomething_ShouldTellMeAInsultContext()
        {
            // arrange
            Setup();

            var messageContext = new MessageContext("tell me a insult");
            // action
            await _chatBot.Process(messageContext);
            // assert
            messageContext.LastMessages.Should().HaveCount(1);
        }
 public async Task Process_GivenSetVolumeContext_ShouldShowSetVolumeContextChange()
 {
     // arrange
     Setup();
     _mockIVolumeSetter.Setup(mc => mc.SetVolume(10));
     var messageContext = new MessageContext("set volume 10");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().Contain("volume set to 10");
 }
 public async Task Process_GivenSetVolumeContextWithNumberTooHigh_ShouldReduceTheNumber()
 {
     // arrange
     Setup();
     _mockIVolumeSetter.Setup(mc => mc.SetVolume(10));
     var messageContext = new MessageContext("set volume 100");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().Contain("volume set to 10");
 }
        public async Task Process_GivenSaySomething_ShouldFailedToRespondContext()
        {
            // arrange
            Setup();

            var messageContext = new MessageContext("tell me a joke");
            // action
            await _chatBot.Process(messageContext);
            // assert
            messageContext.LastMessages.Should().HaveCount(1);
        }
 public async Task Process_GivenGreetingsContext_ShouldResondWithGreetingsContext()
 {
     // arrange
     Setup();
     
     var messageContext = new MessageContext("hi");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().NotBeEmpty();
 }
 public async Task Process_GivenJenkinsMonitorContext_ShouldResondWithJenkinsMonitorContext()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Get("jenkins_monitor_channel", It.IsAny<string>())).Returns("jenkins_monitor_channel");
     _mockISettingsManager.Setup(mc => mc.Get("jenkins_monitor_builds", It.IsAny<string>())).Returns("jenkins_monitor_builds");
     var messageContext = new MessageContext("where are you monitoring jenkins?");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().Contain(x => x.Contains("Im currently monitoring jenkins"));
 }
        public async Task Process_GivenIncorrectChannel_ShouldResondWithRunJenkinsMonitorOnBotChatContext()
        {
            // arrange
            Setup();

            _mockISettingsManager.Setup(mc => mc.Get("jenkins_monitor_channel", "#builds"))
                .Returns("#builds");
            var messageContext = new MessageContext("balbal") { FromUser = "******" };
            // action
            await _chatBot.Process(messageContext);
            // assert
        }
 public async Task Process_GivenCheck_ShouldScanJenkins()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Get("jenkins_monitor_channel", It.IsAny<string>())).Returns("jenkins_monitor_channel");
     _mockISettingsManager.Setup(mc => mc.Get("jenkins_monitor_builds", It.IsAny<string>())).Returns("jenkins_monitor_builds");
     var messageContext = new MessageContext("check jenkins now?");
     // action
     await _chatBot.Process(messageContext);
     // assert
     messageContext.LastMessages.Should().Contain(x => x.Contains("Checking jenkins now."));
 }
 public async Task Process_GivenSetSettingsWithSpace_ShouldResondWithSetSettingsContext()
 {
     // arrange
     Setup();
     _mockISettingsManager.Setup(mc => mc.Set("monitor_channel_jenkins", "builds asdf ss"));
     var messageContext = new MessageContext("set setting monitor_channel_jenkins");
     // action
     await _chatBot.Process(messageContext);
     messageContext.LastMessages.Last().Should().Be("what is the value?");
     await _chatBot.Process(new MessageContext("builds asdf ss"));
     // assert
 }
 public async Task Process_GivenSaySomething_ShouldSaySomethingContext()
 {
     // arrange
     Setup();
     _mockISoundFilePicker.Setup(mc => mc.PickFile("funny"))
         .Returns("hyp.mp3" );
     _mockIMp3Player.Setup(mc => mc.PlayFile("hyp.mp3"))
         .Returns(Task.FromResult(true));
     var messageContext = new MessageContext("say something funny");
     // action
     await _chatBot.Process(messageContext);
     // assert
 }
Exemplo n.º 31
0
        /// <summary>
        /// Generates a message context from a trace event.
        /// </summary>
        /// <param name="eventCache">The event cache.</param>
        /// <param name="source">The source.</param>
        /// <param name="eventType">Type of the event.</param>
        /// <param name="id">The identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>MessageContext.</returns>
        public virtual MessageContext MessageFromTraceEvent(TraceEventCache eventCache, string source,
                                                            TraceEventType eventType, int id, string message, params object[] args)
        {
            try
            {
                if (!eventType.IsValid())
                {
                    return(null);
                }

                //Create default message
                if (string.IsNullOrEmpty(message))
                {
                    message = DefaultMessage();
                }

                var context = new MessageContext(new Exception(message), new List <string>(), new Dictionary <object, object>(),
                                                 new UserInfo(AppDomain.CurrentDomain.FriendlyName)
                {
                    IsAnonymous = true
                });

                // get tags from the stack trace
                context.Tags.AddRange(GetAttributeTags());
                // get user from the stack trace
                var attributeUser = GetAttributeUser();
                if (attributeUser != null)
                {
                    context.User = attributeUser;
                }

                if (args != null)
                {
                    var localArgs = args.Where(a => a != null).ToList();
                    // check the args for custom data
                    var custom = localArgs.FirstOrDefault(a => a is IDictionary);
                    if (custom != null)
                    {
                        context.Data = (IDictionary)custom;
                        localArgs.Remove(custom);
                    }

                    // check the args for tags
                    var tags = localArgs.FirstOrDefault(a => a is IList <string>);
                    if (tags != null)
                    {
                        context.Tags.AddRange((IList <string>)tags);
                        localArgs.Remove(tags);
                    }

                    // check the args for a custom exception
                    var error = localArgs.FirstOrDefault(a => a is Exception);
                    if (error != null)
                    {
                        // use the arg exception for raygun and pass the message as custom data
                        context.Exception = (Exception)error;
                        context.Data.Add("Message", message);
                        localArgs.Remove(error);
                    }
                    else
                    {
                        // wrap the trace message as the exception
                        context.Exception = new Exception(message);
                    }

                    // check for user information
                    var user = localArgs.FirstOrDefault(a => a.HasProperty("username"));
                    if (user != null)
                    {
                        object username;
                        user.TryGetPropertyValue("username", out username);
                        object userId;
                        user.TryGetPropertyValue("id", out userId);
                        object userEmail;
                        user.TryGetPropertyValue("email", out userEmail);
                        object userFullName;
                        user.TryGetPropertyValue("fullname", out userFullName);
                        object userFirstName;
                        user.TryGetPropertyValue("firstname", out userFirstName);
                        object userIsAnonymous;
                        user.TryGetPropertyValue("isAnonymous", out userIsAnonymous);

                        context.User = new UserInfo(username?.ToString())
                        {
                            Id        = userId?.ToString(),
                            Email     = userEmail?.ToString(),
                            FullName  = userFullName?.ToString(),
                            FirstName = userFirstName?.ToString()
                        };
                    }
                    else
                    {
                        user = localArgs.FirstOrDefault(a => a is IUserInfo);
                        if (user != null)
                        {
                            context.User = (IUserInfo)user;
                        }
                    }

                    var grouping = localArgs.FirstOrDefault(a => a.HasProperty("groupkey"));
                    if (grouping != null)
                    {
                        context.Group = GetGrouping(grouping);
                        localArgs.Remove(grouping);
                    }

                    // add the rest
                    var count = 0;
                    foreach (var leftover in localArgs)
                    {
                        context.Data.Add($"arg-{count++}", leftover);
                    }
                }

                return(context);
            }
            catch (Exception e)
            {
                if (NotAlone()) // if someone else is listening, then trace the error
                {
                    Trace.TraceError("Error on MessageFromTraceEvent in RaygunTraceListener : {0}", e.Message);
                }
                return(new MessageContext(e));
            }
        }
Exemplo n.º 32
0
 internal override InvalidInfo AccumUsedTypeDefs(ValidityContext vctxt, MessageContext ctxt, Set <QualifiedTypeName> usedTypes)
 {
     return(FieldType.AccumUsedTypeDefs(vctxt, ctxt, usedTypes));
 }
Exemplo n.º 33
0
        /// <summary>
        /// Validates the query.
        /// </summary>
        /// <param name="indexTypeMapping">The index type mapping.</param>
        /// <param name="query">The query.</param>
        /// <param name="messageContext">The message context.</param>
        protected override void ValidateQuery(IndexTypeMapping indexTypeMapping, BaseMultiIndexIdQuery <SpanQueryResult> query, MessageContext messageContext)
        {
            SpanQuery spanQuery = query as SpanQuery;

            if (spanQuery == null)
            {
                throw new Exception(string.Format("Invalid span query, failed to cast"));
            }

            if (string.IsNullOrEmpty(spanQuery.TargetIndexName))
            {
                spanQuery.TargetIndexName = IndexServerUtils.CheckQueryTargetIndexName(indexTypeMapping);
            }

            if (!indexTypeMapping.IndexCollection.Contains(query.TargetIndexName))
            {
                throw new Exception("Invalid TargetIndexName - " + query.TargetIndexName);
            }

            if (query.IndexIdList == null || query.IndexIdList.Count == 0)
            {
                throw new Exception("No IndexIdList present on the query");
            }

            if (query.PrimaryIdList != null && query.PrimaryIdList.Count != query.IndexIdList.Count)
            {
                throw new Exception("PrimaryIdList.Count does not match with IndexIdList.Count");
            }

            if (spanQuery.Offset < 1 && spanQuery.Span != 0)
            {
                throw new Exception("SpanQuery.Offset should be greater than zero except when SpanQuery.Span is zero");
            }
        }
Exemplo n.º 34
0
 public Task Handle(PizzaOrderedEvent ev, MessageContext context)
 {
     this.State.OrderedAtUtc = ev.OrderedAt;
     Become(Ordered);
     return(Task.CompletedTask);
 }
Exemplo n.º 35
0
 public override void OnMessage(MessageContext messageContext)
 {
     messages?.Add(messageContext.Message);
     messageContext.Complete();
 }
Exemplo n.º 36
0
        /// <inheritdoc />
        protected override async Task <AgentMessage> ProcessAsync(ForwardMessage message, IAgentContext agentContext, MessageContext messageContext)
        {
            await _inboxService.ForwardAsync(message.Message, message.To, agentContext, messageContext);

            return(null);
        }
Exemplo n.º 37
0
        private IEnumerator Examples()
        {
            Log.Debug("ExampleAssistantV2.RunExample()", "Attempting to CreateSession");
            service.CreateSession(OnCreateSession, assistantId);

            while (!createSessionTested)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "Attempting to Message");
            service.Message(OnMessage0, assistantId, sessionId);

            while (!messageTested0)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "Are you open on Christmas?");

            var input1 = new MessageInput()
            {
                Text    = "Are you open on Christmas?",
                Options = new MessageInputOptions()
                {
                    ReturnContext = true
                }
            };

            service.Message(OnMessage1, assistantId, sessionId, input: input1);

            while (!messageTested1)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "What are your hours?");

            var input2 = new MessageInput()
            {
                Text    = "What are your hours?",
                Options = new MessageInputOptions()
                {
                    ReturnContext = true
                }
            };

            service.Message(OnMessage2, assistantId, sessionId, input: input2);

            while (!messageTested2)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "I'd like to make an appointment for 12pm.");

            var input3 = new MessageInput()
            {
                Text    = "I'd like to make an appointment for 12pm.",
                Options = new MessageInputOptions()
                {
                    ReturnContext = true
                }
            };

            service.Message(OnMessage3, assistantId, sessionId, input: input3);

            while (!messageTested3)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "On Friday please.");

            //Dictionary<string, string> userDefinedDictionary = new Dictionary<string, string>();
            //userDefinedDictionary.Add("name", "Watson");

            //Dictionary<string, object> skillDictionary = new Dictionary<string, object>();
            //skillDictionary.Add("user_defined", userDefinedDictionary);

            //Dictionary<string, object> skills = new Dictionary<string, object>();
            //skills.Add("main skill", skillDictionary);



            SerializableDictionary <string, string> userDefinedDictionary = new SerializableDictionary <string, string>();

            userDefinedDictionary.Add("name", "Watson");

            //MessageContextSkill skillDictionary = new MessageContextSkill();
            //skillDictionary.UserDefined = userDefinedDictionary;

            //MessageContextSkills skills = new MessageContextSkills();
            //skills.MainSkill = skillDictionary;


            var input4 = new MessageInput()
            {
                Text    = "On Friday please.",
                Options = new MessageInputOptions()
                {
                    ReturnContext = true
                }
            };

            var context = new MessageContext()
            {
                //Skills = skills
            };

            service.Message(OnMessage4, assistantId, sessionId, input: input4, context: context);

            while (!messageTested4)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.RunExample()", "Attempting to delete session");
            service.DeleteSession(OnDeleteSession, assistantId, sessionId);

            while (!deleteSessionTested)
            {
                yield return(null);
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Assistant examples complete.");
        }
Exemplo n.º 38
0
        private Array ParseArrayParameter(ref string unparsedParameters, Type arrayType, bool isOptional, bool nextParameterIsNumeric, MessageContext messageContext)
        {
            TamaChan.Instance.Logger.LogInfo("Test");
            List <object> objectList = new List <object>();
            string        unparsedParametersBackup = unparsedParameters;

            try
            {
                while (unparsedParameters != null && unparsedParameters.Length > 0)
                {
                    unparsedParametersBackup = unparsedParameters;
                    object member = GetParameter(ref unparsedParameters, arrayType, false, null, null, messageContext);
                    if (Type.GetTypeCode(arrayType) == TypeCode.Char && nextParameterIsNumeric)
                    {
                        if (char.IsNumber((char)member))
                        {
                            unparsedParameters = unparsedParametersBackup;
                            break;
                        }
                    }
                    objectList.Add(member);
                }
            }
            catch
            {
                unparsedParameters = unparsedParametersBackup;
            }
            finally
            {
                if (objectList.Count == 0)
                {
                    if (isOptional)
                    {
                        objectList = null;
                    }
                    else
                    {
                        throw new TargetParameterCountException();
                    }
                }
            }
            if (objectList == null)
            {
                return(null);
            }
            object[] abstractArray = objectList.ToArray();
            Array    concreteArray = Array.CreateInstance(arrayType, abstractArray.Length);

            Array.Copy(abstractArray, concreteArray, concreteArray.Length);
            return(concreteArray);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Processes the incoming <see cref="AgentMessage" />
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="agentContext">The message agentContext.</param>
        /// <param name="messageContext">The message context.</param>
        /// <returns></returns>
        protected override async Task <AgentMessage> ProcessAsync(BasicMessage message, IAgentContext agentContext, MessageContext messageContext)
        {
            var record = new BasicMessageRecord
            {
                Id           = Guid.NewGuid().ToString(),
                ConnectionId = messageContext.Connection.Id,
                Text         = message.Content,
                SentTime     = DateTime.TryParse(message.SentTime, out var dateTime) ? dateTime : DateTime.UtcNow,
                Direction    = MessageDirection.Incoming
            };
            await _recordService.AddAsync(agentContext.Wallet, record);

            messageContext.ContextRecord = record;

            return(null);
        }
    }
Exemplo n.º 40
0
 internal override InvalidInfo CheckValid(ValidityContext vctxt, MessageContext ctxt, RootEnvironment rootEnv)
 {
     return(Parameters.Select(p => p.CheckValid(vctxt, ctxt, rootEnv)).FirstOrDefault(v => v != null) ??
            Result.CheckValid(vctxt, ctxt, rootEnv));
 }
Exemplo n.º 41
0
 internal override InvalidInfo CheckValid(ValidityContext vctxt, MessageContext ctxt, RootEnvironment rootEnv)
 {
     return(FieldType.CheckValid(vctxt, ctxt, rootEnv));
 }
Exemplo n.º 42
0
 public Task Forward(string source, MessageContext context)
 {
     return(interceptMethod(source, context, sender.Dispatch,
                            dispatch => Forward(source, context, new InterceptingDispatcher(sender, dispatch))));
 }
Exemplo n.º 43
0
 public MessagesMVCController(MessageContext context)
 {
     _context  = context;
     client    = new Client();
     messaging = new Messaging(_context);
 }
Exemplo n.º 44
0
 /// <summary>
 ///
 /// A message context with userinput (not RAW MESSAGE PLEASE)
 /// is needed.
 /// </summary>
 /// <param name="con"></param>
 public PrefixCommand(MessageContext con)
 {
     this.Context = con ?? throw new Exception("You shouldn't do this. ");
 }
Exemplo n.º 45
0
 public static void Send <TContent, TData>(this MessageContext context, TData data, TContent content, string endpointname, string id, Dictionary <string, string> headers = null)
 {
     context.Send(data, content, context.CreateOptions(endpointname, id, headers));
 }
Exemplo n.º 46
0
 public static void Publish <TContent>(this MessageContext context, TContent content, EndPoint endpoint, string id, string operationid, string sagaid, string key, Dictionary <string, string> headers = null)
 {
     context.Publish(content, endpoint, context.CreateOrigin(key), context.CreateOptions(string.Empty, id, operationid, sagaid, headers));
 }
        public override InstallSnapshotResponse Handle(MessageContext context, InstallSnapshotRequest req, Stream stream)
        {
            if (_installingSnapshot != null)
            {
                return(new InstallSnapshotResponse
                {
                    Success = false,
                    Message = "Cannot install snapshot because we are already installing a snapshot",
                    CurrentTerm = Engine.PersistentState.CurrentTerm,
                    From = Engine.Name,
                    ClusterTopologyId = Engine.CurrentTopology.TopologyId,
                    LastLogIndex = Engine.PersistentState.LastLogEntry().Index
                });
            }


            if (FromOurTopology(req) == false)
            {
                _log.Info("Got an install snapshot message outside my cluster topology (id: {0}), ignoring", req.ClusterTopologyId);

                return(new InstallSnapshotResponse
                {
                    Success = false,
                    Message = "Cannot install snapshot because the cluster topology id doesn't match, mine is: " + Engine.CurrentTopology.TopologyId,
                    CurrentTerm = Engine.PersistentState.CurrentTerm,
                    From = Engine.Name,
                    ClusterTopologyId = Engine.CurrentTopology.TopologyId,
                    LastLogIndex = Engine.PersistentState.LastLogEntry().Index
                });
            }

            var lastLogEntry = Engine.PersistentState.LastLogEntry();

            if (req.Term < lastLogEntry.Term || req.LastIncludedIndex < lastLogEntry.Index)
            {
                stream.Dispose();

                return(new InstallSnapshotResponse
                {
                    From = Engine.Name,
                    ClusterTopologyId = Engine.CurrentTopology.TopologyId,
                    CurrentTerm = lastLogEntry.Term,
                    LastLogIndex = lastLogEntry.Index,
                    Message = string.Format("Snapshot is too old (term {0} index {1}) while we have (term {2} index {3})",
                                            req.Term, req.LastIncludedIndex, lastLogEntry.Term, lastLogEntry.Index),
                    Success = false
                });
            }

            _log.Info("Received InstallSnapshotRequest from {0} until term {1} / {2}", req.From, req.LastIncludedTerm, req.LastIncludedIndex);

            Engine.OnSnapshotInstallationStarted();

            // this can be a long running task
            _installingSnapshot = Task.Run(() =>
            {
                try
                {
                    Engine.StateMachine.ApplySnapshot(req.LastIncludedTerm, req.LastIncludedIndex, stream);
                    Engine.PersistentState.MarkSnapshotFor(req.LastIncludedIndex, req.LastIncludedTerm, int.MaxValue);
                    Engine.PersistentState.SetCurrentTopology(req.Topology, req.LastIncludedIndex);
                    var tcc = new TopologyChangeCommand {
                        Requested = req.Topology
                    };
                    Engine.StartTopologyChange(tcc);
                    Engine.CommitTopologyChange(tcc);
                }
                catch (Exception e)
                {
                    _log.Warn(string.Format("Failed to install snapshot term {0} index {1}", req.LastIncludedIndex, req.LastIncludedIndex), e);
                    context.ExecuteInEventLoop(() =>
                    {
                        _installingSnapshot = null;
                    });
                }

                // we are doing it this way to ensure that we are single threaded
                context.ExecuteInEventLoop(() =>
                {
                    Engine.UpdateCurrentTerm(req.Term, req.From); // implicitly put us in follower state
                    _log.Info("Updating the commit index to the snapshot last included index of {0}", req.LastIncludedIndex);
                    Engine.OnSnapshotInstallationEnded(req.Term);

                    context.Reply(new InstallSnapshotResponse
                    {
                        From = Engine.Name,
                        ClusterTopologyId = Engine.CurrentTopology.TopologyId,
                        CurrentTerm       = req.Term,
                        LastLogIndex      = req.LastIncludedIndex,
                        Success           = true
                    });
                });
            });

            return(null);
        }
Exemplo n.º 48
0
        void DoTry()
        {
            var transportMessage = receiveMessages.ReceiveMessage(TransactionContext.Current);

            if (transportMessage == null)
            {
                Thread.Sleep(20);
                return;
            }

            var id    = transportMessage.Id;
            var label = transportMessage.Label;

            MessageContext context = null;

            if (id == null)
            {
                HandlePoisonMessage(id, transportMessage);
                return;
            }

            if (errorTracker.MessageHasFailedMaximumNumberOfTimes(id))
            {
                HandlePoisonMessage(id, transportMessage);
                errorTracker.StopTracking(id);
                return;
            }

            Exception transportMessageExceptionOrNull = null;

            try
            {
                BeforeTransportMessage(transportMessage);

                using (var scope = BeginTransaction())
                {
                    var message = serializeMessages.Deserialize(transportMessage);
                    // successfully deserialized the transport message, let's enter a message context
                    context = MessageContext.Establish(message.Headers);
                    MessageContextEstablished(context);

                    var unitsOfWork = unitOfWorkManagers.Select(u => u.Create())
                                      .Where(u => !ReferenceEquals(null, u))
                                      .ToArray(); //< remember to invoke the chain here :)

                    try
                    {
                        foreach (var logicalMessage in message.Messages.Select(MutateIncoming))
                        {
                            context.SetLogicalMessage(logicalMessage);

                            Exception logicalMessageExceptionOrNull = null;
                            try
                            {
                                BeforeMessage(logicalMessage);

                                var typeToDispatch = logicalMessage.GetType();

                                log.Debug("Dispatching message {0}: {1}", id, typeToDispatch);

                                GetDispatchMethod(typeToDispatch)
                                .Invoke(this, new[] { logicalMessage });
                            }
                            catch (Exception exception)
                            {
                                logicalMessageExceptionOrNull = exception;
                                throw;
                            }
                            finally
                            {
                                try
                                {
                                    AfterMessage(logicalMessageExceptionOrNull, logicalMessage);
                                }
                                catch (Exception exceptionWhileRaisingEvent)
                                {
                                    if (logicalMessageExceptionOrNull != null)
                                    {
                                        log.Error(
                                            "An exception occurred while raising the AfterMessage event, and an exception occurred some" +
                                            " time before that as well. The first exception was this: {0}. And then, when raising the" +
                                            " AfterMessage event (including the details of the first error), this exception occurred: {1}",
                                            logicalMessageExceptionOrNull, exceptionWhileRaisingEvent);
                                    }
                                    else
                                    {
                                        log.Error("An exception occurred while raising the AfterMessage event: {0}",
                                                  exceptionWhileRaisingEvent);
                                    }
                                }

                                context.ClearLogicalMessage();
                            }
                        }

                        foreach (var unitOfWork in unitsOfWork)
                        {
                            unitOfWork.Commit();
                        }
                    }
                    catch
                    {
                        foreach (var unitOfWork in unitsOfWork)
                        {
                            try
                            {
                                unitOfWork.Abort();
                            }
                            catch (Exception abortException)
                            {
                                log.Warn("An error occurred while aborting the unit of work {0}: {1}",
                                         unitOfWork, abortException);
                            }
                        }
                        throw;
                    }
                    finally
                    {
                        foreach (var unitOfWork in unitsOfWork)
                        {
                            unitOfWork.Dispose();
                        }
                    }

                    if (scope != null)
                    {
                        scope.Complete();
                    }
                }
            }
            catch (Exception exception)
            {
                transportMessageExceptionOrNull = exception;
                log.Debug("Handling message {0} ({1}) has failed", label, id);
                errorTracker.TrackDeliveryFail(id, exception);
                throw;
            }
            finally
            {
                try
                {
                    AfterTransportMessage(transportMessageExceptionOrNull, transportMessage);
                }
                catch (Exception exceptionWhileRaisingEvent)
                {
                    if (transportMessageExceptionOrNull != null)
                    {
                        log.Error(
                            "An exception occurred while raising the AfterTransportMessage event, and an exception occurred some" +
                            " time before that as well. The first exception was this: {0}. And then, when raising the" +
                            " AfterTransportMessage event (including the details of the first error), this exception occurred: {1}",
                            transportMessageExceptionOrNull, exceptionWhileRaisingEvent);
                    }
                    else
                    {
                        log.Error("An exception occurred while raising the AfterTransportMessage event: {0}", exceptionWhileRaisingEvent);
                    }
                }

                if (context != null)
                {
                    context.Dispose();                  //< dispose it if we entered
                }
            }

            errorTracker.StopTracking(id);
        }
Exemplo n.º 49
0
        public void should_not_throw_exception_if_no_replayer_for_given_MessageHandled()
        {
            Handler.Context = MessageContext.CreateOverride(_targetPeerId, null);

            Assert.DoesNotThrow(() => Handler.Handle(new MessageHandled(MessageId.NextId())));
        }
Exemplo n.º 50
0
 public bool TryReceiveMessage(int timeout, CancellationToken cancellationToken, out MessageContext messageContext)
 {
     return(_parent.TryReceiveMessage(_from, timeout, cancellationToken, out messageContext));
 }
Exemplo n.º 51
0
 public TheMathCommand(MessageContext arg)
 {
     this.Context = arg;
 }
Exemplo n.º 52
0
        public void Start()
        {
            #region init sending commands Worker

            #region Init  Command Queue client
            if (_commandQueueNames != null && _commandQueueNames.Length > 0)
            {
                _commandQueueNames.ForEach(commandQueueName =>
                                           _commandQueueClients.Add(_serviceBusClient.CreateQueueClient(commandQueueName)));
            }
            #endregion

            _sendCommandWorkTask = Task.Factory.StartNew(() =>
            {
                using (var messageStore = IoCFactory.Resolve <IMessageStore>())
                {
                    messageStore.GetAllUnSentCommands()
                    .ForEach(commandContext => _toBeSentCommandQueue.Add(commandContext));
                }
                while (!_exit)
                {
                    try
                    {
                        var commandContext = _toBeSentCommandQueue.Take();
                        SendCommand(commandContext);
                        Task.Factory.StartNew(() =>
                        {
                            using (var messageStore = IoCFactory.Resolve <IMessageStore>())
                            {
                                messageStore.RemoveSentCommand(commandContext.MessageID);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        _logger.Debug("send command quit", ex);
                    }
                }
            }, TaskCreationOptions.LongRunning);
            #endregion

            #region init process command reply worker

            _replySubscriptionClient = _serviceBusClient.CreateSubscriptionClient(_replyTopicName, _replySubscriptionName);

            _subscriptionConsumeTask = Task.Factory.StartNew(() =>
            {
                while (!_exit)
                {
                    BrokeredMessage brokeredMessage = null;
                    try
                    {
                        brokeredMessage = _replySubscriptionClient.Receive();
                        if (brokeredMessage != null)
                        {
                            var reply = new MessageContext(brokeredMessage);
                            ConsumeReply(reply);
                        }
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(1000);
                        _logger.Error("consume reply error", ex);
                    }
                    finally
                    {
                        if (brokeredMessage != null)
                        {
                            brokeredMessage.Complete();
                        }
                    }
                }
            }, TaskCreationOptions.LongRunning);

            #endregion
        }
Exemplo n.º 53
0
 public IAsyncEnumerable <string> GetPrefixesAsync(MessageContext context)
 {
     return(_enumerable);
 }
Exemplo n.º 54
0
 public void Write(MessageContext <DumpMessage> dumpMessage)
 {
     Array.ForEach(dumpers, t => t.Write(dumpMessage));
 }
Exemplo n.º 55
0
 public static void FireAndForget <TContent>(this MessageContext context, TContent content, string endpointname, string id, string operationid, string sagaid, Dictionary <string, string> headers = null)
 {
     context.FireAndForget(content, context.CreateOrigin(), context.CreateOptions(endpointname, id, operationid, sagaid, headers));
 }
Exemplo n.º 56
0
        public IEnumerable <IHandlerResult> InlineButton([StrictName] string callbackQueryData, MessageContext messageContext)
        {
            var newData = messageContext.Get <string>("data")
                          .OrElseThrow(() => new InvalidOperationException("data is required"))
                          + callbackQueryData;

            yield return(new HandlerResultBuilder()
                         .UpdateMessage()
                         .Text(newData)
                         .InlineKeyboard(b => b.Row(r => r.Button("a", "A").Button("b", "B"))
                                         .Row(r => r.Button("c", "C").Button("d", "D")))
                         .Create());

            yield return(HandlerResultCreators.PutToMessageContext("data", newData));
        }
Exemplo n.º 57
0
 public static void Publish <TContent, TData>(this MessageContext context, TData data, TContent content, string endpointname, string id, string key, Dictionary <string, string> headers = null)
 {
     context.Publish(data, content, context.CreateOrigin(key), context.CreateOptions(endpointname, id, headers));
 }
Exemplo n.º 58
0
 /// <summary>
 /// Contruct the command, please Provide a context
 /// for the command.
 /// </summary>
 /// <param name="mcb"></param>
 public TheHelpCommand(MessageContext mcb = null)
 {
     this.Context = mcb;
 }
Exemplo n.º 59
0
        public async Task <bool> HandleIncomingMessage(Shard shard, MessageCreateEvent message, MessageContext ctx, Guild guild, Channel channel, bool allowAutoproxy, PermissionSet botPermissions)
        {
            if (!ShouldProxy(channel, message, ctx))
            {
                return(false);
            }

            // Fetch members and try to match to a specific member
            await using var conn = await _db.Obtain();

            var rootChannel = _cache.GetRootChannel(message.ChannelId);

            List <ProxyMember> members;

            using (_metrics.Measure.Timer.Time(BotMetrics.ProxyMembersQueryTime))
                members = (await _repo.GetProxyMembers(conn, message.Author.Id, message.GuildId !.Value)).ToList();

            if (!_matcher.TryMatch(ctx, members, out var match, message.Content, message.Attachments.Length > 0,
                                   allowAutoproxy))
            {
                return(false);
            }

            // this is hopefully temporary, so not putting it into a separate method
            if (message.Content != null && message.Content.Length > 2000)
            {
                throw new PKError("PluralKit cannot proxy messages over 2000 characters in length.");
            }

            // Permission check after proxy match so we don't get spammed when not actually proxying
            if (!await CheckBotPermissionsOrError(botPermissions, rootChannel.Id))
            {
                return(false);
            }

            // this method throws, so no need to wrap it in an if statement
            CheckProxyNameBoundsOrError(match.Member.ProxyName(ctx));

            // Check if the sender account can mention everyone/here + embed links
            // we need to "mirror" these permissions when proxying to prevent exploits
            var senderPermissions = PermissionExtensions.PermissionsFor(guild, rootChannel, message);
            var allowEveryone     = senderPermissions.HasFlag(PermissionSet.MentionEveryone);
            var allowEmbeds       = senderPermissions.HasFlag(PermissionSet.EmbedLinks);

            // Everything's in order, we can execute the proxy!
            await ExecuteProxy(shard, conn, message, ctx, match, allowEveryone, allowEmbeds);

            return(true);
        }
Exemplo n.º 60
0
 public override void OnMessage(MessageContext messageContext)
 {
     // this can also be done when an async operation, if required, is done
     messageContext.Complete();
 }