diff --git a/ChangeLog.txt b/ChangeLog.txt new file mode 100644 index 000000000000..986b301bebb4 --- /dev/null +++ b/ChangeLog.txt @@ -0,0 +1,2 @@ +2012-??-?? Version 0.9.0 + * Initial Release \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 000000000000..2bb9ad240fa0 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README b/README deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/README.md b/README.md new file mode 100644 index 000000000000..88fd82ac926a --- /dev/null +++ b/README.md @@ -0,0 +1,261 @@ +# Windows Azure SDK for Python + +This project provides a set of Python packages that make it easy to access +the Windows Azure storage and queue services. For documentation on how +to host Python applications on Windows Azure, please see the +[Windows Azure](http://www.windowsazure.com/en-us/develop/python/) +Python Developer Center. + +# Features + +* Tables + * create and delete tables + * create, query, insert, update, merge, and delete entities +* Blobs + * create, list, and delete containers, work with container metadata and permissions, list blobs in container + * create block and page blobs (from a stream, a file, or a string), work with blob blocks and pages, delete blobs + * work with blob properties, metadata, leases, snapshot a blob +* Storage Queues + * create, list, and delete queues, and work with queue metadata + * create, get, peek, update, delete messages +* Service Bus + * Queues: create, list and delete queues; create, list, and delete subscriptions; send, receive, unlock and delete messages + * Topics: create, list, and delete topics; create, list, and delete rules + +# Getting Started +## Download Source Code + +To get the source code of the SDK via **git** just type: + + git clone https://github.com/WindowsAzure/azure-sdk-for-python.git + cd ./azure-sdk-for-python + +## Download Package + +Alternatively, to get the source code via the Python Package Index (PyPI), type + + %SystemDrive%\Python27\Scripts\pip.exe install pyazure + +You can use these packages against the cloud Windows Azure Services, or against +the local Storage Emulator (with the exception of Service Bus features). + +1. To use the cloud services, you need to first create an account with Windows Azure. To use the storage services, you need to set the AZURE_STORAGE_ACCOUNT and the AZURE_STORAGE_ACCESS_KEY environment variables to the storage account name and primary access key you obtain from the Azure Portal. To use Service Bus, you need to set the AZURE_SERVICEBUS_NAMESPACE and the AZURE_SERVICEBUS_ACCESS_KEY environment variables to the service bus namespace and the default key you obtain from the Azure Portal. +2. To use the Storage Emulator, make sure the latest version of the Windows Azure SDK is installed on the machine, and set the EMULATED environment variable to any value ("true", "1", etc.) + +# Usage +## Table Storage + +To ensure a table exists, call **createTableIfNotExists**: + +```Javascript +var tableService = azure.createTableService(); +tableService.createTableIfNotExists('tasktable', function(error){ + if(!error){ + // Table exists + } +}); +``` +A new entity can be added by calling **insertEntity**: + +```Javascript +var tableService = azure.createTableService(), + task1 = { + PartitionKey : 'tasksSeattle', + RowKey: '1', + Description: 'Take out the trash', + DueDate: new Date(2011, 12, 14, 12) + }; +tableService.insertEntity('tasktable', task1, function(error){ + if(!error){ + // Entity inserted + } +}); +``` + +The method **queryEntity** can then be used to fetch the entity that was just inserted: + +```Javascript +var tableService = azure.createTableService(); +tableService.queryEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity){ + if(!error){ + // Entity available in serverEntity variable + } +}); +``` + +## Blob Storage + +The **createContainerIfNotExists** method can be used to create a +container in which to store a blob: + +```Javascript +var blobService = azure.createBlobService(); +blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error){ + if(!error){ + // Container exists and is public + } +}); +``` + +To upload a file (assuming it is called task1-upload.txt, it contains the exact text "hello world" (no quotation marks), and it is placed in the same folder as the script below), the method **createBlockBlobFromStream** can be used: + +```Javascript +var blobService = azure.createBlobService(); +blobService.createBlockBlobFromStream('taskcontainer', 'task1', fs.createReadStream('task1-upload.txt'), 11, function(error){ + if(!error){ + // Blob uploaded + } +}); +``` + +To download the blob and write it to the file system, the **getBlobToStream** method can be used: + +```Javascript +var blobService = azure.createBlobService(); +blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob){ + if(!error){ + // Blob available in serverBlob.blob variable + } +}); +``` + +## Storage Queues + +The **createQueueIfNotExists** method can be used to ensure a queue exists: + +```Javascript +var queueService = azure.createQueueService(); +queueService.createQueueIfNotExists('taskqueue', function(error){ + if(!error){ + // Queue exists + } +}); +``` + +The **createMessage** method can then be called to insert the message into the queue: + +```Javascript +var queueService = azure.createQueueService(); +queueService.createMessage('taskqueue', "Hello world!", function(error){ + if(!error){ + // Message inserted + } +}); +``` + +It is then possible to call the **getMessage** method, process the message and then call **deleteMessage** inside the callback. This two-step process ensures messages don't get lost when they are removed from the queue. + +```Javascript +var queueService = azure.createQueueService(), + queueName = 'taskqueue'; +queueService.getMessages(queueName, function(error, serverMessages){ + if(!error){ + // Process the message in less than 30 seconds, the message + // text is available in serverMessages[0].messagetext + + queueService.deleteMessage(queueName, serverMessages[0].messageid, serverMessages[0].popreceipt, function(error){ + if(!error){ + // Message deleted + } + }); + } +}); +``` + +## ServiceBus Queues + +ServiceBus Queues are an alternative to Storage Queues that might be useful in scenarios where more advanced messaging features are needed (larger message sizes, message ordering, single-operaiton destructive reads, scheduled delivery) using push-style delivery (using long polling). + +The **createQueueIfNotExists** method can be used to ensure a queue exists: + +```Javascript +var serviceBusService = azure.createServiceBusService(); +serviceBusService.createQueueIfNotExists('taskqueue', function(error){ + if(!error){ + // Queue exists + } +}); +``` + +The **sendQueueMessage** method can then be called to insert the message into the queue: + +```Javascript +var serviceBusService = azure.createServiceBusService(); +serviceBusService.sendQueueMessage('taskqueue', 'Hello world!', function( + if(!error){ + // Message sent + } +}); +``` + +It is then possible to call the **receiveQueueMessage** method to dequeue the message. + +```Javascript +var serviceBusService = azure.createServiceBusService(); +serviceBusService.receiveQueueMessage('taskqueue', function(error, serverMessage){ + if(!error){ + // Process the message + } +}); +``` + +## ServiceBus Topics + +ServiceBus topics are an abstraction on top of ServiceBus Queues that make pub/sub scenarios easy to implement. + +The **createTopicIfNotExists** method can be used to create a server-side topic: + +```Javascript +var serviceBusService = azure.createServiceBusService(); +serviceBusService.createTopicIfNotExists('taskdiscussion', function(error){ + if(!error){ + // Topic exists + } +}); +``` + +The **sendTopicMessage** method can be used to send a message to a topic: + +```Javascript +var serviceBusService = azure.createServiceBusService(); +serviceBusService.sendTopicMessage('taskdiscussion', 'Hello world!', function(error){ + if(!error){ + // Message sent + } +}); +``` + +A client can then create a subscription and start consuming messages by calling the **createSubscription** method followed by the **receiveSubscriptionMessage** method. Please note that any messages sent before the subscription is created will not be received. + +```Javascript +var serviceBusService = azure.createServiceBusService(), + topic = 'taskdiscussion', + subscription = 'client1'; + +serviceBusService.createSubscription(topic, subscription, function(error1){ + if(!error1){ + // Subscription created + + serviceBusService.receiveSubscriptionMessage(topic, subscription, function(error2, serverMessage){ + if(!error2){ + // Process message + } + }); + } +}); +``` + +** For more examples please see the [Windows Azure Python Developer Center](http://www.windowsazure.com/en-us/develop/python) ** + +# Need Help? + +Be sure to check out the Windows Azure [Developer Forums on Stack Overflow](http://go.microsoft.com/fwlink/?LinkId=234489) if you have trouble with the provided code. + +# Contribute Code or Provide Feedback + +If you would like to become an active contributor to this project please follow the instructions provided in [Windows Azure Projects Contribution Guidelines](http://windowsazure.github.com/guidelines.html). + +If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/WindowsAzure/azure-sdk-for-python/issues) section of the project. + +# Learn More +[Windows Azure Python Developer Center](http://www.windowsazure.com/en-us/develop/python/) diff --git a/examples/blobuploader/helpers.js b/examples/blobuploader/helpers.js new file mode 100644 index 000000000000..f77aeeb386c6 --- /dev/null +++ b/examples/blobuploader/helpers.js @@ -0,0 +1,10 @@ +//Helper functions +var exports = module.exports; + +exports.renderError = function(response, message) { + response.render("error.ejs", { + locals: { + title: message ? message : "Error" + } + }); +}; \ No newline at end of file diff --git a/examples/blobuploader/package.json b/examples/blobuploader/package.json new file mode 100644 index 000000000000..950ea8916560 --- /dev/null +++ b/examples/blobuploader/package.json @@ -0,0 +1,11 @@ +{ + "name": "productmanager" + , "version": "0.0.1" + , "private": true + , "dependencies": { + "express": ">= 2.4.7" + , "ejs": ">= 0.4.3" + , "formidable": ">= 1.0.6" + , "azure": ">= 0.5.1" + } +} \ No newline at end of file diff --git a/examples/blobuploader/public/Images/delete.png b/examples/blobuploader/public/Images/delete.png new file mode 100644 index 000000000000..ba558aed879f Binary files /dev/null and b/examples/blobuploader/public/Images/delete.png differ diff --git a/examples/blobuploader/public/Images/download.png b/examples/blobuploader/public/Images/download.png new file mode 100644 index 000000000000..f7eb98bd9ff9 Binary files /dev/null and b/examples/blobuploader/public/Images/download.png differ diff --git a/examples/blobuploader/public/css/default.css b/examples/blobuploader/public/css/default.css new file mode 100644 index 000000000000..a6f029bd9154 --- /dev/null +++ b/examples/blobuploader/public/css/default.css @@ -0,0 +1,496 @@ +/*#region -----------------------------Main Layout*/ +html { + height: 100%; + min-height: 700px; +} + +a { + outline: none; +} + +li { + margin: 5px 0 5px; +} + +body { + background: #ebf0f2; + font-family: Actor, sans-serif; + font-size: 100%; + color: #434343; + height: 100%; + min-height: 900px; +} + +.mainWrapper { + position: relative; + background-color: rgba(204, 204, 204, 0.75); + width: 850px; + margin: 0 auto; + min-height: 100%; +} + +.mainLayout { + clear: both; + width: 850px; + padding-bottom: 25px; + height: 100%; +} + +.mainSection { + position: relative; + margin: 50px 0 25px 90px; +} + +header, footer { + font-weight: bold; + font-size: 0.9em; + color: #e6e2df; + background-color: rgba(0, 0, 0, 0.53); + text-transform: uppercase; +} + +.login { + float: right; + padding-right: 12px; +} + +.loginLink { + color: #e6e2df; +} + + .loginLink:hover { + color: #ebf0f2; + } + +.welcomeUser { + color: #92a5bc; + font-size: 0.9em; + margin-right: 12px; +} + +.no-rgba header, .no-rgba footer { + background-color: #666666; +} + +header { + height: 30px; + padding: 15px 0px 0px 10px; +} + + .mainTitle a { + color: #CCC; + } + + .mainTitle a:hover { + color: #CCC; + } + +footer { + text-align: center; + position: absolute; + padding-top: 6px; + height: 25px; + width: 850px; + bottom: 0; +} + + footer a { + color: #e6e2df; + } + + footer a:hover { + color: #ebf0f2; + } + +.splashTitle { + font-size: 4em; + position: absolute; + top: 25%; + left: 38%; +} + +.pageTitle { + font-size: 3em; + margin-bottom: 20px; + margin-left: -29px; +} + +.pageValidation{ + margin-top: 25px; + margin-bottom: 10px; + display: none; +} + +.mainMenu { + position: absolute; + left: 27%; + top: 34%; + list-style: none; + display: inline; +} + +.mainMenu li { + float: left; +} + +.mainMenu li a { + background-position: center; + display: block; + padding: 105px 15px 10px 15px; + text-align: center; + color: Black; + font-size: 1.1em; + width: 100px; +} + +.createList { + background: url("Images/CreateList.png") no-repeat; +} + +.claimItems { + background: url("Images/ClaimItems.png") no-repeat; +} + +.getGifts{ + background: url("Images/GetGifts.png") no-repeat; +} + +.loginMenu { + position: absolute; + top: 33%; + left: 42%; + margin-bottom: 25px; +} + +.loginMenu li { + float: left; + border-right: 2px solid; + padding: 0 12px 0 12px; +} + +.loginMenu li:last-child { + border-right: none; +} + +h1 { + font-size: 1.6em; +} + +h2 { + font-size: 1.3em; +} + + +/*#endregion*/ +/*#region -----------------------------Primary Tags*/ +a { + color: #577fae; + text-decoration: none; +} + + a:hover { + color: #92a5bc; + } + + a#home { + color: #91a1ab; + } +/*#endregion*/ +/*#region -----------------------------Menu*/ +.nav { + float: left; + list-style: none; + margin-left: -10px; +} + + .nav li { + float: left; + margin-left: 18px; + padding: 0; + } + + .nav li a { + color: #e6e2df; + } + + .nav li a:hover { + color: #ebf0f2; + } +/*#endregion*/ +/*#region -----------------------------Form Layout*/ +form { + margin-top: 20px; +} + +fieldset { + border: none; + margin: 0; + padding: 0; +} + + fieldset legend { + display: none; + } + + fieldset ol { + padding: 0; + list-style: none; + } + + fieldset ol li { + padding-bottom: 5px; + } + + fieldset label { + display: block; + font-size: 1.0em; + font-weight: 600; + } + + fieldset label.checkbox { + display: inline; + } + + fieldset input[type="text"], + fieldset input[type="password"], + fieldset select { + border: 1px solid #e2e2e2; + color: #333; + font-size: 1.0em; + margin: 5px 0 6px 0; + padding: 5px; + width: 300px; + } + + fieldset input[type="text"]:focus, + fieldset input[type="password"]:focus { + border: 1px solid #7ac0da; + } + + fieldset input[type="submit"], .submit { + background-color: #92a5bc; + border: solid 1px #787878; + cursor: pointer; + font-size: 1.2em; + font-weight: 600; + padding: 7px; + margin: 10px 0 15px; + } + + fieldset select { + + } +/*#endregion*/ +/*#region -----------------------------Validation*/ +.message-info { + border: solid 1px; + clear: both; + padding: 20px 20px; + margin: 20px 0 15px; + width: 300px; +} + +.validation-summary-valid { + display: none; +} + +.validation-summary-errors { + clear: both; + display: block; + color: #e80c4d; + font-weight: bold; + padding: 20px 0 10px 0; +} + + .validation-summary-errors span { + font-size: 1.0em; + text-align: left; + } + + .validation-summary-errors li { + font-size: 0.9em; + list-style: disc; + text-align: left; + margin: 2px 0 2px; + } + +.message-success { + color: #0ab317; + font-size: 1.0em; + font-weight: bold; + margin: 20px 0 10px 0; +} + +.error { + color: #e80c4d; +} + +.error-label { + color: #e80c4d; + font-weight: bold; +} + +.error-label + input[type="text"], +.error-label + input[type="password"] { + border: solid 1px #e80c4d; +} + +.field-validation-error { + display: inline; + color: #e80c4d; + font-weight: bold; + font-size: 1.0em; +} + +.field-validation-valid { + display: none; +} +/*#endregion*/ +/*#region -----------------------------Main Lists*/ +.listEntry, .itemEntry { + width: 650px; + height: 80px; + background-color: #92a5bc; + margin: 20px 0 20px 0; + padding: 10px; +} +.listTitle { + font-size: 1.3em; + color: #e6e2df; +} + .listTitle:hover { + color: #e6e2df; + } +.listDescription, .itemDescription { + margin: 7px 25px; +} +.listDefault { + color: #ebf0f2; + float: right; + font-size: 1.0em; +} +.itemTitle { + font-size: 1.3em; +} +.itemClaimed { + color: #ebf0f2; + font-size: 1.1em; + vertical-align: top; +} +.itemPriceTag { + border-top: 17px solid transparent; + border-bottom: 17px solid transparent; + border-right: 17px solid #eae071; + width: 0; + height: 0; + margin: -25px 35px; + float: right; +} +.itemPrice { + background-color: #eae071; + padding: 5px; + float: right; + width: 75px; + margin: -4px -35px; + font-size: 1.5em; + text-indent: -2px; + text-align: right; +} +.itemLink { + font-size: 1.0em; + color: #e6e2df; +} + .itemLink:hover { + color: #e6e2df; + } +.editList { + width: 48px; + height: 48px; + display: block; + float: right; + padding-right: 7px; + background: url("Images/edit.png") no-repeat; +} +.addListItem { + width: 48px; + height: 48px; + display: block; + float: right; + padding-right: 12px; + background: url("Images/add.png") no-repeat; +} +.downloadBlob { + display: block; + float: right; + width: 48px; + height: 48px; + background: url("/Images/download.png") no-repeat; +} +.deleteBlob { + display: block; + float: right; + width: 48px; + height: 48px; + background: url("/Images/delete.png") no-repeat; +} +.blobItem { + clear: both; + width: 650px; + padding: 15px 0 15px; +} +.claimItem { + width: 48px; + height: 48px; + display: block; + float: right; + padding-right: 7px; + background: url("Images/claim.png") no-repeat; +} +.createNewList { + height: 64px; + width: 64px; + background: url("Images/CreateList.png") no-repeat; + display: block; + margin-left: 293px; + text-indent: -9999px; +} +.createNewListText { + margin-left: 287px; + font-size: 1.3em; +} +.noscriptsubmit { + display: block; + float: right; +} +.scriptsubmit { + display: none; + float: right; +} +/*#endregion*/ +/*#region -----------------------------Tables*/ +table th { + padding: 8px; + border: none; + background-color: #dedede; +} +table td { + border: none; + padding: 8px; + background-color: #ffffff; + vertical-align: middle; +} +/*#endregion*/ +/*#region -----------------------------Misc*/ +.jquery-dialog { + display: none; +} + +.imageLink { + border: 0px; +} + +.formActions a { + text-decoration: underline; + padding: 0 3px 0 3px; +} +/*#endregion*/ \ No newline at end of file diff --git a/examples/blobuploader/public/css/reset.css b/examples/blobuploader/public/css/reset.css new file mode 100644 index 000000000000..2096f8ea7d96 --- /dev/null +++ b/examples/blobuploader/public/css/reset.css @@ -0,0 +1,48 @@ +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} +body { + line-height: 1; +} +ol, ul { + list-style: none; +} +blockquote, q { + quotes: none; +} +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} \ No newline at end of file diff --git a/examples/blobuploader/server.js b/examples/blobuploader/server.js new file mode 100644 index 000000000000..df0cc497fd1a --- /dev/null +++ b/examples/blobuploader/server.js @@ -0,0 +1,135 @@ +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var express = require('express'); +var formidable = require('formidable'); +var helpers = require('./helpers.js'); + +var app = module.exports = express.createServer(); +// Global request options, set the retryPolicy +var blobClient = azure.createBlobService(azure.ServiceClient.DEVSTORE_STORAGE_ACCOUNT, azure.ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, azure.ServiceClient.DEVSTORE_BLOB_HOST).withFilter(new azure.ExponentialRetryPolicyFilter()); +var containerName = 'webpi'; + +//Configuration +app.configure(function () { + app.set('views', __dirname + '/views'); + app.set('view engine', 'ejs'); + app.use(express.methodOverride()); + // app.use(express.logger()); + app.use(app.router); + app.use(express.static(__dirname + '/public')); +}); + +app.configure('development', function () { + app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); +}); + +app.configure('production', function () { + app.use(express.errorHandler()); +}); + +app.param(':id', function (req, res, next) { + next(); +}); + +//Routes +app.get('/', function (req, res) { + res.render('index.ejs', { locals: { + title: 'Welcome' + } + }); +}); + +app.get('/Upload', function (req, res) { + res.render('upload.ejs', { locals: { + title: 'Upload File' + } + }); +}); + +app.get('/Display', function (req, res) { + blobClient.listBlobs(containerName, function (error, blobs) { + res.render('display.ejs', { locals: { + title: 'List of Blobs', + serverBlobs: blobs + } + }); + }); +}); + +app.get('/Download/:id', function (req, res) { + blobClient.getBlobProperties(containerName, req.params.id, function (err, blobInfo) { + if (err === null) { + res.header('content-type', blobInfo.contentType); + res.header('content-disposition', 'attachment; filename=' + blobInfo.metadata.filename); + blobClient.getBlobToStream(containerName, req.params.id, res, function () { }); + } else { + helpers.renderError(res); + } + }); +}); + +app.post('/uploadhandler', function (req, res) { + var form = new formidable.IncomingForm(); + + form.parse(req, function (err, fields, files) { + var formValid = true; + if (fields.itemName === '') { + helpers.renderError(res); + formValid = false; + } + + if (formValid) { + var extension = files.uploadedFile.name.split('.').pop(); + var newName = fields.itemName + '.' + extension; + + var options = { + contentType: files.uploadedFile.type, + metadata: { fileName: newName } + }; + + blobClient.createBlockBlobFromFile(containerName, fields.itemName, files.uploadedFile.path, options, function (error) { + if (error != null) { + helpers.renderError(res); + } else { + res.redirect('/Display'); + } + }); + } else { + helpers.renderError(res); + } + }); +}); + +app.post('/Delete/:id', function (req, res) { + blobClient.deleteBlob(containerName, req.params.id, function (error) { + if (error != null) { + helpers.renderError(res); + } else { + res.redirect('/Display'); + } + }); +}); + +blobClient.createContainerIfNotExists(containerName, function (error) { + if (error) { + console.log(error); + } else { + setPermissions(); + } +}); + +function setPermissions() { + blobClient.setContainerAcl(containerName, azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, function (error) { + if (error) { + console.log(error); + } else { + app.listen(process.env.port || 1337); + console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); + } + }); +} \ No newline at end of file diff --git a/examples/blobuploader/views/display.ejs b/examples/blobuploader/views/display.ejs new file mode 100644 index 000000000000..c9b1edcae39b --- /dev/null +++ b/examples/blobuploader/views/display.ejs @@ -0,0 +1,39 @@ + +
+

Blobs Available

+ <% if (serverBlobs.length > 0) { %> + + <% } else { %> + Nothing to see here. Click to upload. + <% } %> +
\ No newline at end of file diff --git a/examples/blobuploader/views/error.ejs b/examples/blobuploader/views/error.ejs new file mode 100644 index 000000000000..ebaf718296b4 --- /dev/null +++ b/examples/blobuploader/views/error.ejs @@ -0,0 +1,4 @@ +
+

Error

+

There was a problem processing your request. Please try again.

+
\ No newline at end of file diff --git a/examples/blobuploader/views/index.ejs b/examples/blobuploader/views/index.ejs new file mode 100644 index 000000000000..e46231e4215a --- /dev/null +++ b/examples/blobuploader/views/index.ejs @@ -0,0 +1,4 @@ +
+

Blob Uploader

+

Use this site to upload to Azure blob storage

+
\ No newline at end of file diff --git a/examples/blobuploader/views/layout.ejs b/examples/blobuploader/views/layout.ejs new file mode 100644 index 000000000000..3097c09b40d1 --- /dev/null +++ b/examples/blobuploader/views/layout.ejs @@ -0,0 +1,30 @@ + + + + <%-title%> + + + + + + + + + +
+
+ +
+
+ <%-body%> +
+ +
+ + \ No newline at end of file diff --git a/examples/blobuploader/views/upload.ejs b/examples/blobuploader/views/upload.ejs new file mode 100644 index 000000000000..55f699cd883c --- /dev/null +++ b/examples/blobuploader/views/upload.ejs @@ -0,0 +1,26 @@ + +
+

Upload file

+
+
+ Upload +
    +
  1. + + + +
  2. + +
+ +
+
+
\ No newline at end of file diff --git a/examples/blog/blog.js b/examples/blog/blog.js new file mode 100644 index 000000000000..b1b172620ae4 --- /dev/null +++ b/examples/blog/blog.js @@ -0,0 +1,91 @@ +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var ServiceClient = azure.ServiceClient; +var TableQuery = azure.TableQuery; +var uuid = require('node-uuid'); + +var tableName = 'posts'; +var partition = 'part1'; + +Blog = function () { + this.tableClient = azure.createTableService(ServiceClient.DEVSTORE_STORAGE_ACCOUNT, ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, ServiceClient.DEVSTORE_TABLE_HOST); +}; + +Blog.prototype.findAll = function (callback) { + var tableQuery = TableQuery.select() + .from(tableName); + + this.tableClient.queryEntities(tableQuery, callback); +}; + +Blog.prototype.findById = function (id, callback) { + this.tableClient.queryEntity(tableName, partition, id, callback); +}; + +Blog.prototype.destroy = function (id, callback) { + var entity = { PartitionKey: partition, RowKey: id }; + this.tableClient.deleteEntity(tableName, entity, callback); +}; + +Blog.prototype.save = function (posts, callback) { + if (!Array.isArray(posts)) { + posts = [posts]; + } + + this.savePosts(posts, callback); +}; + +// this could be implemented using batch but for the sake of using both methods use the individual requests + callback. +Blog.prototype.savePosts = function (posts, callback) { + if (posts.length === 0) { + callback(); + } + else { + var post = posts.pop(); + post.created_at = new Date(); + + if (post.comments === undefined) + post.comments = []; + + for (var j = 0; j < post.comments.length; j++) { + post.comments[j].created_at = new Date(); + } + + post.PartitionKey = partition; + post.RowKey = uuid(); + + var provider = this; + this.tableClient.insertEntity(tableName, post, function () { + // Insert remaining posts recursively + provider.savePosts(posts, callback); + }); + } +}; + +Blog.prototype.init = function () { + var provider = this; + this.tableClient.createTableIfNotExists(tableName, function (err, created) { + if (created) { + console.log('Setting up demo data ...'); + + provider.tableClient.beginBatch(); + + var now = new Date().toString(); + provider.tableClient.insertEntity(tableName, { PartitionKey: partition, RowKey: uuid(), title: 'Post one', body: 'Body one', created_at: now }); + provider.tableClient.insertEntity(tableName, { PartitionKey: partition, RowKey: uuid(), title: 'Post two', body: 'Body two', created_at: now }); + provider.tableClient.insertEntity(tableName, { PartitionKey: partition, RowKey: uuid(), title: 'Post three', body: 'Body three', created_at: now }); + provider.tableClient.insertEntity(tableName, { PartitionKey: partition, RowKey: uuid(), title: 'Post four', body: 'Body four', created_at: now }); + + provider.tableClient.commitBatch(function () { + console.log('Done'); + }); + } + }); +}; + +exports.Blog = Blog; diff --git a/examples/blog/package.json b/examples/blog/package.json new file mode 100644 index 000000000000..6927967d7937 --- /dev/null +++ b/examples/blog/package.json @@ -0,0 +1,12 @@ +{ + "name": "application-name" + , "version": "0.0.1" + , "private": true + , "dependencies": { + "express": ">= 2.4.7" + , "stylus": ">= 0.0.1" + , "ejs": ">= 0.4.3" + , "node-uuid": ">= 1.2.0" + , "azure": ">= 0.5.1" + } +} diff --git a/examples/blog/public/stylesheets/style.css b/examples/blog/public/stylesheets/style.css new file mode 100644 index 000000000000..39249d3d45f3 --- /dev/null +++ b/examples/blog/public/stylesheets/style.css @@ -0,0 +1,68 @@ +body { + font-family: Tahoma, "Helvetica Neue", Arial, Helvetica, sans-serif; + font-size: 13px; + text-stroke: 1px rgba(255,255,255,0.10); + color: #555; + background-color: #f3f4f5; +} +h1, +h2 { + margin: 0; + font-size: 22px; + color: #343434; +} +h1 { + font-size: 60px; + text-align: center; + margin-bottom: 20px; +} +#posts { + margin-bottom: 20px; + margin-left: auto; + margin-right: auto; + background-color: #fff; + width: 80%; +} +#posts #newPost { + float: right; + padding-top: 20px; + padding-bottom: 20px; +} +#posts #deletePost { + float: right; +} +#posts .post { + border-style: solid; + border-width: 1px; + border-color: #d3d2d2; + padding: 20px; +} +#posts .post .created_at { + font-size: 10px; + padding-bottom: 5px; +} +#posts .post .title { + font-weight: bold; + text-decoration: underline; + padding-bottom: 5px; +} +.post { + border-style: solid; + border-width: 1px; + border-color: #d3d2d2; + padding: 20px; + background-color: #fff; +} +.post #editPostSubmitDiv { + padding-top: 20px; +} +.post #editPostTitle { + width: 300px; +} +.post #editPostBodyDiv { + padding-top: 20px; +} +.post #editPostBody { + width: 100%; + height: 90px; +} diff --git a/examples/blog/public/stylesheets/style.styl b/examples/blog/public/stylesheets/style.styl new file mode 100644 index 000000000000..c3b2a9d6129b --- /dev/null +++ b/examples/blog/public/stylesheets/style.styl @@ -0,0 +1,66 @@ +body + font-family Tahoma, "Helvetica Neue", Arial, Helvetica, sans-serif + font-size 13px + text-stroke 1px rgba(255, 255, 255, 0.1) + color #555 + background-color #F3F4F5 + +h1, h2 + margin 0 + font-size 22px + color #343434 + +h1 + font-size 60px + text-align center + margin-bottom 20px + +#posts + margin-bottom 20px + margin-left auto + margin-right auto + background-color #fff + width 80% + + #newPost + float right + padding-top 20px + padding-bottom 20px + + #deletePost + float right + + .post + border-style solid; + border-width 1px + border-color #D3D2D2 + padding 20px + + .created_at + font-size 10px + padding-bottom 5px + + .title + font-weight bold + text-decoration underline + padding-bottom 5px + +.post + border-style solid + border-width 1px + border-color #D3D2D2 + padding 20px + background-color #fff + + #editPostSubmitDiv + padding-top 20px + + #editPostTitle + width 300px + + #editPostBodyDiv + padding-top 20px + + #editPostBody + width 100% + height 90px \ No newline at end of file diff --git a/examples/blog/server.js b/examples/blog/server.js new file mode 100644 index 000000000000..180d4e8c5b9f --- /dev/null +++ b/examples/blog/server.js @@ -0,0 +1,79 @@ +// Based on: +// http://howtonode.org/express-mongodb + +var express = require('express'); +var Blog = require('./blog').Blog; + +var app = module.exports = express.createServer(); + +// Configuration + +app.configure(function () { + app.set('views', __dirname + '/views'); + app.set('view engine', 'ejs'); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(require('stylus').middleware({ src: __dirname + '/public' })); + app.use(app.router); + app.use(express.static(__dirname + '/public')); +}); + +app.configure('development', function () { + app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); +}); + +app.configure('production', function () { + app.use(express.errorHandler()); +}); + +// Routes + +var blog = new Blog(); +blog.init(); + +app.get('/', function (req, res) { + blog.findAll(function (error, posts) { + res.render('index.ejs', { locals: { + title: 'Blog', + posts: posts + } + }); + }); +}); + +app.get('/blog/new', function (req, res) { + res.render('blog_new.ejs', { locals: { + title: 'New Blog Post' + } + }); +}); + +app.post('/blog/new', function (req, res) { + blog.save({ + title: req.param('title'), + body: req.param('body') + }, + function () { + res.redirect('/'); + }); +}); + +app.get('/blog/delete/:id', function (req, res) { + blog.destroy(req.params.id, function () { + res.redirect('/'); + }); +}); + +app.get('/blog/:id', function (req, res) { + blog.findById(req.params.id, function (error, post) { + res.render('blog_show.ejs', { + locals: { + title: post.title, + post: post + } + }); + }); +}); + +app.listen(process.env.port || 1337); +console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); diff --git a/examples/blog/views/blog_new.ejs b/examples/blog/views/blog_new.ejs new file mode 100644 index 000000000000..b32db8aaab2b --- /dev/null +++ b/examples/blog/views/blog_new.ejs @@ -0,0 +1,19 @@ +

+ <%-title%> +

+
+
+
+
Title
+ +
+
+
Body
+ +
+
+ +
+ +
+
\ No newline at end of file diff --git a/examples/blog/views/blog_show.ejs b/examples/blog/views/blog_show.ejs new file mode 100644 index 000000000000..f08ab7458c90 --- /dev/null +++ b/examples/blog/views/blog_show.ejs @@ -0,0 +1,17 @@ +

+ <%-title%> +

+
+ <% if (post.created_at) {%> +
+

+ Posted on: <%-post.created_at%> +

+
+ <% }%> +
+

+ <%-post.body%> +

+
+
\ No newline at end of file diff --git a/examples/blog/views/index.ejs b/examples/blog/views/index.ejs new file mode 100644 index 000000000000..04fdc179191e --- /dev/null +++ b/examples/blog/views/index.ejs @@ -0,0 +1,31 @@ +

+ <%-title%> +

+ +
+ <% posts.forEach(function(post){ %> +
+ + + <% if (post.created_at) {%> +
+ Posted on: <%-post.created_at%> +
+ <% }%> + +
+

+ <%-post.body%> +

+
+ + Delete +
+ <% }) %> + + New blog post +
\ No newline at end of file diff --git a/examples/blog/views/layout.ejs b/examples/blog/views/layout.ejs new file mode 100644 index 000000000000..afd73111abfd --- /dev/null +++ b/examples/blog/views/layout.ejs @@ -0,0 +1,8 @@ + + + + + + <%-body%> + + \ No newline at end of file diff --git a/examples/geophoto/controllers/pushpinController.js b/examples/geophoto/controllers/pushpinController.js new file mode 100644 index 000000000000..5f0578207de9 --- /dev/null +++ b/examples/geophoto/controllers/pushpinController.js @@ -0,0 +1,134 @@ +var util = require('util'); +var fs = require('fs'); +var nconf = require('nconf'); + +nconf.file({ file: 'config.json' }); + +var PushpinService = require('../services/pushpinService'); + +var initialized = false; +var pushpinService = new PushpinService(nconf.get('AZURE_STORAGE_ACCOUNT'), nconf.get('AZURE_STORAGE_ACCESS_KEY')); + +exports.io = null; + +exports.setup = function (request, response) { + response.render('setup'); +}; + +exports.setupPOST = function (request, response) { + var showError = function (message) { + // TODO: actually show the error message + response.render('setup'); + }; + + if (request.body.account && + request.body.accessKey && + request.body.bingMapsCredentials) { + + nconf.set('AZURE_STORAGE_ACCOUNT', request.body.account); + nconf.set('AZURE_STORAGE_ACCESS_KEY', request.body.accessKey); + nconf.set('BING_MAPS_CREDENTIALS', request.body.bingMapsCredentials); + + nconf.save(function (error) { + if (error) { + showError(error); + } else { + response.redirect('/'); + } + }); + } else { + showError(); + } +}; + +exports.showPushpins = function (request, response) { + var action = function (error) { + if (error) { + renderPushpins(error); + } else { + initialized = true; + pushpinService.listPushpins(renderPushpins); + } + }; + + var renderPushpins = function (error, entities) { + response.render('index', { + locals: { + error: error, + pushpins: entities, + bingMapsCredentials: nconf.get('BING_MAPS_CREDENTIALS') + } + }); + }; + + if (!exports.isConfigured()) { + response.redirect('/setup'); + } else if (!initialized) { + pushpinService.initialize(action); + } else { + action(); + } +}; + +exports.createPushpin = function (request, response) { + var action = function (error) { + if (!error) { + initialized = true; + } + + var pushpinData = request.body; + var pushpinImage = null; + + if (request.files && request.files.image && request.files.image.size > 0) { + pushpinImage = request.files.image; + } + + pushpinService.createPushpin(pushpinData, pushpinImage, function (createPushpinError) { + if (createPushpinError) { + response.writeHead(500, { 'Content-Type': 'text/plain' }); + response.end(JSON.stringify(util.inspect(createPushpinError))); + } else { + exports.io.sockets.emit('addPushpin', pushpinData); + + response.redirect('/'); + } + }); + }; + + if (!exports.isConfigured()) { + response.redirect('/setup'); + } else if (!initialized) { + pushpinService.initialize(action); + } else { + action(); + } +}; + +exports.socketConnection = function(socket) { + socket.on('removePushpin', function(pushpin) { + pushpinService.removePushpin(pushpin, function(error) { + if (!error) { + exports.io.sockets.emit('removePushpin', pushpin); + socket.emit('removePushpin', pushpin); + } + }); + }); + + socket.on('clearPushpins', function() { + pushpinService.clearPushpins(function(error) { + initialized = false; + if (!error) { + exports.io.sockets.emit('clearPushpins'); + socket.emit('clearPushpins'); + } + }); + }); +}; + +exports.isConfigured = function () { + if (nconf.get('AZURE_STORAGE_ACCOUNT')) { + return true; + } + + return false; +}; \ No newline at end of file diff --git a/examples/geophoto/package.json b/examples/geophoto/package.json new file mode 100644 index 000000000000..b56cf099d35c --- /dev/null +++ b/examples/geophoto/package.json @@ -0,0 +1,12 @@ +{ + "name": "geophoto" + , "version": "0.0.1" + , "dependencies": { + "azure": ">= 0.5.1" + , "express": "2.5.1" + , "ejs": ">= 0.0.1" + , "socket.io": "0.8.7" + , "node-uuid": ">= 1.3.3" + , "nconf": ">= 0.5.1" + } +} diff --git a/examples/geophoto/project/geophoto.csproj b/examples/geophoto/project/geophoto.csproj new file mode 100644 index 000000000000..859b2c24ca82 --- /dev/null +++ b/examples/geophoto/project/geophoto.csproj @@ -0,0 +1,78 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {4D635B79-E016-4B28-B9BD-FB435DBE5A28} + Exe + Properties + geophoto + geophoto + v4.0 + Client + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + package.json + + + Views\layout.ejs + + + Web.cloud.config + + + Web.config + + + + + controllers\pushpinController.js + + + public\scripts\geophoto.js + + + public\stylesheets\style.css + + + server.js + + + services\pushpinService.js + + + + + + + + \ No newline at end of file diff --git a/examples/geophoto/project/geophoto.sln b/examples/geophoto/project/geophoto.sln new file mode 100644 index 000000000000..91f003d25a95 --- /dev/null +++ b/examples/geophoto/project/geophoto.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "geophoto", "geophoto.csproj", "{4D635B79-E016-4B28-B9BD-FB435DBE5A28}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4D635B79-E016-4B28-B9BD-FB435DBE5A28}.Debug|x86.ActiveCfg = Debug|x86 + {4D635B79-E016-4B28-B9BD-FB435DBE5A28}.Debug|x86.Build.0 = Debug|x86 + {4D635B79-E016-4B28-B9BD-FB435DBE5A28}.Release|x86.ActiveCfg = Release|x86 + {4D635B79-E016-4B28-B9BD-FB435DBE5A28}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/examples/geophoto/public/scripts/geophoto.js b/examples/geophoto/public/scripts/geophoto.js new file mode 100644 index 000000000000..2c4c6d378d87 --- /dev/null +++ b/examples/geophoto/public/scripts/geophoto.js @@ -0,0 +1,233 @@ +var map; +var socket; + +var newPushpin; + +var currentPushpin; +var currentPushpinInfobox; + +var pushpins = []; + +function initialize() { + initializeMaps(); + initializeSockets(); + initializeInputs(); +} + +function initializeMaps() { + map = new Microsoft.Maps.Map(document.getElementById('map'), { + credentials: bingMapsCredentials, + center: new Microsoft.Maps.Location(47.6, -122.2), + zoom: 8 + }); + + Microsoft.Maps.Events.addHandler(map, 'click', openPushpinDialog); + + if (initialPushpins) { + addPushpins(initialPushpins); + } +} + +function initializeSockets() { + socket = io.connect(); + + socket.on('addPushpin', function (pushpin) { + addPushpin(pushpin); + }); + + socket.on('removePushpin', function(entity) { + removePushpin(entity); + }); + + socket.on('clearPushpins', function () { + clearPushpins(); + }); +} + +function initializeInputs() { + $('#clearButton').click(emitClearPushpins); +} + +function addPushpins(pushpinList) { + for (var pushpin in pushpinList) { + var currentPushpin = pushpinList[pushpin]; + addPushpin(currentPushpin); + } +} + +function addPushpin(pushpin) { + var previousPushpin = findPushpinData(pushpin.latitude, pushpin.longitude); + if (!previousPushpin) { + var mapPushpin = new Microsoft.Maps.Pushpin(pushpin, null); + attachInfobox(mapPushpin); + map.entities.push(mapPushpin); + pushpins.push(pushpin); + } +} + +function openPushpinDialog(event) { + if (event.targetType === 'map') { + if (currentPushpinInfobox) { + if (currentPushpin) { + currentPushpin = null; + } + + map.entities.remove(currentPushpinInfobox); + currentPushpinInfobox = null; + } else { + if (newPushpin) { + map.entities.remove(newPushpin); + newPushpin = null; + } + + if (currentPushpin) { + currentPushpin = null; + } + + if (currentPushpinInfobox) { + map.entities.remove(currentPushpinInfobox); + currentPushpinInfobox = null; + } + + // Set location into the dialog form + var point = new Microsoft.Maps.Point(event.getX(), event.getY()); + var location = event.target.tryPixelToLocation(point); + + $("#title").val(''); + $("#description").val(''); + $("#latitude").val(location.latitude); + $("#longitude").val(location.longitude); + + // Add pushpin + newPushpin = new Microsoft.Maps.Pushpin(location, null); + map.entities.push(newPushpin); + + // Open dialog to add the pushpin + $("#map-dialog").dialog({ + autoOpen: true, + modal: true, + width: 500, + height: 350, + resizable: true, + buttons: { + Save: savePushpin, + Cancel: cancelPushpin + }, + close: closePushpin + }); + } + } +} + +function savePushpin() { + $('#addPushpinForm').submit(); +} + +function cancelPushpin() { + map.entities.remove(newPushpin); + $(this).dialog("close"); +} + +function closePushpin() { + map.entities.remove(newPushpin); +} + +function clearPushpins() { + map.entities.clear(); + pushpins = []; + newPushpin = null; + currentPushpin = null; + currentPushpinInfobox = null; +} + +function emitRemovePushpin() { + socket.emit('removePushpin', currentPushpin); +} + +function emitClearPushpins() { + socket.emit('clearPushpins'); +} + +function removePushpin(pushpinData) { + var pushpinEntry = findPushpinData(pushpinData.latitude, pushpinData.longitude); + if (pushpinEntry) { + removeByElement(pushpins, pushpinEntry); + + var pushpin = findPushpin(pushpinData.latitude, pushpinData.longitude); + if (pushpin) { + map.entities.remove(pushpin); + } + + if (currentPushpinInfobox) { + map.entities.remove(currentPushpinInfobox); + currentPushpinInfobox = null; + } + } +} + +function attachInfobox(pushpin) { + Microsoft.Maps.Events.addHandler(pushpin, 'click', showPushpinInfo); +} + +function showPushpinInfo(event) { + if (event.targetType == "pushpin") { + var pushpin = event.target; + currentPushpin = findPushpinData(pushpin.getLocation().latitude, pushpin.getLocation().longitude); + if (currentPushpin) { + if (currentPushpinInfobox) { + map.entities.remove(currentPushpinInfobox); + currentPushpinInfobox = null; + } + + var infoboxOptions = { + title: currentPushpin.title, + description: currentPushpin.description, + width: 250, + height: 300, + offset: new Microsoft.Maps.Point(0, 40), + actions: [{ label: 'Remove', eventHandler: emitRemovePushpin }] + }; + + infoboxOptions.description = '

' + currentPushpin.description + '

'; + + if (currentPushpin.imageUrl) { + infoboxOptions.description += ''; + } else { + infoboxOptions.description += '

No image.

'; + } + + currentPushpinInfobox = new Microsoft.Maps.Infobox(pushpin.getLocation(), infoboxOptions); + map.entities.push(currentPushpinInfobox); + } + } +} + +function findPushpinData(latitude, longitude) { + for (var i = 0; i < pushpins.length; i++) { + if (latitude == pushpins[i].latitude && + longitude == pushpins[i].longitude) { + return pushpins[i]; + } + } + + return null; +} + +function findPushpin(latitude, longitude) { + for (var i = 0; i < map.entities.getLength(); i++) { + if (latitude == map.entities.get(i).getLocation().latitude && + longitude == map.entities.get(i).getLocation().longitude) { + return map.entities.get(i); + } + } + + return null; +} + +function removeByElement(arrayName, arrayElement) { + for (var i = 0; i < arrayName.length; i++) { + if (arrayName[i] === arrayElement) { + arrayName.splice(i, 1); + } + } +} \ No newline at end of file diff --git a/examples/geophoto/public/stylesheets/style.css b/examples/geophoto/public/stylesheets/style.css new file mode 100644 index 000000000000..52f4f4ea206c --- /dev/null +++ b/examples/geophoto/public/stylesheets/style.css @@ -0,0 +1,30 @@ +#map { + display: block; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} + +#map-dialog fieldset { + border: 0px; +} + +#map-dialog input, #map-dialog textarea { + width: 100%; +} + +#buttonDiv { + display: block; + position: absolute; + top: 20px; + right: 20px; + width: 100px; + height: 50px; + z-index: 2; +} + +#buttonDiv input { + width: 100%; +} \ No newline at end of file diff --git a/examples/geophoto/server.js b/examples/geophoto/server.js new file mode 100644 index 000000000000..40f90d05729e --- /dev/null +++ b/examples/geophoto/server.js @@ -0,0 +1,44 @@ +/** +* Module dependencies. +*/ + +var express = require('express') + , pushpinController = require('./controllers/pushpinController') + , socketio = require('socket.io'); + +var app = module.exports = express.createServer(); +var io; + +// Configuration + +app.configure(function () { + app.set('views', __dirname + '/views'); + app.set('view engine', 'ejs'); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(express.static(__dirname + '/public')); +}); + +app.configure('development', function () { + app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); +}); + +app.configure('production', function () { + app.use(express.errorHandler()); +}); + +// Routes +app.get('/', pushpinController.showPushpins); +app.get('/setup', pushpinController.setup); +app.post('/setupPOST', pushpinController.setupPOST); +app.post('/createPushpin', pushpinController.createPushpin); + +app.listen(process.env.PORT || 1337); +console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); + +// Setup socket.io +io = socketio.listen(app); +pushpinController.io = io; +io.set('transports', [ 'xhr-polling' ]); +io.sockets.on('connection', pushpinController.socketConnection); \ No newline at end of file diff --git a/examples/geophoto/services/pushpinService.js b/examples/geophoto/services/pushpinService.js new file mode 100644 index 000000000000..c9b56a29f7b5 --- /dev/null +++ b/examples/geophoto/services/pushpinService.js @@ -0,0 +1,131 @@ +var azure = require('azure'); +var uuid = require('node-uuid'); + +var ServiceClient = azure.ServiceClient; + +// Table service 'constants' +var TABLE_NAME = 'pushpins'; +var DEFAULT_PARTITION = 'pushpins'; + +// Blob service 'constants' +var CONTAINER_NAME = 'pushpins'; + +// Expose 'PushpinService'. +exports = module.exports = PushpinService; + +function PushpinService(storageAccount, storageAccessKey) { + this.tableClient = azure.createTableService(storageAccount, storageAccessKey); + this.blobClient = azure.createBlobService(storageAccount, storageAccessKey); +} + +PushpinService.prototype.initialize = function (callback) { + var self = this; + + var createContainer = function () { + // create blob container if it doesnt exist + self.blobClient.createContainerIfNotExists(CONTAINER_NAME, function (createContainerError, created) { + if (createContainerError) { + callback(createContainerError); + } else if (created) { + self.blobClient.setContainerAcl(CONTAINER_NAME, + azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, + callback); + } else { + callback(); + } + }); + }; + + // create table if it doesnt exist + self.tableClient.createTableIfNotExists(TABLE_NAME, function (createTableError) { + if (createTableError) { + callback(createTableError); + } else { + createContainer(); + } + }); +}; + +PushpinService.prototype.createPushpin = function (pushpinData, pushpinImage, callback) { + var self = this; + var rowKey = 'row' + uuid(); + + function insertEntity(error, blob) { + var entity = pushpinData; + entity.RowKey = rowKey; + entity.PartitionKey = DEFAULT_PARTITION; + + if (blob) { + entity.imageUrl = self.blobClient.getBlobUrl(blob.container, blob.blob).url(); + } + + self.tableClient.insertEntity(TABLE_NAME, entity, callback); + }; + + if (pushpinImage) { + self.blobClient.createBlockBlobFromFile(CONTAINER_NAME, rowKey, pushpinImage.path, insertEntity); + } else { + insertEntity(); + } +}; + +PushpinService.prototype.listPushpins = function (callback) { + var self = this; + var tableQuery = azure.TableQuery + .select() + .from(TABLE_NAME); + + self.tableClient.queryEntities(tableQuery, callback); +}; + +PushpinService.prototype.removePushpin = function (pushpin, callback) { + var self = this; + var tableQuery = azure.TableQuery + .select() + .from(TABLE_NAME) + .where('latitude == ? && longitude == ?', pushpin.latitude, pushpin.longitude); + + self.tableClient.queryEntities(tableQuery, function (error, pushpins) { + if (error) { + callback(error); + } else if (pushpins && pushpins.length > 0) { + self.tableClient.deleteEntity(TABLE_NAME, pushpins[0], callback); + } else { + callback(); + } + }); +}; + +PushpinService.prototype.clearPushpins = function (callback) { + var self = this; + var deleteEntities = function (entities) { + if (entities && entities.length > 0) { + var currentEntity = entities.pop(); + self.tableClient.deleteEntity(TABLE_NAME, currentEntity, function (deleteError) { + if (deleteError) { + callback(error); + } else if (currentEntity.imageUrl) { + self.blobClient.deleteBlob(CONTAINER_NAME, currentEntity.RowKey, function (deleteBlobError) { + if (deleteBlobError) { + callback(deleteBlobError); + } else { + deleteEntities(entities); + } + }); + } else { + deleteEntities(entities); + } + }); + } else { + callback(); + } + }; + + exports.listPushpins(function (error, entities) { + if (error) { + callback(error); + } else { + deleteEntities(entities); + } + }); +}; \ No newline at end of file diff --git a/examples/geophoto/views/index.ejs b/examples/geophoto/views/index.ejs new file mode 100644 index 000000000000..b0818f3587ec --- /dev/null +++ b/examples/geophoto/views/index.ejs @@ -0,0 +1,21 @@ +
+
+
+
+
+
+
+
+ + + + +
+
+
+ +
+ +
+ +
\ No newline at end of file diff --git a/examples/geophoto/views/layout.ejs b/examples/geophoto/views/layout.ejs new file mode 100644 index 000000000000..0b5c82cb024a --- /dev/null +++ b/examples/geophoto/views/layout.ejs @@ -0,0 +1,31 @@ + + + + Geophoto + + + + + + + + + + + + + + + + + + <%- body %> + + \ No newline at end of file diff --git a/examples/geophoto/views/setup.ejs b/examples/geophoto/views/setup.ejs new file mode 100644 index 000000000000..92ef17ff920e --- /dev/null +++ b/examples/geophoto/views/setup.ejs @@ -0,0 +1,14 @@ +
+
+
+
+ +
+
+ +
+
+ + +
+
\ No newline at end of file diff --git a/examples/myevents/README.md b/examples/myevents/README.md new file mode 100644 index 000000000000..55ba2081188a --- /dev/null +++ b/examples/myevents/README.md @@ -0,0 +1,5 @@ +# My Events Sample # + +This is the code used in the following video: + +http://channel9.msdn.com/Events/windowsazure/learn/Node-JS-in-Windows-Azure \ No newline at end of file diff --git a/examples/myevents/eventService.js b/examples/myevents/eventService.js new file mode 100644 index 000000000000..8b8bf2d7506b --- /dev/null +++ b/examples/myevents/eventService.js @@ -0,0 +1,101 @@ +var azure = require('./../../lib/azure') + , uuid = require('node-uuid'); +module.exports = EventService; + +function EventService (tableClient, blobClient) { + this.tableClient = tableClient; + this.blobClient = blobClient; +}; + +EventService.prototype = { + + showEvents: function(req, res) { + var self = this; + this.getEvents(function (resp, eventList) { + if (!eventList) { + eventList = []; + } + self.showResults(res, eventList); + }); + }, + + showEvent: function(req, res) { + var self = this; + this.getEvent(req.params.id, function(resp, eventItem) { + if (!eventItem) { + res.render('error', { + title: "Error", + message: 'Event ' + req.params.id + ' not found.' + }); + } else { + res.render('detail', { + title: eventItem.name, + eventItem: eventItem, + imageUrl: self.blobClient.getBlobUrl('photos', eventItem.RowKey).url(), + }); + } + }); + }, + + getEvents: function(callback) { + var query = azure.TableQuery + .select() + .from('events'); + + this.tableClient.queryEntities(query, callback); + }, + + getEvent: function(id, callback) { + this.tableClient.queryEntity('events', 'myEvents', id, callback); + }, + + showResults: function (res, eventList) { + res.render('index', { + title: 'My Events', + eventList: eventList + }); + }, + + newEvent: function(req, res) { + var self = this; + + var createEvent = function(resp, eventList) { + if (!eventList) { + eventList = []; + } + + var count = eventList.length; + + var item = req.body.item; + item.RowKey = uuid(); + item.PartitionKey = 'myEvents'; + + self.tableClient.insertEntity('events', item, function(error) { + if (error) { + console.log(error); + throw error; + } + + console.log('event created, uploading photo.'); + + var options = { + contentType: req.files.item.file.type, + metadata: { fileName: item.RowKey } + }; + + self.blobClient.createBlockBlobFromFile('photos', item.RowKey, req.files.item.file.path, options, function (error1, blockBlob, response) { + if (error1) { + throw error; + } else { + console.log(JSON.stringify(blockBlob)); + res.redirect('/'); + } + }); + + + }); + }; + + this.getEvents(createEvent); + }, +}; diff --git a/examples/myevents/package.json b/examples/myevents/package.json new file mode 100644 index 000000000000..e79c1de45b46 --- /dev/null +++ b/examples/myevents/package.json @@ -0,0 +1,10 @@ +{ + "name": "application-name" + , "version": "0.0.1" + , "private": true + , "dependencies": { + "express": "2.5.1" + , "ejs": ">= 0.0.1" + , "node-uuid": ">= 1.3.3" + } +} diff --git a/examples/myevents/server.js b/examples/myevents/server.js new file mode 100644 index 000000000000..8042c63fbb9f --- /dev/null +++ b/examples/myevents/server.js @@ -0,0 +1,62 @@ + +/** + * Module dependencies. + */ + +var express = require('express') + , EventService = require('./eventService') + , azure = require('./../../lib/azure') + , ServiceClient = azure.ServiceClient; + +var app = module.exports = express.createServer(); + + +var tableClient = azure.createTableService(ServiceClient.DEVSTORE_STORAGE_ACCOUNT, ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, ServiceClient.DEVSTORE_TABLE_HOST); +var blobClient = azure.createBlobService(azure.ServiceClient.DEVSTORE_STORAGE_ACCOUNT, azure.ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, azure.ServiceClient.DEVSTORE_BLOB_HOST).withFilter(new azure.ExponentialRetryPolicyFilter()); + +// Create table and blob +tableClient.createTableIfNotExists('events', function(error) { + if (error) { + throw error; + } +}); +blobClient.createContainerIfNotExists('photos', function(error) { + if (error) { + throw error; + } + blobClient.setContainerAcl('photos', azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, function (error1) { + if (error1) { + throw error1; + } + }); +}); + + +// Configuration + +app.configure(function(){ + app.set('views', __dirname + '/views'); + app.set('view engine', 'ejs'); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(express.static(__dirname + '/public')); +}); + +app.configure('development', function(){ + app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); +}); + +app.configure('production', function(){ + app.use(express.errorHandler()); +}); + +// Routes + +var eventService = new EventService(tableClient, blobClient); +app.get('/', eventService.showEvents.bind(eventService)); +app.post('/events/create', eventService.newEvent.bind(eventService)); +app.get('/events/:id', eventService.showEvent.bind(eventService)) + +app.listen(process.env.PORT || 1337); +console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); diff --git a/examples/myevents/views/detail.ejs b/examples/myevents/views/detail.ejs new file mode 100644 index 000000000000..5a83b734ffc0 --- /dev/null +++ b/examples/myevents/views/detail.ejs @@ -0,0 +1,4 @@ +

<%= eventItem.name %> on <%= eventItem.date %>

+ +

<%= eventItem.description %>

+ \ No newline at end of file diff --git a/examples/myevents/views/error.ejs b/examples/myevents/views/error.ejs new file mode 100644 index 000000000000..7f66ead80d00 --- /dev/null +++ b/examples/myevents/views/error.ejs @@ -0,0 +1,2 @@ +

<%= title %>

+

<%= message %>

\ No newline at end of file diff --git a/examples/myevents/views/index.ejs b/examples/myevents/views/index.ejs new file mode 100644 index 000000000000..94aabb0dfedf --- /dev/null +++ b/examples/myevents/views/index.ejs @@ -0,0 +1,36 @@ +

<%= title %>

+ +

My upcoming events:

+ +<% if (eventList.length == 0) {%> +

No Events found.

+<% } else { %> + +<% } %> + +

Create a new Event:

+
+ + + + + + + + + + + + + + + + + +
+ +
\ No newline at end of file diff --git a/examples/myevents/views/layout.ejs b/examples/myevents/views/layout.ejs new file mode 100644 index 000000000000..fd239dc2ed11 --- /dev/null +++ b/examples/myevents/views/layout.ejs @@ -0,0 +1,13 @@ + + + + <%= title %> + + +
+
+ <%- body %> +
+
+ + \ No newline at end of file diff --git a/examples/samples/blobuploaddownloadsample.js b/examples/samples/blobuploaddownloadsample.js new file mode 100644 index 000000000000..e3c30a594bbb --- /dev/null +++ b/examples/samples/blobuploaddownloadsample.js @@ -0,0 +1,225 @@ +/** +* 1. Demonstrates how to upload all files from a given directory in parallel +* +* 2. Demonstrates how to download all files from a given blob container to a given destination directory. +* +* 3. Demonstrate making requests using AccessConditions. +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; + +var util = require('util'); +var fs = require('fs'); + +var container = 'updownsample'; +var blob = 'updownsample'; +var blobAccess = 'updownaccesssample'; + +var blobService = azure.createBlobService(); + +var processArguments = process.argv; + +function createContainer() { + // Step 0: Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the container ' + container); + uploadSample(); + } + }); +} + +function uploadSample() { + // Sample 1 : Demonstrates how to upload all files from a given directoy + uploadBlobs(processArguments[2], container, function () { + + // Sample 2 : Demonstrates how to download all files from a given + // blob container to a given destination directory. + downloadBlobs(container, processArguments[3], function () { + + // Sample 3 : Demonstrate making requests using AccessConditions. + requestAccessConditionSample(container); + }); + }); +} + +function uploadBlobs(sourceDirectoryPath, containerName, callback) { + // Step 0 : validate directory is valid. + if (!path.existsSync(sourceDirectoryPath)) { + console.log(sourceDirectoryPath + ' is an invalid directory path.'); + } else { + listFilesUpload(sourceDirectoryPath, containerName, callback); + } +} + +function listFilesUpload(sourceDirectoryPath, containerName, callback) { + // Step 1 : Search the directory and generate a list of files to upload. + walk(sourceDirectoryPath, function (error, files) { + if (error) { + console.log(error); + } else { + uploadFilesParallel(files, containerName, callback); + } + }); +} + +function uploadFilesParallel(files, containerName, callback) { + var finished = 0; + + // Step 3 : generate and schedule an upload for each file + files.forEach(function (file) { + var blobName = file.replace(/^.*[\\\/]/, ''); + + blobService.createBlockBlobFromFile(containerName, blobName, file, function (error) { + finished++; + + if (error) { + console.log(error); + } else { + console.log('Blob ' + blobName + ' upload finished.'); + + if (finished === files.length) { + // Step 4 : Wait until all workers complete and the blobs are uploaded + // to the server. + console.log('All files uploaded'); + callback(); + } + } + }); + }); +} + +function downloadBlobs(containerName, destinationDirectoryPath, callback) { + // Step 0. Validate directory + if (!path.existsSync(destinationDirectoryPath)) { + console.log(destinationDirectoryPath + ' is an invalid directory path.'); + } else { + downloadFilesParallel(containerName, destinationDirectoryPath, callback); + } +} + +function downloadFilesParallel(containerName, destinationDirectoryPath, callback) { + // NOTE: does not handle pagination. + blobService.listBlobs(containerName, function (error, blobs) { + if (error) { + console.log(error); + } else { + var blobsDownloaded = 0; + + blobs.forEach(function (blob) { + blobService.getBlobToFile(containerName, blob.name, destinationDirectoryPath + '/' + blob.name, function (error2) { + blobsDownloaded++; + + if (error2) { + console.log(error2); + } else { + console.log('Blob ' + blob.name + ' download finished.'); + + if (blobsDownloaded === blobs.length) { + // Step 4 : Wait until all workers complete and the blobs are downloaded + console.log('All files downloaded'); + callback(); + } + } + }); + }); + } + }); +} + +function requestAccessConditionSample(containerName) { + // Step 1: Create a blob. + blobService.createBlockBlobFromText(containerName, blobAccess, 'hello', function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the blob ' + blobAccess); + downloadBlobProperties(containerName, blobAccess); + } + }); +} + +function downloadBlobProperties(containerName, blobName) { + // Step 2 : Download the blob attributes to get the ETag. + blobService.getBlobProperties(containerName, blobName, function (error, blob) { + if (error) { + console.log(error); + } else { + console.log('Blob Etag is: ' + blob.etag); + testAccess(containerName, blobName, blob.etag); + } + }); +} + +function testAccess(containerName, blobName, etag) { + // Step 2: Use the If-not-match ETag condition to access the blob. By + // using the IfNoneMatch condition we are asserting that the blob needs + // to have been modified in order to complete the request. In this + // sample no other client is accessing the blob, so this will fail as + // expected. + + var options = { accessConditions: { 'If-None-Match': etag} }; + blobService.createBlockBlobFromText(containerName, blobName, 'new hello', options, function (error) { + if (error) { + console.log('Got an expected exception. Details:'); + console.log(error); + } else { + console.log('Blob was incorrectly updated'); + } + }); +} + +if (processArguments.length > 5 || processArguments.length < 4) { + console.log('Incorrect number of arguments'); +} +else if (processArguments.length == 5) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + createContainer(); + } + }); +} +else { + createContainer(); +} + +// Utilitary functions + +var walk = function (dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) return done(err); + var i = 0; + (function next() { + var file = list[i++]; + if (!file) return done(null, results); + file = dir + '/' + file; + fs.stat(file, function (err2, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err3, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + })(); + }); +}; \ No newline at end of file diff --git a/examples/samples/continuationsample.js b/examples/samples/continuationsample.js new file mode 100644 index 000000000000..6f9fd6844135 --- /dev/null +++ b/examples/samples/continuationsample.js @@ -0,0 +1,138 @@ +/** +* This sample demonstrates how to handle continuation tokens and virtual "pages" of results when performing a listing +* operation on the blob service. +* +* This sample peformsthe following steps: +* +* 0. Create container. +* +* 1. Creates 50 blobs. +* +* 2. List the first 10(page size) blobs. +* +* 3. Check whether there are more results. +* +* 4. List the next 10(page size) blobs. +* +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; + +var util = require('util'); + +var container = 'contsample'; +var blob = 'contsample'; + +/** +* The total number of the blobs. +*/ +var totalBlobsCount = 50; + +/** +* The number of the blobs in one page. +*/ +var pageSize = 10; + +var blobService = azure.createBlobService(); + +function createContainer() { + // Step 0: Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the container ' + container); + createBlobs(totalBlobsCount); + } + }); +} + +function createBlobs(currentBlobsCount) { + // Step 1 : upload totalBlobsCount blobs to the container. + blobService.createBlockBlobFromText(container, blob + currentBlobsCount, 'blob' + currentBlobsCount, function (error) { + if (error) { + console.log(error); + } else if (currentBlobsCount > 1) { + createBlobs(--currentBlobsCount); + } else { + console.log('Created ' + totalBlobsCount + ' blobs.'); + listPages(); + } + }); +} + +function listPages() { + // Step 2 : Perform a listing in "pages". A Page is a virtual construct + // to allow the client to return a certain number of results at a time. + // A good example of this is when using the entries in UI or improving + // latency by only downloading the needed results. + + // In addition continuation tokens are expected from the blob service + // when doing list operations and must be taken in account. For + // convenience an iterator is provided via the listBlobs + // methods which will handle the continuation token between requests in + // a method that is opaque to the user. + + // The first list operation will return up to pageSize blobs, Note there + // is no continuation is specified as this is the first request. + blobService.listBlobs(container, { maxresults: pageSize }, function (error, page, pageContinuation) { + if (error) { + console.log(error); + } else { + console.log('There are ' + page.length + ' blobs in this page.'); + listNextPage(pageContinuation); + } + }); +} + +function listNextPage(pageContinuation) { + // Step 3 : Check whether there are more results and list them in pages + // of pageSize. + + // The hasNextPage() checks to see if the listing + // provided a continuation token meaning there are additional results on + // the service to be queried. This will be returned even if the + // requested "page size" has been satisfied if there are more blobs on + // the service. + + if (pageContinuation.hasNextPage()) { + // Step 4 : make the next request from the last continuation token. + + pageContinuation.getNextPage(function (error, page, nextPageContinuation) { + console.log('There are ' + page.length + ' blobs in this page.'); + listNextPage(nextPageContinuation); + }); + } + else { + console.log('Listing blob in pages completed.'); + } +} + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + createContainer(); + } + }); +} +else { + createContainer(); +} \ No newline at end of file diff --git a/examples/samples/leaseblobsample.js b/examples/samples/leaseblobsample.js new file mode 100644 index 000000000000..e67f967296df --- /dev/null +++ b/examples/samples/leaseblobsample.js @@ -0,0 +1,117 @@ +/** +* This sample demonstrates how multiple clients can attempt to acquire a lease in order to provide a locking mechanism +* over write operations on a given blob. +* +* To simulate N workers please run multiple instances of this sample. Each instance will : +* +* 1. Try to acquire a lease on a uploaded blob. +* +* 2. If succeed, then renew the lease, print out the current process holds the lease every 40 seconds until the process +* is killed. +* +* 3. If fail, then sleep for 10 seconds and go back to step 1. +* +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; + +var workerWithLeaseSleepTimeInMs = 40 * 1000; +var workerWithoutLeaseSleepTimeInMs = 10 * 1000; + +var container = 'leasesample'; +var blob = 'leasesample'; +var leaseId; + +var blobClient = azure.createBlobService(); + +function createContainer(callback) { + // Step 0: Check if the target container exists. + blobClient.createContainerIfNotExists(container, function () { + console.log('Created the container ' + container); + callback(); + }); +}; + +function uploadBlob(callback) { + // Step 1: Create text blob. + blobClient.createBlockBlobFromText(container, blob, 'Hello world!', function () { + console.log('Created the blob ' + blob); + callback(); + }); +}; + +function getLease(currentLease) { + if (currentLease == null) { + // Step 2a: this worker doesn't hold a lease, then try to acquire the lease. + blobClient.acquireLease(container, blob, function (leaseError, lease) { + if (lease != null) { + leaseId = lease.id; + + // Succeed in acquiring a lease. + console.log('Worker acquired the lease whose ID is ' + leaseId); + + setTimeout(function () { + getLease(lease); + }, workerWithLeaseSleepTimeInMs); + } + else { + // Fail in acquiring a lease. + console.log('Worker failed in acquiring the lease.'); + + setTimeout(function () { + getLease(null); + }, workerWithoutLeaseSleepTimeInMs); + } + }); + } + else { + // Step 2b: This worker holds a lease, then renew the lease. + + // Traditionally there is some work this worker must do while it + // holds the lease on the blob prior to releasing it. + blobClient.renewLease(container, blob, leaseId, function (leaseError, lease) { + if (lease) { + console.log('Worker renewed the lease whose ID is ' + lease.id); + } + else { + console.log('Worker failed in renewing the lease.'); + } + + setTimeout(function () { + getLease(lease); + }, workerWithLeaseSleepTimeInMs); + }); + } +}; + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobClient.deleteContainer(container, function () { + createContainer(function () { + uploadBlob(function () { + getLease(null); + }); + }); + }); +} +else { + createContainer(function () { + uploadBlob(function () { + getLease(null); + }); + }); +} \ No newline at end of file diff --git a/examples/samples/retrypolicysample.js b/examples/samples/retrypolicysample.js new file mode 100644 index 000000000000..51add3c4ab1f --- /dev/null +++ b/examples/samples/retrypolicysample.js @@ -0,0 +1,103 @@ +/** +* Demonstrates how to define a customized retry policy. +* +* In this sample, we define a customized retry policy which retries on the "The specified container is being deleted" +* exception besides the server exceptions. +* +* Note that only in the cloud(not the storage emulator), "The specified container is being deleted" exceptions will be +* sent if users immediately recreate a container after delete it. +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; +var ExponentialRetryPolicyFilter = azure.ExponentialRetryPolicyFilter; + +var util = require('util'); + +var container = 'retrypolicysample'; + +var blobServiceNoRetry = azure.createBlobService(); +var blobService; + +function setRetryPolicy() { + // Step 1 : Set the retry policy to customized retry policy which will + // retry on any status code other than the excepted one, including + // the "The specified container is being deleted" exception . + + var retryOnContainerBeingDeleted = new ExponentialRetryPolicyFilter(); + retryOnContainerBeingDeleted.retryCount = 3; + retryOnContainerBeingDeleted.retryInterval = 30000; + + retryOnContainerBeingDeleted.shouldRetry = function(statusCode, retryData) { + console.log('Made the request at ' + new Date().toUTCString() + ', received StatusCode: ' + statusCode); + + var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0; + + return (currentCount < this.retryCount); + }; + + blobService = blobServiceNoRetry.withFilter(retryOnContainerBeingDeleted); + createContainer(); +} + +function createContainer() { + // Step 2: Create a container with a random name. + blobService.createContainer(container, function(error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + deleteContainer(); + } + }); +} + +function deleteContainer() { + // Step 3 : Delete a container. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + createContainerAgain(); + } + }); +}; + +function createContainerAgain() { + // Step 4 : Attempt to create the container immediately while it was still beeing deleted. + blobService.createContainer(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + } + }); +}; + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobServiceNoRetry.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + setRetryPolicy(); + } + }); +} +else { + setRetryPolicy(); +} \ No newline at end of file diff --git a/examples/samples/sassample.js b/examples/samples/sassample.js new file mode 100644 index 000000000000..3d948e32aa48 --- /dev/null +++ b/examples/samples/sassample.js @@ -0,0 +1,194 @@ +/** +* In this sample, we demonstrate how to generate and use the blob level shared access signature and the container level +* shared access signature. +* +* In the blob level shared access signature sample, there are the following steps: +* +* a. Create a container and a blob. +* +* b. Generate a shared access signature URL for the blob. +* +* c. Download that blob through that URL (should fail as the policy was never uploaded). +* +* In the container level shared access signature sample, there are the following steps: +* +* a. Create a container and a blob. +* +* b. Upload a "ReadWrite" policy and a "Read" permission to the container, generate their shared access +* signatures. +* +* c. Use both shared access signatures to read that blob (Expect a failure from the "Read" permission shared access signature since it has already expired.). +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; + +var util = require('util'); +var ISO8061Date = require('../../lib/util/iso8061date'); + +var container = 'sassample'; +var blob = 'sassample'; + +var blobService = azure.createBlobService(); + +function createContainer() { + // Step 0: Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the container ' + container); + createBlob(); + } + }); +} + +function createBlob() { + // Step 1: Create the blob + blobService.createBlockBlobFromText(container, blob, 'test blob', function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the blob ' + container); + downloadBlobUsingSharedAccessSignature(); + } + }); +} + +function downloadBlobUsingSharedAccessSignature() { + var startDate = new Date(); + var expiryDate = new Date(startDate); + expiryDate.setMinutes(startDate.getMinutes() + 5); + + var sharedAccessPolicy = { + AccessPolicy: { + Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.READ, + Start: startDate, + Expiry: expiryDate + } + }; + + var signature = blobService.generateSharedAccessSignature(container, blob, sharedAccessPolicy); + + var sharedBlobService = azure.createBlobService(); + var sharedAccessSignature = new azure.SharedAccessSignature(sharedBlobService.storageAccount, sharedBlobService.storageAccessKey); + sharedBlobService.authenticationProvider = sharedAccessSignature; + + sharedAccessSignature.permissionSet = [signature]; + + // Step 3: Download the blob by using the shared access signature URL. Since the read policy was never uploaded this should fail. + sharedBlobService.getBlobProperties(container, blob, function (error) { + if (error) { + console.log('Failed to download the blob since the permission was invalid.'); + } else { + console.log('Downloaded the blob ' + blob + ' by using the shared access signature URL ' + signature.url()); + } + + createPolicies(); + }); +} + +function createPolicies() { + // Step 4: Create a "ReadWrite" policy and a "Read" policy. + var readWriteStartDate = new Date(); + var readWriteExpiryDate = new Date(readWriteStartDate); + readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10); + + var readWriteSharedAccessPolicy = { + Id: 'readwrite', + AccessPolicy: { + Start: readWriteStartDate, + Expiry: readWriteExpiryDate, + Permissions: 'rw' + } + }; + + var readSharedAccessPolicy = { + Id: 'read', + AccessPolicy: { + Expiry: readWriteStartDate, + Permissions: 'r' + } + }; + + var options = {}; + options.signedIdentifiers = [readWriteSharedAccessPolicy, readSharedAccessPolicy]; + + blobService.setContainerAcl(container, BlobConstants.BlobContainerPublicAccessType.CONTAINER, options, function(error) { + if (error) { + console.log(error); + } else { + console.log('Uploaded the permissions for the container ' + container); + usePermissions(readWriteSharedAccessPolicy, readSharedAccessPolicy); + } + }); +} + +function usePermissions(readWriteSharedAccessPolicy, readSharedAccessPolicy) { + // Step 5: Read, write the blob using the shared access signature from "ReadWrite" policy. + var sharedAccessSignature = blobService.generateSharedAccessSignature(container, null, readWriteSharedAccessPolicy); + + var sharedBlobService = azure.createBlobService(); + var sharedAccessSignatureProvider = new azure.SharedAccessSignature(sharedBlobService.storageAccount, sharedBlobService.storageAccessKey); + sharedBlobService.authenticationProvider = sharedAccessSignatureProvider; + + sharedAccessSignatureProvider.permissionSet = [sharedAccessSignature]; + + sharedBlobService.getBlobProperties(container, blob, function (error) { + if (error) { + console.log('Failed to download the blob since the permission was invalid.'); + } else { + console.log('Downloaded the blob ' + blob + ' by using the shared access signature URL ' + sharedAccessSignature.url()); + } + + useIncorrectPermission(readSharedAccessPolicy); + }); +} + +function useIncorrectPermission(readSharedAccessPolicy) { + // Step 6: Expect an exception from using the already expired "Read" permission to read the blob. + var sharedAccessSignature = blobService.generateSharedAccessSignature(container, null, readSharedAccessPolicy); + + var sharedBlobService = azure.createBlobService(); + var sharedAccessSignatureProvider = new azure.SharedAccessSignature(sharedBlobService.storageAccount, sharedBlobService.storageAccessKey); + sharedBlobService.authenticationProvider = sharedAccessSignatureProvider; + + sharedAccessSignatureProvider.permissionSet = [sharedAccessSignature]; + + sharedBlobService.getBlobProperties(container, blob, function (error) { + if (error) { + console.log('Failed to download the blob since the permission was invalid.'); + } else { + console.log('Downloaded the blob ' + blob + ' by using the shared access signature URL ' + sharedAccessSignature.url()); + } + }); +} + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + createContainer(); + } + }); +} +else { + createContainer(); +} \ No newline at end of file diff --git a/examples/samples/sbqueue.js b/examples/samples/sbqueue.js new file mode 100644 index 000000000000..827c376f1368 --- /dev/null +++ b/examples/samples/sbqueue.js @@ -0,0 +1,80 @@ +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var util = require('util'); + +var queue = 'queuesample'; + +var serviceBusClient = azure.createServiceBusService(); + +function createQueue() { + // Step 0: Create queue. + serviceBusClient.createQueue(queue, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the queue ' + queue); + sendMessages(); + } + }); +} + +function sendMessages() { + // Step 1: Send a few messages to later be consumed. + serviceBusClient.sendQueueMessage(queue, 'Send Message Works', function(error1) { + if (error1) { + console.log(error1); + } else { + console.log('Sent first Message'); + serviceBusClient.sendQueueMessage(queue, 'Send Message Still Works', function(error2) { + if (error2) { + console.log(error2); + } else { + console.log('Sent Second Message'); + receiveMessages(); + } + }); + } + }); +} + +function receiveMessages() { + // Step 2: Receive the messages. + serviceBusClient.receiveQueueMessage(queue, function (error1, message1) { + if (error1) { + console.log(error1); + } else { + console.log(message1.body); + serviceBusClient.receiveQueueMessage(queue, function (error2, message2) { + if (error2) { + console.log(error2); + } else { + console.log(message2.body); + } + }); + } + }); +} + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + serviceBusClient.deleteQueue(queue, function (error) { + if (error) { + console.log(error); + } else { + createQueue(); + } + }); +} +else { + createQueue(); +} \ No newline at end of file diff --git a/examples/samples/sbtopic.js b/examples/samples/sbtopic.js new file mode 100644 index 000000000000..5e138e566d34 --- /dev/null +++ b/examples/samples/sbtopic.js @@ -0,0 +1,118 @@ +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var util = require('util'); + +var topic = 'topicsample'; +var subscription1 = 'subscription1'; +var subscription2 = 'subscription2'; + +var serviceBusClient = azure.createServiceBusService(); + +function createTopic() { + // Step 0: Create topic. + serviceBusClient.createTopic(topic, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the topic ' + topic); + createSubscriptions(); + } + }); +} + +function createSubscriptions() { + // Step 1: Create subscriptions. + serviceBusClient.createSubscription(topic, subscription1, function (error1) { + if (error1) { + console.log(error1); + } else { + serviceBusClient.createSubscription(topic, subscription2, function (error2) { + if (error2) { + console.log(error2); + } else { + sendMessages(); + } + }); + } + }); +} + +function sendMessages() { + // Step 2: Send a few messages to later be consumed. + serviceBusClient.sendTopicMessage(topic, 'Send Message Works', function(error1) { + if (error1) { + console.log(error1); + } else { + console.log('Sent first Message'); + serviceBusClient.sendTopicMessage(topic, 'Send Message Still Works', function (error2) { + if (error2) { + console.log(error2); + } else { + console.log('Sent Second Message'); + receiveMessagesSubscription1(); + } + }); + } + }); +} + +function receiveMessagesSubscription1() { + // Step 3: Receive the messages for subscription 1. + serviceBusClient.receiveSubscriptionMessage(topic, subscription1, function (error1, message1) { + if (error1) { + console.log(error1); + } else { + console.log(message1.body); + serviceBusClient.receiveSubscriptionMessage(topic, subscription1, function (error2, message2) { + if (error2) { + console.log(error2); + } else { + console.log(message2.body); + receiveMessagesSubscription2(); + } + }); + } + }); +} + +function receiveMessagesSubscription2() { + // Step 3: Receive the messages for subscription 2. + serviceBusClient.receiveSubscriptionMessage(topic, subscription2, function (error1, message1) { + if (error1) { + console.log(error1); + } else { + console.log(message1.body); + serviceBusClient.receiveSubscriptionMessage(topic, subscription2, function (error2, message2) { + if (error2) { + console.log(error2); + } else { + console.log(message2.body); + } + }); + } + }); +} + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + serviceBusClient.deleteTopic(topic, function (error) { + if (error) { + console.log(error); + } else { + createTopic(); + } + }); +} +else { + createTopic(); +} \ No newline at end of file diff --git a/examples/samples/snapshotsample.js b/examples/samples/snapshotsample.js new file mode 100644 index 000000000000..3f4dcc7b9766 --- /dev/null +++ b/examples/samples/snapshotsample.js @@ -0,0 +1,225 @@ +/** +* This sample is used to provide an overview of blob snapshots and how to work with them. +* +* 1. Upload 3 blocks and commit them. +* +* 2. Take a snapshot for that blob. +* +* 3. Re-upload one of the three blocks and commit them. +* +* 4. Take a snapshot again. +* +* 5. List blobs including snapshots. +* +* 6. Promote the first snapshot. +* +* 7. Delete the first snapshot. +* +* 8. List all snapshots for this blob. +*/ + +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var BlobConstants = azure.Constants.BlobConstants; +var ServiceClient = azure.ServiceClient; +var CloudBlobClient = azure.CloudBlobClient; + +var util = require('util'); + +var container = 'snapshotsample'; +var blob = 'snapshotsample'; + +var blockId1 = 'b1'; +var blockId2 = 'b2'; +var blockId3 = 'b3'; + +var blockContent1 = 'content1'; +var blockContent2 = 'content2'; +var blockContentAlternative2 = 'alternative2'; +var blockContent3 = 'content3'; + +var blobClient = azure.createBlobService(); + +function createContainer() { + // Step 0: Check if the target container exists. + blobClient.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the container ' + container); + uploadblockBlobs(); + } + }); +} + +function uploadblockBlobs() { + // Step 1: Upload 3 blocks and commit them. + var blockList = { + LatestBlocks: [blockId1, blockId2, blockId3] + }; + + blobClient.createBlobBlockFromText(blockList.LatestBlocks[0], container, blob, blockContent1, blockContent1.length, function (error1) { + if (error1) { + console.log(error1); + } else { + console.log('Uploaded the block whose ID is ' + blockList.LatestBlocks[0]); + blobClient.createBlobBlockFromText(blockList.LatestBlocks[1], container, blob, blockContent2, blockContent2.length, function (error2) { + if (error2) { + console.log(error2); + } else { + console.log('Uploaded the block whose ID is ' + blockList.LatestBlocks[1]); + blobClient.createBlobBlockFromText(blockList.LatestBlocks[2], container, blob, blockContent3, blockContent3.length, function (error3) { + if (error3) { + console.log(error3); + } else { + console.log('Uploaded the block whose ID is ' + blockList.LatestBlocks[2]); + blobClient.commitBlobBlocks(container, blob, blockList, function (error4) { + if (error4) { + console.log(error4); + } + else { + console.log('Committed the blob ' + blob); + createSnapshot(); + } + }); + } + }); + } + }); + } + }); +} + +function createSnapshot() { + // Step 2 : Creates a snapshot. + blobClient.createBlobSnapshot(container, blob, function (error, snapshot1) { + if (error) { + console.log(error); + } else { + console.log('Created a snapshot for the blob ' + blob); + + createBlob(snapshot1); + } + }); +} + +function createBlob (snapshot) { + // Step 3: Update the block 2, commit the blob again. + blobClient.createBlobBlockFromText(blockId2, container, blob, blockContentAlternative2, blockContentAlternative2.length, function (error) { + if (error) { + console.log(error); + } else { + console.log('Uploaded the block whose ID is ' + blockId2); + + var blockList = { + LatestBlocks: [blockId1, blockId2, blockId3] + }; + + blobClient.commitBlobBlocks(container, blob, blockList, function (error2) { + if (error2) { + console.log(error2); + } else { + console.log('Committed the blob ' + blob); + createAnotherSnapshot(snapshot); + } + }); + } + }); +} + +function createAnotherSnapshot (snapshot) { + // Step 4 : Creates another snapshot. + blobClient.createBlobSnapshot(container, blob, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created a snapshot for the blob ' + blob); + + listSnapshots(snapshot); + } + }); +}; + +function listSnapshots (snapshotId) { + // Step 5 : List the blobs, including snapshots + blobClient.listBlobs(container, { include: 'snapshots' }, function (error, blobResults) { + if (error) { + console.log(error); + } else { + console.log('Listing the blobs under the container ' + container); + + blobResults.forEach(function (blobResult) { + console.log(' Blob: ' + blobResult.url); + }); + + promoteSnapshot(snapshotId); + } + }); +}; + +function promoteSnapshot (snapshot) { + // Step 6 : Promote, delete the snapshot1. + blobClient.createBlockBlobFromText(container, blob, 'promoted', { snapshotId: snapshot }, function (error) { + if (error) { + console.log(error); + } else { + console.log('Promoted the snapshot ' + snapshot); + deleteSnapshot(snapshot); + } + }); +} + +function deleteSnapshot (snapshot) { + // Step 7 : Delete the first snapshot. + blobClient.deleteBlob(container, blob, { snapshotId: snapshot }, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the snapshot ' + snapshot); + + listOnlySnapshots(); + } + }); +}; + +function listOnlySnapshots () { + // Step 8 : List the snapshots. + blobClient.listBlobs(container, { prefix: blob, include: 'snapshots' }, function (error, blobResults) { + if (error) { + console.log(error); + } else { + console.log('Listing snapshots for the blob ' + blob); + + blobResults.forEach(function (blobResult) { + if (blobResult.snapshot) { + console.log(' Snapshot: ' + blobResult.snapshot); + } + }); + } + }); +}; + +var arguments = process.argv; + +if (arguments.length > 3) { + console.log('Incorrect number of arguments'); +} +else if (arguments.length == 3) { + // Adding a third argument on the command line, whatever it is, will delete the container before running the sample. + blobClient.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + createContainer(); + } + }); +} +else { + createContainer(); +} \ No newline at end of file diff --git a/examples/tasklist/home.js b/examples/tasklist/home.js new file mode 100644 index 000000000000..d27630de414a --- /dev/null +++ b/examples/tasklist/home.js @@ -0,0 +1,96 @@ +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var TableQuery = azure.TableQuery; + +module.exports = Home; +var uuid = require('node-uuid'); + +function Home(client) { + this.client = client; +}; + +Home.prototype = { + showResults: function (res, taskList) { + res.render('home', { + locals: { + title: 'Task list', + layout: false, + taskList: taskList + } + }); + }, + + getItems: function (allItems, callback) { + var query = TableQuery.select().from('tasks'); + if (!allItems) { + query = query.where('completed eq ?', false); + } + + this.client.queryEntities(query, callback); + }, + + showItems: function (req, res) { + var self = this; + this.getItems(false, function (resp, taskList) { + if (!taskList) { + self.taskList = []; + } + + self.showResults(res, taskList); + }); + }, + + newItem: function (req, res) { + var self = this; + var createItem = function (resp, taskList) { + if (!taskList) { + self.taskList = []; + } + + var item = req.body.item; + item.RowKey = uuid(); + item.PartitionKey = 'partition1'; + item.completed = false; + + self.client.insertEntity('tasks', item, function () { + self.showItems(req, res); + }); + }; + + this.getItems(true, createItem); + }, + + markCompleted: function (req, res) { + var self = this; + + var postedItems = req.body.completed; + if (!postedItems.forEach) + postedItems = [postedItems]; + + var process = { + processNextItem: function (err) { + var item = postedItems.pop(); + if (item) process.getItemToUpdate(item); + else self.getItems(false, function (resp, taskitems) { + self.showResults(res, taskitems); + }); + }, + getItemToUpdate: function (item) { + self.client.queryEntity('tasks', 'partition1', item, process.updateItem); + }, + updateItem: function (resp, task) { + if (task) { + task.completed = true; + self.client.updateEntity('tasks', task, process.processNextItem); + } + } + }; + + process.processNextItem(); + } +}; \ No newline at end of file diff --git a/examples/tasklist/package.json b/examples/tasklist/package.json new file mode 100644 index 000000000000..74dfb183e8d7 --- /dev/null +++ b/examples/tasklist/package.json @@ -0,0 +1,12 @@ +{ + "name": "application-name" + , "version": "0.0.1" + , "private": true + , "dependencies": { + "express": ">= 2.4.7" + , "ejs": ">= 0.4.3" + , "jade": ">= 0.18.0" + , "node-uuid": "> = 1.2.0" + , "azure": ">= 0.5.1" + } +} \ No newline at end of file diff --git a/examples/tasklist/server.js b/examples/tasklist/server.js new file mode 100644 index 000000000000..82ea34779526 --- /dev/null +++ b/examples/tasklist/server.js @@ -0,0 +1,72 @@ +// Module dependencies. +var path = require('path'); +if (path.existsSync('./../../lib/azure.js')) { + azure = require('./../../lib/azure'); +} else { + azure = require('azure'); +} + +var express = require('express'); +var uuid = require('node-uuid'); +var Home = require('./home'); +var ServiceClient = azure.ServiceClient; + +var app = module.exports = express.createServer(); +var client = azure.createTableService(ServiceClient.DEVSTORE_STORAGE_ACCOUNT, ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, ServiceClient.DEVSTORE_TABLE_HOST); + +// table creation +client.createTableIfNotExists("tasks", function (res, created) { + if (created) { + var item = { + name: 'Add readonly todo list', + category: 'Site work', + date: '12/01/2011', + RowKey: uuid(), + PartitionKey: 'partition1', + completed: false + }; + + client.insertEntity("tasks", item, null, function () { + setupApplication(); + }); + } else { + setupApplication(); + } +}); + +function setupApplication() { + // Configuration + app.configure(function () { + app.set('views', __dirname + '/views'); + + // NOTE: Uncomment this line and comment next one to use ejs instead of jade + // app.set('view engine', 'ejs'); + + app.set('view engine', 'jade'); + + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(express.static(__dirname + '/public')); + }); + + app.configure('development', function() { + app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); + }); + + app.configure('production', function() { + app.use(express.errorHandler()); + }); + + var home = new Home(client); + + // Routes + + app.get('/', home.showItems.bind(home)); + app.get('/home', home.showItems.bind(home)); + app.post('/home/newitem', home.newItem.bind(home)); + app.post('/home/completed', home.markCompleted.bind(home)); + + app.listen(process.env.PORT || 1337); + console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); +} \ No newline at end of file diff --git a/examples/tasklist/views/home.ejs b/examples/tasklist/views/home.ejs new file mode 100644 index 000000000000..417f05a6d697 --- /dev/null +++ b/examples/tasklist/views/home.ejs @@ -0,0 +1,60 @@ + + + Index + + +

My Task List

+ +
+ + + + + + + + + <% taskList.forEach(function(item){ %> + + + + + + + <% }) %> +
NameCategoryDateComplete
<%-item.name%><%-item.category%><%-item.date%> + +
+ +

+ +

+
+ +
+ + + + + + + + + + + + + +
Item Name: + +
Item Category: + +
Item Date: + +
+

+ +

+
+ + diff --git a/examples/tasklist/views/home.jade b/examples/tasklist/views/home.jade new file mode 100644 index 000000000000..582f758b3c48 --- /dev/null +++ b/examples/tasklist/views/home.jade @@ -0,0 +1,40 @@ +html +head + title Index +body + h1 My Task List + + form(action="/home/completed", method="post") + table(border="1") + tr + td Name + td Category + td Date + td Complete + + each item in taskList + tr + td #{item.name} + td #{item.category} + td #{item.date} + td + input(type="checkbox", name="completed", value="#{item.RowKey}") + p + input(type="submit", value="Complete") + hr + form(action="/home/newitem", method="post") + table(border="1") + tr + td Item Name: + td + input(name="item[name]", type="textbox") + tr + td Item Category: + td + input(name="item[category]", type="textbox") + tr + td Item Date: + td + input(name="item[date]", type="textbox") + p + input(type="submit", value="Add item") \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 000000000000..6c0bfe3a0d8b --- /dev/null +++ b/package.json @@ -0,0 +1,36 @@ +{ + "name": "azure", + "author": "Microsoft Corporation", + "version": "0.5.2", + "description": "Windows Azure Client Library for node", + "tags" : ["azure", "sdk"], + "keywords": [ "node", "azure" ], + "main": "./lib/azure.js", + "engines": { "node": ">= 0.4.7" }, + "licenses": [ { "type": "Apache", "url": "http://www.apache.org/licenses/LICENSE-2.0" } ], + "dependencies": { + "xml2js" : ">= 0.1.11", + "sax": ">= 0.1.1", + "qs": ">= 0.3.1", + "log": ">= 1.2.0", + "xmlbuilder": ">= 0.3.1", + "mime": ">= 1.2.4", + "dateformat": "1.0.2-1.2.3" + }, + "devDependencies": { + "nodeunit": ">= 0.6.4" + }, + "homepage": "http://github.com/WindowsAzure/azure-sdk-for-node", + "repository": { + "type": "git", + "url": "git@github.com:WindowsAzure/azure-sdk-for-node.git" + }, + "bugs" : { + "url" : "http://github.com/WindowsAzure/azure-sdk-for-node/issues" + }, + "scripts": { + "test": "node test/runtests.js", + "jshint": "node test/runjshint.js", + "extendedtests": "node test/runextendedtests.js" + } +}