예제 #1
0
        public async Task SendToDeviceAsync()
        {
            foreach (JObject jo in ja_messages)
            {
                JObject     jo_header              = (JObject)jo[RbFormatType.RbHeader];
                string      jo_TargetType          = (string)jo_header["TargetType"];
                string      jo_TargetDeviceGroupId = (string)jo_header["TargetDeviceGroupId"];
                string      jo_TargetDeviceId      = jo_header["TargetDeviceId"].ToString().ToLower();
                string      msg         = JsonConvert.SerializeObject(jo);
                QueueClient queueClient = new QueueClient(storageConnString, jo_TargetDeviceId);

                if (jo_TargetType == RbTargetType.Device)
                {
                    // Create the queue if it doesn't already exist
                    await queueClient.CreateIfNotExistsAsync();

                    await queueClient.SendMessageAsync(msg);
                }
                else
                {
                    DeviceGroup   dg         = new DeviceGroup(jo_TargetDeviceGroupId, sqlConnString);
                    List <string> deviceList = dg.GetDeviceGroupList();
                    foreach (string deviceId in deviceList)
                    {
                        // Create the queue if it doesn't already exist
                        await queueClient.CreateIfNotExistsAsync();

                        await queueClient.SendMessageAsync(msg);
                    }
                }
            }
        }
        private async Task ReceiveStringAsync(Action <string> action)
        {
            var queueClient = new QueueClient(_connectionString, _queueName, new QueueClientOptions
            {
                MessageEncoding = _messageEncoding,
            });

            await queueClient.CreateIfNotExistsAsync();

            while (true)
            {
                try
                {
                    var retrievedMessages = (await queueClient.ReceiveMessagesAsync()).Value;

                    if (retrievedMessages.Length > 0)
                    {
                        foreach (var retrievedMessage in retrievedMessages)
                        {
                            action(retrievedMessage.Body.ToString());
                            await queueClient.DeleteMessageAsync(retrievedMessage.MessageId, retrievedMessage.PopReceipt);
                        }
                    }
                    else
                    {
                        await Task.Delay(1000);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    await Task.Delay(1000);
                }
            }
        }
    private static async Task <QueueClient> GetCommandQueueAsync()
    {
        var connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");

        if (connectionString is not null)
        {
            try
            {
                var queue = new QueueClient(connectionString, CommandHandler.ProcessorQueue, new QueueClientOptions
                {
                    // By default messages received from the queue are expected to be Base64-encoded
                    // and are decoded before calling the function.
                    MessageEncoding = QueueMessageEncoding.Base64
                });

                await queue.CreateIfNotExistsAsync()
                .ConfigureAwait(false);

                return(queue);
            }
            catch
            {
                throw;
            }
        }

        return(null);
    }
예제 #4
0
        public async Task <QueueClient> CreateQueue(string queueName)
        {
            QueueClient queue = new QueueClient(StorageConnectionString, queueName);
            await queue.CreateIfNotExistsAsync();

            return(queue);
        }
예제 #5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  message     = req.Query["message"];
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            message = message ?? data?.message;

            var storageConnection = Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process);
            var queueClient       = new QueueClient(storageConnection, "myqueue-items");

            if (!await queueClient.ExistsAsync()) //check if exists explicitly to avoid 409 trace information in the logs.
            {
                await queueClient.CreateIfNotExistsAsync();
            }

            var base64String = GetUTF8String(message);

            var receipt = await queueClient.SendMessageAsync(base64String);

            return(new OkObjectResult($"Added a new message with id {receipt.Value.MessageId}"));
        }
예제 #6
0
        // Helper method for creating queueClient
        async Task <QueueClient> CreateQueueClient()
        {
            if (String.IsNullOrWhiteSpace(_connectionString) || String.IsNullOrWhiteSpace(_queueName))
            {
                throw new NullReferenceException("ConnectionString or Queue name is null. Remember to call Init() method, providing a connection string and queue name");
            }

            var queueClientOptions = new QueueClientOptions()
            {
                MessageEncoding = QueueMessageEncoding.Base64
            };

            // Instantiate a QueueClient which will be used to create and manipulate the queue
            QueueClient queueClient = new QueueClient(_connectionString, _queueName, queueClientOptions);

            var logMessagePrefix = $"Ensuring queue '{queueClient.Name}' exists. ";

            if (await queueClient.ExistsAsync())
            {
                _logger.LogTrace(logMessagePrefix + "Allready exists");
            }
            else
            {
                _logger.LogTrace(logMessagePrefix + "Did not exsist. Will create it");
            }

            // Create the queue if it doesn't already exist
            await queueClient.CreateIfNotExistsAsync();

            return(queueClient);
        }
예제 #7
0
        public async Task EnqueueAsync(
            EventWrapper item,
            CancellationToken cancellationToken)
        {
            try
            {
                await _queueClient.CreateIfNotExistsAsync(
                    cancellationToken :
                    cancellationToken);

                var message = JsonSerializer.Serialize(
                    item,
                    _jsonSerializerOptions);
                await _queueClient.SendMessageAsync(
                    message,
                    cancellationToken);
            }
            catch (RequestFailedException ex)
            {
                _logger.LogError(
                    ex,
                    "Failed to enqueue event");
                throw;
            }
        }
        public async Task <ValueModel <Message> > Enqueue <T>(T contract) where T : class
        {
            contract.ThrowIfNull(nameof(contract));

            var data = _serializer.SerializeToJson(contract);

            var message = new Message
            {
                Type = contract.GetType().Name,
                Data = data
            };

            var messageJson = _serializer.SerializeToJson(message);

            await _queueClient.CreateIfNotExistsAsync();

            if (await _queueClient.ExistsAsync())
            {
                await _queueClient.SendMessageAsync(messageJson);

                return(new ValueModel <Message>(message));
            }

            return(new ValueModel <Message>());
        }
예제 #9
0
        /// <summary>
        /// Send the given message to the specified queue
        /// </summary>
        /// <param name="connectionStringName">
        /// The name of the connection string to use to connect to the queue
        /// </param>
        /// <param name="queueName">
        /// The name of the queue to post the message to
        /// </param>
        /// <param name="messageToSend">
        /// The message to put on the queue
        /// </param>
        /// <remarks>
        /// If the queue does not exist it will be created
        /// </remarks>
        private async Task SendQueueMessage(string connectionStringName,
                                            string queueName,
                                            string messageToSend)
        {
            // get the connection string named...
            if (!string.IsNullOrWhiteSpace(connectionStringName))
            {
                // Get the connection string for the name
                // Create a connection to the cloud storage account to use
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true)
                .AddJsonFile("local.settings.json", true)
                .AddJsonFile("config.local.json", true)
                .AddJsonFile("config.json", true)
                .AddJsonFile("connectionstrings.json", true)
                .AddEnvironmentVariables();

                IConfigurationRoot config = builder.Build();

                string connectionString = config.GetConnectionString(connectionStringName);
                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    throw new NullReferenceException($"No connection string configured for {connectionStringName}");
                }

                QueueClient queueClient = new QueueClient(connectionString, queueName);

                // Create the queue if it does not exist
                await queueClient.CreateIfNotExistsAsync();

                // and send the message
                await queueClient.SendMessageAsync(messageToSend);
            }
        }
예제 #10
0
    static async Task Main()
    {
        var queueClient = new QueueClient("UseDevelopmentStorage=true", "native-integration-asq");

        await queueClient.CreateIfNotExistsAsync().ConfigureAwait(false);

        Console.WriteLine("Press Enter to send a native message.");
        Console.WriteLine("Press any other key to exit.");
        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            #region send-a-native-message

            var nativeMessage = new NativeMessage
            {
                Content = $"Hello from native sender @ {DateTimeOffset.Now}"
            };

            var serializedMessage = JsonConvert.SerializeObject(nativeMessage);

            await queueClient.SendMessageAsync(serializedMessage).ConfigureAwait(false);

            #endregion

            Console.WriteLine("Message sent");
        }
    }
        public async Task ProcessQueueMessage([QueueTrigger("tasks")] string message)
        {
            try
            {
                if (this.hub.State == ConnectionState.Disconnected)
                {
                    await this.hub.Start();
                }

                AzureTask task = JsonSerializer.Deserialize <AzureTask>(message);
                task.Duration = this.GetRandomNumber(5, 15);
                task.Status   = EnumStatus.Success;
                task.Finished = true;
                task.QRCode   = await this.CreateQRCode();

                string updatedTaskJson = JsonSerializer.Serialize(task);
                //Sending tasks to queue
                QueueClient queueClient = new QueueClient(this.config["AzureWebJobsStorage"], this.config["Queue:ResultQueueName"]);
                await queueClient.CreateIfNotExistsAsync();

                await queueClient.SendMessageAsync(updatedTaskJson);

                Console.WriteLine($"Task id:{task.Id} name:{task.Name} proccesed");

                await this.hubProxy.Invoke("BrodcastTask", updatedTaskJson);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public static async Task <bool> SafeCreateIfNotExistsAsync(this QueueClient queueClient, TimeSpan?timeout, CancellationToken cancellationToken = default)
        {
            Stopwatch sw = Stopwatch.StartNew();

            if (timeout == null)
            {
                timeout = TimeSpan.FromSeconds(41);                  // Assuming 40 seconds max time, and then some.
            }
            do
            {
                if (sw.Elapsed > timeout.Value)
                {
                    throw new TimeoutException("Table was not deleted within the timeout.");
                }

                try
                {
                    var response = await queueClient.CreateIfNotExistsAsync();

                    if (response.Status == 201)
                    {
                        return(true);
                    }
                }
                catch (StorageException e) when(IsAzureQueueBeingDeleted(e))
                {
                    // The table is currently being deleted. Try again until it works.
                    await Task.Delay(1000);
                }
            } while (true);
        }
예제 #13
0
        /// <inheritdoc/>
        public async Task CreateQueueIfNotExistsAsync(string queueName)
        {
            ThrowIfNotSpecified(queueName);

            QueueClient queueClient = CreateQueueClient(queueName);
            await queueClient.CreateIfNotExistsAsync();
        }
        public async Task <bool> Create(string queueName)
        {
            try
            {
                var queueClient = new QueueClient(Options.ConnectionString, queueName);
                await queueClient.CreateIfNotExistsAsync();

                if (await queueClient.ExistsAsync())
                {
                    WriteLine($"Queue created: '{queueClient.Name}'");
                    return(true);
                }
                else
                {
                    WriteLine($"Make sure the Azurite storage emulator running and try again.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                WriteLine($"Exception: {ex.Message}\n\n");
                WriteLine($"Make sure the Azurite storage emulator running and try again.");
                return(false);
            }
        }
예제 #15
0
        public async Task InsertNewStudent(StudentEntity student)
        {
            StudentEntity newStudent = new StudentEntity(student.Faculty, student.CNP);

            newStudent.FirstName   = student.FirstName;
            newStudent.LastName    = student.LastName;
            newStudent.CNP         = student.CNP;
            newStudent.Email       = student.Email;
            newStudent.PhoneNumber = student.PhoneNumber;
            newStudent.YearOfStudy = student.YearOfStudy;
            newStudent.Faculty     = student.Faculty;

            string jsonStudent = JsonConvert.SerializeObject(newStudent);

            byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(jsonStudent);
            string base64String   = System.Convert.ToBase64String(plainTextBytes);

            QueueClient queueClient = new QueueClient(
                _connectionString,
                "students-queue"
                );

            queueClient.CreateIfNotExistsAsync().GetAwaiter().GetResult();
            await queueClient.SendMessageAsync(base64String);
        }
예제 #16
0
        private async Task <QueueClient> CreateCloudQueueAsync(string queueName)
        {
            var       cacheKey = $"CloudQueue|{queueName}";
            Exception cacheEx  = null;
            var       queue    = await _cache.GetOrCreateAsync(cacheKey, e => Task.Run(async delegate
            {
                try
                {
                    e.SetSlidingExpiration(TimeSpan.FromMinutes(30));

                    var queueClient = new QueueClient(_infrastructureConfig.Storage.ConnectionString, queueName);
                    await queueClient.CreateIfNotExistsAsync();

                    return(queueClient);
                }
                catch (Exception ex)
                {
                    cacheEx = ex;
                }

                return(null);
            }));

            if (cacheEx != null || queue == null)
            {
                _cache.Remove(cacheKey);

                if (cacheEx != null)
                {
                    throw cacheEx;
                }
            }

            return(queue);
        }
        public static async Task Run([TimerTrigger("0 */30 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            TableStorageOperations cloudTableClient = await TableStorageOperations.GetClientAsync();

            TableQuery <TenantModel> query   = new TableQuery <TenantModel>().Where(TableQuery.GenerateFilterConditionForBool(nameof(TenantModel.IsIotHubDeployed), QueryComparisons.Equal, true));
            List <TenantModel>       tenants = await cloudTableClient.QueryAsync <TenantModel>("tenant", query);

            if (tenants != null && tenants.Count > 0)
            {
                // Get the connection string from app settings
                string connectionString = Environment.GetEnvironmentVariable("AzureStorageConnectionString", EnvironmentVariableTarget.Process);

                // Instantiate a QueueClient which will be used to create and manipulate the queue
                QueueClient queueClient = new QueueClient(connectionString, "tenantstosync");

                await queueClient.CreateIfNotExistsAsync();

                if (queueClient.Exists())
                {
                    foreach (var tenant in tenants)
                    {
                        var tenantMessage = JsonConvert.SerializeObject(new TenantQueueItem(tenant.TenantId));

                        // Send a message to the queue
                        var encodedString = Base64Encode(tenantMessage);
                        queueClient.SendMessage(encodedString);
                    }
                }
            }
        }
예제 #18
0
        private async Task <QueueClient> InitializeQueueClient(string queueName, QueueClientOptions options)
        {
            var queueClient = new QueueClient(_settingService.GetStorageAccount(), queueName, options);
            await queueClient.CreateIfNotExistsAsync();

            return(queueClient);
        }
        public async Task <IActionResult> Post([FromBody] PayloadV5 payload)
        {
            string payloadFieldsUnpacked = string.Empty;

            // Check that the post data is good
            if (!this.ModelState.IsValid)
            {
                log.WarnFormat("QueuedController validation failed {0}", this.ModelState.Messages());

                return(this.BadRequest(this.ModelState));
            }

            try
            {
                QueueClient queueClient = new QueueClient(storageConnectionString, queueName);

                await queueClient.CreateIfNotExistsAsync();

                await queueClient.SendMessageAsync(Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(payload)));
            }
            catch (Exception ex)
            {
                log.Error("Unable to open/create queue or send message", ex);

                return(this.Problem("Unable to open queue (creating if it doesn't exist) or send message", statusCode: 500, title: "Uplink payload not sent"));
            }

            return(this.Ok());
        }
예제 #20
0
        private async Task WriteQueueMessages(string queueName, int numMessages)
        {
            QueueClient queue = _queueServiceClient.GetQueueClient(queueName);
            await queue.CreateIfNotExistsAsync();

            int numThreads = 10;

            if (numMessages <= numThreads)
            {
                numThreads = 1;
            }
            int         messagesPerThread = numMessages / numThreads;
            List <Task> tasks             = new List <Task>();

            for (int i = 0; i < numThreads; i++)
            {
                tasks.Add(AddMessagesAsync(messagesPerThread, queue));
            }

            int remainder = numMessages / numThreads;

            tasks.Add(AddMessagesAsync(remainder, queue));

            await Task.WhenAll(tasks);
        }
예제 #21
0
        private async Task <QueueClient> EnsureExistsAsync(string queueName)
        {
            var queueClient = new QueueClient(_connectionString, queueName);
            await queueClient.CreateIfNotExistsAsync();

            return(queueClient);
        }
예제 #22
0
        public static async Task <QueueClient> CreateQueue(string queueName = "streaming")
        {
            var queueClient = new QueueClient(connectionString: _connectionString, queueName);
            await queueClient.CreateIfNotExistsAsync();

            return(queueClient);
        }
예제 #23
0
        public async Task InitializeAsync()
        {
            DataProvider = new DataProviderFactory().GetDataProvider(Env.GetString("AZURE_STORAGE_TYPE"));
            await DataProvider.InitializeAsync(credential);

            // App Config
            ConfigurationClient = new ConfigurationClient(new Uri(Env.GetString("AZURE_APP_CONFIG_ENDPOINT")), credential);

            // Blob
            BlobServiceClient = new BlobServiceClient(new Uri(Env.GetString("AZURE_STORAGE_BLOB_ENDPOINT")), credential);
            ContainerClient   = BlobServiceClient.GetBlobContainerClient(Env.GetString("AZURE_STORAGE_BLOB_CONTAINER_NAME"));
            await ContainerClient.CreateIfNotExistsAsync(PublicAccessType.BlobContainer);

            // Queue
            QueueServiceClient = new QueueServiceClient(new Uri(Env.GetString("AZURE_STORAGE_QUEUE_ENDPOINT")), credential);
            QueueClient        = QueueServiceClient.GetQueueClient(Env.GetString("AZURE_STORAGE_QUEUE_NAME"));
            await QueueClient.CreateIfNotExistsAsync();

            // FormRecognizerClient
            FormRecognizerClient = new FormRecognizerClient(
                new Uri(Env.GetString("AZURE_FORM_RECOGNIZER_ENDPOINT")),
                credential);

            // TextAnalyticsClient
            TextAnalyticsClient = new TextAnalyticsClient(
                new Uri(Env.GetString("AZURE_TEXT_ANALYTICS_ENDPOINT")),
                credential);
        }
예제 #24
0
        public virtual async Task Init()
        {
            _queue = new QueueClient(AzureTestsHelper.DevelopmetStorage, "kalixleotestqueue");
            await _queue.CreateIfNotExistsAsync();

            _azureQueue = new AzureQueueStorage(_queue);
        }
예제 #25
0
        private async Task <QueueClient> QueueClient(string queueName)
        {
            QueueClient queueClient = new QueueClient(connectionStringStorage, queueName);

            await queueClient.CreateIfNotExistsAsync();

            return(queueClient);
        }
예제 #26
0
        public async Task InsertMessageAsync(string queueName, string message)
        {
            var queue = new QueueClient(_connectionString, queueName);

            await queue.CreateIfNotExistsAsync();

            await queue.SendMessageAsync(message);
        }
        public async Task SendMessageAsync <T>(T item)
        {
            string      msgBody    = JsonConvert.SerializeObject(item);
            QueueClient orderQueue = new QueueClient(config[Constants.KEY_STORAGE_CNN], config[Constants.KEY_QUEUE]);
            await orderQueue.CreateIfNotExistsAsync();

            await orderQueue.SendMessageAsync(msgBody);
        }
예제 #28
0
        public async Task <QueueClient> GetQueue()
        {
            QueueClient client = new QueueClient(connectionString, QueueName);

            await client.CreateIfNotExistsAsync();

            return(client);
        }
예제 #29
0
        /// <summary>
        /// The object value will get serialized into json. <br />
        /// The value is of type object because we don't really
        /// care about concrete types at this point.
        /// </summary>
        public async Task SendAsync(object value, string queueName)
        {
            var client = new QueueClient(connectionString, queueName);
            await client.CreateIfNotExistsAsync();

            string json = JsonSerializer.Serialize(value);
            await client.SendMessageAsync(json);
        }
예제 #30
0
 public async Task CreateIfNotExistsAsync()
 {
     await Task.WhenAll(
         _container.CreateIfNotExistsAsync(),
         _queue.CreateIfNotExistsAsync(),
         _dlQueue.CreateIfNotExistsAsync()
         ).ConfigureAwait(false);
 }