Ejemplo n.º 1
0
        static void CreateQueueMessages()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            IConfigurationRoot configuration = builder.Build();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(configuration.GetConnectionString("StorageConnectionString"));
            CloudQueueClient    queueclient    = storageAccount.CreateCloudQueueClient();

            CloudQueue queue = queueclient.GetQueueReference("myqueuemessages");

            queue.CreateIfNotExists();

            CloudQueueMessage message = null;

            for (int nQueueMessageIndex = 0; nQueueMessageIndex <= 100; nQueueMessageIndex++)
            {
                message = new CloudQueueMessage(Convert.ToString(nQueueMessageIndex));
                queue.AddMessage(message); Console.WriteLine(nQueueMessageIndex);
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Program p = new Program();

            p.GetMessage(QueueName);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("");
            string           t           = storageAccount.QueueEndpoint.ToString();
            CloudQueueClient queueClient = new CloudQueueClient(storageAccount.QueueStorageUri, storageAccount.Credentials);
            CloudQueue       Queue       = queueClient.GetQueueReference(QueueName);

            //var Signature = Convert.ToBase64String(new HMACSHA512(Encoding.UTF8.GetBytes(StringToSign)))
            if (Queue.CreateIfNotExists())
            {
                //HttpWebRequest req = WebRequest.Create()
                Console.WriteLine("Created Queue named: {0}", QueueName);
            }
            else
            {
                Console.WriteLine("Queue {0} already exists", QueueName);
            }
        }
Ejemplo n.º 3
0
        public void Dequeue_the_next_message()
        {
            // Retrieve storage account from connection string
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("myqueue");

            // Get the next message
            CloudQueueMessage retrievedMessage = queue.GetMessage();

            //Process the message in less than 30 seconds, and then delete the message
            if (retrievedMessage != null)
            {
                queue.DeleteMessage(retrievedMessage);
            }
        }
Ejemplo n.º 4
0
        // POST api/values
        public string Post(string testToRun, HttpPostedFileBase zipFile)
        {
            string requestId = Guid.NewGuid().ToString("N");
            string blobName  = requestId + ".zip";
            CloudStorageAccount storageAccount          = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["TestComparisonStorage"].ToString());
            CloudBlobClient     blobClient              = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  testComparisonContainer = blobClient.GetContainerReference("testzips");
            CloudBlockBlob      blob = testComparisonContainer.GetBlockBlobReference(blobName);

            blob.UploadFromStream(zipFile.InputStream);
            CloudQueueClient      queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue            queue       = queueClient.GetQueueReference("run-and-compare-tests");
            TestComparisonRequest request     = new TestComparisonRequest()
            {
                TestComparisonId = requestId,
                TestToRun        = testToRun
            };

            queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(request)));
            return(requestId);
        }
Ejemplo n.º 5
0
        StorageUri queueStorageUri = new StorageUri(new Uri("https://FROM_PORTAL.queue.core.windows.net/"));         // from Azure portal

        async void Queue_Clicked(object sender, EventArgs ea)
        {
            CloudStorageAccount storageAccount = CreateStorageAccount();

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("xqueue");

            CloudQueueMessage message = new CloudQueueMessage("Mobile Queue !" + DateTime.Now.Second);
            await queue.AddMessageAsync(message);

            Debug.WriteLine("added to queue");

            Debug.WriteLine("count : " + queue.ApproximateMessageCount);

            CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();

            Debug.WriteLine("retrieved from queue " + retrievedMessage.AsString);
        }
Ejemplo n.º 6
0
        public static Boolean PlaceQueueMessage(string bierRapportJson)
        {
            // Retrieve storage account from connection string.
            string connectionString            = Environment.GetEnvironmentVariable("StorageConnectionString");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Create the queue client.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a container.
            CloudQueue queue = queueClient.GetQueueReference("bierrapportmessages");

            // Create the queue if it doesn't already exist
            queue.CreateIfNotExists();

            // Create a message and add it to the queue.
            CloudQueueMessage message = new CloudQueueMessage(bierRapportJson);

            queue.AddMessage(message);
            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Queueからメッセージを受信する
        /// </summary>
        /// <param name="queueName">Queue名称</param>
        /// <param name="connectionString">Storageアカウント接続文字列</param>
        /// <returns>メッセージ</returns>
        public static List <string> GetMessages(string queueName, string connectionString)
        {
            List <string> messages = new List <string>();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
            CloudQueue          queue          = queueClient.GetQueueReference(queueName);

            IEnumerable <CloudQueueMessage> queueMessages;

            while ((queueMessages = queue.GetMessages(32)) != null && queueMessages.Count() > 0)
            {
                foreach (CloudQueueMessage queueMessage in queueMessages)
                {
                    messages.Add(queueMessage.AsString);
                    queue.DeleteMessage(queueMessage);
                }
            }

            return(messages);
        }
Ejemplo n.º 8
0
        public override bool OnStart()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(
                (a, b) => b(RoleEnvironment.GetConfigurationSettingValue(a)));

            // Задайте максимальное число одновременных подключений
            ServicePointManager.DefaultConnectionLimit = 12;

            // Дополнительные сведения по управлению изменениями конфигурации
            // см. раздел MSDN по ссылке http://go.microsoft.com/fwlink/?LinkId=166357.

            //StorageCredentialsAccountAndKey accountAndKey = new StorageCredentialsAccountAndKey("account",
            //  System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("key")));
            CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudQueueClient    client  = account.CreateCloudQueueClient();

            _queue = client.GetQueueReference("queue");
            _queue.CreateIfNotExist();

            return(base.OnStart());
        }
        public void OpContextTestClientRequestIDOnQueue()
        {
            CloudQueueClient qClient = GenerateCloudQueueClient();
            CloudQueue       queue   = qClient.GetQueueReference("test");

            string uniqueID = Guid.NewGuid().ToString();

            Action act = () => queue.Exists(null, new OperationContext()
            {
                ClientRequestID = uniqueID
            });

            TestHelper.VerifyHeaderWasSent("x-ms-client-request-id", uniqueID, XStoreSelectors.QueueTraffic().IfHostNameContains(qClient.Credentials.AccountName), act);

            act = () => queue.EndExists(queue.BeginExists(null, new OperationContext()
            {
                ClientRequestID = uniqueID
            }, null, null));

            TestHelper.VerifyHeaderWasSent("x-ms-client-request-id", uniqueID, XStoreSelectors.QueueTraffic().IfHostNameContains(qClient.Credentials.AccountName), act);
        }
Ejemplo n.º 10
0
        private static void Delete()
        {
            // Retrieve storage account from connection string
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("myqueue");

            // Get the next message
            CloudQueueMessage retrievedMessage = queue.GetMessage();

            //Process the message in less than 30 seconds, and then delete the message
            if (retrievedMessage != null)
            {
                queue.DeleteMessage(retrievedMessage);
            }
        }
Ejemplo n.º 11
0
        public async Task ProcessMessageAsync(string queuename)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the queue client.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue.
            CloudQueue queue = queueClient.GetQueueReference(queuename);

            foreach (CloudQueueMessage message in queue.GetMessages(30, TimeSpan.FromMinutes(5), null, null))
            {
                // Process all messages in less than 5 minutes, deleting each message after processing.
                await queue.DeleteMessageAsync(message);

                Random r = new Random();
                Console.WriteLine("message delete" + r.Next(0, 1000));
            }
        }
Ejemplo n.º 12
0
        public void Get_the_queue_length()
        {
            // Retrieve storage account from connection string
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create the queue client.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue.
            CloudQueue queue = queueClient.GetQueueReference("myqueue");

            // Fetch the queue attributes.
            queue.FetchAttributes();

            // Retrieve the cached approximate message count.
            int?cachedMessageCount = queue.ApproximateMessageCount;

            // Display number of messages.
            Console.WriteLine("Number of messages in queue: " + cachedMessageCount);
        }
Ejemplo n.º 13
0
        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                                                                 configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));

            var storageAccount            = CloudStorageAccount.FromConfigurationSetting(Utils.ConfigurationString);
            CloudQueueClient queueStorage = storageAccount.CreateCloudQueueClient();

            _queue = queueStorage.GetQueueReference(Utils.CloudQueueKey);

            _queue.CreateIfNotExist();

            CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();

            _container = blobStorage.GetContainerReference(Utils.CloudBlobKey);

            _container.CreateIfNotExist();

            return(base.OnStart());
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue       queue       = queueClient.GetQueueReference("myqueue");

            queue.CreateIfNotExists();
            for (int i = 0; i < 10; i++)
            {
                queue.AddMessage(new CloudQueueMessage("Hello" + i));
            }
            queue.FetchAttributes();

            // Retrieve the cached approximate message count.
            int?cachedMessageCount = queue.ApproximateMessageCount;

            // Display number of messages.
            Console.WriteLine("Number of messages in queue: " + cachedMessageCount);
            Console.ReadKey();
        }
Ejemplo n.º 15
0
        public static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ConnectionString"));

            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            CloudQueue queue = queueClient.GetQueueReference("--process_queue--");

            queue.CreateIfNotExists();

            #region Insert queue

            for (int i = 0; i < 500; i++)
            {
                CloudQueueMessage msg = new CloudQueueMessage(string.Format("Operation: {0}", i));
                queue.AddMessage(msg);
                Console.WriteLine("Added new message: {0}", i);
            }

            #endregion
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Delete de current message, the idea is doing at the end of the process
        /// </summary>
        public void DeleteCurrentMessage()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(this.ProcessConfigConn);
            CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
            string     qName = MediaButler.Common.Configuration.ButlerSendQueue;
            CloudQueue queue = queueClient.GetQueueReference(qName);

            try
            {
                string id = this.CurrentMessage.Id;
                queue.DeleteMessage(this.CurrentMessage);
                Trace.TraceInformation("[{0}] in prosess type {1} instnace {2} at {4} delete message {3}",
                                       this.GetType().FullName, this.ProcessTypeId, this.ProcessInstanceId, id, "KeepMessageHidden");
            }
            catch (Exception X)
            {
                Trace.TraceError("[{0}] in prosess type {1} instnace {2} at {4} has an erro: {3}",
                                 this.GetType().FullName, this.ProcessTypeId, this.ProcessInstanceId, X.Message, "KeepMessageHidden");
                throw;
            }
        }
Ejemplo n.º 17
0
        public ActionResult Contact()
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(System.Configuration.ConfigurationManager.AppSettings["CloudStorageAccount"]);
                CloudQueueClient    client         = storageAccount.CreateCloudQueueClient();
                CloudQueue          queue          = client.GetQueueReference("zeroyxzqueue");
                queue.CreateIfNotExists();

                Trace.TraceInformation("About to write a message to the queue");
                queue.AddMessage(new CloudQueueMessage("The time is now" + DateTime.Now.ToShortTimeString()));
                Trace.TraceWarning("Message has been written");
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error:" + ex.Message.ToString());
            }
            ViewBag.Message = "Your contact page.";

            return(View());
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> SendTelemetry([FromBody] Telemetry t)
        {
            var json = JsonConvert.SerializeObject(t);

            var bytes = Encoding.UTF8.GetBytes(json);

            var storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=aletomeaworksasync;AccountKey=gS/ED+jA1gVXVVSrhVBWwL9sm/caRl9K8R7V+EzEyADfZYjY258NfwVhDvw+8xBHogIGwOB/0IjQ5cF2FCtbxw==;EndpointSuffix=core.windows.net");

            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a container.
            CloudQueue queue = queueClient.GetQueueReference("telemetryqueue");

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

            CloudQueueMessage message = new CloudQueueMessage(json);
            await queue.AddMessageAsync(message);

            return(Ok(new { message = "success", result = true }));
        }
Ejemplo n.º 19
0
        public async Task <string> DequeueAsync(string queueName)
        {
            //Cria uma referência a conta de Armazenamento do Azure
            CloudStorageAccount storageAccountClient =
                CloudStorageAccount.Parse(Properties.Resources.StringConnection);

            //Cria um objeto cliente de queue/fila a partir da conta de armazenamento
            CloudQueueClient queueClient = storageAccountClient.CreateCloudQueueClient();

            //Crio um objeto que referencia uma determinada queue/fila
            CloudQueue cloudQueue = queueClient.GetQueueReference(queueName);

            //Crio a fila se ela não existir
            await cloudQueue.CreateIfNotExistsAsync();

            //Adiciono a mensagem na queue/fila
            var message = cloudQueue.GetMessageAsync().Result;
            await cloudQueue.DeleteMessageAsync(message);

            return(message.AsString);
        }
Ejemplo n.º 20
0
        public async Task EnqueueAsync(QueueMessage message)
        {
            //Cria uma referência a conta de Armazenamento do Azure
            CloudStorageAccount storageAccountClient =
                CloudStorageAccount.Parse(Properties.Resources.StringConnection);

            //Cria um objeto cliente de queue/fila a partir da conta de armazenamento
            CloudQueueClient queueClient = storageAccountClient.CreateCloudQueueClient();

            //Crio um objeto que referencia uma determinada queue/fila
            CloudQueue cloudQueue = queueClient.GetQueueReference(message.QueueName);

            //Crio a fila se ela não existir
            bool result = cloudQueue.CreateIfNotExistsAsync().Result;

            //Crio uma mensagem a partir do objeto serializado
            CloudQueueMessage cloudQueueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(message));

            //Adiciono a mensagem na queue/fila
            await cloudQueue.AddMessageAsync(cloudQueueMessage);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Make azure call to write to Queue
        /// </summary>
        /// <param name="count">no of calls to be made</param>
        public static void MakeAzureCallToWriteQueueWithSdk(int count)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount =
                CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("myqueue");

            queue.CreateIfNotExists();

            // Create a message and add it to the queue.
            CloudQueueMessage message = new CloudQueueMessage("Hello, World" + DateTime.UtcNow);

            queue.AddMessage(message);

            queue.DeleteIfExists();
        }
Ejemplo n.º 22
0
        public void ClearCrawler()
        {
            // Retrieve storage account from connection string
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to CommandQueue
            CloudQueue commandQueue = queueClient.GetQueueReference(WebRole.AZURE_COMMAND_QUEUE);

            // Create the queue if it doesn't already exist
            commandQueue.CreateIfNotExists();

            // Create queue message
            CloudQueueMessage message = new CloudQueueMessage(Commands.CMD_CLEAR_CRAWLER.ToString());

            // Add message to command queue
            commandQueue.AddMessage(message);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates an instance of Azure Storage Queue by account details and the queue name
        /// </summary>
        /// <param name="accountName">Storage account name</param>
        /// <param name="storageKey">Storage key (primary or secondary)</param>
        /// <param name="queueName">Name of the queue. If queue doesn't exist it will be created</param>
        public AzureStorageQueuePublisher(string accountName, string storageKey, string queueName)
        {
            if (accountName == null)
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (storageKey == null)
            {
                throw new ArgumentNullException(nameof(storageKey));
            }
            if (queueName == null)
            {
                throw new ArgumentNullException(nameof(queueName));
            }

            var account             = new CloudStorageAccount(new StorageCredentials(accountName, storageKey), true);
            CloudQueueClient client = account.CreateCloudQueueClient();

            _queue = client.GetQueueReference(queueName);
            _queue.CreateIfNotExistsAsync().Wait();
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            Task.Run(async() =>
            {
                Console.WriteLine("Job Starting");
                int length       = Convert.ToInt32(ConfigurationManager.AppSettings["Iterations"]);
                int timeInterval = Convert.ToInt32(ConfigurationManager.AppSettings["TimeIntervalMS"]);

                for (int i = 0; i < length; i++)
                {
                    if (queue == null)
                    {
                        // Retrieve storage account information from connection string.
                        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

                        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

                        queue = queueClient.GetQueueReference("queue");

                        try
                        {
                            await queue.CreateIfNotExistsAsync();
                        }
                        catch
                        {
                            Console.WriteLine("If you are running with the default configuration please make sure you have started the storage emulator.  ess the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                            Console.ReadLine();
                            throw;
                        }
                    }


                    await queue.AddMessageAsync(new CloudQueueMessage($"Message number: {i}"));
                    Console.WriteLine($"Message number {i} added to queue.");

                    Thread.Sleep(timeInterval);
                }
            }).Wait();
            Console.WriteLine("Job Finished");
        }
Ejemplo n.º 25
0
        public ActionResult Create([Bind(Include = "name,id")] studentz studentz, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                db.studentz.Add(studentz);
                db.SaveChanges();
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("storageconnectionstring"));

                CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();


                CloudQueue queue = queueClient.GetQueueReference("demoqueue");


                queue.CreateIfNotExists();

                CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("id:" + studentz.id.ToString() + "studentname" + studentz.name);
                queue.AddMessage(cloudQueueMessage);

                if (image != null && image.ContentLength > 0)
                {
                    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                    CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("newblob");
                    cloudBlobContainer.CreateIfNotExists();
                    cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(studentz.id.ToString() + ".png");
                    cloudBlockBlob.UploadFromStream(image.InputStream);
                }



                return(RedirectToAction("Index"));
            }

            return(View(studentz));
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("apsettings.json");

            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", true, true)
                                    .Build();

            CloudStorageAccount account = CloudStorageAccount.Parse(config["connectionString"]);
            CloudQueueClient    client  = account.CreateCloudQueueClient();

            CloudQueue queue = client.GetQueueReference("filaprocesos");

            CloudQueueMessage peekMessage = queue.PeekMessage();

            CloudBlobClient    blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("operationscontainer");

            container.CreateIfNotExists();

            foreach (var item in queue.GetMessages(20, TimeSpan.FromSeconds(100)))
            {
                string     filePath = string.Format(@"log_{0}.txt", item.Id);
                TextWriter tempFile = File.CreateText(filePath);
                var        message  = queue.GetMessage().AsString;
                tempFile.WriteLine(message);
                Console.WriteLine("Archivo creado");
                tempFile.Close();
                using (var fileStream = System.IO.File.OpenRead(filePath))
                {
                    CloudBlockBlob myBlob = container.GetBlockBlobReference(string.Format(@"log_{0}.txt", item.Id));
                    myBlob.UploadFromStream(fileStream);
                    Console.WriteLine("Blob creado");
                }
                queue.DeleteMessage(item);
            }
        }
Ejemplo n.º 27
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string functionLogPrefix = "[BeerAdviceFunction] ";

            log.LogInformation("{0}Queue triggered", functionLogPrefix);

            string city = req.Query["city"].ToString();

            if (city == null || city.Trim().Length == 0)
            {
                return(new BadRequestObjectResult("Please enter a city on the query string. For example use the city Muiden '?city=muiden'"));
            }

            // Make city name readable
            if (city.Length > 1)
            {
                city = char.ToUpper(city[0]) + city.Substring(1).ToLower();
            }
            else
            {
                city = city.ToUpper();
            }

            CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(StorageName, StorageKey), true);
            CloudQueueClient    cloudQueueClient    = cloudStorageAccount.CreateCloudQueueClient();
            CloudQueue          cloudQueue          = cloudQueueClient.GetQueueReference("beeradvicequeue");
            await cloudQueue.CreateIfNotExistsAsync();

            String date = DateTime.Now.ToString("dd-MM-yyyy_HH-mm");
            String cloudQueueMessage = $"{city}|{date}";
            await cloudQueue.AddMessageAsync(new CloudQueueMessage(cloudQueueMessage));

            string imageName = $"{city}-beer_advice-{date}.png";
            string imageUrl  = StorageUrl + imageName;

            log.LogInformation("{0}Generated image url: {1}", functionLogPrefix, imageUrl);
            return(new OkObjectResult(imageUrl));
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            CostCenter costCenter = await GetCostCenterAsync(costCenterAPIUrl, Expense.SubmitterEmail);

            if (costCenter != null)
            {
                Expense.CostCenter    = costCenter.CostCenterName;
                Expense.ApproverEmail = costCenter.ApproverEmail;
            }
            else
            {
                Expense.CostCenter    = "Unkown";
                Expense.ApproverEmail = "Unknown";
            }

            // Write to DB, but don't wait right now
            _context.Expense.Add(Expense);
            Task t = _context.SaveChangesAsync();

            // Serialize the expense and write it to the Azure Storage Queue
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_queueInfo.ConnectionString);
            CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
            CloudQueue          queue          = queueClient.GetQueueReference(_queueInfo.QueueName);
            await queue.CreateIfNotExistsAsync();

            CloudQueueMessage queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(Expense));
            await queue.AddMessageAsync(queueMessage);

            // Ensure the DB write is complete
            t.Wait();

            _metrics.Measure.Counter.Increment(MetricsRegistry.CreatedExpenseCounter);

            return(RedirectToPage("./Index"));
        }
        public static bool DeleteResponseMessages(string UserName)
        {
            try
            {
                StorageCredentials  credentials = new StorageCredentials(ACCOUNT, AccountKey);
                CloudStorageAccount cs          = new CloudStorageAccount(credentials, true);
                CloudStorageAccount account     =
                    CloudStorageAccount.Parse(Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

                // Create the queue client.
                CloudQueueClient queueClient = account.CreateCloudQueueClient();

                // Retrieve a reference to a container.
                CloudQueue queue = queueClient.GetQueueReference(UserName);

                // Create the queue if it doesn't already exist
                queue.CreateIfNotExists();

                // Fetch the queue attributes.
                queue.FetchAttributes();

                // Retrieve the cached approximate message count.
                int?cachedMessageCount = queue.ApproximateMessageCount;

                for (int i = 0; i < cachedMessageCount; i++)
                {
                    // Get the next message
                    CloudQueueMessage retrievedMessage = queue.GetMessage();

                    //Process the message in less than 30 seconds, and then delete the message
                    queue.DeleteMessage(retrievedMessage);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 30
0
        public async void Use_async_wait_pattern()
        {
            // Retrieve storage account from connection string
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create the queue client
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

            // Retrieve a reference to a queue
            CloudQueue queue = queueClient.GetQueueReference("myqueue");

            // Create the queue if it doesn't already exist
            if (await queue.CreateIfNotExistsAsync())
            {
                Console.WriteLine("Queue '{0}' Created", queue.Name);
            }
            else
            {
                Console.WriteLine("Queue '{0}' Exists", queue.Name);
            }

            // Create a message to put in the queue
            CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("My message");

            // Async enqueue the message
            await queue.AddMessageAsync(cloudQueueMessage);

            Console.WriteLine("Message added");

            // Async dequeue the message
            CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();

            Console.WriteLine("Retrieved message with content '{0}'", retrievedMessage.AsString);

            // Async delete the message
            await queue.DeleteMessageAsync(retrievedMessage);

            Console.WriteLine("Deleted message");
        }