Ejemplo n.º 1
0
        public void Errors()
        {
            // Get a connection string to our Azure Storage account
            string connectionString = ConnectionString;

            // Get a reference to a queue named "sample-queue" and then create it
            QueueClient queue = new QueueClient(connectionString, Randomize("sample-queue"));

            queue.Create();

            try
            {
                // Try to create the queue again
                queue.Create();
            }
            catch (StorageRequestFailedException ex)
                when(ex.ErrorCode == QueueErrorCode.QueueAlreadyExists)
                {
                    // Ignore any errors if the queue already exists
                }
            catch (StorageRequestFailedException ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }

            // Clean up after the test when we're finished
            queue.Delete();
        }
Ejemplo n.º 2
0
        private void SendPdfDocument(object sender, EventArgs e)
        {
            QueueClient client = null;

            byte[] pdf = null;
            try
            {
                pdf = this.pdfCreator.GetPdf(this.outDir);

                this.ClearPdfCreatorFilePathes();
                this.pdfCreator.Reset();

                client = QueueClient.Create(DocQueueName);
                client.Send(new BrokeredMessage(pdf));
            }
            catch (MessageSizeExceededException ex)
            {
                this.StartToProcessChunkDoc(pdf, client);

                Console.WriteLine(ex.Message);                 ////log
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                client.Close();
            }
        }
Ejemplo n.º 3
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                try
                {
                    var queueClient = QueueClient.Create(_queueName);
                    var message     = await queueClient.GetMessageAsync();

                    if (message != null)
                    {
                        string response;

                        response = await RunSproAsync(message.SessionType, message.UserName);

                        //response = $"ANSWER FOR {message.MessageId} : {message.UserName}   {message.SessionType}";
                        var resultClient = ResultClient.Create();
                        await resultClient.Set(message.MessageId, response).ConfigureAwait(false);
                    }
                    else
                    {
                        await Task.Delay(1000);
                    }
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.ServiceMessage(this.Context, "EXCEPTION : " + ex.ToString());
                    await Task.Delay(250);
                }
            }
        }
Ejemplo n.º 4
0
        public void AddMessageToQueue(string fileName)
        {
            QueueClient     client = QueueClient.Create("uploadqueue");
            BrokeredMessage msg    = new BrokeredMessage(JsonConvert.SerializeObject(fileName));

            client.Send(msg);
        }
Ejemplo n.º 5
0
        public void Export(IOrderedEnumerable <IFile> files)
        {
            using (var pdfStream = GeneratePdf(files))
            {
                var queueClient = QueueClient.Create(QueueName);
                var messageName = new NameParser(Path.GetFileName(files.First().FullName)).Prefix;
                var byteChunks  = SplitMemoryStream(pdfStream);

                var index        = 0;
                var partitionKey = Guid.NewGuid().ToString();
                using (var transaction = new TransactionScope())
                {
                    foreach (var byteChunk in byteChunks)
                    {
                        var message = new BrokeredMessage(byteChunk)
                        {
                            Label        = messageName,
                            PartitionKey = partitionKey, // for transaction purposes
                            Properties   =
                            {
                                { "Size",     byteChunks.Count },
                                { "Position", index            }
                            }
                        };
                        queueClient.Send(message);
                        index++;
                    }
                    transaction.Complete();
                }
                queueClient.Close();
            }
        }
Ejemplo n.º 6
0
        private void ReceiveFileFromServiceBus()
        {
            var client = QueueClient.Create(_fileQueueName, ReceiveMode.ReceiveAndDelete);

            while (true)
            {
                var firstmessage = client.Receive();
                if (firstmessage != null)
                {
                    var partCount      = (long)firstmessage.Properties["PartCount"];
                    var partNumber     = (int)firstmessage.Properties["Part"];
                    var sequenceNumber = (int)firstmessage.Properties["Sequence"];
                    var bytes          = new List <byte>();
                    bytes.AddRange(firstmessage.GetBody <byte[]>());
                    while (partNumber < partCount)
                    {
                        var b = client.Receive();
                        bytes.AddRange(b.GetBody <byte[]>());
                        partNumber = (int)b.Properties["Part"];
                    }

                    File.WriteAllBytes(Path.Combine(_saveFilePath, @"AzureDocument" + sequenceNumber + ".pdf"), bytes.ToArray());
                }
            }
        }
Ejemplo n.º 7
0
        private void TimerCallBackMethod(object obj)
        {
            try
            {
                string queueName = ConfigurationManager.AppSettings["centralQueue"];

                var client = QueueClient.Create(queueName);
                var state  = new StateModelData()
                {
                    Status          = this.status,
                    CurrentSettings = new Settings()
                    {
                        Timeout      = int.Parse(ConfigurationManager.AppSettings["timeout"]),
                        BarcodeValue = this.barcodeSeparator
                    }
                };

                client.Send(new BrokeredMessage(state));
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 8
0
        // Process a local file, send it to the queue and move the file
        private static void ProcessLocalFile(FileInfo fileInfo)
        {
            try
            {
                var queueClient = QueueClient.Create(queueName);

                var fileContents = File.ReadAllBytes(fileInfo.FullName, );
                if (fileContents.Length == 0)
                {
                    throw new Exception("File is empty");
                }

                var message = new BrokeredMessage(fileContents);
                message.Properties.Add("FileName", fileInfo.Name);

                queueClient.Send(message);

                File.Move(fileInfo.FullName, sentFolder + "\\" + fileInfo.Name);

                Console.WriteLine("Processed file " + fileInfo.Name);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                File.Move(fileInfo.FullName, errorFolder + "\\" + fileInfo.Name);
            }
        }
        /// <summary>
        /// Create a queue and send a message.
        /// </summary>
        /// <param name="connectionString">
        /// A connection string to your Azure Storage account.
        /// </param>
        /// <param name="queueName">
        /// The name of the queue to create and send a message to.
        /// </param>
        public static void SendMessage(string connectionString, string queueName)
        {
            #region Snippet:Azure_Storage_Queues_Samples_Sample01a_HelloWorld_SendMessage
            // We'll need a connection string to your Azure Storage account.
            // You can obtain your connection string from the Azure Portal
            // (click Access Keys under Settings in the Portal Storage account
            // blade) or using the Azure CLI with:
            //
            //     az storage account show-connection-string --name <account_name> --resource-group <resource_group>
            //
            // You would normally provide the connection string to your
            // application using an environment variable.
            //@@ string connectionString = "<connection_string>";

            // Name of the queue we'll send messages to
            //@@ string queueName = "sample-queue";

            // Get a reference to a queue and then create it
            QueueClient queue = new QueueClient(connectionString, queueName);
            queue.Create();

            // Send a message to our queue
            queue.SendMessage("Hello, Azure!");
            #endregion Snippet:Azure_Storage_Queues_Samples_Sample01a_HelloWorld_SendMessage
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.Title = "Sender";

            // Create the queue if it does not exist already
            string connectionString =
                ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists("servicebusqueue"))
            {
                namespaceManager.CreateQueue("servicebusqueue");
            }

            // Create Queue Client
            QueueClient queueClient = QueueClient.Create("servicebusqueue");

            Console.WriteLine("Enter text to send to the queue and press Enter.");

            string message = string.Empty;

            while ((message = Console.ReadLine()) != string.Empty)
            {
                // Create and Send Message to Queue
                var brokeredMessage = new BrokeredMessage(message);
                queueClient.Send(brokeredMessage);
            }
        }
Ejemplo n.º 11
0
        // Receive messages from the queue
        private static void Receive()
        {
            Console.WriteLine("------------- RECEIVE MESSAGE FROM QUEUE ------------------");
            var queueClient = QueueClient.Create(queueName, ReceiveMode.ReceiveAndDelete);

            while (true)
            {
                try
                {
                    var message = queueClient.Receive(TimeSpan.FromSeconds(10));

                    if (message == null)
                    {
                        Console.WriteLine("No message found");
                        continue;
                    }

                    ProcessMessage(message);
                }
                catch (TimeoutException)
                {
                    Console.WriteLine("No message found");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
        }
Ejemplo n.º 12
0
        public void SendMethod1()
        {
            var client = QueueClient.Create("customqueue");

            client.Send(new BrokeredMessage("Hello World!!!"));
            client.Close();
        }
Ejemplo n.º 13
0
        public void Enqueue()
        {
            // Get a connection string to our Azure Storage account.  You can
            // obtain your connection string from the Azure Portal (click
            // Access Keys under Settings in the Portal Storage account blade)
            // or using the Azure CLI with:
            //
            //     az storage account show-connection-string --name <account_name> --resource-group <resource_group>
            //
            // And you can provide the connection string to your application
            // using an environment variable.
            string connectionString = ConnectionString;

            // Get a reference to a queue named "sample-queue" and then create it
            QueueClient queue = new QueueClient(connectionString, Randomize("sample-queue"));

            queue.Create();
            try
            {
                // Add a message to our queue
                queue.EnqueueMessage("Hello, Azure!");

                // Verify we uploaded one message
                Assert.AreEqual(1, queue.PeekMessages(10).Value.Count());
            }
            finally
            {
                // Clean up after the test when we're finished
                queue.Delete();
            }
        }
Ejemplo n.º 14
0
        public void Connect(string queueName)
        {
            var namespaceManager = NamespaceManager.Create();
            var queueDesc        = namespaceManager.QueueExists(queueName) ? namespaceManager.GetQueue(queueName) : namespaceManager.CreateQueue(queueName);

            _queueClient = QueueClient.Create(queueDesc.Path);
        }
Ejemplo n.º 15
0
        public UserQueue(IOptions <UserQueueOptions> options)
        {
            var connectionString = options.Value.ConnectionString;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentException($"{nameof(connectionString)}");
            }

            var inQueueName = options.Value.InQueueName;

            if (string.IsNullOrWhiteSpace(inQueueName))
            {
                throw new ArgumentException($"{nameof(inQueueName)}");
            }

            var outQueueName = options.Value.OutQueueName;

            if (string.IsNullOrWhiteSpace(outQueueName))
            {
                throw new ArgumentException($"{nameof(outQueueName)}");
            }

            _inQueueClient = new QueueClient(connectionString, inQueueName);
            _inQueueClient.Create();

            _outQueueClient = new QueueClient(connectionString, outQueueName);
            _outQueueClient.Create();
        }
Ejemplo n.º 16
0
        // Send messages from the local file system to the remote queue
        private static void Send()
        {
            Console.WriteLine("------------- SEND FILES TO QUEUE ------------------");
            while (true)
            {
                try {
                    var directoryInfo = new DirectoryInfo(newFolder);
                    var fileInfos     = directoryInfo.GetFiles();
                    if (fileInfos.Length == 0)
                    {
                        Console.WriteLine("No files found");
                        continue;
                    }

                    var queueClient = QueueClient.Create(queueName);
                    foreach (var fileInfo in fileInfos)
                    {
                        ProcessLocalFile(fileInfo);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
                finally
                {
                    Thread.Sleep(5000);
                }
            }
        }
Ejemplo n.º 17
0
        public void EnQueue(Message message)
        {
            try
            {
                Logger.Current.Informational("Recieved messaage. " + message.ToString());
                CreateQueueIfNotExists();
                QueueClient     queueClient       = QueueClient.Create(queueName);
                var             serializedMessage = JsonConvert.SerializeObject(message);
                BrokeredMessage brokeredMessage   = new BrokeredMessage(serializedMessage);

                Logger.Current.Informational("Sending messaage. ");
                queueClient.Send(brokeredMessage);

                Logger.Current.Informational("Message sent successfully. ");
            }
            catch (MessagingException ex)
            {
                if (!ex.IsTransient)
                {
                    Logger.Current.Error("Non-Transient error occurred while queing the message." + message.ToString());
                    throw;
                }
                else
                {
                    HandleTransientErrors(ex, message);
                }
            }
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            Console.Title = "Receiver";

            // Creating the topic if it does not exist already using the service bus connection string stored in the app.config file
            string connectionString =
                ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists("servicebusqueue"))
            {
                namespaceManager.CreateQueue("servicebusqueue");
            }


            QueueClient client = QueueClient.Create("servicebusqueue");

            while (true)
            {
                var message = client.Receive();
                if (message != null)
                {
                    try
                    {
                        Console.WriteLine(message.GetBody <string>());
                    }
                    finally
                    {
                        message.Complete();
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private static async Task AutoReading()
        {
            // another way to handle messages - using AutoReader

            var client = QueueClient.Create(connectionString, "MyQueue");
            var writer = client.CreateWriter();

            byte[][] batch =
            {
                new byte[] { 0x01, 0x02, 0x03 },
                new byte[] { 0x04, 0x05, 0x06 },
                new byte[] { 0x07, 0x08, 0x09 },
            };

            writer.WriteMany(batch);

            writer.Close();

            // reading
            var autoReader = client.CreateAutoReader("MySubscription");
            await autoReader.Start(Handler);

            await Task.Delay(1000);

            await autoReader.Stop();

            autoReader.Close();
        }
        private void sendQ_Click(object sender, EventArgs e)
        {
            var    sendingClient = QueueClient.Create(qNametxt.Text);
            object msgBody       = sendQueuetxt.Text;

            sendingClient.Send(new BrokeredMessage(msgBody));
            MessageBox.Show("Message Sent To: " + qNametxt.Text + " Queue");
        }
Ejemplo n.º 21
0
        private void MyInit()
        {
            // IniWithoutLuis();

            InitWithLuis();

            _queueClient = QueueClient.Create(QueueName);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            QueueClient     queueClient = QueueClient.Create("uploadqueue");
            BrokeredMessage message     = queueClient.Receive();
            var             msgText     = message?.GetBody <string>();
            string          fileName    = JsonConvert.DeserializeObject <string>(msgText);

            ProcessFileData.ProcessFile(fileName);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            // Note! Database must be configured for memory optimized tables before queue creation

            // creating queue
            var factory = new QueueFactory(connectionString);

            factory.DeleteQueue("MyQueue");
            factory.CreateQueue("MyQueue");

            // connecting to queue
            var client = QueueClient.Create(connectionString, "MyQueue");

            // creating subscription
            client.CreateSubscription("MySubscription");

            // creating writer
            var writer = client.CreateWriter();

            // writing message to queue
            byte[] message = { 0x01, 0x02, 0x03 };
            var    id      = writer.Write(message);

            // writing batch of messages to queue
            byte[][] batch =
            {
                new byte[] { 0x01, 0x02, 0x03 },
                new byte[] { 0x01, 0x02, 0x04 },
                new byte[] { 0x01, 0x02, 0x05 },
            };

            var ids = writer.WriteMany(batch, true);

            writer.Close();

            // creating reader for subscription
            var reader = client.CreateReader("MySubscription");

            // reading 1000 messages from subscription
            var messages = reader.Read(1000);

            // making massages completed after handling
            reader.Complete();

            reader.Close();

            // another way to handle messages - using AutoReader
            AutoReading().Wait();

            // deleting subscription
            client.DeleteSubscription("MySubscription");

            // deleting queue
            factory.DeleteQueue("MyQueue");

            Console.ReadKey();
        }
Ejemplo n.º 24
0
        private static void AddMessage(string msg, int?duration)
        {
            var queue = new QueueClient(ConnectionString, QueueName);

            queue.Create();
            var item = new QueueItem {
                Message = msg, Duration = duration ?? 5000
            };

            queue.SendMessage(GetMessageContent(item));
        }
Ejemplo n.º 25
0
        private void StartHandler()
        {
            var manager = NamespaceManager.Create();

            if (!manager.QueueExists(_ptQueue))
            {
                return;
            }
            _ptQueueClient = QueueClient.Create(_ptQueue);
            StartListening();
        }
Ejemplo n.º 26
0
        public void SendQueueTest()
        {
            var name          = "vadtest";
            var sendingClient = QueueClient.Create(name);

            object msgBody = RandomValue.String(3);

            sendingClient.Send(new BrokeredMessage(msgBody));

            Console.WriteLine("Message was sent");
        }
Ejemplo n.º 27
0
        public void SendReceiveTest()
        {
            var client = QueueClient.Create("files", ReceiveMode.ReceiveAndDelete);

            client.Send(new BrokeredMessage("Files"));

            var message = client.Receive();
            var s       = message.GetBody <string>();

            Console.WriteLine(s);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> Index(string sessionType, string username)
        {
            ViewData["Hostname"] = Environment.MachineName;

            var queueClient = QueueClient.Create("RequestQueue");
            var message     = new QueueMessage(sessionType, username);

            var response = await queueClient.PushAsync(message);

            ViewData["FormData"] = response.Item2.MessageId;
            return(View());
        }
Ejemplo n.º 29
0
 public Task SendMessages(IEnumerable <Event> events)
 {
     return(Task.Run(() =>
     {
         var client = QueueClient.Create(_connectionString, _queueName);
         using (var writer = client.CreateWriter())
         {
             var data = events.Select(x => x.ToByteArray());
             writer.WriteMany(data);
         }
     }));
 }
Ejemplo n.º 30
0
        public QueueWriter(string connectionString, string queueName)
        {
            ParmCheck.NotNullOrEmpty(nameof(connectionString), connectionString);
            ParmCheck.NotNullOrEmpty(nameof(queueName), queueName);

            _queueClient = new QueueClient(connectionString, queueName);

            if (_queueClient.Exists() == false)
            {
                _queueClient.Create();
            }
        }