Beispiel #1
0
        /// <summary>
        /// The main entry point.
        /// </summary>
        /// <param name="args">
        /// The command line arguments. Not used.
        /// </param>
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello!");

            // Create a connection to the web api server
            string command;
            var client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:10281/");

            do
            {
                // Load the file to transmit
                string fileName = string.Empty;
                while (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
                {
                    Console.Write("Enter the full name of the file you like to send to server: ");
                    fileName = Console.ReadLine();
                }

                var fileInfo = new FileInfo(fileName);

                // Get the SAS-URLs from the server
                Console.WriteLine("Asking Server for SAS-URLs");
                HttpResponseMessage resp = client.GetAsync("api/Data").Result;
                resp.EnsureSuccessStatusCode();
                var dataDto = resp.Content.ReadAsAsync<DataDto>().Result;

                Console.WriteLine("Server responds:");
                Console.WriteLine("BLOB Container URL: " + dataDto.BlobContainerUrl);
                Console.WriteLine("BLOB Container SAS Token: " + dataDto.BlobSasToken);
                Console.WriteLine("Queue URL: " + dataDto.QueueUrl);
                Console.WriteLine("Queue SAS Token: " + dataDto.QueueSasToken);

                // Load file to BLOB Storage
                Console.WriteLine("Create or overwrite the blob with contents from a local file...");
                var container = new CloudBlobContainer(new Uri(dataDto.BlobContainerUrl + dataDto.BlobSasToken));
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileInfo.Name);
                using (var fileStream = File.OpenRead(fileInfo.FullName))
                {
                    blockBlob.UploadFromStream(fileStream);
                }

                Console.WriteLine("done.");

                // Add message to queue
                Console.Write("Add a new message to the queue...");
                var queue = new CloudQueue(new Uri(dataDto.QueueUrl + dataDto.QueueSasToken));
                var message = new CloudQueueMessage(blockBlob.Uri.ToString());
                queue.AddMessage(message);
                Console.WriteLine("done.");

                Console.WriteLine("Press Enter to upload the next file or type 'quit' for exit");
                command = Console.ReadLine();
            }
            while (command != "quit");
        }
Beispiel #2
0
        public bool enqueue(string queueName, Message operationMessage)
        {
            var message = JsonConvert.SerializeObject(operationMessage);

            try
            {
                queue = queueClient.GetQueueReference(queueName);
                queue.CreateIfNotExists();


                queue.AddMessage(new CloudQueueMessage(message));
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException);
                return false;
            }
        }
Beispiel #3
0
        public void CloudQueueMessageQueueAddLargeMessage()
        {
            long maxStringLength    = CloudQueueMessage.MaxMessageSize;
            long maxByteArrayLength = CloudQueueMessage.MaxMessageSize * 3 / 4;

            string     name  = GenerateNewQueueName();
            CloudQueue queue = DefaultQueueClient.GetQueueReference(name);

            queue.Create();

            {
                char[] longMessageChars = new char[maxStringLength];
                for (long i = 0; i < longMessageChars.LongLength; i++)
                {
                    longMessageChars[i] = (char)('A' + (i % 26));
                }

                CloudQueueMessage longMessageFromString = new CloudQueueMessage(new string(longMessageChars));

                // Do not encode the message. This allows a maximally-sized string to be used.
                queue.EncodeMessage = false;

                // The following call should succeed.
                queue.AddMessage(longMessageFromString);

                CloudQueueMessage retrievedMessage = queue.GetMessage();
                Assert.AreEqual(longMessageFromString.AsString, retrievedMessage.AsString);
            }

            {
                byte[] longMessageBytes = new byte[maxByteArrayLength];
                for (long i = 0; i < longMessageBytes.LongLength; i++)
                {
                    longMessageBytes[i] = (byte)i;
                }

                CloudQueueMessage longMessageFromByteArray = new CloudQueueMessage(longMessageBytes);

                // The following call should throw an exception because byte array messages must be base 64 encoded.
                queue.EncodeMessage = false;

                TestHelper.ExpectedException <ArgumentException>(
                    () => queue.AddMessage(longMessageFromByteArray),
                    "AddMessage should throw an exception because byte array messages must be base 64 encoded");

                // Encode the message in base 64. This is the only way to use byte arrays in a message.
                queue.EncodeMessage = true;

                // The following call should succeed.
                queue.AddMessage(longMessageFromByteArray);

                CloudQueueMessage retrievedMessage = queue.GetMessage();
                byte[]            expectedBytes    = longMessageFromByteArray.AsBytes;
                byte[]            foundBytes       = retrievedMessage.AsBytes;

                Assert.AreEqual(expectedBytes.Length, foundBytes.Length);

                for (int i = 0; i < expectedBytes.Length; i++)
                {
                    Assert.AreEqual(expectedBytes[i], foundBytes[i]);
                }
            }

            queue.Delete();
        }
        private static bool QueueBase64EncodingTestVerifyLength(CloudQueue queue, CloudQueueMessage message)
        {
            const long MaxMessageSize = 64 * 1024; // 64kb

            if (queue.EncodeMessage && Convert.ToBase64String(message.AsBytes).Length > MaxMessageSize
                || !queue.EncodeMessage && message.AsBytes.Length > MaxMessageSize)
            {
                TestHelper.ExpectedException<ArgumentException>(() => { queue.AddMessage(message); }, "Binary data must be Base64 encoded");
                return true;
            }

            return false;
        }
        /// <summary>
        /// Perform a PUT and GET queue message test customized by a few parameters.
        /// </summary>
        private void QueueBase64EncodingTest(CloudQueue queue, CloudQueue queueRefWithoutBase64Encoding, bool useBase64Encoding, bool useString, bool hasInvalidCharacter, int messageLength, char invalidXmlChar, char validXmlChar)
        {
            queue.EncodeMessage = useBase64Encoding;
            CloudQueueMessage originalMessage = null;
            bool expectedExceptionThrown = false;

            if (!useString)
            {
                // hasInvalidCharacter is ignored
                byte[] data = new byte[messageLength];
                Random random = new Random();
                random.NextBytes(data);
                originalMessage = new CloudQueueMessage(data);
            }
            else
            {
                string message = CreateMessageString(messageLength, hasInvalidCharacter, invalidXmlChar, validXmlChar);
                originalMessage = new CloudQueueMessage(message);
            }

            // check invalid use case and length validation
            if (!useString && !queue.EncodeMessage)
            {
                TestHelper.ExpectedException<ArgumentException>(() => { queue.AddMessage(originalMessage); }, "Binary data must be Base64 encoded");
                expectedExceptionThrown = true;
            }
            else
            {
                expectedExceptionThrown = QueueBase64EncodingTestVerifyLength(queue, originalMessage);
            }

            if (!expectedExceptionThrown)
            {
                // check invalid XML characters validation
                if (!queue.EncodeMessage && hasInvalidCharacter && messageLength > 0)
                {
                    TestHelper.ExpectedException<ArgumentException>(() => { queue.AddMessage(originalMessage); }, "Invalid characters should throw if Base64 encoding is not used");
                    expectedExceptionThrown = true;
                }
                else
                {
                    // good to send messages
                    queue.AddMessage(originalMessage);
                    queue.AddMessage(originalMessage);

                    if (useString)
                    {
                        QueueBase64EncodingTestDownloadMessageAndVerify(queue, queueRefWithoutBase64Encoding, originalMessage.AsString);
                    }
                    else
                    {
                        QueueBase64EncodingTestDownloadMessageAndVerify(queue, queueRefWithoutBase64Encoding, originalMessage.AsBytes);
                    }
                }
            }
        }
        public void UpdateQueueSASTest()
        {
            CloudQueueClient client = GenerateCloudQueueClient();
            CloudQueue queue = client.GetQueueReference(GenerateNewQueueName());

            try
            {
                queue.Create();
                string messageContent = Guid.NewGuid().ToString();
                CloudQueueMessage message = new CloudQueueMessage(messageContent);
                queue.AddMessage(message);
                SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.ProcessMessages,
                };
                string id = Guid.NewGuid().ToString();
                string sasToken = queue.GetSharedAccessSignature(policy, null);

                StorageCredentials sasCreds = new StorageCredentials(sasToken);
                CloudQueue sasQueue = new CloudQueue(queue.Uri, sasCreds);

                TestHelper.ExpectedException(
                    () => sasQueue.PeekMessage(),
                    "Peek when Sas does not allow Read access on the queue",
                    HttpStatusCode.NotFound);

                sasQueue.AddMessage(message);

                SharedAccessQueuePolicy policy2 = new SharedAccessQueuePolicy()
                {
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions = SharedAccessQueuePermissions.Add | SharedAccessQueuePermissions.ProcessMessages | SharedAccessQueuePermissions.Read,
                };

                string sasToken2 = queue.GetSharedAccessSignature(policy2, null);
                sasCreds.UpdateSASToken(sasToken2);
                sasQueue = new CloudQueue(queue.Uri, sasCreds);

                sasQueue.PeekMessage();
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
Beispiel #7
0
        public void CloudQueueMessageEncryptionWithStrictMode()
        {
            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();

            resolver.Add(aesKey);

            CloudQueueClient client = GenerateCloudQueueClient();
            string           name   = GenerateNewQueueName();
            CloudQueue       queue  = client.GetQueueReference(name);

            try
            {
                queue.CreateIfNotExists();

                string            messageStr = Guid.NewGuid().ToString();
                CloudQueueMessage message    = new CloudQueueMessage(messageStr);

                QueueEncryptionPolicy policy = new QueueEncryptionPolicy(aesKey, null);

                // Add message with policy.
                QueueRequestOptions createOptions = new QueueRequestOptions()
                {
                    EncryptionPolicy = policy
                };
                createOptions.RequireEncryption = true;

                queue.AddMessage(message, null, null, createOptions, null);

                // Set policy to null and add message while RequireEncryption flag is still set to true. This should throw.
                createOptions.EncryptionPolicy = null;

                TestHelper.ExpectedException <InvalidOperationException>(
                    () => queue.AddMessage(message, null, null, createOptions, null),
                    "Not specifying a policy when RequireEnryption is set to true should throw.");

                // Retrieve message
                QueueEncryptionPolicy retrPolicy      = new QueueEncryptionPolicy(null, resolver);
                QueueRequestOptions   retrieveOptions = new QueueRequestOptions()
                {
                    EncryptionPolicy = retrPolicy
                };
                retrieveOptions.RequireEncryption = true;

                CloudQueueMessage retrMessage = queue.GetMessage(null, retrieveOptions, null);

                // Update message with plain text.
                string updatedMessage = Guid.NewGuid().ToString("N");
                retrMessage.SetMessageContent(updatedMessage);

                queue.UpdateMessage(retrMessage, TimeSpan.FromSeconds(0), MessageUpdateFields.Content | MessageUpdateFields.Visibility);

                // Retrieve updated message with RequireEncryption flag but no metadata on the service. This should throw.
                TestHelper.ExpectedException <StorageException>(
                    () => queue.GetMessage(null, retrieveOptions, null),
                    "Retrieving with RequireEncryption set to true and no metadata on the service should fail.");

                // Set RequireEncryption to false and retrieve.
                retrieveOptions.RequireEncryption = false;
                queue.GetMessage(null, retrieveOptions, null);
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }