コード例 #1
0
            public async Task ThenExecuteStepSucceedsAsync()
            {
                // Arrange
                AS4Message as4Message = await GetEncryptedAS4MessageAsync();

                var context = new MessagingContext(as4Message, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { Decryption                        =
                                     {
                                         Encryption                    = Limit.Allowed,
                                         DecryptCertificateInformation = new CertificateFindCriteria
                                         {
                                             CertificateFindValue = "",
                                             CertificateFindType  = X509FindType.FindByIssuerName
                                         }
                                     } }
                    }
                };

                // Act
                StepResult stepResult = await ExerciseDecryption(context);

                // Assert
                Assert.False(stepResult.MessagingContext.AS4Message.IsEncrypted);
            }
コード例 #2
0
        /// <summary>
        /// Create a new <see cref="AS4Response"/> instance.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="webResponse"></param>
        /// <returns></returns>
        public static async Task <AS4Response> Create(MessagingContext requestMessage, HttpWebResponse webResponse)
        {
            var response       = new AS4Response(requestMessage, webResponse);
            var responseStream = webResponse.GetResponseStream() ?? Stream.Null;
            var contentStream  = VirtualStream.Create(webResponse.ContentLength, forAsync: true);

            await responseStream.CopyToFastAsync(contentStream);

            contentStream.Position = 0;

            response.ReceivedStream =
                new ReceivedMessage(
                    contentStream,
                    webResponse.ContentType,
                    webResponse.ResponseUri?.AbsolutePath ?? "unknown",
                    webResponse.ContentLength);

            response.ReceivedAS4Message = await TryDeserializeReceivedStream(response.ReceivedStream, CancellationToken.None);

            if (Logger.IsInfoEnabled)
            {
                if (response.ReceivedAS4Message.IsEmpty == false)
                {
                    LogReceivedAS4Response(
                        requestMessage.AS4Message,
                        response.ReceivedAS4Message);
                }
            }

            return(response);
        }
コード例 #3
0
        protected override async Task <CompareItemsResult> ExecuteAsync(CompareItemsMessage message)
        {
            return(await Task.Run(() => {
                var buildPath = Path.Combine(MessagingContext.GetBuildPath(), message.AppName, message.SessionId);
                var files = new List <string> ();

                using (var hashAlgorithm = Hash.GetAlgorithm()) {
                    foreach (var file in message.Items)
                    {
                        var targetPath = Path.Combine(buildPath, PlatformPath.GetPathForCurrentPlatform(file.ItemSpec));

                        if (!File.Exists(targetPath))
                        {
                            files.Add(file.ItemSpec);
                        }
                        else
                        {
                            using (var stream = File.OpenRead(targetPath)) {
                                var localHash = hashAlgorithm.ComputeHashAsString(stream);

                                if (file.Hash != localHash)
                                {
                                    files.Add(file.ItemSpec);
                                }
                            }
                        }
                    }
                }

                return new CompareItemsResult {
                    MissingFiles = files
                };
            }).ConfigureAwait(continueOnCapturedContext: false));
        }
コード例 #4
0
        /// <summary>
        /// Execute the step for a given <paramref name="messagingContext" />.
        /// </summary>
        /// <param name="messagingContext">Message used during the step execution.</param>
        /// <returns></returns>
        public Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            if (messagingContext == null)
            {
                throw new ArgumentNullException(nameof(messagingContext));
            }

            if (messagingContext.AS4Message == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(VerifyPullRequestAuthorizationStep)} requires a MessagingContext with a AS4Message to verify the PullRequest");
            }

            AS4Message as4Message = messagingContext.AS4Message;

            var authorizationMap = new PullAuthorizationMapService(_pullAuthorizationMapProvider);

            if (authorizationMap.IsPullRequestAuthorized(as4Message))
            {
                return(StepResult.SuccessAsync(messagingContext));
            }

            string mpc = (as4Message.FirstSignalMessage as PullRequest)?.Mpc ?? string.Empty;

            throw new SecurityException(
                      $"{messagingContext.LogTag} PullRequest for MPC {mpc} is not authorized. " +
                      "Either change the PullRequest MPC or add the MPC value to the authorization map");
        }
コード例 #5
0
        private async Task <MessagingContext> InsertReceivedAS4MessageAsync(MessagingContext messagingContext)
        {
            using (DatastoreContext context = _createDatastoreContext())
            {
                MessageExchangePattern messageExchangePattern =
                    messagingContext.Mode == MessagingContextMode.PullReceive
                        ? MessageExchangePattern.Pull
                        : MessageExchangePattern.Push;

                try
                {
                    var        service    = new InMessageService(_config, new DatastoreRepository(context));
                    AS4Message as4Message = await service
                                            .InsertAS4MessageAsync(
                        messagingContext.AS4Message,
                        messagingContext.ReceivedMessage,
                        messagingContext.SendingPMode,
                        messageExchangePattern,
                        _messageBodyStore)
                                            .ConfigureAwait(false);

                    messagingContext.ModifyContext(as4Message);
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(messagingContext);
                }
                catch (Exception ex)
                {
                    return(new MessagingContext(ex));
                }
            }
        }
コード例 #6
0
        public async Task Returns_With_Error_PMode_Not_Found_When_ReceivePMode_Is_Not_Defined(string id)
        {
            // Arrange
            var stub = new Mock <IConfig>();

            stub.Setup(c => c.GetReceivingPModes())
            .Returns(new[] { new ReceivingProcessingMode {
                                 Id = "existing-id"
                             } });

            var sut = new ReceiveMessageTransformer(stub.Object);

            sut.Configure(
                new Dictionary <string, string>
            {
                [ReceiveMessageTransformer.ReceivingPModeKey] = id
            });

            var msg = new ReceivedMessage(
                AS4Message.Empty.ToStream(),
                Constants.ContentTypes.Soap);

            // Act
            MessagingContext actual = await sut.TransformAsync(msg);

            // Assert
            MessageUnit primaryMessageUnit = actual.AS4Message.MessageUnits.First();

            Assert.IsType <Error>(primaryMessageUnit);
            var error = (Error)primaryMessageUnit;

            Assert.Equal(
                ErrorAlias.ProcessingModeMismatch,
                error.ErrorLines.First().ShortDescription);
        }
コード例 #7
0
            public async Task SendingPModeCorrectlyDetermined()
            {
                const string sendingPModeId = "Forward_SendingPMode_Id";

                var receivingPMode = new ReceivingProcessingMode()
                {
                    MessageHandling = new MessageHandling()
                    {
                        Item = new AS4.Model.PMode.Forward()
                        {
                            SendingPMode = sendingPModeId
                        }
                    }
                };

                var config = new StubConfig(sendingPModes: new Dictionary <string, SendingProcessingMode>()
                {
                    { sendingPModeId, new SendingProcessingMode()
                      {
                          Id = sendingPModeId
                      } }
                },
                                            receivingPModes: new Dictionary <string, ReceivingProcessingMode>());

                var context = new MessagingContext(new ReceivedMessage(Stream.Null), MessagingContextMode.Forward)
                {
                    ReceivingPMode = receivingPMode
                };

                var sut    = new DetermineRoutingStep(config);
                var result = await sut.ExecuteAsync(context);

                Assert.True(result.Succeeded);
                Assert.NotNull(result.MessagingContext.SendingPMode);
            }
コード例 #8
0
        /// <summary>
        /// Execute the step for a given <paramref name="messagingContext"/>.
        /// </summary>
        /// <param name="messagingContext">The Message used during the step execution.</param>
        /// <returns></returns>
        public async Task <StepResult> ExecuteAsync(MessagingContext messagingContext)
        {
            if (messagingContext?.AS4Message == null)
            {
                throw new InvalidOperationException(
                          $"{nameof(StoreAS4MessageStep)} requires an AS4Message to save but no AS4Message is present in the MessagingContext");
            }

            Logger.Trace("Storing the AS4Message with Operation=ToBeProcessed...");
            using (DatastoreContext context = _createContext())
            {
                var repository = new DatastoreRepository(context);
                var service    = new OutMessageService(_config, repository, _messageBodyStore);
                service.InsertAS4Message(
                    messagingContext.AS4Message,
                    messagingContext.SendingPMode,
                    messagingContext.ReceivingPMode);

                try
                {
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
                catch
                {
                    messagingContext.ErrorResult = new ErrorResult(
                        "Unable to store the received message due to an exception occured during the saving operation",
                        ErrorAlias.Other);

                    throw;
                }
            }

            Logger.Trace("Stored the AS4Message with Operation=ToBeProcesed");
            return(await StepResult.SuccessAsync(messagingContext));
        }
コード例 #9
0
        public async Task Adds_ReceivePMode_When_PMode_Setting_Is_Defined(string id)
        {
            // Arrange
            var stub = new Mock <IConfig>();

            stub.Setup(c => c.GetReceivingPModes())
            .Returns(new[] { new ReceivingProcessingMode {
                                 Id = "existing-id"
                             } });

            var sut = new ReceiveMessageTransformer(stub.Object);

            sut.Configure(
                new Dictionary <string, string>
            {
                [ReceiveMessageTransformer.ReceivingPModeKey] = null
            });

            var msg = new ReceivedMessage(
                AS4Message.Empty.ToStream(),
                Constants.ContentTypes.Soap);

            // Act
            MessagingContext result = await sut.TransformAsync(msg);

            // Assert
            bool expectedNotConfiguredPMode = result.ReceivingPMode == null;
            bool expectedConfiguredPMode    = result.ReceivingPMode?.Id == id;

            Assert.True(expectedNotConfiguredPMode || expectedConfiguredPMode);
        }
コード例 #10
0
        public ActionResult Index()
        {
            string user = User.Identity.GetUserName();

            using (var db = new MessagingContext())
            {
                var query = from m in db.Messages
                            orderby m.Time
                            where m.ToUserID == user && !m.Seen
                            select new MessageViewModel
                {
                    fromUser    = m.FromUserID,
                    MessageText = m.MessageText,
                    Time        = m.Time,
                    Image       = m.Image
                };


                MessagesViewModel messagesVM = new MessagesViewModel();
                messagesVM.Messages = query.ToList();



                return(View(messagesVM));
            }
        }
コード例 #11
0
        public JsonResult MessagesViewed()
        {
            string user = User.Identity.GetUserName();

            using (var db = new MessagingContext())
            {
                var updateQuery = db.Messages.Where(f => f.ToUserID == user).ToList();

                updateQuery.ForEach(a => a.Seen = true);

                var ImageDeleteQuery = db.Messages.Where(f => f.ToUserID == user && f.Image != null).ToList();

                foreach (var item in ImageDeleteQuery)
                {
                    string fullPath = Request.MapPath("~/ContentUser/" + Encoding.ASCII.GetString(item.Image));
                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                    }
                }

                //db.Messages.RemoveRange(db.Messages.Where(f => f.ToUserID == user && f.Image != null));
                db.SaveChanges();

                return(Json(new { result = "ok" }));
            }
        }
        /// <summary>
        /// Transform a given <see cref="ReceivedMessage"/> to a Canonical <see cref="MessagingContext"/> instance.
        /// </summary>
        /// <param name="message">Given message to transform.</param>
        /// <returns></returns>
        public async Task <MessagingContext> TransformAsync(ReceivedMessage message)
        {
            // We receive an AS4Message from Minder, we should convert it to a SubmitMessage if the action is submit.
            // In any other case, we should just return an MessagingContext which contains the as4Message.
            var transformer      = new AS4MessageTransformer();
            var messagingContext = await transformer.TransformAsync(message);

            var as4Message = messagingContext.AS4Message;

            if (as4Message?.FirstUserMessage?.CollaborationInfo?.Action?.Equals("Submit", StringComparison.OrdinalIgnoreCase) ?? false)
            {
                var properties = as4Message.FirstUserMessage?.MessageProperties;

                UserMessage transformed = TransformUserMessage(as4Message.FirstUserMessage, properties);
                as4Message.UpdateMessageUnit(as4Message.FirstUserMessage, transformed);

                messagingContext = new MessagingContext(as4Message, MessagingContextMode.Submit);

                AssignPModeToContext(messagingContext);

                return(messagingContext);
            }

            return(new MessagingContext(as4Message, MessagingContextMode.Receive));
        }
コード例 #13
0
        private static async Task <StepResult> ExerciseCompression(MessagingContext context)
        {
            var sut = new CompressAttachmentsStep();

            // Act
            return(await sut.ExecuteAsync(context));
        }
コード例 #14
0
        private X509Certificate2 GetCertificate(MessagingContext messagingContext)
        {
            Decryption decryption = messagingContext.ReceivingPMode.Security.Decryption;

            if (decryption.DecryptCertificateInformation == null)
            {
                throw new ConfigurationErrorsException(
                          "Cannot start decrypting: no certificate information found " +
                          $"in ReceivingPMode {messagingContext.ReceivingPMode.Id} to decrypt the message. " +
                          "Please use either a <CertificateFindCriteria/> or <PrivateKeyCertificate/> to specify the certificate information");
            }

            if (decryption.DecryptCertificateInformation is CertificateFindCriteria certFindCriteria)
            {
                return(_certificateRepository.GetCertificate(
                           certFindCriteria.CertificateFindType,
                           certFindCriteria.CertificateFindValue));
            }

            if (decryption.DecryptCertificateInformation is PrivateKeyCertificate embeddedCertInfo)
            {
                return(new X509Certificate2(
                           rawData: Convert.FromBase64String(embeddedCertInfo.Certificate),
                           password: embeddedCertInfo.Password,
                           keyStorageFlags: X509KeyStorageFlags.Exportable
                           | X509KeyStorageFlags.MachineKeySet
                           | X509KeyStorageFlags.PersistKeySet));
            }

            throw new NotSupportedException(
                      "The decrypt-certificate information specified in the ReceivingPMode " +
                      $"{messagingContext.ReceivingPMode.Id} could not be used to retrieve the certificate used for decryption. " +
                      "Please use either a <CertificateFindCriteria/> or <PrivateKeyCertificate/> to specify the certificate information");
        }
コード例 #15
0
            public async Task TestIfAttachmentContentTypeIsSetBackToOriginal()
            {
                // Arrange
                AS4Message as4Message = await GetEncryptedAS4MessageAsync();

                var context = new MessagingContext(as4Message, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { Decryption                        =
                                     {
                                         Encryption                    = Limit.Allowed,
                                         DecryptCertificateInformation = new CertificateFindCriteria {
                                             CertificateFindType       = X509FindType.FindBySerialNumber
                                         }
                                     } }
                    }
                };

                // Act
                StepResult result = await ExerciseDecryption(context);

                // Assert
                IEnumerable <Attachment> attachments = result.MessagingContext.AS4Message.Attachments;

                Assert.All(attachments, a => Assert.Equal("image/jpeg", a.ContentType));
            }
コード例 #16
0
        private static async void ReceiveEntity(Entity entity, Function messageCallback, CancellationToken token)
        {
            var message             = new ReceivedEntityMessage(entity);
            MessagingContext result = await messageCallback(message, token).ConfigureAwait(false);

            result?.Dispose();
        }
コード例 #17
0
        public void CommitQueue(int userId, int nodeId, int readerId, int readerNodeId, string queueName)
        {
            using (var ctx = new MessagingContext())
            {
                //var r = ctx.Readers.FirstOrDefault(reader => reader.UserId == userId && reader.NodeId == nodeId);
                var r = ctx.Readers.FirstOrDefault(reader => reader.UserId == readerId && reader.NodeId == readerNodeId);

                /* For now, remember messages only until the last user read them */
                var q = ctx.MsgQueues.FirstOrDefault(queue => queue.Name == queueName && queue.UserId == userId && queue.NodeId == nodeId);

                int highestIndex = ctx.Readers.FirstOrDefault(reader => reader.UserId == readerId && reader.NodeId == readerNodeId).Position;

                foreach (Message m in q.Messages.FindAll(m => (m.MsgIdx > highestIndex)))
                {
                    if (m.MsgIdx > highestIndex)
                    {
                        highestIndex = m.MsgIdx;
                    }
                }

                r.Position = highestIndex;
                q.Messages.RemoveAll(m => (m.MsgIdx <= q.Readers.Min(rUser => (rUser.Position))));

                ctx.SaveChanges();
            }
        }
コード例 #18
0
        private async Task <StepResult> DecryptAS4MessageAsync(MessagingContext messagingContext)
        {
            try
            {
                Logger.Trace("Start decrypting AS4Message ...");
                X509Certificate2 decryptionCertificate = GetCertificate(messagingContext);
                messagingContext.AS4Message.Decrypt(decryptionCertificate);
                Logger.Info($"{messagingContext.LogTag} AS4Message is decrypted correctly");

                JournalLogEntry entry =
                    JournalLogEntry.CreateFrom(
                        messagingContext.AS4Message,
                        $"Decrypted using certificate {decryptionCertificate.FriendlyName}");

                return(await StepResult
                       .Success(messagingContext)
                       .WithJournalAsync(entry));
            }
            catch (Exception ex) when(ex is CryptoException || ex is CryptographicException)
            {
                Logger.Error(ex);

                messagingContext.ErrorResult = new ErrorResult(
                    description: "Decryption of message failed",
                    alias: ErrorAlias.FailedDecryption);

                Logger.Error(messagingContext.ErrorResult.Description);
                return(StepResult.Failed(messagingContext));
            }
        }
コード例 #19
0
        public async Task MessageIsCreatedWithMessageProperties()
        {
            // Arrange
            var pmode = CreateSendingPMode(fromParty: null, toParty: null);

            var submitMessage = CreateSubmitMessage(pmode, fromParty: null, toParty: null);

            submitMessage.MessageProperties = new []
            {
                new AS4.Model.Common.MessageProperty("originalSender", "unregistered:C1"),
                new AS4.Model.Common.MessageProperty("finalRecipient", "unregistered:C2")
            };

            var context = new MessagingContext(submitMessage)
            {
                SendingPMode = pmode
            };

            // Act
            var result = await ExerciseCreation(context);

            var as4Message = result.MessagingContext.AS4Message;

            // Assert
            Assert.True(result.Succeeded);
            Assert.Equal(2, as4Message.FirstUserMessage.MessageProperties.Count());
            Assert.Equal("unregistered:C1", as4Message.FirstUserMessage.MessageProperties.FirstOrDefault(p => p.Name.Equals("originalSender"))?.Value);
            Assert.Equal("unregistered:C2", as4Message.FirstUserMessage.MessageProperties.FirstOrDefault(p => p.Name.Equals("finalRecipient"))?.Value);
        }
コード例 #20
0
        protected MessagingContext CreateEncryptedAS4Message()
        {
            Stream attachmentStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello, encrypt me"));
            var    attachment       = new Attachment("attachment-id", attachmentStream, "text/plain");

            AS4Message as4Message = AS4Message.Empty;

            as4Message.AddMessageUnit(new UserMessage($"user-{Guid.NewGuid()}"));
            as4Message.AddAttachment(attachment);

            var message = new MessagingContext(as4Message, MessagingContextMode.Unknown)
            {
                SendingPMode = new SendingProcessingMode()
            };

            message.SendingPMode.Security.Encryption.IsEnabled       = true;
            message.SendingPMode.Security.Encryption.Algorithm       = "http://www.w3.org/2009/xmlenc11#aes128-gcm";
            message.SendingPMode.Security.Encryption.CertificateType = PublicKeyCertificateChoiceType.CertificateFindCriteria;
            message.SendingPMode.Security.Encryption.EncryptionCertificateInformation = new CertificateFindCriteria()
            {
                CertificateFindType  = X509FindType.FindBySerialNumber,
                CertificateFindValue = "some dummy value"
            };

            return(message);
        }
コード例 #21
0
        public async Task CanCreateMessageWithPModeWithoutFromParty()
        {
            // Arrange
            var receivingParty = CreatePModeParty("receiver", "c3", "eu.edelivery.services");

            var pmode = CreateSendingPMode(fromParty: null, toParty: receivingParty);

            var fromParty = CreateSubmitMessageParty("sender", "type", "c2");

            var submitMessage = CreateSubmitMessage(pmode, fromParty: fromParty, toParty: null);

            var context = new MessagingContext(submitMessage)
            {
                SendingPMode = pmode
            };

            // Act
            StepResult result = await ExerciseCreation(context);

            // Assert
            Assert.True(result.Succeeded);
            var as4Message = result.MessagingContext.AS4Message;

            Assert.False(as4Message.IsEmpty);
            Assert.True(as4Message.IsUserMessage);
            Assert.Equal(fromParty.Role, as4Message.FirstUserMessage.Sender.Role);
            Assert.Equal(fromParty.PartyIds.First().Id, as4Message.FirstUserMessage.Sender.PartyIds.First().Id);
            Assert.Equal(fromParty.PartyIds.First().Type, as4Message.FirstUserMessage.Sender.PartyIds.First().Type.UnsafeGet);
        }
コード例 #22
0
        private async Task <AS4Message> ExerciseCreateError(MessagingContext ctx)
        {
            var        sut    = new CreateAS4ErrorStep(GetDataStoreContext);
            StepResult result = await sut.ExecuteAsync(ctx);

            return(result.MessagingContext.AS4Message);
        }
コード例 #23
0
        private async Task UpdateRetryStatusForMessageAsync(MessagingContext ctx, SendResult result)
        {
            if (ctx.MessageEntityId.HasValue)
            {
                using (DatastoreContext db = _createDatastore())
                {
                    var repository = new DatastoreRepository(db);
                    var service    = new MarkForRetryService(repository);
                    service.UpdateAS4MessageForSendResult(
                        messageId: ctx.MessageEntityId.Value,
                        status: result);

                    await db.SaveChangesAsync()
                    .ConfigureAwait(false);
                }
            }

            if (ctx.AS4Message?.IsPullRequest == true)
            {
                using (DatastoreContext db = _createDatastore())
                {
                    var service = new PiggyBackingService(db);
                    service.ResetSignalMessagesToBePiggyBacked(ctx.AS4Message.SignalMessages, result);

                    await db.SaveChangesAsync()
                    .ConfigureAwait(false);
                }
            }
        }
コード例 #24
0
        public async Task Fails_To_Store_SignalMessage_When_ReplyPattern_Response_For_Pulled_UserMessage()
        {
            // Arrange
            string userMessageId = $"user-{Guid.NewGuid()}";

            GetDataStoreContext.InsertInMessage(
                new InMessage(userMessageId)
            {
                MEP = MessageExchangePattern.Pull
            });

            var receipt = new Receipt($"receipt-{Guid.NewGuid()}", userMessageId);
            var context = new MessagingContext(
                AS4Message.Create(receipt),
                MessagingContextMode.Receive)
            {
                SendingPMode = new SendingProcessingMode {
                    Id = "shortcut-send-pmode-retrieval"
                },
                ReceivingPMode = new ReceivingProcessingMode
                {
                    ReplyHandling = { ReplyPattern = ReplyPattern.Response }
                }
            };

            // Act / Assert
            await Assert.ThrowsAsync <InvalidOperationException>(
                () => ExerciseStoreSignalMessageAsync(context));
        }
コード例 #25
0
        protected override async Task <GetItemResult> ExecuteAsync(GetItemMessage message)
        {
            return(await Task.Run <GetItemResult> (() => {
                var targetPath = Path.GetFullPath(Path.Combine(
                                                      MessagingContext.GetBuildPath(),
                                                      message.AppName,
                                                      message.SessionId,
                                                      PlatformPath.GetPathForCurrentPlatform(message.ItemSpec)));

                var result = new GetItemResult();

                if (File.Exists(targetPath))
                {
                    result.FileExists = true;

                    // Avoiding sending the payload if the file is too large based on the defined limit by the the client
                    if (new System.IO.FileInfo(targetPath).Length > message.LimitLength)
                    {
                        result.FileLengthExceedsLimit = true;
                    }
                    else
                    {
                        result.Content = File.ReadAllBytes(targetPath);
                    }
                }

                return result;
            }).ConfigureAwait(continueOnCapturedContext: false));
        }
コード例 #26
0
            public async Task ThenAgreementRefIsNotEnoughAsync(string name, string type)
            {
                // Arrange
                var agreementRef = new AS4.Model.PMode.AgreementReference {
                    Value = name, Type = type, PModeId = "pmode-id"
                };

                ArrangePModeThenAgreementRefIsNotEnough(agreementRef);

                var userMessage = new UserMessage(
                    Guid.NewGuid().ToString(),
                    new AS4.Model.Core.CollaborationInfo(
                        agreement: new AgreementReference(name, type, "pmode-id"),
                        service: new Service("service"),
                        action: "action",
                        conversationId: "1"));

                var messagingContext = new MessagingContext(AS4Message.Create(userMessage), MessagingContextMode.Receive);

                // Act
                StepResult result = await _step.ExecuteAsync(messagingContext);

                // Assert
                Assert.False(result.Succeeded);
                ErrorResult errorResult = result.MessagingContext.ErrorResult;

                Assert.Equal(ErrorCode.Ebms0010, errorResult.Code);
            }
コード例 #27
0
        private static async Task <StepResult> ExecuteSteps(
            IEnumerable <IStep> steps,
            MessagingContext context)
        {
            StepResult result = StepResult.Success(context);

            var currentContext = context;

            foreach (IStep step in steps)
            {
                result = await step.ExecuteAsync(currentContext).ConfigureAwait(false);

                if (result.CanProceed == false || result.Succeeded == false || result.MessagingContext?.Exception != null)
                {
                    return(result);
                }

                if (result.MessagingContext != null && currentContext != result.MessagingContext)
                {
                    currentContext = result.MessagingContext;
                }
            }

            return(result);
        }
コード例 #28
0
            private static async Task <StepResult> ExerciseEncryption(MessagingContext message)
            {
                var sut = new EncryptAS4MessageStep(CreateStubCertificateRepository().Object);

                // Act
                return(await sut.ExecuteAsync(message));
            }
コード例 #29
0
        /* This thread ensures that messages aggregated from various partners are added to the queue in the correct order */
        public void HandleQueueBuffer()
        {
            /* Iterate over all the queues and look for messages that expired their indexing period and should enter the queue */
            using (var ctx = new MessagingContext())
            {
                foreach (var q in ctx.MsgQueues)
                {
                    var messages = ctx.QueueBuffer.Where(m => (m.QueueId == q.Id));

                    var messageList = new List <QueueBuffer>();

                    foreach (var m in messages)
                    {
                        if (DateTime.UtcNow.Ticks + Config <long> .GetInstance()["TIMEZONE_CORRECTION"] > m.Timestamp + Config <int> .GetInstance()["QUEUE_GRACE_PERIOD"])
                        {
                            /* Add this message to the queue. We assume that by now all slaves have synced */
                            messageList.Add(m);
                        }
                    }

                    /* Sort by time of arrival */
                    messageList.Sort((a, b) => ((int)(a.Timestamp - b.Timestamp)));

                    foreach (var m in messageList)
                    {
                        WriteQueue(ctx, m.UserId, m.NodeId, m.QueueId, m.Data, m.Timestamp);

                        ctx.QueueBuffer.Remove(m);

                        /* Important to save here for consistancy */
                        ctx.SaveChanges();
                    }
                }
            }
        }
コード例 #30
0
            public async Task Takes_Sending_PMode_Into_Account_When_Verifies_Non_Multihop_Signal()
            {
                // Arrange
                var as4Msg = AS4Message.Create(new Receipt($"receipt-{Guid.NewGuid()}", $"reftoid-{Guid.NewGuid()}"));

                as4Msg.AddMessageUnit(new UserMessage(messageId: $"user-{Guid.NewGuid()}"));

                var ctx = new MessagingContext(as4Msg, MessagingContextMode.Receive)
                {
                    ReceivingPMode = new ReceivingProcessingMode
                    {
                        Security = { SigningVerification = { Signature = Limit.Required } }
                    },
                    SendingPMode = new SendingProcessingMode
                    {
                        Security = { SigningVerification = { Signature = Limit.Ignored } }
                    }
                };

                // Act
                StepResult result = await ExerciseVerify(ctx);

                // Assert
                Assert.True(result.CanProceed);
            }
コード例 #31
0
 public static void CleanupTestTrack()
 {
     int deleteResult = -1;
     MessagingContext context = null;
     #region Clean database of records added during test
     try
     {
         using (context = new MessagingContext(connectionStringName))
         {
             MessagePing recordToDelete = context.FindOne(new object[] { recordId });
             bool recordIsNotAvailable = null != recordToDelete;
             if (recordIsNotAvailable)
             {
                 context.Remove(recordToDelete);
                 deleteResult = context.SaveChanges();
             }
         }
     }
     catch { }
     finally
     {
         if (null != context)
         {
             context.Dispose();
         }
     }
     #endregion
 }
コード例 #32
0
 public void ConnectToDatabase()
 {
     using (var context = new MessagingContext(connectionStringName))
     {
         Assert.IsNotNull(context, "Context could not be instantiated.");
         Assert.IsNotNull(context.Database, "Context is instantiated, but Database reference is not set.");
         Assert.IsNotNull(context.Database.Connection, "Active connection refernece could not be obtained");
         try
         {
             context.Database.Connection.Open();
             Assert.IsTrue(context.Database.Connection.State == ConnectionState.Open, "Connection is not in open state, Current state - " + context.Database.Connection.State.ToString());
         }
         catch { }
         finally
         {
             context.Database.Connection.Close();
         }
         Assert.IsTrue(context.Database.Connection.State == ConnectionState.Closed, "Connection is successfully closed, Current state - " + context.Database.Connection.State.ToString());
     }
 }
コード例 #33
0
        private MessagePing SeedRecord()
        {
            MessagePing testSubject = new MessagePing();
            MessagePing operationResult = null;
            testSubject.Id = recordId;
            testSubject.Source = "+919840200524";
            testSubject.Destination = "+918903442090";
            testSubject.Message = "Hello!!";
            testSubject.MessageSentUTC = DateTime.UtcNow;

            using (var context = new MessagingContext(connectionStringName))
            {
                operationResult = context.Add(testSubject);
            }
            return operationResult;
        }
コード例 #34
0
        private MessagePing AssertRecordExistence(Guid recordId, MessagingContext context)
        {
            MessagePing testSubject;

            testSubject = context.FindOne(new object[] { recordId });
            try
            {
                Assert.IsNotNull(testSubject, "Record not found in database");
            }
            catch
            {
                testSubject = SeedRecord();
            }

            return testSubject;
        }
コード例 #35
0
        public void SearchMessageInDatabase()
        {
            #region Test Setup
            List<MessagePing> testSubjects;
            string source = "+919840200524";
            #endregion

            #region Test
            using (var context = new MessagingContext(connectionStringName))
            {
                var checkRecordExistence = AssertRecordExistence(recordId, context);

                testSubjects = context.Where(d => d.Source == source).ToList<MessagePing>();

                Assert.IsNotNull(testSubjects, "Record not found in database");
                CollectionAssert.Contains(testSubjects, checkRecordExistence, "Record found in the database did not match record id");
            }
            #endregion
        }
コード例 #36
0
        public void GetMessageRecordFromDatabase()
        {
            #region Test Setup
            MessagePing testSubject;
            #endregion

            #region Test
            using (var context = new MessagingContext(connectionStringName))
            {
                var checkRecordExistence = AssertRecordExistence(recordId, context);
                testSubject = context.FindOne(new object[] { recordId });
                Assert.IsNotNull(testSubject, "Record not found in database");
                Assert.IsTrue(recordId == testSubject.Id, "Record found in the database did not match record id");
            }
            #endregion
        }
コード例 #37
0
        public void UpdateRecordToDatabase()
        {
            #region Test Setup
            MessagePing testSubject;
            #endregion

            #region Test

            using (var context = new MessagingContext(connectionStringName))
            {
                try
                {
                    testSubject = AssertRecordExistence(recordId, context);
                }
                catch (AssertFailedException)
                {
                    AddRecordsToDatabase();
                    testSubject = AssertRecordExistence(recordId, context);
                }

                testSubject.Message = updatedMessage;
                context.SaveChanges();
            }

            testSubject = null;

            using (var context = new MessagingContext(connectionStringName))
            {
                testSubject = context.FindOne(new object[] { recordId });
                Assert.IsNotNull(testSubject, "Record not found in database");
                Assert.IsTrue(updatedMessage == testSubject.Message, "Record was not updated");
            }

            #endregion
        }
コード例 #38
0
ファイル: WorkerProcess.cs プロジェクト: ksivasenthil/PingMe
 internal WorkerProcess(DbContext storageInstance, IMembershipService membershipInstance, IProfileService profileInstance)
 {
     this.Storage = storageInstance as MessagingContext;
     MembershipService = membershipInstance;
     ProfileService = profileInstance;
 }