Inheritance: MonoBehaviour
示例#1
0
        public int CreateEmailQueue(string inputData)
        {
            MessageQueueResponse response = new MessageQueueResponse();
            using (var context = new hamptondwellEntities())
            {

                MessageQueue messageQueue = new MessageQueue();

                messageQueue.ModifiedBy_UserID = -1;
                messageQueue.Active = true;
                messageQueue.Status_MessageQueueStatusID = -1;
                messageQueue.MessageResponse = string.Empty;

                if (messageQueue.MessageQueueID == 0)
                {
                    messageQueue.CreatedOn = DateTime.UtcNow;
                    messageQueue.CreatedBy_UserID = -1;
                    messageQueue.OccurredOn = DateTime.UtcNow;
                    messageQueue.Type_MessageQueueTypeID = -1;
                    messageQueue.MessageBody = inputData;

                }
                messageQueue.ModifiedOn = DateTime.UtcNow;

                if (messageQueue.MessageQueueID == 0)
                    context.AddObject("MessageQueues", messageQueue);

                context.SaveChanges();
            }
            return 1;
        }
 public frmDefineCharts(MessageQueue message)
 {
     InitializeComponent();
     helpProvider1.HelpNamespace = Path.Combine(WOTHelper.GetEXEPath(), "Help", "WoT_Stats.chm");
     helpProvider1.SetHelpNavigator(this, HelpNavigator.TopicId);
     helpProvider1.SetHelpKeyword(this, "520");
 }
        public List<PromocionBE> listar(PromocionBE objPromocionBE)
        {
            string rutaColaIn = @".\private$\fidecine_promocion";
            if (!MessageQueue.Exists(rutaColaIn))
                MessageQueue.Create(rutaColaIn);
            MessageQueue colaIn = new MessageQueue(rutaColaIn);
            colaIn.Formatter = new XmlMessageFormatter(new Type[] { typeof(Promocion) });
            Message mensajeIn = colaIn.Receive();
            Promocion obj = (Promocion)mensajeIn.Body;
            new PromocionDAO().insertar(obj);

            List<PromocionBE> listaPromocion = new List<PromocionBE>();
            PromocionBE tempPromocionBE = null;

            foreach (Promocion objPromocion in new PromocionDAO().listar(objPromocionBE.VigenciaInicio, objPromocionBE.VigenciaFin))
            {
                tempPromocionBE = new PromocionBE();
                tempPromocionBE.IdPromocion = objPromocion.IdPromocion;
                tempPromocionBE.ProductoNombre = objPromocion.Producto.Nombre;
                tempPromocionBE.Puntos = objPromocion.Puntos;
                tempPromocionBE.VigenciaInicio = objPromocion.vigenciaInicio.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
                tempPromocionBE.VigenciaFin = objPromocion.vigenciaFin.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
                listaPromocion.Add(tempPromocionBE);
            }

            return listaPromocion;
        }
示例#4
0
 public StreamByteReceiver(IEndPoint remote, Stream client)
 {
     Remote = remote;
     this.client = client;
     Received = new MessageQueue<byte[]>();
     Listen();
 }
示例#5
0
文件: Program.cs 项目: tmassey/mtos
        public static void Main(string[] args)
        {
            InitConnection();
            while (true)
            {
                try
                {

                    _TaskQueue = new MessageQueue<TaskMessage>(true, _Connection);
                    _LogQueue = new MessageQueue<TaskLogMessage>(false, _Connection);
                    _ProgressQueue = new MessageQueue<TaskProgressMessage>(false, _Connection);
                    _TaskQueue.OnReceivedMessage += _TaskQueue_OnReceivedMessage;
                    _LogQueue.Publish(new TaskLogMessage
                        {
                            MessageId = Guid.NewGuid(),
                            TransmisionDateTime = DateTime.Now,
                            TaskId = Guid.Empty,
                            LogLevel = LogLevel.Info,
                            LogMessage = "Node UP: " + Dns.GetHostName()
                        });

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    continue;
                }
                while (true)
                {
                }
            }
        }
            public MessageArrivedState(MessageArrivedEventHandler handler, ServiceEventMessage message,MessageQueue queue, AckMessageInfo ackMessageInfo)
			{
                AckMessageInfo = ackMessageInfo;
				Handler = handler;
				Message = message;
                Queue = queue;
			}
 public WhenReceivingMessages()
 {
     messageProcessor = new FakeMessageProcessor<String>();
     testQueue = TestMessageQueue.Create();
     testQueue.EnsureQueueExists();
     testQueue.Purge();
 }
示例#8
0
        public void Upload(string host, string fileName, string userName, string password, MessageQueue message, string playerName)
        {
            try
            {
                FileInfo toUpload = new FileInfo(fileName);

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://" + host + "/" + toUpload.Name);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    request.Credentials = new NetworkCredential(userName, password);

                Stream ftpStream = request.GetRequestStream();
                //will do this at a later stage
                //byte[] byteFile = WOTStatistics.Core.GZIP.Compress(File.ReadAllBytes(toUpload.FullName));
                byte[] byteFile = File.ReadAllBytes(toUpload.FullName);

                ftpStream.Write(byteFile, 0, byteFile.Length);
                ftpStream.Close();
                // return (String.Format("Info : File submitted to FTP site. [{0}]", playerName));
            }
            catch
            {
            }
        }
示例#9
0
        public string Download(string host, string fileName, string userName, string password, MessageQueue message, string playerName)
        {
            try
            {
                FileInfo fi = new FileInfo(fileName);
                WebClient request = new WebClient();

                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    request.Credentials = new NetworkCredential(userName, password);

                byte[] fileData = request.DownloadData(@"ftp://" + host + "/" + fi.Name);

                string dropFileName = WOTHelper.GetTempFolder() + @"\" + fi.Name;
                //will dot this at a later stage
                //File.WriteAllBytes(dropFileName, WOTStatistics.Core.GZIP.Decompress(fileData));
                File.WriteAllBytes(dropFileName, fileData);

                message.Add("Info : Retrieved file from FTP. [" + playerName + "]");
                return dropFileName;
            }
            catch (Exception ex)
            {
                message.Add("Error : " + ex.Message);
                return fileName;
            }
        }
示例#10
0
 static void ByMSMQ()
 {
     Console.WriteLine("Opening MSMQ...");
     //messageQueue = !MessageQueue.Exists(QueueName) ? MessageQueue.Create(QueueName) : new MessageQueue(QueueName);4
     messageQueue = new MessageQueue(QueueName);
     Console.WriteLine("Server is ready");
     Console.WriteLine("Launch client app");
     RSA_public_key_receive();
     Console.WriteLine("Receiving open RSA-key...");
     Console.WriteLine("Making DES-key...");
     des_provider = new DESCryptoServiceProvider();
     des_provider.GenerateKey();
     des_provider.GenerateIV();
     Console.WriteLine("Crypt DES-key with open RSA-key...");
     DES_key = Encrypt_RSA(des_provider.Key);
     Console.WriteLine("Sending encrypted DES-key and initialization vector(IV)...");
     messageQueue.Send(DES_key);
     messageQueue.Send(des_provider.IV);
     Console.WriteLine("Getting data from Access...");
     GetData();
     Console.WriteLine("Crypt data...");
     var myMemoryStream = new MemoryStream();
     EncryptAndSerialize(myMemoryStream, data_to_recieve.ToArray());
     Console.WriteLine("Transfering data...");
     //Console.WriteLine("length = " + myMemoryStream.Length);
     messageQueue.Send(myMemoryStream.ToArray());
     Console.WriteLine("Successfull");
     Console.ReadKey();
 }
示例#11
0
        public MessageQueueStructure(MessageQueue messageQueue, SharedObjects sharedObjects)
        {
            this.messageQueue = messageQueue;
            this.sharedObjects = sharedObjects;

            InitializeSuffixes();
        }
		public Message(MessageQueue queue, string id, byte[] data, byte[] checksum = null, System.DateTime? expires = null, System.DateTime? enqueuedTime = null, System.DateTime? dequeuedTime = null, int dequeuedCount = 0)
			: base(id, data, checksum, expires, enqueuedTime, dequeuedTime, dequeuedCount)
		{
			if(queue == null)
				throw new ArgumentNullException("queue");

			_queue = queue;
		}
示例#13
0
		public SecurityRemoteProxy(MessageQueue channel, Security target)
		{
			_target = target;
			_channel = channel;

			_r_PlaceOrder = Address.FromDelegate<MessageQueueReader>(target.r_PlaceOrder);
			_r_Check = Address.FromDelegate<MessageQueueReader>(target.r_Check);
		}
示例#14
0
 public LocalConnection(LocalSender s, LocalReceiver r)
 {
     Sender = s;
     Receiver = r;
     Received = new MessageQueue<object>();
     Receiver.Received.Subscribe(n=> Received.Post(n));
     IsAlive = true;
 }
示例#15
0
	public MessageQueueCacheDependency(string queueName)
	{
		queue = new MessageQueue(queueName);

		// Wait for the queue message on another thread.
		WaitCallback callback = new WaitCallback(WaitForMessage);
		ThreadPool.QueueUserWorkItem(callback);
	}
 public WhenSendingMessages()
 {
     serializer = new BinarySerializer();
     messageSender = new MessageSender<String>(TestMessageQueue.Path, serializer);
     testQueue = TestMessageQueue.Create();
     testQueue.EnsureQueueExists();
     testQueue.Purge();
 }
 public WhenInitializingMessageReceiver()
 {
     messageProcessor = new FakeMessageProcessor<String>();
     processingQueue = TestMessageQueue.Create("processing");
     testQueue = TestMessageQueue.Create();
     testQueue.EnsureQueueExists();
     testQueue.Purge();
 }
示例#18
0
 public ByteConnection(IByteSender sender, IByteReceiver receiver)
 {
     this.sender = sender;
     this.receiver = receiver;
     receiver.Received.Subscribe(HandleReceived);
     Received = new MessageQueue<byte[]>();
     sender.Error += HandleError;
     receiver.Error += HandleError;
 }
示例#19
0
	protected void cmdModfiy_Click(object sender, EventArgs e)
	{
		MessageQueue queue = new MessageQueue(queueName);
		
		// (You could send a custom object instead
		//  of a string.)
		queue.Send("Invalidate!");
		lblInfo.Text += "Message sent<br/>";
	}
 public override Dictionary<string, string> handle(MessageQueue.Message message)
 {
     Dictionary<string,string> data = JsonConvert.DeserializeObject<Dictionary<string,string>>(message.Body);
     this.form.add_row(Convert.ToInt16(data["ID"]), data["first_name"], data["last_name"], data["city"], data["state"], data["phone"]);
     message.ack();
     Dictionary<string, string> response = new Dictionary<string, string>();
     response.Add("message", String.Format("This is a Account Handler  response to " +
            "message {0}", message.CorrelationId));
     return response;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="loger"></param>
        public TracingRecordRabbitmq(string host, string userName, string pwd, MessageQueue.ILoger loger = null)
        {
            Raven.MessageQueue.WithRabbitMQ.Options rabbitMQOptions = new Options();
            rabbitMQOptions.SerializerType = SerializerType.NewtonsoftJson;
            rabbitMQOptions.HostName = host;
            rabbitMQOptions.UserName = userName;
            rabbitMQOptions.Password = pwd;
            rabbitMQOptions.Loger = loger;

            rabbitMQClient = RabbitMQClient.GetInstance(rabbitMQOptions);
        }
示例#22
0
 public RobotContol(DateTime start, Guid taskId)
 {
     _starttime = start;
     _taskid = taskId;
     NetworkLock = "Lock";
     ConsoleLock = "Lock";
     InitConnection();
     Mds = new MongoDataService();
     _ProgressQueue = new MessageQueue<TaskProgressMessage>(false, _Connection);
     Warehouse = Mds.GetCollectionQueryModel<Warehouse>().FirstOrDefault();
 }
示例#23
0
            public static MessageQueue[] CreateGroup(int count)
            {
                Ensure.Positive(count, "count");

                MessageQueue[] queues = new MessageQueue[count];
                for (int i = 0; i < count; i++) {
                    queues[i] = new MessageQueue(i);
                }

                return queues;
            }
 public override Dictionary<string, string> handle(MessageQueue.Message message)
 {
     Console.WriteLine("ExampleHandler2 handling message {0}: {1}",
     message.CorrelationId, message.Body);
     Random rnd = new Random();
     Thread.Sleep(rnd.Next(0, 5));
     Console.WriteLine("Return");
     Dictionary<string,string> response = new Dictionary<string, string>();
     response.Add("message", String.Format("This is an Altitude Handler  response to message {0}",
         message.CorrelationId));
     return response;
 }
示例#25
0
 public ShowModalDialogPsMessage(string url, string width, string height, Hashtable handleParams)
 {
     messageQueue = new MessageQueue();
     if (JobContext.IsJob)
     {
         jobHandle = JobContext.JobHandle;
     }
     Width = width ?? string.Empty;
     Height = height ?? string.Empty;
     HandleParams = handleParams;
     Url = url;
 }
示例#26
0
 public Message(MessageQueue mq)
 {
     string text= "";
     for (int i = 0; i < mq.ReturnList().Count; i++)
     {
         if(mq.ReturnList()[i] == null)
         {
             text = text + "," + mq.ReturnList()[i];
         }
     }
     this.Msg = text;
 }
示例#27
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();

        InitConnection ();
        _TaskQueue = new MessageQueue<TaskMessage> (false, _Connection);
        _LogQueue = new MessageQueue<TaskLogMessage> (true, _Connection);
        _ProgressQueue = new MessageQueue<TaskProgressMessage> (true, _Connection);
        _LogQueue.OnReceivedMessage += _Log_OnReceivedMessage;
        _ProgressQueue.OnReceivedMessage += _ProgressQueue_OnReceivedMessage;
    }
示例#28
0
 public async Task Invoke(IDictionary<string, object> environment)
 {
     using (Stream memoryStream = await RequestAsStream(environment))
     using (MessageQueue queue = new MessageQueue(queuePath))
     using (Message message = new Message())
     {
         message.BodyStream = memoryStream;
         IDictionary<string, string[]> requestHeaders = (IDictionary<string, string[]>) environment["owin.RequestHeaders"];
         string messageType = requestHeaders["MessageType"].Single();
         message.Extension = MsmqHeaderSerializer.CreateHeaders(messageType);
         queue.Send(message, MessageQueueTransactionType.Single);
     }
 }
示例#29
0
        public static void StartLogging()
        {
            Contexts.Add(RootContext);
            _messageQueue = new MessageQueue();
            _udpListener = new UdpListener();
            _udpListener.Start(_messageQueue);

            _tickTimer = new DispatcherTimer {Interval = UpdatePeriod};
            _tickTimer.Tick += tickTimer_Tick;
            _tickTimer.Start();

            Running = true;
            AddLoggerEvent("Log capture started");
        }
示例#30
0
        public RecordReader(string filename)
        {
            fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

            var schema = new MessageSchema();
            schema.Register(MessageIds.Metadata, MetadataMsg.GetRootAsMetadata);
            schema.Register(MessageIds.BodyFrameData, BodyFrameDataMsg.GetRootAsBodyFrameData);

            messages = new MessageQueue(schema);

            metadata = ReadNextMessage() as Metadata;
            if (metadata == null)
                throw new InvalidDataException(Resources.IllegalRecordDataFormat);
        }
示例#31
0
        public void MonitorService(CancellationToken token)
        {
            using (var serverQueue = new MessageQueue(MonitorQueueName))
            {
                serverQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(Settings) });

                while (!token.IsCancellationRequested)
                {
                    var asyncReceive = serverQueue.BeginPeek();

                    if (WaitHandle.WaitAny(new WaitHandle[] { stopWaitEvent, asyncReceive.AsyncWaitHandle }) == 0)
                    {
                        break;
                    }

                    var message = serverQueue.EndPeek(asyncReceive);
                    serverQueue.Receive();
                    var settings = (Settings)message.Body;
                    lastTimeout = settings.Timeout;
                    WriteSettings(settings);
                }
            }
        }
示例#32
0
        public void MonitorService(CancellationToken token)
        {
            using (MessageQueue serverQueue = new MessageQueue(Queues.Monitor))
            {
                serverQueue.Formatter = new XmlMessageFormatter(new[] { typeof(Config) });

                while (!token.IsCancellationRequested)
                {
                    var asyncReceive = serverQueue.BeginPeek();

                    if (WaitHandle.WaitAny(new[] { _stopWaitEvent, asyncReceive.AsyncWaitHandle }) == 0)
                    {
                        break;
                    }

                    var message = serverQueue.EndPeek(asyncReceive);
                    serverQueue.Receive();
                    var config = (Config)message.Body;
                    _lastTimeout = config.Timeout;
                    WriteConfigs(config);
                }
            }
        }
示例#33
0
        static void ReadMessages()
        {
            using (var messageQueue = new MessageQueue(QueuePath))
            {
                var messages = messageQueue.GetAllMessages();

                foreach (var message in messages)
                {
                    message.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                    Console.WriteLine($"\n -- Received Message: {message.Body}");
                }

                messageQueue.Purge();

                Console.WriteLine("Press R to Refresh");
                var response = Console.ReadKey();

                if (response.KeyChar.ToString().ToUpper() == "R")
                {
                    ReadMessages();
                }
            }
        }
示例#34
0
        public void NotExistedQueueCreatingTest()
        {
            router = new Router();

            if (MessageQueue.Exists(PathTaskQueue))
            {
                MessageQueue.Delete(PathTaskQueue);
            }
            if (MessageQueue.Exists(PathClientAnswerQueue))
            {
                MessageQueue.Delete(PathClientAnswerQueue);
            }
            if (MessageQueue.Exists(PathServiceQueue))
            {
                MessageQueue.Delete(PathServiceQueue);
            }
            if (MessageQueue.Exists(PathConfirmationQueue))
            {
                MessageQueue.Delete(PathConfirmationQueue);
            }

            router.QueueCreate(PathTaskQueue, PathClientAnswerQueue, PathServiceQueue, PathConfirmationQueue);
        }
示例#35
0
        private void Create()
        {
            try
            {
                String qname    = getLine("\nName of Queue to create? ");
                String hostname = getLine("\nName of Queue Server (ENTER for local)? ", false);
                //String fullname= getQueueFullName(hostname,qname);
                if ((hostname == null) || (hostname == ""))
                {
                    hostname = ".";
                }

                String fullname = hostname + "\\private$\\" + qname;
                Console.WriteLine("create ({0})", fullname);
                myQueue           = MessageQueue.Create(fullname);
                myQueue.Formatter = new StringMessageFormatter();
                Console.WriteLine("Create: OK.");
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Queue creation failure: {0}", ex1.Message);
            }
        }
示例#36
0
        //**************************************************
        // Sends an image to a queue, using the BinaryMessageFormatter.
        //**************************************************

        public void SendMessage()
        {
            try{
                // Create a new bitmap.
                // The file must be in the \bin\debug or \bin\retail folder, or
                // you must give a full path to its location.
                Image myImage = Bitmap.FromFile("SentImage.bmp");

                // Connect to a queue on the local computer.
                MessageQueue myQueue = new MessageQueue(".\\myQueue");

                Message myMessage = new Message(myImage, new BinaryMessageFormatter());

                // Send the image to the queue.
                myQueue.Send(myMessage);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            return;
        }
示例#37
0
    public void ReceiveById_StringTimespanTransactiontype()
    {
        // <snippet19>

        // Connect to a transactional queue on the local computer.
        MessageQueue queue = new MessageQueue(".\\exampleTransQueue");

        // Create a new message.
        Message msg = new Message("Example Message Body");

        // Send the message.
        queue.Send(msg, "Example Message Label",
                   MessageQueueTransactionType.Single);

        // Get the message's Id property value.
        string id = msg.Id;

        // Receive the message from the queue.
        msg = queue.ReceiveById(id, TimeSpan.FromSeconds(10.0),
                                MessageQueueTransactionType.Single);

        // </snippet19>
    }
示例#38
0
        void ResolveMessageQueue(double curTime)
        {
            // show notification from threads
            if (curTime - MessageQueue.latestDequeueTime > MessageQueue.DEQUEUE_INTERVAL)
            {
                UcbNotificationMessage msg = MessageQueue.Dequeue();
                if (msg != null)
                {
                    switch (msg.type)
                    {
                    case UcbNotificationMessageTypes.Info:
                        ShowNotification(new GUIContent(msg.content));
                        break;

                    case UcbNotificationMessageTypes.Error:
                        EditorUtility.DisplayDialog("Error", msg.content, "OK");
                        break;
                    }
                }

                MessageQueue.latestDequeueTime = curTime;
            }
        }
示例#39
0
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Messaging.MessagingService)))
            {
                string queueName = ".\\private$\\MessagingServiceQueue";
                if (!MessageQueue.Exists(queueName))
                {
                    MessageQueue.Create(queueName, true);
                }

                string dlqName = ".\\private$\\MessagingServiceDLQ";
                if (!MessageQueue.Exists(dlqName))
                {
                    MessageQueue.Create(dlqName, true);
                }

                host.Open();

                Console.WriteLine();
                Console.WriteLine("Press <ENTER> to terminate the host application");
                Console.ReadLine();
            }
        }
        //**************************************************
        // Associates selected message property values
        // with high priority messages.
        //**************************************************

        public void SendHighPriorityMessages()
        {
            // Connect to a message queue.
            MessageQueue myQueue = new
                                   MessageQueue(".\\myQueue");

            // Associate selected default property values with high
            // priority messages.
            myQueue.DefaultPropertiesToSend.Priority =
                MessagePriority.High;
            myQueue.DefaultPropertiesToSend.Label =
                "High Priority Message";
            myQueue.DefaultPropertiesToSend.Recoverable      = true;
            myQueue.DefaultPropertiesToSend.TimeToReachQueue =
                new TimeSpan(0, 0, 30);

            // Send messages using these defaults.
            myQueue.Send("High priority message data 1.");
            myQueue.Send("High priority message data 2.");
            myQueue.Send("High priority message data 3.");

            return;
        }
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     texboxConteudo.Text = string.Empty;
     if (textBoxNomeFila.Text != "")
     {
         if (MessageQueue.Exists($".\\Private$\\{textBoxNomeFila.Text}"))
         {
             MessageQueue msgQ = new MessageQueue($".\\Private$\\{textBoxNomeFila.Text}");
             msgQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
             var mensagem = "-----Todos títulos---- \r\n";
             foreach (var msgs in msgQ.GetAllMessages())
             {
                 mensagem += msgs.Label + "\r\n";
             }
             mensagem           += "-----fim de títulos----";
             texboxConteudo.Text = mensagem;
         }
         else
         {
             MessageBox.Show("A fila informada não existe");
         }
     }
 }
示例#42
0
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <typeparam name="T">用户的数据类型</typeparam>
        /// <param name="queuePath">消息路径</param>
        /// <returns>用户填充在消息当中的数据</returns>
        public static T ReceiveMessage <T>(string queuePath, MessageQueueTransaction tran = null)
        {
            //连接到本地队列
            MessageQueue myQueue = new MessageQueue(queuePath);

            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(T) });
            try
            {
                //从队列中接收消息
                System.Messaging.Message myMessage = tran == null?myQueue.Receive() : myQueue.Receive(tran);

                return((T)myMessage.Body); //获取消息的内容
            }
            catch (MessageQueueException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (InvalidCastException e)
            {
                Console.WriteLine(e.Message);
            }
            return(default(T));
        }
示例#43
0
        public bool OpenQueue()
        {
            try
            {
                if (MessageQueue.Exists(_name))
                {
                    queue = new MessageQueue(_name);
                }
                else
                {
                    queue = MessageQueue.Create(_name);
                }

                queue.SetPermissions(GetUsersGroupLocalizedName(), MessageQueueAccessRights.FullControl);
                queue.Formatter = new BinaryMessageFormatter();
                return(true);
            }
            catch (Exception e)
            {
                queue = null;
                return(false);
            }
        }
示例#44
0
        public void ChangePrix()
        {
            int pad = 0;

            int.TryParse(PAD_TEXT, out pad);
            if (CurrentTicket != null && pad > 0)
            {
                OK_ACTION = OK_ACTIONS.PRIX;
                BTN_SAVE();
                return;
            }


            MessageQueue.Enqueue("Tapez Prix de vente...");
            PAD_TEXT = "";

            OK_ACTION = OK_ACTIONS.PRIX;
            NotifyOfPropertyChange("PAD_TEXT");
            NotifyOfPropertyChange("OkStatus");

            NotifyOfPropertyChange("CmdStatus");
            NotifyOfPropertyChange("CmdColor");
        }
示例#45
0
        void ReinitializeInputQueue()
        {
            if (_inputQueue != null)
            {
                try
                {
                    _inputQueue.Close();
                    _inputQueue.Dispose();
                }
                catch (Exception exception)
                {
                    _log.Warn("An error occurred when closing/disposing the queue handle for '{0}': {1}", _inputQueueName, exception);
                }
                finally
                {
                    _inputQueue = null;
                }
            }

            GetInputQueue();

            _log.Info("Input queue handle successfully reinitialized");
        }
        public void Should_not_warn_if_queue_has_public_access_set_to_deny(MessageQueueAccessRights accessRights)
        {
            // Set up a queue with the specified access for everyone/anonymous explicitly set to DENY.
            var everyoneGroupName  = new SecurityIdentifier(WellKnownSidType.WorldSid, null).Translate(typeof(NTAccount)).ToString();
            var anonymousGroupName = new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).ToString();

            using (var queue = MessageQueue.Create(@".\private$\" + testQueueName, false))
            {
                queue.SetPermissions(everyoneGroupName, accessRights, AccessControlEntryType.Deny);
                queue.SetPermissions(anonymousGroupName, accessRights, AccessControlEntryType.Deny);
            }

            QueuePermissions.CheckQueue(testQueueName);
            Assert.IsFalse(logOutput.ToString().Contains("Consider setting appropriate permissions"));

            // Resetting the queue permission to delete the queue to enable the cleanup of the unit test
            var path = @".\private$\" + testQueueName;

            using (var queueToModify = new MessageQueue(path))
            {
                queueToModify.SetPermissions(everyoneGroupName, MessageQueueAccessRights.DeleteQueue, AccessControlEntryType.Allow);
            }
        }
示例#47
0
        private void OnTcpClientDisconnected(Guid oldConnectionID)
        {
            if (oldConnectionID == ConnectionId)
            {
                var itemsToSend = MessageQueue.ToList();

                ActiveConnection = null;
                if (!IsOnline)
                {
                    return;
                }
                IsOnline = false;
                OnDisconnected?.Invoke(this);

                if (_pushNotificationSender != null)
                {
                    foreach (var item in itemsToSend)
                    {
                        _pushNotificationSender.SendNotification(item.SerializedMessage);
                    }
                }
            }
        }
示例#48
0
文件: MsmqUtil.cs 项目: silijon/Rebus
        /// <summary>
        /// Verifies that the queue with the given <paramref name="path"/> is transaction. If that is not the case, a <see cref="RebusApplicationException"/>
        /// is thrown with an explanation of the problem
        /// </summary>
        public static void EnsureMessageQueueIsTransactional(string path)
        {
            using (var queue = new MessageQueue(path))
            {
                if (queue.Transactional)
                {
                    return;
                }

                var message =
                    string.Format(
                        @"The queue {0} is NOT transactional!

Everything around Rebus is built with the assumption that queues are transactional, so Rebus will malfunction if queues aren't transactional. 

To remedy this, ensure that any existing queues are transactional, or let Rebus create its queues automatically.

If Rebus allowed you to work with non-transactional queues, it would not be able to e.g. safely move a received message into an error queue. Also, MSMQ does not behave well when moving messages in/out of transactional/non-transactional queue.",
                        path);

                throw new RebusApplicationException(message);
            }
        }
        public static IGlobalConfiguration <SqlServerStorage> UseMsmq(this IGlobalConfiguration <SqlServerStorage> configuration, string pathPattern, params string[] queues)
        {
            if (string.IsNullOrEmpty(pathPattern))
            {
                throw new ArgumentNullException(nameof(pathPattern));
            }
            if (queues == null)
            {
                throw new ArgumentNullException(nameof(queues));
            }

            foreach (var queueName in queues)
            {
                var path = string.Format(pathPattern, queueName);

                if (!MessageQueue.Exists(path))
                {
                    using (var queue = MessageQueue.Create(path, transactional: true))
                        queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
                }
            }
            return(configuration.UseMsmqQueues(pathPattern, queues));
        }
示例#50
0
        /// <summary>
        /// Send Method For Sending Data into MSMQ.
        /// </summary>
        /// <param name="input"></param>
        public void Send(string input)
        {
            MessageQueue messageQ;

            //If Queue Does not Exists it will create a Queue in MSMQ.
            if (MessageQueue.Exists(@".\Private$\messageq"))
            {
                messageQ = new MessageQueue(@".\Private$\messageq");
            }
            else
            {
                messageQ = MessageQueue.Create(@".\Private$\messageq");
            }

            //Creating Message and Sending it to MSMQ.
            Message message = new Message();

            message.Formatter = new BinaryMessageFormatter();
            message.Body      = input;
            message.Label     = "Registration";
            message.Priority  = MessagePriority.Normal;
            messageQ.Send(message);
        }
示例#51
0
        static void Main(string[] args)
        {
            if (!MessageQueue.Exists(QUEUE_NAME))
            {
                MessageQueue.Create(QUEUE_NAME, true);
            }

            ServiceHost host = new ServiceHost(typeof(Service));

            LocalDatabase.Instance.open();
            host.Open();

            Console.WriteLine("Press ENTER to terminate the service host");
            Console.ReadLine();

            LocalDatabase.Instance.close();
            host.Close();

            if (MessageQueue.Exists(QUEUE_NAME))
            {
                MessageQueue.Delete(QUEUE_NAME);
            }
        }
示例#52
0
    // Demonstrates:
    // public Int32 Add (MessageQueuePermissionEntry value)
    public void AddExample()
    {
        // Connect to a queue on the local computer.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // Create a new instance of MessageQueuePermission.
        MessageQueuePermission permission = new MessageQueuePermission();

        // Get an instance of MessageQueuePermissionEntryCollection from the
        // permission's PermissionEntries property.
        MessageQueuePermissionEntryCollection collection =
            permission.PermissionEntries;

        // Create a new instance of MessageQueuePermissionEntry.
        MessageQueuePermissionEntry entry = new MessageQueuePermissionEntry(
            MessageQueuePermissionAccess.Receive,
            queue.MachineName,
            queue.Label,
            queue.Category.ToString());

        // Add the entry to the collection.
        collection.Add(entry);
    }
示例#53
0
        /// <summary>
        /// 记录请求信息
        /// </summary>
        /// <param name="requestMessage">请求信息</param>
        public void InsertMessage(TRest requestMessage)
        {
            lock (WeixinContextGlobal.Lock)
            {
                var userName       = requestMessage.FromUserName;
                var messageContext = GetMessageContext(userName, true);
                if (messageContext.RequestMessages.Count > 0)
                {
                    //如果不是新建的对象,把当前对象移到队列尾部(新对象已经在底部)
                    var messageContextInQueue =
                        MessageQueue.FindIndex(z => z.UserName == userName);

                    if (messageContextInQueue >= 0)
                    {
                        MessageQueue.RemoveAt(messageContextInQueue); //移除当前对象
                        MessageQueue.Add(messageContext);             //插入到末尾
                    }
                }

                messageContext.LastActiveTime = DateTime.Now;       //记录请求时间
                messageContext.RequestMessages.Add(requestMessage); //录入消息
            }
        }
示例#54
0
        /// <summary>
        /// Create a sender bus
        /// </summary>
        /// <returns></returns>
        private static ISendOnlyBus CreateBus()
        {
            /// initialize a new configuration
            var configuration = new BusConfiguration();

            /// set the transport mechanism
            configuration.UseTransport <MsmqTransport>();
            /// set the persistence mechanism
            configuration.UsePersistence <InMemoryPersistence>();

            /*
             *  Standalone process MUST manually configure MSMQ
             */
            if (!MessageQueue.Exists(@".\private$\MvcSubscriber"))
            {
                MessageQueue.Create(@".\private$\MvcSubscriber", true);
            }

            /// create a new bus instance (disposable)
            var bus = Bus.CreateSendOnly(configuration);

            return(bus);
        }
        //***************************************************
        // Provides an event handler for the ReceiveCompleted
        // event.
        //***************************************************

        private static void MyReceiveCompleted(Object source,
                                               ReceiveCompletedEventArgs asyncResult)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)source;

                // End the asynchronous receive operation.
                Message m = mq.EndReceive(asyncResult.AsyncResult);

                // Process the message here.
                Console.WriteLine("Message received.");
            }
            catch (MessageQueueException)
            {
                // Handle sources of MessageQueueException.
            }

            // Handle other exceptions.

            return;
        }
示例#56
0
        /// <summary>
        /// Disposes the input queue instance
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            try
            {
                if (disposing)
                {
                    if (_inputQueue != null)
                    {
                        _inputQueue.Dispose();
                        _inputQueue = null;
                    }
                }
            }
            finally
            {
                _disposed = true;
            }
        }
示例#57
0
文件: MSMQ.cs 项目: MyLobin/MyMvc
        /**/
        /// <summary>
        /// 连接消息队列并从队列中接收消息
        /// </summary>
        public static string ReceiveMessage()
        {
            //连接到本地队列
            MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue");

            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            try
            {
                //从队列中接收消息
                System.Messaging.Message myMessage = myQueue.Receive();
                string book = (string)myMessage.Body; //获取消息的内容
                return(book);
            }
            catch (MessageQueueException e)
            {
                Msg = e.Message;
            }
            catch (InvalidCastException e)
            {
                Msg = e.Message;
            }
            return(null);
        }
示例#58
0
        /*
         * FUNCTION : Process
         *
         * DESCRIPTION : This function receives message from the listener and call the ProcessMessage function to process the message
         *
         * PARAMETERS : List<Client> clientList: list of client
         *              MyMessage message: received message
         *
         * RETURNS : NONE
         */
        private static void Process(List <Client> clientList)
        {
            bool done = false;
            // Create message queue between Listener and Processor
            MessageQueue msgQueue_Processor = MyMessage.createMessageQueue("Processor");

            while (!done)
            {
                // Receive message from listener
                MyMessage message = (MyMessage)(msgQueue_Processor.Receive().Body);
                Console.WriteLine("PROCESSOR - Received message: " + message.From + ", " + message.Action + ", " + message.To); // logging

                // Process message
                ProcessMessage(message, clientList);

                // Delete the message queue and exit the loop if the server is shutting down
                if (message.Action == Actions.SERVER_SHUTDOWN)
                {
                    MessageQueue.Delete(@".\Private$\Processor");
                    done = true;
                }
            }
        }
示例#59
0
    static void Main()
    {
        Console.Title = "Samples.MsmqToSqlRelay.NativeMsmqToSql";
        #region receive-from-msmq-using-native-messaging
        // The address of the queue that will be receiving messages from other MSMQ publishers
        string queuePath = @".\private$\MsmqToSqlRelay";

        //Create message queue object
        MessageQueue addressOfMsmqBridge = new MessageQueue(queuePath, QueueAccessMode.SendAndReceive);
        // for the sample's sake. Might need to fine tune the exact filters required.
        addressOfMsmqBridge.MessageReadPropertyFilter.SetAll();

        // Add an event handler for the ReceiveCompleted event.
        addressOfMsmqBridge.ReceiveCompleted += MsmqBridgeOnReceiveCompleted;

        // Begin the asynchronous receive operation.
        addressOfMsmqBridge.BeginReceive();
        #endregion

        Console.WriteLine("Watching MSMQ: {0} for messages. Received messages will be sent to the SqlRelay", queuePath);
        Console.WriteLine("Press any key to quit.");
        ConsoleKeyInfo key = Console.ReadKey();
    }
示例#60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueReader"/> class.
        /// </summary>
        /// <param name="queueName">Name of the message queue.</param>
        /// <param name="receiver">The implementation of this interface will be invoked for each received log entry.</param>
        public QueueReader(string queueName, ILogReceiver receiver)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }
            _queueName = queueName;
            _receiver  = receiver;

            if (!MessageQueue.Exists(queueName))
            {
                throw new ArgumentOutOfRangeException("queueName", queueName, "Queue do not exist.");
            }

            _queue = new MessageQueue(_queueName);
            _queue.ReceiveCompleted += OnReceived;
            _queue.Formatter         = new XmlMessageFormatter(new[] { typeof(LogEntryDTO) });
            _queue.BeginReceive();
        }