public byte[] SaveEnvelopeData(ImmutableEnvelope envelope)
        {
            //  string contract, Guid messageId, Uri sender,
            var itemContracts = new MessageContract[envelope.Items.Length];

            using (var content = new MemoryStream())
            {
                int position = 0;
                for (int i = 0; i < envelope.Items.Length; i++)
                {
                    var item = envelope.Items[i];

                    string name;
                    if (!_dataSerializer.TryGetContractNameByType(item.MappedType, out name))
                    {
                        var error = string.Format("Failed to find contract name for {0}", item.MappedType);
                        throw new InvalidOperationException(error);
                    }
                    // normal serializers have a nasty habbit of closing the stream after they are done
                    // we can suppress that or use a wrapper now instead
                    using (var itemStream = new MemoryStream())
                    {
                        _dataSerializer.Serialize(item.Content, itemStream);
                        var bytes = itemStream.ToArray();
                        content.Write(bytes, 0, bytes.Length);
                    }


                    int size            = (int)content.Position - position;
                    var attribContracts = EnvelopeConvert.ItemAttributesToContract(item.GetAllAttributes());
                    itemContracts[i] = new MessageContract(name, size, position, attribContracts);

                    position += size;
                }

                var envelopeAttribs = EnvelopeConvert.EnvelopeAttributesToContract(envelope.GetAllAttributes());


                var contract = new EnvelopeContract(envelope.EnvelopeId, envelopeAttribs, itemContracts,
                                                    envelope.DeliverOnUtc, envelope.CreatedOnUtc);

                using (var stream = new MemoryStream())
                {
                    // skip header
                    stream.Seek(EnvelopeHeaderContract.FixedSize, SeekOrigin.Begin);
                    // save envelope attributes
                    _envelopeSerializer.SerializeEnvelope(stream, contract);
                    var envelopeBytes = stream.Position - EnvelopeHeaderContract.FixedSize;
                    // copy data
                    content.WriteTo(stream);
                    // write the header
                    stream.Seek(0, SeekOrigin.Begin);
                    var header = new EnvelopeHeaderContract(EnvelopeHeaderContract.Schema2DataFormat, envelopeBytes, 0);
                    header.WriteToStream(stream);
                    return(stream.ToArray());
                }
            }
        }
        public void SendEnvelope(ImmutableEnvelope envelope)
        {
            var queue = GetOutboundQueue();
            var data = _streamer.SaveEnvelopeData(envelope);

            if (Transaction.Current == null)
            {
                queue.PutMessage(data, envelope.DeliverOnUtc);

                SystemObserver.Notify(new EnvelopeSent(queue.Name, envelope.EnvelopeId, false,
                    envelope.Items.Select(x => x.MappedType.Name).ToArray(), envelope.GetAllAttributes()));
            }
            else
            {
                var action = new CommitActionEnlistment(() =>
                    {
                        queue.PutMessage(data);
                        SystemObserver.Notify(new EnvelopeSent(queue.Name, envelope.EnvelopeId, true,
                            envelope.Items.Select(x => x.MappedType.Name).ToArray(), envelope.GetAllAttributes()));
                    });
                Transaction.Current.EnlistVolatile(action, EnlistmentOptions.None);
            }
        }
        public static MyMessageContext Factory(ImmutableEnvelope envelope, ImmutableMessage message)
        {
            ImmutableAttribute address =
                envelope.GetAllAttributes().Where(a => a.Key == ContextAttributes.ORIGINATING_MACHINE).FirstOrDefault();

            return(new MyMessageContext
            {
                OriginatingMachine = address == null ? "" : address.Value,
                CreatedOnUtc = envelope.CreatedOnUtc,
                DeliveredOnUtc = envelope.DeliverOnUtc,
                EnvelopeId = envelope.EnvelopeId,
                MessageIndex = message.Index,
                MappedType = message.MappedType.AssemblyQualifiedName
            });
        }
Esempio n. 4
0
        public static EnvelopeBuilder CloneProperties(string newId, ImmutableEnvelope envelope)
        {
            if (newId == envelope.EnvelopeId)
            {
                throw new InvalidOperationException("Envelope cloned for modification should have new identity.");
            }
            var builder = new EnvelopeBuilder(newId);

            builder.OverrideCreatedOnUtc(envelope.CreatedOnUtc);
            builder.DeliverOnUtc(envelope.DeliverOnUtc);

            foreach (var attribute in envelope.GetAllAttributes())
            {
                builder.AddString(attribute.Key, attribute.Value);
            }
            return(builder);
        }
Esempio n. 5
0
        public void DispatchMessage(ImmutableEnvelope message)
        {
            // We either accept commands, events or control messages.


            // if tis is control message
            var controls = message
                           .GetAllAttributes()
                           .Where(ia => ia.Key.StartsWith("router-"))
                           .ToArray();

            if (controls.Length > 0)
            {
                if (message.Items.Length > 0)
                {
                    throw new InvalidOperationException("Router control message should not have any content");
                }

                _storage.UpdateSingletonEnforcingNew <RouteTable>(rt => UpgradeRouterTable(controls, rt));
                foreach (var attribute in controls)
                {
                    Console.WriteLine("  route {0}: {1}", attribute.Key, attribute.Value);
                }
                ReloadRouteMap();
                return;
            }

            // replace with your logic to detect commands.
            if (message.Items.All(m => m.Content is IPS_SampleCommand))
            {
                _queueFactory.GetWriteQueue("commands").PutMessage(_streamer.SaveEnvelopeData(message));
                return;
            }
            if (message.Items.All(m => m.Content is IPS_SampleEvent))
            {
                PublishEvent(message);
                return;
            }

            throw new InvalidOperationException(
                      "This is not command, event or control message. Please handle this case.");
        }
Esempio n. 6
0
        public void DispatchMessage(ImmutableEnvelope message)
        {
            // We either accept commands, events or control messages.

            // if tis is control message
            var controls = message
                .GetAllAttributes()
                .Where(ia => ia.Key.StartsWith("router-"))
                .ToArray();

            if (controls.Length > 0)
            {
                if (message.Items.Length > 0)
                {
                    throw new InvalidOperationException("Router control message should not have any content");
                }

                _storage.UpdateSingletonEnforcingNew<RouteTable>(rt => UpgradeRouterTable(controls, rt));
                foreach (var attribute in controls)
                {
                    Console.WriteLine("  route {0}: {1}",attribute.Key, attribute.Value);
                }
                ReloadRouteMap();
                return;
            }

            // replace with your logic to detect commands.
            if (message.Items.All(m => m.Content is IPS_SampleCommand))
            {
                _queueFactory.GetWriteQueue("commands").PutMessage(this._streamer.SaveEnvelopeData(message));
                return;
            }
            if (message.Items.All(m => m.Content is IPS_SampleEvent))
            {
                PublishEvent(message);
                return;
            }

            throw new InvalidOperationException(
                "This is not command, event or control message. Please handle this case.");
        }
Esempio n. 7
0
        public static void PrintTo(this ImmutableEnvelope envelope, TextWriter writer, Func <object, string> serializer)
        {
            //.AppendFormat("{0,12}: {1}", attribute.GetName(), attribute.GetValue())
            writer.WriteLine(string.Format("{0,12}: {1}", "EnvelopeId", envelope.EnvelopeId));
            writer.WriteLine(string.Format("{0,12}: {1:yyyy-MM-dd HH:mm:ss} (UTC)", "Created", envelope.CreatedOnUtc));
            if (envelope.DeliverOnUtc != DateTime.MinValue)
            {
                writer.WriteLine(string.Format("{0,12}: {1:yyyy-MM-dd HH:mm:ss} (UTC)", "Deliver On", envelope.DeliverOnUtc));
            }

            foreach (var attribute in envelope.GetAllAttributes())
            {
                writer.WriteLine(string.Format("{0,12}: {1}", attribute.Key, attribute.Value));
            }

            foreach (var message in envelope.Items)
            {
                writer.WriteLine();
                writer.WriteLine("{0}. {1}", message.Index, message.MappedType);

                foreach (var attribute in message.GetAllAttributes())
                {
                    writer.WriteLine(string.Format("{0,12}: {1}", attribute.Key, attribute.Value));
                }

                try
                {
                    var buffer = serializer(message.Content);
                    writer.WriteLine(buffer);
                }
                catch (Exception ex)
                {
                    writer.WriteLine("Rendering failure");
                    writer.WriteLine(ex);
                }

                writer.WriteLine();
            }
        }
        public byte[] SaveEnvelopeData(ImmutableEnvelope envelope)
        {
            //  string contract, Guid messageId, Uri sender,
            var itemContracts = new MessageContract[envelope.Items.Length];
            using (var content = new MemoryStream())
            {
                int position = 0;
                for (int i = 0; i < envelope.Items.Length; i++)
                {
                    var item = envelope.Items[i];

                    string name;
                    if (!_dataSerializer.TryGetContractNameByType(item.MappedType, out name))
                    {
                        var error = string.Format("Failed to find contract name for {0}", item.MappedType);
                        throw new InvalidOperationException(error);
                    }
                    // normal serializers have a nasty habbit of closing the stream after they are done
                    // we can suppress that or use a wrapper now instead
                    using (var itemStream = new MemoryStream())
                    {
                        _dataSerializer.Serialize(item.Content, itemStream);
                        var bytes = itemStream.ToArray();
                        content.Write(bytes, 0, bytes.Length);
                    }

                    int size = (int) content.Position - position;
                    var attribContracts = EnvelopeConvert.ItemAttributesToContract(item.GetAllAttributes());
                    itemContracts[i] = new MessageContract(name, size, position, attribContracts);

                    position += size;
                }

                var envelopeAttribs = EnvelopeConvert.EnvelopeAttributesToContract(envelope.GetAllAttributes());

                var contract = new EnvelopeContract(envelope.EnvelopeId, envelopeAttribs, itemContracts,
                    envelope.DeliverOnUtc, envelope.CreatedOnUtc);

                using (var stream = new MemoryStream())
                {
                    // skip header
                    stream.Seek(EnvelopeHeaderContract.FixedSize, SeekOrigin.Begin);
                    // save envelope attributes
                    _envelopeSerializer.SerializeEnvelope(stream, contract);
                    var envelopeBytes = stream.Position - EnvelopeHeaderContract.FixedSize;
                    // copy data
                    content.WriteTo(stream);
                    // write the header
                    stream.Seek(0, SeekOrigin.Begin);
                    var header = new EnvelopeHeaderContract(EnvelopeHeaderContract.Schema2DataFormat, envelopeBytes, 0);
                    header.WriteToStream(stream);
                    return stream.ToArray();
                }
            }
        }