|
| 1 | +namespace DocumentDB.Samples.CollectionManagement |
| 2 | +{ |
| 3 | + using Microsoft.Azure.Documents; |
| 4 | + using Microsoft.Azure.Documents.Client; |
| 5 | + using Microsoft.Azure.Documents.Linq; |
| 6 | + using System; |
| 7 | + using System.Collections.Generic; |
| 8 | + using System.Configuration; |
| 9 | + using System.Linq; |
| 10 | + using System.Threading.Tasks; |
| 11 | + |
| 12 | + //----------------------------------------------------------------------------------------------------------- |
| 13 | + // This sample demonstrates the basic CRUD operations on a DatabaseCollection resource for Azure DocumentDB |
| 14 | + // |
| 15 | + // For advanced concepts like; |
| 16 | + // DocumentCollection IndexPolicy management please consult DocumentDB.Samples.IndexManagement |
| 17 | + //----------------------------------------------------------------------------------------------------------- |
| 18 | + |
| 19 | + public class Program |
| 20 | + { |
| 21 | + private static DocumentClient client; |
| 22 | + |
| 23 | + //Get an Id for your database & collection from config |
| 24 | + private static readonly string databaseId = ConfigurationManager.AppSettings["DatabaseId"]; |
| 25 | + private static readonly string collectionId = ConfigurationManager.AppSettings["CollectionId"]; |
| 26 | + |
| 27 | + //Read the DocumentDB endpointUrl and authorisationKeys from config |
| 28 | + //These values are available from the Azure Management Portal on the DocumentDB Account Blade under "Keys" |
| 29 | + //NB > Keep these values in a safe & secure location. Together they provide Administrative access to your DocDB account |
| 30 | + private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndPointUrl"]; |
| 31 | + private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"]; |
| 32 | + |
| 33 | + public static void Main(string[] args) |
| 34 | + { |
| 35 | + try |
| 36 | + { |
| 37 | + //Get a DocumentClient |
| 38 | + using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey)) |
| 39 | + { |
| 40 | + RunDemoAsync().Wait(); |
| 41 | + } |
| 42 | + } |
| 43 | + catch (DocumentClientException de) |
| 44 | + { |
| 45 | + Exception baseException = de.GetBaseException(); |
| 46 | + Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message); |
| 47 | + } |
| 48 | + catch (Exception e) |
| 49 | + { |
| 50 | + Exception baseException = e.GetBaseException(); |
| 51 | + Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message); |
| 52 | + } |
| 53 | + finally |
| 54 | + { |
| 55 | + Console.WriteLine("End of demo, press any key to exit."); |
| 56 | + Console.ReadKey(); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private static async Task RunDemoAsync() |
| 61 | + { |
| 62 | + //Try get a Database if exists, else create the Database resource |
| 63 | + Database database = await GetOrCreateDatabaseAsync(databaseId); |
| 64 | + |
| 65 | + //Create a new collection on the Database |
| 66 | + DocumentCollection collection = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionId }); |
| 67 | + Console.WriteLine("Created Collection {0}.", collection); |
| 68 | + |
| 69 | + //Read Collection Feed on the Database |
| 70 | + List<DocumentCollection> cols = await ReadCollectionsFeedAsync(database.SelfLink); |
| 71 | + foreach (var col in cols) |
| 72 | + { |
| 73 | + Console.WriteLine(col); |
| 74 | + } |
| 75 | + |
| 76 | + //To list collections on a Database you could also just do a simple Linq query like this |
| 77 | + //The DocumentClient will transparently execute multiple calls to the Database Service |
| 78 | + //if it receives a continuation token. For larger sets of results the above method might be |
| 79 | + //preferred because you can control the number of records to return per call |
| 80 | + cols = client.CreateDocumentCollectionQuery(database.CollectionsLink).ToList(); |
| 81 | + foreach (var col in cols) |
| 82 | + { |
| 83 | + Console.WriteLine(col); |
| 84 | + } |
| 85 | + |
| 86 | + //Cleanup, |
| 87 | + //Deleting a DocumentCollection will delete everything linked to the collection. |
| 88 | + //As will deleting the Database. Therefore, we don't actually need to explictly delete the collection |
| 89 | + //it's just being done for demonstration purposes. |
| 90 | + await client.DeleteDocumentCollectionAsync(collection.SelfLink); |
| 91 | + await client.DeleteDatabaseAsync(database.SelfLink); |
| 92 | + } |
| 93 | + |
| 94 | + /// <summary> |
| 95 | + /// This method uses a ReadCollectionsFeedAsync method to read a list of all collections on a database. |
| 96 | + /// It demonstrates a pattern for how to control paging and deal with continuations |
| 97 | + /// This should not be needed for reading a list of collections as there are unlikely to be many hundred, |
| 98 | + /// but this same pattern is introduced here and can be used on other ReadFeed methods. |
| 99 | + /// </summary> |
| 100 | + /// <returns>A List of DocuemntCollection entities</returns> |
| 101 | + private static async Task<List<DocumentCollection>> ReadCollectionsFeedAsync(string databaseSelfLink) |
| 102 | + { |
| 103 | + string continuation = null; |
| 104 | + List<DocumentCollection> collections = new List<DocumentCollection>(); |
| 105 | + |
| 106 | + do |
| 107 | + { |
| 108 | + FeedOptions options = new FeedOptions |
| 109 | + { |
| 110 | + RequestContinuation = continuation, |
| 111 | + MaxItemCount = 50 |
| 112 | + }; |
| 113 | + |
| 114 | + FeedResponse<DocumentCollection> response = (FeedResponse<DocumentCollection>) await client.ReadDocumentCollectionFeedAsync(databaseSelfLink, options); |
| 115 | + |
| 116 | + foreach (DocumentCollection col in response) |
| 117 | + { |
| 118 | + collections.Add(col); |
| 119 | + } |
| 120 | + |
| 121 | + continuation = response.ResponseContinuation; |
| 122 | + |
| 123 | + } while (!String.IsNullOrEmpty(continuation)); |
| 124 | + |
| 125 | + return collections; |
| 126 | + } |
| 127 | + |
| 128 | + /// <summary> |
| 129 | + /// Get the database by name, or create a new one if one with the name provided doesn't exist. |
| 130 | + /// </summary> |
| 131 | + /// <param name="id">The name of the database to search for, or create.</param> |
| 132 | + private static async Task<Database> GetOrCreateDatabaseAsync(string id) |
| 133 | + { |
| 134 | + // Create a query object for database, filter by name. |
| 135 | + IEnumerable<Database> query = from db in client.CreateDatabaseQuery() |
| 136 | + where db.Id == id |
| 137 | + select db; |
| 138 | + |
| 139 | + // Run the query and get the database (there should be only one) or null if the query didn't return anything. |
| 140 | + // Note: this will run synchronously. If async exectution is preferred, use IDocumentServiceQuery<T>.ExecuteNextAsync. |
| 141 | + Database database = query.FirstOrDefault(); |
| 142 | + if (database == null) |
| 143 | + { |
| 144 | + // Create the database. |
| 145 | + database = await client.CreateDatabaseAsync(new Database { Id = id }); |
| 146 | + } |
| 147 | + |
| 148 | + return database; |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments