예제 #1
0
        static IObservable <T> FromQueue <T>(string serverQueue)
        {
            return(Observable.Create <T>(observer =>
            {
                var responseQueue = Environment.MachineName + "\\Private$\\" + Guid.NewGuid().ToString();
                var queue = MessageQueue.Create(responseQueue);

                var frm = new System.Messaging.BinaryMessageFormatter();
                var srv = new MessageQueue(serverQueue);
                srv.Formatter = frm;
                queue.Formatter = frm;

                srv.Send("S " + responseQueue);

                var loop = NewThreadScheduler.Default.ScheduleLongRunning(cancel =>
                {
                    while (!cancel.IsDisposed)
                    {
                        var msg = queue.Receive();
                        observer.OnNext((T)msg.Body);
                    }
                });

                return new CompositeDisposable(
                    loop,
                    Disposable.Create(() =>
                {
                    srv.Send("D " + responseQueue);
                    MessageQueue.Delete(responseQueue);
                })
                    );
            }));
        }
        public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage)
        {
            var result = new List<int>();

            using (var messageQueue = new MessageQueue(String.Format(_pathPattern, queue)))
            {
                var current = 0;
                var end = @from + perPage;
                var enumerator = messageQueue.GetMessageEnumerator2();

                var formatter = new BinaryMessageFormatter();

                while (enumerator.MoveNext())
                {
                    if (current >= @from && current < end)
                    {
                        var message = enumerator.Current;

                        message.Formatter = formatter;
                        result.Add(int.Parse((string)message.Body));
                    }

                    if (current >= end) break;

                    current++;
                }
            }

            return result;
        }
예제 #3
0
        public void Send()
        {
            BinaryMessageFormatter formatter=new BinaryMessageFormatter();
            Message requestMessage = new Message("Hello World", formatter);
            requestMessage.ResponseQueue = replyQueue;
            requestQueue.Send(requestMessage);

            Console.WriteLine("Sent request");
            Console.WriteLine("\tType:          {0}", requestMessage.BodyType);
            Console.WriteLine("\tTime:          {0}",DateTime.Now.ToString("HH:mm:ss.ffffff"));
            Console.WriteLine("\tMessage ID:    {0}",requestMessage.Id);
            Console.WriteLine("\tCorrel:        {0}", requestMessage.CorrelationId);
            Console.WriteLine("\tReply To   :   {0}", requestMessage.ResponseQueue.Path);
            Console.WriteLine("\tContents:       {0}", requestMessage.Body.ToString());
        }
        public static IMessageFormatter GetMessageFormatter(this MessageFormatType formatType)
        {
            IMessageFormatter formatter = null;
            switch (formatType) {
                case MessageFormatType.XML:
                    formatter = new XmlMessageFormatter();
                    break;
                case MessageFormatType.Binary:
                    formatter = new BinaryMessageFormatter();
                    break;
                default:
                    throw new NotSupportedException(String.Format("Message format type {0} is not supported.", formatType));
            }

            return formatter;
        }
예제 #5
0
        // Handles both normal and large message send operations
        private void SendGeneric(bool useLargeMessageSample)
        {
            progressBarReceive.Visibility = Visibility.Hidden;
            Utilities.StartProgressBar(progressBarSend);
            try
            {
                MessageQueueTransaction transaction = new MessageQueueTransaction();
                transaction.Begin();

                IMessageFormatter formatter = new BinaryMessageFormatter();
                Message message = new Message();

                FileInfo fileInfo = new FileInfo(textFileName.Text);
                FileStream fStream = fileInfo.OpenRead();
                byte[] b = new byte[fStream.Length];
                fStream.Read(b, 0, b.Length);
                MemoryStream mStream = new MemoryStream(b, 0, b.Length, false);

                message.Label = fileInfo.Name;
                message.Formatter = formatter;
                message.UseDeadLetterQueue = true;
                message.Body = mStream;

                int fragmentSize = 0;
                if (textFragmentSize.Text.Length != 0)
                {
                    fragmentSize = Int32.Parse(textFragmentSize.Text, CultureInfo.InvariantCulture);
                }

                if (useLargeMessageSample)
                {
                    LargeMessageQueue largeMessageQueue = new LargeMessageQueue(this.queue, fragmentSize);
                    largeMessageQueue.Send(message, transaction);
                }
                else
                {
                    this.queue.Send(message, transaction);
                }

                transaction.Commit();

                Utilities.StopProgressBar(progressBarSend);
                this.SetQueueViewerStatus();

                MessageBox.Show("Send successful!", "Success!");
            }
            catch (Exception ex)
            {
                Utilities.ErrorProgressBar(progressBarSend);
                this.SetQueueViewerStatus();

                MessageBox.Show("Send Error: " + ex.Message, "Error!");
            }
        }
예제 #6
0
        static void Method(string json, TypeNameHandling param)
        {
            //Unsafe 2
            var data = JsonConvert.DeserializeObject <Model>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects
            });
            var serializeSettings = new JsonSerializerSettings();

            serializeSettings.TypeNameHandling = TypeNameHandling.All;
            serializeSettings.TypeNameHandling = (TypeNameHandling)2;
            serializeSettings = new JsonSerializerSettings
            {
                TypeNameHandling = param
            };
            serializeSettings.TypeNameHandling = GetHandling("");

            // Unsafe 5
            BinaryMessageFormatter binaryMessage = new System.Messaging.BinaryMessageFormatter();

            binaryMessage.Read(new Message());


            // Unsafe 7
            System.Web.UI.ObjectStateFormatter formatter = new System.Web.UI.ObjectStateFormatter();
            formatter.Deserialize("");
            formatter.Deserialize(new MemoryStream());

            // Unsafe 8
            XmlObjectSerializer xmlObjectSerializer = null;

            xmlObjectSerializer.ReadObject(new MemoryStream());

            // Unsafe 11
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(InsecureDeserialize));

            dataContractJsonSerializer.ReadObject(new MemoryStream());
            dataContractJsonSerializer.ReadObject(XmlDictionaryReader.Create(""));
            dataContractJsonSerializer.ReadObject(XmlDictionaryReader.Create(""), false);
            dataContractJsonSerializer.ReadObject(XmlReader.Create(""));
            dataContractJsonSerializer.ReadObject(XmlReader.Create(""), false);

            // Unsafe 12
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(InsecureDeserialize));

            xmlSerializer.Deserialize(new MemoryStream());
            xmlSerializer.Deserialize(TextReader.Null);
            xmlSerializer.Deserialize(XmlReader.Create(""));
            xmlSerializer.Deserialize(XmlReader.Create(""), "\"");
            xmlSerializer.Deserialize(XmlReader.Create(""), new System.Xml.Serialization.XmlDeserializationEvents());
            xmlSerializer.Deserialize(XmlReader.Create(""), "\"", new System.Xml.Serialization.XmlDeserializationEvents());

            // Unsafe 13
            System.Messaging.XmlMessageFormatter xmlMessageFormatter = new XmlMessageFormatter();
            xmlMessageFormatter.Read(new System.Messaging.Message());

            // Unsafe 14
            System.Resources.ResourceReader resourceReader = new System.Resources.ResourceReader("");
            resourceReader = new System.Resources.ResourceReader(new MemoryStream());

            // Unsafe 15
            fastJSON.JSON.ToObject("");

            // Unsafe 16
            ServiceStack.Text.JsonSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.JsonSerializer.DeserializeFromReader(TextReader.Null, typeof(InsecureDeserialize));
            ServiceStack.Text.JsonSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.TypeSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.TypeSerializer.DeserializeFromReader(TextReader.Null, typeof(InsecureDeserialize));
            ServiceStack.Text.TypeSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.CsvSerializer.DeserializeFromString(typeof(InsecureDeserialize), "");
            ServiceStack.Text.CsvSerializer.DeserializeFromReader <InsecureDeserialize>(TextReader.Null);
            ServiceStack.Text.CsvSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.XmlSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.XmlSerializer.DeserializeFromReader <InsecureDeserialize>(TextReader.Null);
            ServiceStack.Text.XmlSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());
        }
예제 #7
0
		/// <summary>
		/// Attempts to extract the content of a message in string format.
		/// </summary>
		/// <param name="message">Message to extract.</param>
		/// <param name="usedMessageFormatterType">Informs which formatter was used to extract the message.</param>
		/// <returns>A string if successful else null.</returns>
		private string ExtractMessageContent(System.Messaging.Message message)
		{
			string result = null;

			//create an array of formatters, ordered as we are going to attempt to use them
			IMessageFormatter[] formatterArray = new IMessageFormatter[3];
			formatterArray[0] = new ActiveXMessageFormatter();
			formatterArray[1] = new XmlMessageFormatter();
			formatterArray[2] = new BinaryMessageFormatter();

			//attempt to read the message body using the different formatters			
			foreach (IMessageFormatter formatter in formatterArray)
			{				
				try
				{
					//attempt to extract the message
					message.Formatter = formatter;					
					if (message.Formatter is ActiveXMessageFormatter)
						result = Convert.ToString(message.Body);
					else
					{
						message.BodyStream.Position=0;									
						StreamReader sr = new StreamReader(message.BodyStream);	//do not dispose this stream else the underlying stream will close				
						result = sr.ReadToEnd(); 				
					}
					
					//message has been successfully extracted (else we would have thrown an exception)					

					//check the xml formatter has given us valid xml
					if (!(formatter is XmlMessageFormatter && !IsXml(result)))						
						break;
				}
				catch 
				{
					result = null;
				}
			}
			if (result == null)
				result = Locale.UserMessages.UnableToDisplayBinaryMessage;
			
			return result;
		}
예제 #8
0
        static IObserver <Point> Msmq()
        {
            var q     = "BARTDE-M6500\\Private$\\MouseService";
            var queue = default(MessageQueue);

            if (MessageQueue.Exists(q))
            {
                queue = new MessageQueue(q);
            }
            else
            {
                queue = MessageQueue.Create(q);
            }

            var format = new System.Messaging.BinaryMessageFormatter();

            queue.Formatter = format;

            var incoming = Observable.Create <string>(observer =>
            {
                return(NewThreadScheduler.Default.ScheduleLongRunning(cancel =>
                {
                    while (!cancel.IsDisposed)
                    {
                        var msg = queue.Receive();
                        observer.OnNext((string)msg.Body);
                    }
                }));
            });

            var sub = new ReplaySubject <Point>();

            var map = new Dictionary <string, IDisposable>();

            incoming.Subscribe(clientQueue =>
            {
                var command = clientQueue[0];
                var target  = clientQueue.Substring(2);

                switch (command)
                {
                case 'S':
                    {
                        var cq = new MessageQueue(target);

                        var crm      = new System.Messaging.BinaryMessageFormatter();
                        cq.Formatter = crm;

                        map[target] = sub.Subscribe(pt =>
                        {
                            cq.Send(pt);
                        });
                    }
                    break;

                case 'D':
                    {
                        var d = default(IDisposable);
                        if (map.TryGetValue(target, out d))
                        {
                            d.Dispose();
                        }
                    }
                    break;

                default:
                    throw new Exception("Don't know what you're talking about!");
                }
            });

            return(sub);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BinaryMessageConverter"/> class.
 /// </summary>
 /// <param name="binaryMessageFormatter">The binary message formatter.</param>
 public BinaryMessageConverter(BinaryMessageFormatter binaryMessageFormatter)
 {
     this.binaryMessageFormatter = binaryMessageFormatter;            
 }
        // throws exception if hole is found in the large message sequence
        // If not found, message is moved to the subqueue if moveMessage flag is true
        private int CheckReceiveMessage(MessageQueue subQueue, string correlationId, string largeSequenceId)
        {
            LargeMessageProperties largeMessageProperties = null;
            IMessageFormatter formatter = new BinaryMessageFormatter();

            // If AppSpecific is zero, it is first fragment
            if (this.message.AppSpecific != Parameters.HEADER_FRAGMENT_ID)
            {
                try
                {
                    Message lastMessageInSubQueue = subQueue.PeekByLookupId(MessageLookupAction.Last, 0);
                    lastMessageInSubQueue.Formatter = formatter;

                    if (this.message.AppSpecific == Parameters.TRAILER_FRAGMENT_ID)
                    {
                        // If message in main queue is a trailer fragment, check if the last message in subqueue
                        // corresponds to the last expected message with application data
                        largeMessageProperties = this.GetLargeMessageHeader(this.message);
                        if (lastMessageInSubQueue.AppSpecific != largeMessageProperties.FragmentCount)
                        {
                            // Fragment(s) in the middle (before the trailer fragment) missing, send delete status message
                            this.SendToStatusQueue(correlationId, (int)Parameters.ReceiveAction.Delete, largeSequenceId);
                            return (int)Parameters.ReceiveAction.Restart;
                        }
                    }
                    else if (((this.message.AppSpecific != (lastMessageInSubQueue.AppSpecific + 1)) &&
                        (lastMessageInSubQueue.AppSpecific != Parameters.HEADER_FRAGMENT_ID)) ||
                        ((this.message.AppSpecific != 1) && (lastMessageInSubQueue.AppSpecific == Parameters.HEADER_FRAGMENT_ID)))
                    {
                        // Fragment(s) in the middle missing, send delete status message
                        this.SendToStatusQueue(correlationId, (int)Parameters.ReceiveAction.Delete, largeSequenceId);
                        return (int)Parameters.ReceiveAction.Restart;
                    }
                }
                catch (InvalidOperationException)
                {
                    // No message in subqueue, send delete status message
                    this.SendToStatusQueue(correlationId, (int)Parameters.ReceiveAction.Delete, largeSequenceId);
                    return (int)Parameters.ReceiveAction.Restart;
                }
            }
            else
            {
                largeMessageProperties = this.GetLargeMessageHeader(this.message);
            }

            // Move message to sub-queue
            try
            {
                NativeMethods.MoveLargeMessage(this.queue, subQueue.FormatName, this.message.LookupId);
            }
            catch (InvalidOperationException)
            {
                // look for another large message sequence
                return ((int)Parameters.ReceiveAction.Restart);
            }

            if (this.message.AppSpecific == Parameters.TRAILER_FRAGMENT_ID)
            {
                // All fragments available in subqueue
                return ((int)Parameters.ReceiveAction.Complete);
            }

            // More fragments are expected
            return ((int)Parameters.ReceiveAction.Pending);
        }
예제 #11
0
        private IMessageFormatter SetQueueFormatterAndProperties(MessageQueue activeQueue, eMessageFormat messageFormat, Type customType)
        {
            IMessageFormatter objFormatter = null;
            MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter();

            // Message Formatter
            switch (messageFormat)
            {
                case eMessageFormat.XMLSerialize:
                    if (customType == null)
                    {
                        objFormatter = new XmlMessageFormatter();
                    }
                    else
                    {
                        objFormatter = new XmlMessageFormatter(new Type[] { customType });
                    }

                    break;
                case eMessageFormat.ActiveXSerialize:
                    objFormatter = new ActiveXMessageFormatter();
                    break;
                case eMessageFormat.BinarySerialize:
                    objFormatter = new BinaryMessageFormatter();
                    break;
            }

            // Messages in Private Queue
            // Ensure these properties are received (CorrelationID defaults to False)
            objMessagePropertyFilter.SetDefaults();
            objMessagePropertyFilter.CorrelationId = true;
            objMessagePropertyFilter.AppSpecific = true;
            objMessagePropertyFilter.ArrivedTime = true;
            activeQueue.MessageReadPropertyFilter = objMessagePropertyFilter;

            // Message Formatter
            activeQueue.Formatter = objFormatter;

            return objFormatter;
        }
예제 #12
0
        static IObserver<Point> Msmq()
        {
            var q = "BARTDE-M6500\\Private$\\MouseService";
            var queue = default(MessageQueue);
            if (MessageQueue.Exists(q))
            {
                queue = new MessageQueue(q);
            }
            else
            {
                queue = MessageQueue.Create(q);
            }

            var format = new System.Messaging.BinaryMessageFormatter();
            queue.Formatter = format;

            var incoming = Observable.Create<string>(observer =>
            {
                return NewThreadScheduler.Default.ScheduleLongRunning(cancel =>
                {
                    while (!cancel.IsDisposed)
                    {
                        var msg = queue.Receive();
                        observer.OnNext((string)msg.Body);
                    }
                });
            });

            var sub = new ReplaySubject<Point>();

            var map = new Dictionary<string, IDisposable>();

            incoming.Subscribe(clientQueue =>
            {
                var command = clientQueue[0];
                var target = clientQueue.Substring(2);

                switch (command)
                {
                    case 'S':
                        {
                            var cq = new MessageQueue(target);

                            var crm = new System.Messaging.BinaryMessageFormatter();
                            cq.Formatter = crm;

                            map[target] = sub.Subscribe(pt =>
                            {
                                cq.Send(pt);
                            });
                        }
                        break;
                    case 'D':
                        {
                            var d = default(IDisposable);
                            if (map.TryGetValue(target, out d))
                                d.Dispose();
                        }
                        break;
                    default:
                        throw new Exception("Don't know what you're talking about!");
                }
            });

            return sub;
        }
 public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
 {
     object[] values = new object[4];
     values[0] = new ActiveXMessageFormatter();
     values[1] = new BinaryMessageFormatter();
     values[2] = new XmlMessageFormatter();
     return new TypeConverter.StandardValuesCollection(values);
 }
        // Main method that performs the peek operation
        // If normal message, returns message to application
        // If large message, performs reassembly and return message to application
        // This method throws LargeMessageQueueException and does not delete fragments if holes are found
        private Message PeekGeneric(string correlationId, TimeSpan timeout)
        {
            // Holds the initial state of the filter value. this is done so that this filter
            // is reverted back to its initial state (initial = when it entered the API)
            bool receiveFilterCorrelationId = this.queue.MessageReadPropertyFilter.CorrelationId;
            bool receiveFilterAppSpecific = this.queue.MessageReadPropertyFilter.AppSpecific;
            bool receiveFilterBody = this.queue.MessageReadPropertyFilter.Body;
            bool receiveFilterLookupId = this.queue.MessageReadPropertyFilter.LookupId;
            this.queue.MessageReadPropertyFilter.CorrelationId = true;
            this.queue.MessageReadPropertyFilter.AppSpecific = true;
            this.queue.MessageReadPropertyFilter.Body = true;
            this.queue.MessageReadPropertyFilter.LookupId = true;

            try
            {
                this.stream = new MemoryStream();

                // Holds the message Id of first fragment
                string largeSequenceId = string.Empty;

                LargeMessageProperties largeMessageProperties = null;
                MessageQueue subQueue = null;

                // The overall send formatting is BinaryMessageFormatter, so the receive should also be that
                IMessageFormatter formatter = new BinaryMessageFormatter();

                int checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                int statusMessageAppSpecific = (int)Parameters.ReceiveAction.None;
                Message statusMessage = null;
                Cursor mainQueueCursor = null;
                Cursor subQueueCursor = null;

                do
                {
                    // First gets the status message from the status queue, reference the sub-queue using the
                    // identifier in status message, perform corresponding peek operation
                    if (checkPeekMessageStatus == (int)Parameters.ReceiveAction.Restart)
                    {
                        mainQueueCursor = this.queue.CreateCursor();
                        try
                        {
                            // throws exception if status queue is empty
                            statusMessage = this.PeekFromStatusQueue(correlationId);
                            statusMessage.Formatter = formatter;
                            statusMessageAppSpecific = statusMessage.AppSpecific;
                            largeSequenceId = statusMessage.CorrelationId;

                            if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.Complete)
                            {
                                checkPeekMessageStatus = (int)Parameters.ReceiveAction.None;
                            }
                            else
                            {
                                throw new LargeMessageQueueException(largeSequenceId, "Fragments missing");
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            this.message = this.PeekFromMsmq(correlationId, timeout, mainQueueCursor, PeekAction.Current);
                            this.message.Formatter = formatter;

                            // If normal message, return single message to application
                            if (this.message.CorrelationId == Utilities.GetEmptyCorrelationIdStr())
                            {
                                return this.message;
                            }

                            if (this.message.AppSpecific == Parameters.HEADER_FRAGMENT_ID)
                            {
                                largeSequenceId = this.message.Id;
                                checkPeekMessageStatus = (int)Parameters.ReceiveAction.Pending;
                            }
                            else
                            {
                                largeSequenceId = this.message.CorrelationId;
                                subQueue = this.GetSubQueue(largeSequenceId);
                                subQueueCursor = subQueue.CreateCursor();
                                try
                                {
                                    // Throws exception if subqueue is empty
                                    this.message = subQueue.Peek(TimeSpan.Zero, subQueueCursor, PeekAction.Current);
                                    this.message.Formatter = formatter;
                                }
                                catch (MessageQueueException)
                                {
                                    throw new LargeMessageQueueException(largeSequenceId, "Fragments from header to " +
                                        (this.message.AppSpecific - 1) + " missing");
                                }
                                catch (InvalidOperationException)
                                {
                                    throw new LargeMessageQueueException(largeSequenceId, "Fragments from header to " +
                                        (this.message.AppSpecific - 1) + " missing");
                                }

                                if (this.message.AppSpecific == Parameters.HEADER_FRAGMENT_ID)
                                {
                                    checkPeekMessageStatus = (int)Parameters.ReceiveAction.Pending;
                                }
                                else
                                {
                                    checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                                }
                            }
                        }
                    }

                    if (checkPeekMessageStatus != (int)Parameters.ReceiveAction.Restart)
                    {
                        if (subQueue != null)
                        {
                            try
                            {
                                while (true)
                                {
                                    this.message = subQueue.Peek(TimeSpan.Zero, subQueueCursor, PeekAction.Next);
                                    this.message.Formatter = formatter;
                                }
                            }
                            catch (MessageQueueException)
                            {
                                // Don't do anything and just come out of the loop
                            }
                            catch (InvalidOperationException)
                            {
                                // Don't do anything and just come out of the loop
                            }
                        }

                        try
                        {
                            // the previous AppSpecific is the last message peek from the subqueue
                            int previousAppSpecific = this.message.AppSpecific;
                            while (checkPeekMessageStatus != (int)Parameters.ReceiveAction.Complete)
                            {
                                this.message = this.PeekByCorrelationId(largeSequenceId, timeout, mainQueueCursor, PeekAction.Next);
                                this.message.Formatter = formatter;

                                if (this.message.AppSpecific == Parameters.TRAILER_FRAGMENT_ID)
                                {
                                    // If message in main queue is a trailer fragment, check if the last message in subqueue
                                    // corresponds to the last expected message with application data
                                    largeMessageProperties = this.GetLargeMessageHeader(this.message);
                                    if (previousAppSpecific != largeMessageProperties.FragmentCount)
                                    {
                                        throw new LargeMessageQueueException(largeSequenceId, "Fragments from " +
                                            previousAppSpecific + " to trailer missing");
                                    }

                                    checkPeekMessageStatus = (int)Parameters.ReceiveAction.Complete;
                                }
                                else if (((this.message.AppSpecific != (previousAppSpecific + 1)) &&
                                    (previousAppSpecific != Parameters.HEADER_FRAGMENT_ID)) ||
                                    ((this.message.AppSpecific != 1) && (previousAppSpecific == Parameters.HEADER_FRAGMENT_ID)))
                                {
                                    if (previousAppSpecific == Parameters.HEADER_FRAGMENT_ID)
                                    {
                                        throw new LargeMessageQueueException(largeSequenceId, "Fragments from 1 to " +
                                            (this.message.AppSpecific - 1) + " missing");
                                    }
                                    else
                                    {
                                        throw new LargeMessageQueueException(largeSequenceId, "Fragments from " + (previousAppSpecific + 1) +
                                            " to " + (this.message.AppSpecific - 1) +
                                            " missing");
                                    }
                                }
                                else
                                {
                                    this.AssembleFragments();
                                }

                                previousAppSpecific = this.message.AppSpecific;
                            }
                        }
                        catch (MessageQueueException)
                        {
                            // Don't do anything
                        }
                        catch (InvalidOperationException)
                        {
                            // Don't do anything
                        }

                        // Last fragment has the control values
                        if (this.message.AppSpecific == Parameters.TRAILER_FRAGMENT_ID)
                        {
                            // All message fragments assembled
                            this.PrepareLargeMessage(largeMessageProperties);
                            checkPeekMessageStatus = (int)Parameters.ReceiveAction.Complete;
                        }
                        else
                        {
                            throw new LargeMessageQueueException(largeSequenceId, "Fragments after " +
                                this.message.AppSpecific + " to trailer missing");
                        }
                    }

                    if (checkPeekMessageStatus == (int)Parameters.ReceiveAction.Restart)
                    {
                        try
                        {
                            this.stream.Dispose();
                        }
                        catch (NullReferenceException)
                        {
                            // Don't do anything
                        }

                        try
                        {
                            mainQueueCursor.Close();
                            subQueueCursor.Close();
                        }
                        catch (NullReferenceException)
                        {
                            // Don't do anything
                        }

                        this.stream = new MemoryStream();
                    }
                } while (checkPeekMessageStatus != (int)Parameters.ReceiveAction.Complete);

                return this.message;
            }
            finally
            {
                if (this.stream != null)
                {
                    this.stream.Close();
                }

                this.queue.MessageReadPropertyFilter.CorrelationId = receiveFilterCorrelationId;
                this.queue.MessageReadPropertyFilter.AppSpecific = receiveFilterAppSpecific;
                this.queue.MessageReadPropertyFilter.LookupId = receiveFilterLookupId;
                this.queue.MessageReadPropertyFilter.Body = receiveFilterBody;
            }
        }
예제 #15
0
		private Message[] PeekMessages(MessageQueue activeQueue, bool blnDynamicConnection, MessageFormat eMessageFormat, System.Type CustomType)
		{
			Message objMessage;
			Message[] arrCurrentMessages = new Message[0];
			Message[] arrCopyOfMessages = null;
			IMessageFormatter objFormatter = null ;
			MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter();
			int intArrayIndex;

			// Message Formatter
			switch (eMessageFormat)
			{
				case MessageFormat.XMLSerialize:
					if (CustomType == null)
					{
						objFormatter = new XmlMessageFormatter();
					}
					else
					{
					// objFormatter = new XmlMessageFormatter(new Type() [CustomType]);
					}

					break;
				case MessageFormat.ActiveXSerialize:
					objFormatter = new ActiveXMessageFormatter();
					break;
				case MessageFormat.BinarySerialize:
					objFormatter = new BinaryMessageFormatter();
					break;
			}

			// Messages in Private Queue
			// Ensure these properties are received (CorrelationID defaults to False)
			objMessagePropertyFilter.SetDefaults();
			objMessagePropertyFilter.CorrelationId = true;
			objMessagePropertyFilter.AppSpecific = true;
			objMessagePropertyFilter.ArrivedTime = true;
			activeQueue.MessageReadPropertyFilter = objMessagePropertyFilter;

			// Message Formatter
			activeQueue.Formatter = objFormatter;

			// Dynamic Connection whilst gathering messages
			if (blnDynamicConnection == true)
			{
				IEnumerator objMessageEnumerator = activeQueue.GetEnumerator();
				intArrayIndex = 0;
				while (objMessageEnumerator.MoveNext())
				{
					objMessage = (Message) objMessageEnumerator.Current;
					if (intArrayIndex > 0)
					{
						arrCopyOfMessages = new Message[intArrayIndex];
						arrCurrentMessages.CopyTo(arrCopyOfMessages,0);
						arrCurrentMessages=arrCopyOfMessages;
					}
					arrCurrentMessages[intArrayIndex] = objMessage;
					intArrayIndex += 1;
				}
			}
			else // Snapshot of messages currently in Queue
			{
				arrCurrentMessages = null ;
				try
				{
					arrCurrentMessages = activeQueue.GetAllMessages();
				}
				catch (System.Messaging.MessageQueueException excM)
				{
					throw excM;
				}
			}

			return arrCurrentMessages;

		}
예제 #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BinaryMessageConverter"/> class.
 /// </summary>
 public BinaryMessageConverter()
 {
     binaryMessageFormatter = new BinaryMessageFormatter();
 }
        // Main method that performs the receive operation
        // If normal message, returns message to application
        // If large message, performs reassembly and return message to application
        // This method throws LargeMessageQueueException and  delete fragments if holes are found
        private Message ReceiveGeneric(string correlationId, TimeSpan timeout, MessageQueueTransaction transaction, MessageQueueTransactionType transactionType)
        {
            MessageQueueTransaction internalTransaction = transaction;
            bool transactionFlag = (internalTransaction != null) ? true : false;
            MessageQueueTransaction deleteTransaction = null;

            // Holds the initial state of the filter value. this is done so that this filter
            // is reverted back to its initial state (initial = when it entered the API)
            bool receiveFilterCorrelationId = this.queue.MessageReadPropertyFilter.CorrelationId;
            bool receiveFilterAppSpecific = this.queue.MessageReadPropertyFilter.AppSpecific;
            bool receiveFilterBody = this.queue.MessageReadPropertyFilter.Body;
            bool receiveFilterLookupId = this.queue.MessageReadPropertyFilter.LookupId;
            this.queue.MessageReadPropertyFilter.CorrelationId = true;
            this.queue.MessageReadPropertyFilter.AppSpecific = true;
            this.queue.MessageReadPropertyFilter.Body = true;
            this.queue.MessageReadPropertyFilter.LookupId = true;

            try
            {
                // Creates an internal transaction if there was no transaction from the application
                if (!transactionFlag)
                {
                    internalTransaction = new MessageQueueTransaction();
                    internalTransaction.Begin();
                }

                // Holds the message Id of first fragment
                string largeSequenceId = string.Empty;

                LargeMessageProperties largeMessageProperties = null;
                MessageQueue subQueue = null;

                // The overall send formatting is BinaryMessageFormatter, so the receive should also be that
                IMessageFormatter formatter = new BinaryMessageFormatter();

                int checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                int statusMessageAppSpecific = (int)Parameters.ReceiveAction.None;

                do
                {
                    // First gets the status message from the status queue, reference the sub-queue using the
                    // identifier in status message, perform corresponding receive/reject operation
                    this.stream = new MemoryStream();
                    bool lookForStatusMessage = true;
                    Message statusMessage = null;

                    while (lookForStatusMessage)
                    {
                        try
                        {
                            // API firsts peeks from status queue and then receives/deletes the status message.
                            // This is done to clear junk status messages that may have come to occupy the status queue
                            statusMessage = this.PeekFromStatusQueue(correlationId);
                            statusMessage.Formatter = formatter;
                            statusMessageAppSpecific = statusMessage.AppSpecific;
                            largeSequenceId = (string)statusMessage.Body;
                            if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.Delete)
                            {
                                try
                                {
                                    deleteTransaction = new MessageQueueTransaction();
                                    deleteTransaction.Begin();

                                    statusMessage = this.ReceiveFromStatusQueue(statusMessage.LookupId, deleteTransaction, MessageQueueTransactionType.None, false);
                                    statusMessage.Formatter = formatter;
                                    throw new LargeMessageQueueException(largeSequenceId, "Fragments missing");
                                }
                                catch (InvalidOperationException)
                                {
                                    deleteTransaction.Abort();
                                    deleteTransaction.Dispose();
                                    lookForStatusMessage = true;
                                }
                            }
                            else
                            {
                                checkPeekMessageStatus = (int)Parameters.ReceiveAction.None;
                            }

                            try
                            {
                                subQueue = this.GetSubQueue(largeSequenceId);

                                // throws exception if subqueue empty
                                this.message = subQueue.PeekByLookupId(MessageLookupAction.Last, 0);
                                this.message.Formatter = formatter;
                                try
                                {
                                    statusMessage = this.ReceiveFromStatusQueue(statusMessage.LookupId, internalTransaction, transactionType, false);
                                    statusMessage.Formatter = formatter;
                                    lookForStatusMessage = false;
                                }
                                catch (InvalidOperationException)
                                {
                                    lookForStatusMessage = true;
                                }
                            }
                            catch (InvalidOperationException)
                            {
                                // Comes here when GetSubQueue throws exception. Just do a descructive receive and start status queue peek again
                                // this exception occurs when status queue contains junk data (status message for nonexistent subqueue)
                                try
                                {
                                    statusMessage = this.ReceiveFromStatusQueue(statusMessage.LookupId, internalTransaction, transactionType, true);
                                    statusMessage.Formatter = formatter;
                                }
                                catch (InvalidOperationException)
                                {
                                    // The status message to be received destructively has not been removed from queue. Don't do anything
                                }

                                lookForStatusMessage = true;
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            lookForStatusMessage = false;

                            if (correlationId == null)
                            {
                                try
                                {
                                    this.GetNextMessageSequenceInQueue(this.queue, largeSequenceId);
                                }
                                catch (InvalidOperationException)
                                {
                                    // Empty main queue
                                    this.message = this.queue.Peek(timeout);
                                    this.message.Formatter = formatter;
                                }
                            }
                            else
                            {
                                // If correlationId does not exist in queue, throw it to application
                                this.PeekFromMsmq(correlationId, timeout, this.queue.CreateCursor(), PeekAction.Current);
                            }

                            this.message.Formatter = formatter;

                            // If normal message, return single message to application
                            if (this.message.CorrelationId == Utilities.GetEmptyCorrelationIdStr())
                            {
                                this.ReceiveFromMsmq(this.queue, this.message.LookupId, internalTransaction, transactionType);
                                return this.message;
                            }

                            if (this.message.AppSpecific == Parameters.HEADER_FRAGMENT_ID)
                            {
                                largeSequenceId = this.message.Id;
                            }
                            else
                            {
                                largeSequenceId = this.message.CorrelationId;
                            }

                            subQueue = this.GetSubQueue(largeSequenceId);
                        }

                        checkPeekMessageStatus = (int)Parameters.ReceiveAction.None;
                    }

                    while ((checkPeekMessageStatus != (int)Parameters.ReceiveAction.Complete) && (checkPeekMessageStatus != (int)Parameters.ReceiveAction.Restart))
                    {
                        if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.Complete)
                        {
                            checkPeekMessageStatus = (int)Parameters.ReceiveAction.Complete;
                        }
                        else
                        {
                            checkPeekMessageStatus = this.CheckReceiveMessage(subQueue, correlationId, largeSequenceId);
                        }

                        if (checkPeekMessageStatus == (int)Parameters.ReceiveAction.Complete)
                        {
                            if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.None)
                            {
                                statusMessageAppSpecific = (int)Parameters.ReceiveAction.Complete;
                                this.SendToStatusQueue(correlationId, statusMessageAppSpecific, largeSequenceId);
                                checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                            }
                            else if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.Complete)
                            {
                                try
                                {
                                    while (true)
                                    {
                                        this.message = this.ReceiveFromMsmq(subQueue, TimeSpan.Zero, internalTransaction, transactionType);
                                        this.message.Formatter = formatter;

                                        // First fragment has the control values
                                        if (this.message.AppSpecific == Parameters.HEADER_FRAGMENT_ID)
                                        {
                                            largeSequenceId = this.message.Id;
                                        }
                                        else if (this.message.AppSpecific == Parameters.TRAILER_FRAGMENT_ID)
                                        {
                                            largeMessageProperties = this.GetLargeMessageHeader(this.message);

                                            // All message fragments assembled
                                            this.PrepareLargeMessage(largeMessageProperties);

                                            if (!transactionFlag)
                                            {
                                                internalTransaction.Commit();
                                            }

                                            return this.message;
                                        }
                                        else
                                        {
                                            this.AssembleFragments();
                                        }
                                    }
                                }
                                finally
                                {
                                }
                            }
                            else if (statusMessageAppSpecific == (int)Parameters.ReceiveAction.Delete)
                            {
                                throw new LargeMessageQueueException(largeSequenceId, "Fragments missing");
                            }
                        }
                        else if (checkPeekMessageStatus == (int)Parameters.ReceiveAction.Pending)
                        {
                            try
                            {
                                this.message = this.queue.PeekByCorrelationId(largeSequenceId, timeout);
                                this.message.Formatter = formatter;
                            }
                            catch (InvalidOperationException)
                            {
                                // This exception is thrown if more messages available in queue but not with largeSequenceId

                                // Checking again because the exception could be because another application may
                                // have moved the successive fragment to subqueue
                                if (!this.CheckCompleteMessage(subQueue))
                                {
                                    throw new LargeMessageQueueException(largeSequenceId, "Fragment after " +
                                        this.message.AppSpecific + " missing");
                                }
                                else
                                {
                                    // look for another large message sequence
                                    checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                                }
                            }
                            catch (MessageQueueException)
                            {
                                // This exception is thrown if no messages available in queue

                                // Checking again because the exception could be because another application may
                                // have moved the successive fragment to subqueue
                                if (!this.CheckCompleteMessage(subQueue))
                                {
                                    throw new LargeMessageQueueException(largeSequenceId, "Fragment after " +
                                        this.message.AppSpecific + " missing");
                                }
                                else
                                {
                                    // look for another large message sequence
                                    checkPeekMessageStatus = (int)Parameters.ReceiveAction.Restart;
                                }
                            }
                        }
                    }

                    this.stream.Close();
                } while (checkPeekMessageStatus == (int)Parameters.ReceiveAction.Restart);

                return null;
            }
            catch (LargeMessageQueueException lqe)
            {
                if (!string.IsNullOrEmpty(lqe.CorrelationId))
                {
                    this.PerformHouseKeeping(lqe.CorrelationId);

                    if (deleteTransaction != null)
                    {
                        deleteTransaction.Commit();
                        deleteTransaction.Dispose();
                    }
                }

                if (!transactionFlag)
                {
                    internalTransaction.Abort();
                }

                throw;
            }
            catch (Exception)
            {
                if (!transactionFlag)
                {
                    internalTransaction.Abort();
                }

                if (deleteTransaction != null)
                {
                    deleteTransaction.Abort();
                    deleteTransaction.Dispose();
                }

                throw;
            }
            finally
            {
                if (this.stream != null)
                {
                    this.stream.Close();
                }

                this.queue.MessageReadPropertyFilter.CorrelationId = receiveFilterCorrelationId;
                this.queue.MessageReadPropertyFilter.AppSpecific = receiveFilterAppSpecific;
                this.queue.MessageReadPropertyFilter.LookupId = receiveFilterLookupId;
                this.queue.MessageReadPropertyFilter.Body = receiveFilterBody;
            }
        }