Ejemplo n.º 1
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            DeckModel deck = (this.Parent != null && this.Parent.Parent != null) ? this.Parent.Parent.Target as DeckModel : null;

            ImageSheetModel sheet = this.Target as ImageSheetModel;
            if(sheet == null) {
                ///create our imagesheet based on what type of image it is
                if (image_ != null) {
                    // ImageIt image
                    // RJA - added disposition setting (previously,  this was the default)
                    this.Target = sheet = new ImageSheetModel((Guid)this.TargetId, this.image_, this.Disposition | SheetDisposition.Remote, false, this.Bounds.Location, this.Bounds.Size, this.Height);
                    ///make the image visible
                    sheet.Visible = true;
                } else {
                    // Background image
                    this.Target = sheet = new ImageSheetModel(deck, ((Guid)this.TargetId), this.Disposition | SheetDisposition.Remote, this.Bounds, this.MD5, this.Height);
                }

            }
            if (image_ != null) {
                using (Synchronizer.Lock(sheet.SyncRoot)) {
                    sheet.Image = this.image_;
                }
            }
            base.UpdateTarget(context);

            return true;
        }
        public RescueExceptionReceiveContext(ReceiveContext context, Exception exception)
            : base(context)
        {
            _exception = exception;

            _exceptionTimestamp = DateTime.UtcNow;
        }
        /// <summary>
        /// Handle this messsage being received and add this sheet to the appropriate place.
        /// </summary>
        /// <param name="context">The receiving context</param>
        /// <returns>True if handled, false otherwise</returns>
        protected override bool UpdateTarget( ReceiveContext context )
        {
            QuickPollSheetModel sheet = this.Target as QuickPollSheetModel;
            if( sheet == null ) {
                // Create a new sheet
                using( context.Model.Workspace.Lock() ) {
                    if( (~context.Model.Workspace.CurrentPresentation) != null ) {
                        using( Synchronizer.Lock( (~context.Model.Workspace.CurrentPresentation).SyncRoot ) ) {
                            this.Target = sheet = new QuickPollSheetModel( ((Guid)this.TargetId), (~context.Model.Workspace.CurrentPresentation).QuickPoll );
                        }
                    } else {
                        using( Synchronizer.Lock( context.Participant.SyncRoot ) ) {
                            if( context.Participant.Role is Model.Network.InstructorModel ) {
                                using( Synchronizer.Lock( context.Participant.Role.SyncRoot ) ) {
                                    using( Synchronizer.Lock( ((Model.Network.InstructorModel)context.Participant.Role).CurrentPresentation.SyncRoot ) ) {
                                        this.Target = sheet = new QuickPollSheetModel( ((Guid)this.TargetId), ((Model.Network.InstructorModel)context.Participant.Role).CurrentPresentation.QuickPoll );
                                    }
                                }
                            }
                        }
                    }
                }

            }

            // Update the parameters of the sheet
            using( Synchronizer.Lock( sheet.SyncRoot ) ) {
                sheet.QuickPollId = this.Id;
            }

            base.UpdateTarget( context );

            return true;
        }
        protected override bool UpdateTarget(ReceiveContext context)
        {
            DeckTraversalModel traversal = this.Target as DeckTraversalModel;
            if(traversal == null)
                return false;

            PresentationModel presentation = (this.Parent != null && this.Parent.Parent != null) ? this.Parent.Parent.Target as PresentationModel : null;
            if(presentation == null)
                return false;

            using(Synchronizer.Lock(presentation.SyncRoot)) {
                if(!presentation.DeckTraversals.Contains(traversal))
                    presentation.DeckTraversals.Add((DeckTraversalModel) this.Target);
            }

            TableOfContentsModel.Entry current = (this.Predecessor != null && this.Predecessor.Child != null)
                ? this.Predecessor.Child.Target as TableOfContentsModel.Entry: null;
            if(current != null) {
                using(Synchronizer.Lock(traversal.SyncRoot)) {
                    traversal.Current = current;
                }
            }

            return false;
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (Stream cryptoStream = _provider.GetDecryptStream(body, receiveContext))
                using (var jsonReader = new BsonReader(cryptoStream))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                var messageEncoding = GetMessageEncoding(receiveContext);

                MessageEnvelope envelope;
                using (var body = receiveContext.GetBody())
                using (var reader = new StreamReader(body, messageEncoding, false, 1024, true))
                using (var jsonReader = new JsonTextReader(reader))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpointProvider, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
 protected override bool UpdateTarget(ReceiveContext context)
 {
     if (SubmissionStatusModel.GetInstance().Role == "student"
         && sender_.Role == "instructor") {
         Guid id1;
         Guid id2;
         using(Synchronizer.Lock(SubmissionStatusModel.GetInstance().SyncRoot)){
             id1 = SubmissionStatusModel.GetInstance().Id;
         }
         using (Synchronizer.Lock(sender_.SyncRoot)) {
             id2 = sender_.Id;
         }
         if (id1 == id2) {
             using (Synchronizer.Lock(SubmissionStatusModel.GetInstance().SyncRoot)) {
                 SubmissionStatusModel.GetInstance().SubmissionStatus = SubmissionStatusModel.Status.Received;
             }
         }
     } else if (SubmissionStatusModel.GetInstance().Role == "instructor"
         && sender_.Role == "student") {
         Guid id1;
         using (Synchronizer.Lock(sender_.SyncRoot)) {
             id1 = sender_.Id;
         }
         using (Synchronizer.Lock(SubmissionStatusModel.GetInstance().SyncRoot)) {
             ///we need to toggle the Id in order for the listener to recognize the event.
             SubmissionStatusModel.GetInstance().Id = Guid.Empty;
             SubmissionStatusModel.GetInstance().Id = id1;
         }
     }
     return true;
 }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (var jsonReader = new BsonReader(body))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Ejemplo n.º 9
0
        string GetBodyString(ReceiveContext context)
        {
            using (var stream = context.GetBody())
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);

                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            object obj;
            var headers = new Header[0];
            using (Stream body = receiveContext.GetBody())
            {
                obj = _formatter.Deserialize(body, x => headers = x);
            }

            return new StaticConsumeContext(_sendEndpointProvider, _publishEndpoint, receiveContext, obj, headers);
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            IMessageDeserializer deserializer;
            if (!TryGetSerializer(receiveContext.ContentType, out deserializer))
            {
                throw new SerializationException(
                    $"No deserializer was registered for the message content type: {receiveContext.ContentType}. Supported content types include {string.Join(", ", _deserializers.Values.Select(x => x.ContentType))}");
            }

            return deserializer.Deserialize(receiveContext);
        }
        /// <summary>
        /// Returns a stream for decrypting the message
        /// </summary>
        /// <param name="provider">The crypto stream provider</param>
        /// <param name="stream">The original stream to which the encrypted message content is written</param>
        /// <param name="context">The second context of the message</param>
        /// <returns>A stream for serializing the message which will be encrypted</returns>
        public static Stream GetDecryptStream(this ICryptoStreamProvider provider, Stream stream, ReceiveContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            object keyIdObj;
            string keyId = context.TransportHeaders.TryGetHeader(EncryptedMessageSerializer.EncryptionKeyHeader, out keyIdObj)
                ? keyIdObj.ToString()
                : default(string);

            return provider.GetDecryptStream(stream, keyId, CryptoStreamMode.Read);
        }
Ejemplo n.º 13
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            PresentationModel presentation = this.Target as PresentationModel;
            if(presentation != null) {
                using(Synchronizer.Lock(context.Classroom.SyncRoot)) {
                    if(context.Classroom.Presentations.Contains(presentation))
                        context.Classroom.Presentations.Remove(presentation);
                }
            }

            return true;
        }
Ejemplo n.º 14
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            bool update = base.UpdateTarget(context);

            InstructorModel instructor = this.Parent != null ? this.Parent.Target as InstructorModel : null;
            if(instructor != null) {
                using(Synchronizer.Lock(instructor.SyncRoot)) {
                    instructor.CurrentPresentation = this.Target as PresentationModel;
                }
            }

            return update;
        }
Ejemplo n.º 15
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            DeckModel deck = this.Target as DeckModel;
            if(deck == null) {
                this.Target = deck = new DeckModel(((Guid) this.TargetId), this.Disposition | DeckDisposition.Remote, this.HumanName);
            } else {
                using(Synchronizer.Lock(deck.SyncRoot)) {
                    deck.HumanName = this.HumanName;
                }
            }
            using (Synchronizer.Lock(deck.SyncRoot)) {
                deck.DeckBackgroundColor = this.DeckBackgroundColor;
            }

            return true;
        }
Ejemplo n.º 16
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            DeckModel deck = (this.Parent != null && this.Parent.Parent != null) ? this.Parent.Parent.Target as DeckModel : null;

            XPSPageSheetModel sheet = this.Target as XPSPageSheetModel;
            if (sheet == null)
            {
                if (this.m_DocumentPageWrapper != null)
                {
                    this.Target = sheet = new XPSPageSheetModel(this.m_DocumentPageWrapper, (Guid)this.TargetId, this.Disposition | SheetDisposition.Remote, new Rectangle(0, 0, this.Width, this.Height), this.Height);
                }
            }

            base.UpdateTarget(context);

            return true;
        }
        protected override bool UpdateTarget(ReceiveContext context)
        {
            Debug.Assert(this.Content != null);
            if(this.Content.image == null)
                throw new ArgumentException("The deserialized content image is null.", "Content");

            this.Target = this.Content;

            DeckModel deck = this.Parent != null ? this.Parent.Target as DeckModel : null;
            if(deck != null) {
                using(Synchronizer.Lock(deck.SyncRoot)) {
                    // Note: If the deck already has content with this hash, nothing will happen.
                    deck.AddSlideContent(this.Content.key, this.Content.image);
                }
            }

            return true;
        }
Ejemplo n.º 18
0
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                XDocument document;
                using (Stream body = receiveContext.GetBody())
                using (var xmlReader = new XmlTextReader(body))
                    document = XDocument.Load(xmlReader);

                var json = new StringBuilder(1024);

                using (var stringWriter = new StringWriter(json, CultureInfo.InvariantCulture))
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;

                    XmlMessageSerializer.XmlSerializer.Serialize(jsonWriter, document.Root);
                }

                MessageEnvelope envelope;
                using (var stringReader = new StringReader(json.ToString()))
                using (var jsonReader = new JsonTextReader(stringReader))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Ejemplo n.º 19
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            TextSheetModel sheet = this.Target as TextSheetModel;
            if (sheet == null) {
                ///if we sent it, this means that by definition the sheet is public
                ///edit: made is_editable true so that instructors can copy and paste student code
                this.Target = sheet = new TextSheetModel(((Guid)this.TargetId), this.Text, true, true, this.Bounds, this.color_, this.font_);
            }

            using (Synchronizer.Lock(sheet.SyncRoot)) {
                sheet.Text = this.Text;
                sheet.Font = this.font_;
                sheet.IsEditable = false;
                ///if we sent it, this means that by definition the sheet is public
                sheet.IsPublic = true;
                sheet.Color = this.color_;
            }

            base.UpdateTarget(context);

            return true;
        }
Ejemplo n.º 20
0
        public static Error ProcessOnReceive(
            ILayerStack layerStack, MessageType messageType, ReceiveContext receiveContext, IBonded layerData, Logger logger)
        {
            Error error = null;

            if (layerStack != null)
            {
                if (layerData == null)
                {
                    logger.Site().Warning("Layer stack present but no layer data received.");
                }

                error = layerStack.OnReceive(messageType, receiveContext, layerData);

                if (error != null)
                {
                    logger.Site().Warning("Layer error occurred receiving message of type {0} (Code: {1} Message: {2}).",
                        messageType, error.error_code, error.message);
                }
            }
            return error;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Handle the receipt of this message
        /// </summary>
        /// <param name="context">The context of the receiver from which the message was sent</param>
        protected override bool UpdateTarget( ReceiveContext context )
        {
            QuickPollModel poll = this.Target as QuickPollModel;

            // Update Target and poll
            if( poll == null ) {
                if( this.m_Model == null ) {
                    this.Target = poll = null;
                    return false;
                } else {
                    // Create a new model
                    using( Synchronizer.Lock( this.m_Model.SyncRoot ) ) {
                        this.Target = poll = new QuickPollModel( ((Guid)this.TargetId), this.m_Model );
                    }

                    // Find a parent PresentationModel message
                    PresentationModel presentation = null;
                    Message parent = this.Parent;
                    while( parent != null && presentation == null ) {
                        if( parent.Target is PresentationModel ) {
                            presentation = parent.Target as PresentationModel;
                        } else {
                            parent = parent.Parent;
                        }
                    }
                    if( presentation == null )
                        return false;

                    using( Synchronizer.Lock( presentation.SyncRoot ) ) {
                        if( presentation.QuickPoll == null || !presentation.QuickPoll.Equals( poll ) )
                            presentation.QuickPoll = poll;
                    }
                }
            } else {
                // No properties can get updated
            }

            return true;
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                ProtocolBuffersMessageEnvelope envelope;
                long offset;
                using (var body = receiveContext.GetBody())
                {
                    envelope = Serializer.DeserializeWithLengthPrefix<ProtocolBuffersMessageEnvelope>(body, PrefixStyle.Fixed32);

                    offset = body.Position;
                }

                return new ProtocolBuffersConsumeContext(receiveContext, envelope, offset);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
 protected override bool UpdateTarget(ReceiveContext context)
 {
     //Update model, intiate response
     context.Model.VersionExchange.ReceiveVersionRequest(context.Participant,this);
     return false;
 }
Ejemplo n.º 24
0
 public static void LogTransportFaulted(this ReceiveContext context, Exception exception)
 {
     _logFault(context.InputAddress, GetMessageId(context), exception);
 }
Ejemplo n.º 25
0
 public Task Consume(ReceiveContext <TCommand> messageContext)
 {
     Guard.NotNull(messageContext, nameof(messageContext));
     return(this.channel.Send(messageContext.CreateSendContext()));
 }
        /// <summary>
        /// Returns a stream for decrypting the message
        /// </summary>
        /// <param name="provider">The crypto stream provider</param>
        /// <param name="stream">The original stream to which the encrypted message content is written</param>
        /// <param name="context">The second context of the message</param>
        /// <returns>A stream for serializing the message which will be encrypted</returns>
        public static Stream GetDecryptStream(this ICryptoStreamProvider provider, Stream stream, ReceiveContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var keyId = context.TransportHeaders.TryGetHeader(EncryptedMessageSerializer.EncryptionKeyHeader, out var keyIdObj)
                ? keyIdObj.ToString()
                : default;

            return(provider.GetDecryptStream(stream, keyId, CryptoStreamMode.Read));
        }
Ejemplo n.º 27
0
 public Task Consume(ReceiveContext <TEvent> messageContext)
 {
     Guard.NotNull(messageContext, nameof(messageContext));
     return(this.channel.Publish(messageContext.CreateSendContext()));
 }
 public Task PostReceive(ReceiveContext context)
 {
     // called after the message has been received and processed
     return(Task.CompletedTask);
 }
 public async Task PreReceive(ReceiveContext context)
 {
     await Task.Run(() => Console.WriteLine($"[{DateTime.Now}] Message pre received"));
 }
 public async Task ReceiveFault(ReceiveContext context, Exception exception)
 {
     await Task.Run(() => Console.WriteLine($"[{DateTime.Now}] Message receive faulted. Exception: {exception.Message}"));
 }
 public async Task PostReceive(ReceiveContext context)
 {
     await Task.Run(() => Console.WriteLine($"[{DateTime.Now}] Post received observer"));
 }
Ejemplo n.º 32
0
 string GetBodyString(ReceiveContext context)
 {
     return(Encoding.UTF8.GetString(context.GetBody()));
 }
Ejemplo n.º 33
0
 protected override bool UpdateTarget(ReceiveContext context)
 {
     //Update model
     context.Model.VersionExchange.ReceiveVersionResponse(context.Participant, this);
     return(false);
 }
Ejemplo n.º 34
0
 public Task Handle(ReceiveContext <TestBaseCommand> context, CancellationToken cancellationToken)
 {
     Console.WriteLine(context.Message.Id);
     RubishBox.Rublish.Add(nameof(TestBaseCommandHandler));
     return(Task.FromResult(0));
 }
Ejemplo n.º 35
0
 public async Task ReceiveFault(ReceiveContext context, Exception exception)
 {
     _receiveFault.TrySetResult(Tuple.Create(context, exception));
 }
Ejemplo n.º 36
0
 Task IPipe <ReceiveContext> .Send(ReceiveContext context)
 {
     return(_receivePipe.Send(context));
 }
 public Task ReceiveFault(ReceiveContext context, Exception exception)
 {
     // called when an exception occurs early in the message processing, such as deserialization, etc.
     Console.Error.WriteLineAsync($"MASSTRANSIT ReceiveFault! Exception: " + exception.Message);
     return(Task.CompletedTask);
 }
Ejemplo n.º 38
0
 public Task PreReceive(ReceiveContext context)
 {
     return(Task.Run(() => { counterAll += 1; }));
 }
 static Guid GetMessageId(ReceiveContext context)
 {
     return(context.TransportHeaders.TryGetHeader("MessageId", out var messageIdValue)
         ? new Guid(messageIdValue.ToString())
         : NewId.NextGuid());
 }
		static void TraceMessage(ReceiveContext context)
		{
			using (var ms = new MemoryStream())
			{
				context.CopyBodyTo(ms);
				var msg = Encoding.UTF8.GetString(ms.ToArray());
				_logger.Debug(string.Format("{0} body:\n {1}", DateTime.UtcNow, msg));
			}
		}
Ejemplo n.º 41
0
        public void Receive(Func <IReceiveContext, Action <IReceiveContext> > callback, TimeSpan timeout)
        {
            int messageCount = Count;

            bool waited = false;

            if (messageCount == 0)
            {
                if (!_messageReady.WaitOne(timeout, true))
                {
                    return;
                }

                waited = true;
            }

            bool monitorExitNeeded = true;

            if (!Monitor.TryEnter(_messageLock, timeout))
            {
                return;
            }

            try
            {
                for (LinkedListNode <LoopbackMessage> iterator = _messages.First;
                     iterator != null;
                     iterator = iterator.Next)
                {
                    if (iterator.Value != null)
                    {
                        LoopbackMessage message = iterator.Value;
                        if (message.ExpirationTime.HasValue && message.ExpirationTime <= DateTime.UtcNow)
                        {
                            _messages.Remove(iterator);
                            return;
                        }

                        ReceiveContext context = ReceiveContext.FromBodyStream(message.Body);
                        context.SetMessageId(message.MessageId);
                        context.SetContentType(message.ContentType);
                        if (message.ExpirationTime.HasValue)
                        {
                            context.SetExpirationTime(message.ExpirationTime.Value);
                        }

                        Action <IReceiveContext> receive = callback(context);
                        if (receive == null)
                        {
                            continue;
                        }

                        _messages.Remove(iterator);

                        using (message)
                        {
                            Monitor.Exit(_messageLock);
                            monitorExitNeeded = false;

                            receive(context);
                            return;
                        }
                    }
                }

                if (waited)
                {
                    return;
                }

                // we read to the end and none were accepted, so we are going to wait until we get another in the queue
                _messageReady.WaitOne(timeout, true);
            }
            finally
            {
                if (monitorExitNeeded)
                {
                    Monitor.Exit(_messageLock);
                }
            }
        }
Ejemplo n.º 42
0
 protected override bool UpdateTarget(ReceiveContext context)
 {
     DeckModel deck = this.Target as DeckModel;
     if(deck == null) {
         this.Target = deck = new DeckModel(((Guid) this.TargetId), this.Disposition | DeckDisposition.Remote, this.HumanName);
     } else {
         using(Synchronizer.Lock(deck.SyncRoot)) {
             deck.HumanName = this.HumanName;
         }
     }
     if ((this.Disposition & DeckDisposition.Remote) == 0) {
         using (Synchronizer.Lock(deck.SyncRoot)) {
             deck.DeckBackgroundColor = this.DeckBackgroundColor;
             deck.DeckBackgroundTemplate = this.DeckBackgroundTemplate;
         }
         //if the background template is not exist in BackgroundTemplate.xml, then save it to the xml file
         if (this.DeckBackgroundTemplate != null) {
             BackgroundTemplateXmlService xmlservice = new BackgroundTemplateXmlService();
             if (!xmlservice.IsTemplateExist(this.DeckBackgroundTemplate.Name))
                 xmlservice.SaveTemplate(this.DeckBackgroundTemplate);
         }
     }
     return true;
 }
Ejemplo n.º 43
0
 public CopyBodySerializer(ReceiveContext context)
 {
     _context    = context;
     ContentType = context.ContentType;
 }
Ejemplo n.º 44
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            using(Synchronizer.Lock(context.Participant.SyncRoot)) {
                context.Participant.Role = this.Target as RoleModel;
            }

            return false;
        }
Ejemplo n.º 45
0
 public Task <TResponse> Consume(ReceiveContext <TRequest> messageContext)
 {
     Guard.NotNull(messageContext, nameof(messageContext));
     return(this.channel.Request <TRequest, TResponse>(messageContext.CreateSendContext()));
 }
Ejemplo n.º 46
0
 public Task Move(ReceiveContext context, IPipe <SendContext> pipe)
 {
     return(TaskUtil.Completed);
 }
Ejemplo n.º 47
0
        async Task ISendTransport.Move(ReceiveContext context, IPipe <SendContext> pipe)
        {
            IPipe <ModelContext> modelPipe = Pipe.New <ModelContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async modelContext =>
                {
                    Guid?messageId = context.TransportHeaders.Get("MessageId", default(Guid?));

                    try
                    {
                        IBasicProperties properties;

                        RabbitMqBasicConsumeContext basicConsumeContext;
                        if (context.TryGetPayload(out basicConsumeContext))
                        {
                            properties = basicConsumeContext.Properties;
                        }
                        else
                        {
                            properties         = modelContext.Model.CreateBasicProperties();
                            properties.Headers = new Dictionary <string, object>();
                        }

                        var moveContext = new RabbitMqMoveContext(context, properties);

                        await pipe.Send(moveContext).ConfigureAwait(false);

//                        properties.Headers["Content-Type"] = context.ContentType.MediaType;

//                        if (messageId.HasValue)
//                            properties.MessageId = messageId.ToString();

                        byte[] body;
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var bodyStream = context.GetBody())
                            {
                                bodyStream.CopyTo(memoryStream);
                            }

                            body = memoryStream.ToArray();
                        }

                        var task = modelContext.BasicPublishAsync(_sendSettings.ExchangeName, "", true, properties, body, true);
                        context.AddPendingTask(task);

                        if (_log.IsDebugEnabled)
                        {
                            context.InputAddress.LogMoved(modelContext.ConnectionContext.HostSettings.GetSendAddress(_sendSettings),
                                                          messageId?.ToString() ?? "N/A", "Moved");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.Error("Move To Error Queue Fault: " + _sendSettings.ExchangeName, ex);
                        }

                        throw;
                    }
                });
            });

            await _modelCache.Send(modelPipe, context.CancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 48
0
        static Encoding GetMessageEncoding(ReceiveContext receiveContext)
        {
            var contentEncoding = receiveContext.TransportHeaders.Get("Content-Encoding", default(string));

            return string.IsNullOrWhiteSpace(contentEncoding) ? Encoding.UTF8 : Encoding.GetEncoding(contentEncoding);
        }
Ejemplo n.º 49
0
 public Error OnReceive(MessageType messageType, ReceiveContext context, Dummy layerData)
 {
     layerData.string_value += value;
     list.Add(layerData.string_value);
     return(null);
 }
Ejemplo n.º 50
0
        public async Task <IMessage> DispatchRequest(string serviceName, string methodName, ReceiveContext context, IMessage message)
        {
            string    qualifiedName = serviceName + "." + methodName;
            Stopwatch serviceTime   = null;

            logger.Site().Information("Got request [{0}] from {1}.", qualifiedName, context.Connection);

            try
            {
                ServiceMethodInfo methodInfo;
                lock (dispatchTableLock)
                {
                    if (!dispatchTable.TryGetValue(qualifiedName, out methodInfo))
                    {
                        var errorMessage = "Got request for unknown method [" + qualifiedName + "].";

                        logger.Site().Error(errorMessage);
                        var error = new Error
                        {
                            message    = errorMessage,
                            error_code = (int)ErrorCode.METHOD_NOT_FOUND
                        };
                        return(Message.FromError(error));
                    }
                }

                if (methodInfo.CallbackType != ServiceCallbackType.RequestResponse)
                {
                    var errorMessage = "Method [" + qualifiedName + "] invoked as if it were " +
                                       ServiceCallbackType.RequestResponse + ", but it was registered as " +
                                       methodInfo.CallbackType + ".";

                    logger.Site().Error(errorMessage);
                    var error = new Error
                    {
                        message    = errorMessage,
                        error_code = (int)ErrorCode.INVALID_INVOCATION
                    };
                    return(Message.FromError(error));
                }

                IMessage result;

                try
                {
                    serviceTime = Stopwatch.StartNew();
                    // Cast to appropriate return type which we validated when registering the service
                    result = await(Task <IMessage>) methodInfo.Callback(message, context, CancellationToken.None);
                    serviceTime.Stop();
                }
                catch (Exception ex)
                {
                    logger.Site()
                    .Error(ex, "Failed to complete method [{0}]. With exception: {1}", qualifiedName, ex.Message);
                    result = Message.FromError(
                        Errors.MakeInternalServerError(ex, context.RequestMetrics.request_id, includeDetails: false));
                }
                return(result);
            }
            finally
            {
                Update(context.RequestMetrics, serviceName, methodName, serviceTime);
            }
        }
Ejemplo n.º 51
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            InstructorModel role = this.Target as InstructorModel;
            if(role == null)
                this.Target = role = new InstructorModel(((Guid) this.TargetId));

            using(Synchronizer.Lock(role.SyncRoot)) {
                role.AcceptingStudentSubmissions = this.AcceptingStudentSubmissions;
                // Deserialize the extension
                ExtensionWrapper extension = this.Extension as ExtensionWrapper;
                if (extension != null) {
                    if( extension.ExtensionType.Equals( new Guid( "{65A946F4-D1C5-426b-96DB-7AF4863CE296}" ) ) ) {
                        bool acceptingQuickPollSubmissions = (bool)extension.ExtensionObject;
                        role.AcceptingQuickPollSubmissions = acceptingQuickPollSubmissions;
                    }
                    else {
                        Trace.WriteLine("Unknown Extension id=" + extension.ExtensionType.ToString());
                    }
                }
                role.ForcingStudentNavigationLock = this.ForcingStudentNavigationLock;
            }

            // Update the clock skew from our current value.
            using( Synchronizer.Lock( context.Model.ViewerState.Diagnostic.SyncRoot ) ) {
                context.Model.ViewerState.Diagnostic.AddSkewEntry( this.InstructorClockTicks );
            }

            base.UpdateTarget(context);

            return true;
        }
Ejemplo n.º 52
0
 public Error OnReceive(MessageType messageType, ReceiveContext context, Dummy layerData)
 {
     throw new LayerStackException();
 }
Ejemplo n.º 53
0
        protected override bool UpdateTarget(ReceiveContext context)
        {
            StudentModel role = this.Target as StudentModel;
            if(role == null)
                this.Target = role = new StudentModel(((Guid) this.TargetId));

            base.UpdateTarget(context);

            return true;
        }
Ejemplo n.º 54
0
        static Encoding GetMessageEncoding(ReceiveContext receiveContext)
        {
            var contentEncoding = receiveContext.TransportHeaders.Get("Content-Encoding", default(string));

            return(string.IsNullOrWhiteSpace(contentEncoding) ? Encoding.UTF8 : Encoding.GetEncoding(contentEncoding));
        }
Ejemplo n.º 55
0
 public static void LogFaulted(this ReceiveContext context, Exception exception)
 {
     _logReceiveFault(context.InputAddress, GetMessageId(context), context.ElapsedTime, exception);
 }
 public Task PreReceive(ReceiveContext context)
 {
     // called immediately after the message was delivery by the transport
     Console.Out.WriteLineAsync($"MASSTRANSIT PreReceive: On Address: {context.InputAddress}");
     return(Task.CompletedTask);
 }
Ejemplo n.º 57
0
 public Task PostReceive(ReceiveContext context)
 {
     return(Task.Run(() => { }));
 }
Ejemplo n.º 58
0
 public async Task PostReceive(ReceiveContext context)
 {
     _postReceive.TrySetResult(context);
 }
Ejemplo n.º 59
0
        public Task ProcessWebSocketRequestAsync(WebSocket webSocket, CancellationToken disconnectToken)
        {
            if (webSocket == null)
            {
                throw new ArgumentNullException("webSocket");
            }

            var receiveContext = new ReceiveContext(webSocket, disconnectToken, MaxIncomingMessageSize, _receiveLoopBufferSize);

            return ProcessWebSocketRequestAsync(webSocket, disconnectToken, state =>
            {
                var context = (ReceiveContext)state;

                return WebSocketMessageReader.ReadMessageAsync(context.WebSocket, context.BufferSize, context.MaxIncomingMessageSize, context.DisconnectToken);
            },
            receiveContext);
        }
Ejemplo n.º 60
0
 public Task ReceiveFault(ReceiveContext context, Exception exception)
 {
     return(Task.Run(() => { }));
 }