コード例 #1
0
        public async Task ThenMultiHopSignalMessageIsToBeForwarded()
        {
            // Arrange
            SignalMessage signal = CreateMultihopSignalMessage(
                refToMessageId: "someusermessageid",
                pmodeId: "Forward_Push");

            // Act
            await StubSender.SendAS4Message(_receiveAgentUrl, AS4Message.Create(signal));

            // Assert
            InMessage inMessage = _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == signal.MessageId);

            Assert.NotNull(inMessage);
            Assert.True(inMessage.Intermediary);
            Assert.Equal(Operation.ToBeForwarded, inMessage.Operation);

            Stream messageBody = await Registry.Instance
                                 .MessageBodyStore
                                 .LoadMessageBodyAsync(inMessage.MessageLocation);

            AS4Message savedMessage = await SerializerProvider.Default
                                      .Get(inMessage.ContentType)
                                      .DeserializeAsync(messageBody, inMessage.ContentType);

            Assert.NotNull(savedMessage.EnvelopeDocument.SelectSingleNode("//*[local-name()='RoutingInput']"));
        }
コード例 #2
0
        public Property Only_Entries_With_Allowed_Operations_Are_Deleted()
        {
            return(Prop.ForAll(
                       SupportedProviderSettings(),
                       Arb.From <Operation>(),
                       (specificSettings, operation) =>
            {
                // Arrange
                OverrideWithSpecificSettings(specificSettings);

                string id = GenId();
                InMessage m = CreateInMessage(id, insertionTime: DayBeforeYesterday);
                m.Operation = operation;

                IConfig config = EnsureLocalConfigPointsToCreatedDatastore();
                var spy = new DatabaseSpy(config);
                spy.InsertInMessage(m);

                // Act
                ExerciseStartCleaning();

                // Assert
                bool hasEntries = spy.GetInMessages(id).Any();
                string description = $"InMessage {(hasEntries ? "isn't" : "is")} deleted, with Operation: {operation}";
                return (hasEntries == !AllowedOperations.Contains(operation)).Collect(description);
            }));
        }
コード例 #3
0
        public async Task ThenInMessageOperationIsToBeForwarded()
        {
            const string messageId = "forwarding_message_id";

            var as4Message = AS4Message.Create(
                new UserMessage(
                    messageId,
                    new CollaborationInfo(
                        agreement: new AgreementReference(
                            value: "forwarding/agreement",
                            type: "forwarding",
                            // Make sure that the forwarding receiving pmode is used; therefore
                            // explicitly set the Id of the PMode that must be used by the receive-agent.
                            pmodeId: "Forward_Push"),
                        service: new Service(
                            value: "Forward_Push_Service",
                            type: "eu:europa:services"),
                        action: "Forward_Push_Action",
                        conversationId: "eu:europe:conversation")));

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, as4Message);

            // Assert
            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
            Assert.True(String.IsNullOrWhiteSpace(await response.Content.ReadAsStringAsync()));

            InMessage receivedUserMessage = _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == messageId);

            Assert.NotNull(receivedUserMessage);
            Assert.Equal(Operation.ToBeForwarded, receivedUserMessage.Operation);
        }
コード例 #4
0
        public async Task ThenReceivedMultihopUserMessageIsSetAsIntermediaryAndForwarded()
        {
            // Arrange
            var userMessage = new UserMessage(
                "test-" + Guid.NewGuid(),
                new
                CollaborationInfo(
                    agreement: new AgreementReference(
                        value: "http://agreements.europa.org/agreement",
                        pmodeId: "Forward_Push_Multihop"),
                    service: new Service(
                        value: "Forward_Push_Multihop_Service",
                        type: "eu:europa:services"),
                    action: "Forward_Push_Multihop_Action",
                    conversationId: "eu:europe:conversation"));
            var multihopPMode = new SendingProcessingMode {
                MessagePackaging = { IsMultiHop = true }
            };
            AS4Message multihopMessage = AS4Message.Create(userMessage, multihopPMode);

            // Act
            HttpResponseMessage response = await StubSender.SendAS4Message(_receiveAgentUrl, multihopMessage);

            // Assert
            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

            InMessage inUserMessage = _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == userMessage.MessageId);

            Assert.NotNull(inUserMessage);
            Assert.True(inUserMessage.Intermediary);
            Assert.Equal(Operation.ToBeForwarded, inUserMessage.Operation);
        }
コード例 #5
0
        public async Task ThenExecuteStepWithReceivingPModeAsync()
        {
            // Arrange
            var entity = new InMessage($"error-{Guid.NewGuid()}");

            entity.InitializeIdFromDatabase(1);

            var fixture = new MessagingContext(
                EmptyNotifyMessageEnvelope(Status.Error),
                new ReceivedEntityMessage(entity))
            {
                SendingPMode = new SendingProcessingMode
                {
                    ErrorHandling = { NotifyMethod = new LocationMethod("not-empty-location") }
                }
            };

            GetDataStoreContext.InsertInMessage(new InMessage($"entity-{Guid.NewGuid()}"));

            var   spySender = new SpySender();
            IStep sut       = CreateSendNotifyStepWithSender(spySender);

            // Act
            await sut.ExecuteAsync(fixture);

            // Assert
            Assert.True(spySender.IsNotified);
        }
コード例 #6
0
        public Property Updates_Bundled_MessageUnits_For_Forwarding()
        {
            return(Prop.ForAll(
                       CreateUserReceiptArb(),
                       messageUnits =>
            {
                // Before
                Assert.All(
                    messageUnits,
                    u => GetDataStoreContext.InsertInMessage(new InMessage(u.MessageId)));

                // Arrange
                AS4Message received = AS4Message.Create(messageUnits);

                // Act
                ExerciseUpdateReceivedMessage(
                    received,
                    CreateNotifyAllSendingPMode(),
                    CreateForwardingReceivingPMode())
                .GetAwaiter()
                .GetResult();

                // Assert
                IEnumerable <InMessage> updates =
                    GetDataStoreContext.GetInMessages(
                        m => received.MessageIds.Contains(m.EbmsMessageId));

                Assert.All(updates, u => Assert.True(u.Intermediary));

                InMessage primaryUpdate = updates.First(u => u.EbmsMessageId == received.GetPrimaryMessageId());
                Assert.Equal(Operation.ToBeForwarded, primaryUpdate.Operation);
            }));
        }
コード例 #7
0
        public async Task InMessageStatusIsCorrectlyPersisted()
        {
            long savedInMessageId;

            using (var db = this.GetDataStoreContext())
            {
                var inMessage = new InMessage(Guid.NewGuid().ToString());
                inMessage.SetStatus(InStatus.Notified);

                db.InMessages.Add(inMessage);

                await db.SaveChangesAsync();

                savedInMessageId = inMessage.Id;

                Assert.NotEqual(default(long), savedInMessageId);
            }

            using (var db = this.GetDataStoreContext())
            {
                var inMessage = db.InMessages.FirstOrDefault(i => i.Id == savedInMessageId);

                Assert.NotNull(inMessage);
                Assert.Equal(InStatus.Notified, inMessage.Status.ToEnum <InStatus>());
            }
        }
コード例 #8
0
        public async Task InMessageMessageTypeIsCorrectlyPersisted()
        {
            long savedInMessageId;

            using (var db = this.GetDataStoreContext())
            {
                var inMessage = new InMessage(Guid.NewGuid().ToString());
                inMessage.EbmsMessageType = MessageType.Receipt;

                db.InMessages.Add(inMessage);

                await db.SaveChangesAsync();

                savedInMessageId = inMessage.Id;

                Assert.NotEqual(default(long), savedInMessageId);
            }

            using (var db = this.GetDataStoreContext())
            {
                var inMessage = db.InMessages.FirstOrDefault(i => i.Id == savedInMessageId);

                Assert.NotNull(inMessage);
                Assert.Equal(MessageType.Receipt, inMessage.EbmsMessageType);
            }
        }
コード例 #9
0
        public async Task PModeInformationIsCorrectlyPersisted()
        {
            long savedId;

            const string pmodeId      = "pmodeId";
            const string pmodeContent = "<pmode><id>pmodeId</id></pmode>";

            using (var db = GetDataStoreContext())
            {
                var message = new InMessage("some-message-id");
                message.SetPModeInformation(pmodeId, pmodeContent);

                db.InMessages.Add(message);

                await db.SaveChangesAsync();

                savedId = message.Id;
            }

            using (var db = this.GetDataStoreContext())
            {
                var message = db.InMessages.FirstOrDefault(i => i.Id == savedId);

                Assert.NotNull(message);
                Assert.Equal(pmodeId, message.PModeId);
                Assert.Equal(pmodeContent, message.PMode);
            }
        }
コード例 #10
0
        private void ParseInitialize(InMessage message)
        {
            int count = message.ReadUShort();

            for (int i = 0; i < count; i++)
            {
                var creature = new Creature(message.ReadUInt());
                creature.Type = (CreatureType)message.ReadByte();
                creature.Name = message.ReadString();

                //Trace.WriteLine(String.Format("Creature[{0}]: {1}", i, creature.Name));

                creature.Health = message.ReadByte();
                var direction = (Direction)message.ReadByte();
                creature.LookDirection = direction;
                creature.TurnDirection = direction;

                //Outfit
                creature.Outfit       = message.ReadOutfit();
                creature.LightLevel   = message.ReadByte();
                creature.LightColor   = message.ReadByte();
                creature.Speed        = message.ReadUShort();
                creature.Skull        = message.ReadByte();
                creature.Shield       = message.ReadByte();
                creature.Emblem       = message.ReadByte();
                creature.IsImpassable = message.ReadByte() == 0x01;

                client.BattleList.AddCreature(creature);
            }

            ParseTibiaPackets(message);
        }
コード例 #11
0
ファイル: MessageHandler.cs プロジェクト: devBoolean/Boolean
        public static void HandleEvent(Session Session, InMessage InMessage)
        {
            if (Session.Character == null)
            {
                if (InMessage.Id != 206 && InMessage.Id != 415)
                {
                    Solution.AppendPaint();
                    Solution.AppendLine("MessageHandler: ({0})Tried to bypass authenticating.", Session.Id);
                    SessionHandler.CloseClientSocket(Session.Args);
                    return;
                }
            }

            if (Events.ContainsKey(InMessage.Id))
            {
                var Event     = Events[InMessage.Id];
                var EventName = Event.ToString().Split('.')[Event.ToString().Split('.').Count() - 1];

                try
                {
                    Event.Invoke(Session, InMessage);
                }
                catch (Exception e)
                {
                    Solution.AppendPaint();
                    Solution.AppendLine(e.ToString());
                }

                Solution.AppendLine("HandleEvent: ({0}){1}({2})", Session.Id, EventName, InMessage.Id);
            }
            else
            {
                Solution.AppendLine("HandleEvent: ({0}){1}({2})", Session.Id, Encoding.ASCII.GetString(InMessage.Context), InMessage.Id);
            }
        }
コード例 #12
0
ファイル: Connection.cs プロジェクト: Herhangi/HerhangiOT
        protected virtual void ParseHeader(IAsyncResult ar)
        {
            if (!EndRead(ar))
            {
                return;
            }

            uint recvChecksum = InMessage.GetUInt32(); //Adler Checksum
            uint checksum     = Tools.AdlerChecksum(InMessage.Buffer, InMessage.Position, InMessage.Length - 6);

            if (checksum != recvChecksum)
            {
                InMessage.SkipBytes(-4);
            }

            if (!IsFirstMessageReceived)
            {
                IsFirstMessageReceived = true;
                ProcessFirstMessage(checksum == recvChecksum);
            }
            else
            {
                if (IsEncryptionEnabled && !InMessage.XteaDecrypt(XteaKey))
                {
                    return;
                }

                ProcessMessage();
            }
        }
コード例 #13
0
            public async Task ThenMessageIsForwarded()
            {
                // Arrange
                InMessage receivedInMessage = InPersistentUserMessage();

                await InsertInMessageIntoDatastore(receivedInMessage);

                MessagingContext messagingContext = ContextWithReferencedToBeForwardMessage();

                // Act
                await ExerciseCreateForwardMessage(messagingContext);

                // Assert
                // Verify if there exists a correct OutMessage record.
                using (DatastoreContext db = GetDataStoreContext())
                {
                    OutMessage outMessage = db.OutMessages.First(m => m.EbmsMessageId == receivedInMessage.EbmsMessageId);

                    Assert.Equal(Operation.ToBeProcessed, outMessage.Operation);
                    Assert.Equal(messagingContext.SendingPMode.MessagePackaging.Mpc, outMessage.Mpc);
                    Assert.Equal(messagingContext.SendingPMode.MepBinding.ToString(), outMessage.MEP.ToString());

                    InMessage inMessage = db.InMessages.First(m => m.EbmsMessageId == receivedInMessage.EbmsMessageId);

                    Assert.Equal(Operation.Forwarded, inMessage.Operation);
                }
            }
コード例 #14
0
        public static string RenderMessage(InMessage message, int depth = 0)
        {
            var builder = new MessageBuilder()
                          .AddText($"== User ==")
                          .AddText($"Id: {message.Sender.Id}")
                          .AddText($"IsBot: {message.Sender.IsBot}")
                          .AddText($"Username: {message.Sender.Username}")
                          .AddText($"FirstName: {message.Sender.FirstName}");

            if (message.Sender.LastName != null)
            {
                builder.AddText($"LastName: {message.Sender.LastName}");
            }
            builder.AddText($"Language: {message.Sender.Language}");
            var offset = string.Join("", Enumerable.Repeat("    ", depth));

            if (message.Reply != null)
            {
                builder.AddText($"== Reply ==\n" + RenderMessage(message.Reply, depth + 1));
            }
            for (var i = 0; i < message.Forwarded.Length; i++)
            {
                builder.AddText($"== Forwarded #{i} ==\n" + RenderMessage(message.Forwarded[i], depth + 1));
            }
            for (var i = 0; i < message.Attachments.Length; i++)
            {
                var attachment = message.Attachments[i];
                var aset       = string.Join("", Enumerable.Repeat("    ", depth == 0 ? 1 : depth));
                builder.AddText($"== Attachment #{i} : {attachment.GetType().Name} ==\n{aset}{RenderAttachment(attachment).Replace("\n", "\n" + aset)}");
            }
            return(offset + builder.Build().Text.Replace("\n", "\n" + offset));
        }
コード例 #15
0
        public async Task Agent_Processes_Signed_Encrypted_UserMessage_With_Static_ReceivingPMode()
        {
            await TestStaticReceive(
                StaticReceiveSettings,
                async (url, msh) =>
            {
                // Arrange
                string ebmsMessageId = $"user-{Guid.NewGuid()}";
                AS4Message m         = SignedEncryptedAS4UserMessage(msh, ebmsMessageId);

                // Act
                HttpResponseMessage response =
                    await StubSender.SendAS4Message(url, m);

                // Assert
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                var spy          = new DatabaseSpy(msh.GetConfiguration());
                InMessage actual = await PollUntilPresent(
                    () => spy.GetInMessageFor(im => im.EbmsMessageId == ebmsMessageId),
                    timeout: TimeSpan.FromSeconds(15));

                Assert.Equal(Operation.ToBeDelivered, actual.Operation);
                Assert.Equal(InStatus.Received, actual.Status.ToEnum <InStatus>());
                Assert.Equal(DefaultPModeId, actual.PModeId);
            });
        }
コード例 #16
0
        private void ParsePacket(InMessage message)
        {
            while (message.ReadPosition < message.Size)
            {
                var packetType = (TibiaCastPacketType)message.ReadByte();

                switch (packetType)
                {
                case TibiaCastPacketType.CloseShopWindow:
                    //this.g(ax);
                    message.ReadByte();
                    break;

                case TibiaCastPacketType.Initialize:
                    ParseInitialize(message);
                    break;

                case TibiaCastPacketType.TibiaPackets:
                    ParseTibiaPackets(message);
                    break;

                case TibiaCastPacketType.Message:
                    message.ReadString();
                    message.ReadString();
                    break;

                default:
                    throw new Exception(string.Format("Unknown packet type ({0}) when reading TibiaCast file.", packetType));
                }
            }
        }
コード例 #17
0
        private static ExchangeItem GetPlatformExchangeFromConfig(ExchangeElement configElement)
        {
            var item = new ExchangeItem()
            {
                Name = configElement.Name, PrefetchCount = configElement.PrefetchCount, Type = configElement.Type, Out = new List <OutMessage>(), In = new List <InMessage>()
            };

            foreach (var outEl in configElement.Out.Cast <OutgoingElement>())
            {
                var outItem = new OutMessage()
                {
                    Key = outEl.Key, Name = outEl.Name, Persist = outEl.Persist, Timeout = outEl.Timeout
                };
                item.Out.Add(outItem);
            }
            foreach (var inElement in configElement.In.Cast <IncomingElement>())
            {
                var inItem = new InMessage()
                {
                    Key = inElement.Key, Name = inElement.Name, Type = inElement.Type, React = inElement.React
                };
                item.In.Add(inItem);
            }

            return(item);
        }
コード例 #18
0
        public async Task Deliver_Message_Only_When_Referenced_Payloads_Are_Delivered()
        {
            AS4Message as4Message = await CreateAS4MessageFrom(deliveragent_message);

            string deliverLocation = DeliverPayloadLocationOf(as4Message.Attachments.First());

            CleanDirectoryAt(Path.GetDirectoryName(deliverLocation));

            // Act
            IPMode pmode = CreateReceivedPMode(
                deliverMessageLocation: DeliveryRoot,
                deliverPayloadLocation: @"%# \ (+_O) / -> Not a valid path");

            InMessage inMessage = CreateInMessageRepresentingUserMessage(as4Message.GetPrimaryMessageId(), as4Message, pmode);

            await InsertInMessageAsync(inMessage);

            // Assert
            var       spy    = DatabaseSpy.Create(_as4Msh.GetConfiguration());
            InMessage actual = await PollUntilPresent(
                () => spy.GetInMessageFor(im => im.Id == inMessage.Id && im.Status == InStatus.Exception.ToString()),
                TimeSpan.FromSeconds(10));

            Assert.Empty(Directory.EnumerateFiles(DeliveryRoot));
            Assert.Equal(InStatus.Exception, actual.Status.ToEnum <InStatus>());
            Assert.Equal(Operation.DeadLettered, actual.Operation);
        }
コード例 #19
0
        /// <summary>
        /// Prepare <see cref="InMessage"/> as a message that has yet to be determined what it's endpoint will be.
        /// This is used for (quick) saving the incoming message but process the message on a later time.
        /// </summary>
        /// <returns></returns>
        public InMessage BuildAsToBeProcessed()
        {
            if (_messageUnit == null)
            {
                throw new InvalidDataException("Builder needs a Message Unit for building an InMessage");
            }

            var inMessage = new InMessage(_messageUnit.MessageId)
            {
                EbmsRefToMessageId = _messageUnit.RefToMessageId,
                ContentType        = _contentType,
                InsertionTime      = DateTimeOffset.Now,
                ModificationTime   = DateTimeOffset.Now,
                MessageLocation    = _location,
                EbmsMessageType    = DetermineMessageType(_messageUnit),
                MEP       = _mep,
                Operation = Operation.NotApplicable
            };

            inMessage.SetPModeInformation(_pmode);
            inMessage.SetStatus(InStatus.Received);
            inMessage.AssignAS4Properties(_messageUnit);

            return(inMessage);
        }
コード例 #20
0
        private async Task TestExecutionException(
            Operation expected,
            MessagingContext context,
            Func <IAgentExceptionHandler, Func <Exception, MessagingContext, Task <MessagingContext> > > getExercise)
        {
            // Arrange
            var inMessage = new InMessage(ebmsMessageId: _expectedId);

            inMessage.SetStatus(InStatus.Received);

            GetDataStoreContext.InsertInMessage(inMessage);

            IAgentExceptionHandler sut = CreateInboundExceptionHandler();
            var exercise = getExercise(sut);

            // Act
            await exercise(new Exception(), context);

            // Assert
            GetDataStoreContext.AssertInMessage(_expectedId, m => Assert.Equal(InStatus.Exception, m.Status.ToEnum <InStatus>()));
            GetDataStoreContext.AssertInException(
                _expectedId,
                ex =>
            {
                Assert.Equal(expected, ex.Operation);
                Assert.Null(ex.MessageLocation);
            });
        }
コード例 #21
0
        public async Task SignalMessage_Gets_Saved_As_Duplicate_When_InMessage_Exists_With_Same_EbmsRefToMessageId()
        {
            // Arrange
            string ebmsMessageId      = $"receipt-{Guid.NewGuid()}";
            string ebmsRefToMessageId = $"user-{Guid.NewGuid()}";

            GetDataStoreContext.InsertInMessage(
                new InMessage(ebmsMessageId)
            {
                EbmsRefToMessageId = ebmsRefToMessageId
            });

            var receipt = new Receipt(ebmsMessageId, ebmsRefToMessageId);
            var context = new MessagingContext(
                AS4Message.Create(receipt),
                new ReceivedMessage(Stream.Null),
                MessagingContextMode.Receive);

            // Act
            await Step.ExecuteAsync(context);

            // Assert
            InMessage actual = GetDataStoreContext.GetInMessage(
                m => m.EbmsMessageId == ebmsMessageId &&
                m.EbmsRefToMessageId == ebmsRefToMessageId &&
                m.IsDuplicate);

            Assert.True(actual != null, "Saved Receipt should be marked as duplicate");
        }
コード例 #22
0
        private void InsertToBeForwardedInMessage(string pmodeId, MessageExchangePattern mep, AS4Message tobeForwarded)
        {
            foreach (MessageUnit m in tobeForwarded.MessageUnits)
            {
                string location =
                    Registry.Instance
                    .MessageBodyStore
                    .SaveAS4Message(
                        _as4Msh.GetConfiguration().InMessageStoreLocation,
                        tobeForwarded);

                var inMessage = new InMessage(m.MessageId)
                {
                    Intermediary = true,
                    Operation    =
                        m.MessageId == tobeForwarded.PrimaryMessageUnit.MessageId
                            ? Operation.ToBeForwarded
                            : Operation.NotApplicable,
                    MessageLocation = location,
                    MEP             = mep,
                    ContentType     = tobeForwarded.ContentType
                };

                ReceivingProcessingMode forwardPMode =
                    _as4Msh.GetConfiguration()
                    .GetReceivingPModes()
                    .First(p => p.Id == pmodeId);

                inMessage.SetPModeInformation(forwardPMode);
                inMessage.SetStatus(InStatus.Received);
                inMessage.AssignAS4Properties(m);
                _databaseSpy.InsertInMessage(inMessage);
            }
        }
コード例 #23
0
        public async Task OutMessageIsCreatedForToBeForwardedMessage()
        {
            // Arrange
            const string messageId  = "message-id";
            var          as4Message = AS4Message.Create(CreateForwardPushUserMessage(messageId));

            // Act
            InsertToBeForwardedInMessage(
                pmodeId: "Forward_Push",
                mep: MessageExchangePattern.Push,
                tobeForwarded: as4Message);

            // Assert: if an OutMessage is created with the correct status and operation.
            InMessage inMessage = await PollUntilPresent(
                () => _databaseSpy.GetInMessageFor(
                    m => m.EbmsMessageId == messageId &&
                    m.Operation == Operation.Forwarded),
                TimeSpan.FromSeconds(15));

            Assert.NotNull(AS4XmlSerializer.FromString <ReceivingProcessingMode>(inMessage.PMode));

            OutMessage outMessage = await PollUntilPresent(
                () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == messageId),
                timeout : TimeSpan.FromSeconds(5));

            Assert.True(outMessage.Intermediary);
            Assert.Equal(Operation.ToBeProcessed, outMessage.Operation);
            Assert.NotNull(AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode));
        }
コード例 #24
0
            public async Task PModeInformationIsCorrectlyRetrieved()
            {
                const string messageId = "messageId";
                const string pmodeId   = "TestPModeId";

                using (var db = GetDataStoreContext())
                {
                    var inMessage = new InMessage(messageId)
                    {
                        MessageLocation = "test"
                    };
                    inMessage.SetPModeInformation(new SendingProcessingMode()
                    {
                        Id = pmodeId
                    });

                    db.InMessages.Add(inMessage);

                    await db.SaveChangesAsync();
                }

                using (var db = GetDataStoreContext())
                {
                    var inMessage = db.InMessages.FirstOrDefault(m => m.EbmsMessageId == messageId);
                    Assert.NotNull(inMessage);
                    Assert.False(String.IsNullOrWhiteSpace(inMessage.PModeId));
                    Assert.False(String.IsNullOrWhiteSpace(inMessage.PMode));
                }
            }
コード例 #25
0
        public async Task ForwardingWithPullOnPush()
        {
            // Arrange
            const string messageId  = "message-id";
            AS4Message   as4Message = AS4Message.Create(CreateForwardPullUserMessage(messageId));

            // Act
            InsertToBeForwardedInMessage(
                pmodeId: "Forward_Pull",
                mep: MessageExchangePattern.Push,
                tobeForwarded: as4Message);

            // Assert: if an OutMessage is created with the correct status and operation.
            InMessage inMessage = await PollUntilPresent(
                () => _databaseSpy.GetInMessageFor(
                    m => m.EbmsMessageId == messageId &&
                    m.Operation == Operation.Forwarded),
                TimeSpan.FromSeconds(15));

            var receivingPMode = AS4XmlSerializer.FromString <ReceivingProcessingMode>(inMessage.PMode);

            Assert.NotNull(receivingPMode);

            OutMessage outMessage = await PollUntilPresent(
                () => _databaseSpy.GetOutMessageFor(
                    m => m.EbmsMessageId == messageId &&
                    m.Operation == Operation.ToBeProcessed),
                TimeSpan.FromSeconds(5));

            var sendingPMode = AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode);

            Assert.NotNull(sendingPMode);
            Assert.Equal(MessageExchangePattern.Pull, outMessage.MEP);
            Assert.Equal(sendingPMode.MessagePackaging.Mpc, outMessage.Mpc);
        }
コード例 #26
0
            public async Task IdIsCorrectlyRetrieved()
            {
                const string messageId = "messageId";

                using (var db = GetDataStoreContext())
                {
                    var inMessage = new InMessage(messageId)
                    {
                        MessageLocation = "test"
                    };

                    Assert.Equal(default(int), inMessage.Id);

                    db.InMessages.Add(inMessage);

                    await db.SaveChangesAsync();
                }

                using (var db = GetDataStoreContext())
                {
                    var inMessage = db.InMessages.FirstOrDefault(m => m.EbmsMessageId == messageId);
                    Assert.NotNull(inMessage);
                    Assert.NotEqual(default(int), inMessage.Id);
                }
            }
コード例 #27
0
        /// <summary>
        /// Updates a set of <see cref="InMessage"/> entities using a <paramref name="updateAction"/> function
        /// for which the given <paramref name="predicate"/> holds.
        /// </summary>
        /// <param name="predicate">The predicate function to locate a set of <see cref="InMessage"/> entities</param>
        /// <param name="updateAction">The update function to change the located <see cref="InMessage"/> entities</param>
        public void UpdateInMessages(Expression <Func <InMessage, bool> > predicate, Action <InMessage> updateAction)
        {
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (updateAction == null)
            {
                throw new ArgumentNullException(nameof(updateAction));
            }

            var inMessageIds = _datastoreContext.InMessages.Where(predicate).Select(m => new { m.EbmsMessageId, m.Id }).ToArray();

            if (inMessageIds.Any())
            {
                foreach (var idSet in inMessageIds)
                {
                    InMessage message = GetInMessageEntityFor(idSet.Id);
                    if (message != null)
                    {
                        updateAction(message);
                        message.ModificationTime = DateTimeOffset.Now;
                    }
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Update a found InMessage (by AS4 Message Id) in the Data store
        /// </summary>
        /// <param name="messageId"></param>
        /// <param name="updateAction"></param>
        public void UpdateInMessage(string messageId, Action <InMessage> updateAction)
        {
            if (messageId == null)
            {
                throw new ArgumentNullException(nameof(messageId));
            }

            if (updateAction == null)
            {
                throw new ArgumentNullException(nameof(updateAction));
            }

            // There might exist multiple InMessage records for the given messageId, therefore we cannot use
            // caching here.
            long[] inMessageIds = _datastoreContext.InMessages.Where(m => m.EbmsMessageId.Equals(messageId)).Select(m => m.Id).ToArray();

            foreach (long id in inMessageIds)
            {
                InMessage message = GetInMessageEntityFor(id);
                if (message == null)
                {
                    LogManager.GetCurrentClassLogger().Warn($"Unable to update InMessage {messageId}.  There exists no such InMessage.");
                    return;
                }

                updateAction(message);
                message.ModificationTime = DateTimeOffset.Now;
            }
        }
コード例 #29
0
ファイル: MessageHandler.cs プロジェクト: devBoolean/Boolean
        public static void HandleBytes(Session Session, ref byte[] Bytes)
        {
            if (Encoding.ASCII.GetString(Bytes) == "<policy-file-request/>\x0")
            {
                Session.Send(PolicyFileRequest);
                return;
            }

            var Pointer = new int();

            try
            {
                for (; Pointer < Bytes.Length;)
                {
                    var MessageLength = Base64Encoding.DecodeInt32(new byte[] { Bytes[Pointer++], Bytes[Pointer++], Bytes[Pointer++] });
                    var MessageId     = Base64Encoding.DecodeInt32(new byte[] { Bytes[Pointer++], Bytes[Pointer++] });

                    var ContextLength = (MessageLength - 2);
                    var Context       = new byte[ContextLength];

                    Array.Copy(Bytes, Pointer, Context, 0, ContextLength);

                    Pointer += ContextLength;

                    var InMessage = new InMessage(MessageId, Context);

                    HandleEvent(Session, InMessage);
                }
            }
            catch { }
        }
コード例 #30
0
 private async Task InsertInMessageIntoDatastore(InMessage receivedInMessage)
 {
     using (DatastoreContext db = GetDataStoreContext())
     {
         db.InMessages.Add(receivedInMessage);
         await db.SaveChangesAsync();
     }
 }