private static async Task<DocumentCollection> CreateDocumentCollection(DocumentClient client, Database database, string collectionId)
        {
            var collectionSpec = new DocumentCollection { Id = collectionId };
            var requestOptions = new RequestOptions { OfferType = "S1" };

            return await client.CreateDocumentCollectionAsync(database.SelfLink, collectionSpec, requestOptions);
        }
        private async Task<DocumentClient> GetDocumentDbClient()
        {
            var client = new DocumentClient(new Uri(_endPointUrl), _authorizationKKry);

            var database = client.CreateDatabaseQuery().
                Where(db => db.Id == DocumentDbId).AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = DocumentDbId
                    });    
            }

            DocumentCollection = client.CreateDocumentCollectionQuery
                ("dbs/" + database.Id).Where(c => c.Id == _collectionId).AsEnumerable().FirstOrDefault();

            if (DocumentCollection == null)
            {
                DocumentCollection = await client.CreateDocumentCollectionAsync("dbs/" + DocumentDbId,
                new DocumentCollection
                {
                    Id = _collectionId
                });

            }
           

            return client;
        }
Beispiel #3
0
        private static void CreateDocumentCollection(DocumentClient documentClient)
        {
            // Create the database if it doesn't exist.

            try
            {
                documentClient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName))
                    .GetAwaiter()
                    .GetResult();
            }
            catch (DocumentClientException de)
            {
                // If the document collection does not exist, create it
                if (de.StatusCode == HttpStatusCode.NotFound)
                {
                    var collectionInfo = new DocumentCollection
                    {
                        Id = CollectionName,
                        IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 })
                    };

                    documentClient.CreateDocumentCollectionAsync(
                        UriFactory.CreateDatabaseUri(DatabaseName),
                        collectionInfo,
                        new RequestOptions { OfferThroughput = 400 }).GetAwaiter().GetResult();
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #4
0
 public static async Task<HttpStatusCode> CreateCollection(DocumentClient client, Database database, string collectionName)
 {
     var result = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection
     {
         Id = collectionName
     });
     return result.StatusCode;
 }
Beispiel #5
0
        //SELECT C.id AS CourseId, C.Name AS CourseName
        //from CourseCollection AS C
        //Join Session IN C.Sessions
        //WHERE Session.Name = "Introduction"

        #region Helpers
        private static async Task<DocumentCollection> GetDocumentCollection(DocumentClient client, Database database)
        {
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "CourseCollection").AsEnumerable().FirstOrDefault();
            if (documentCollection == null)
            {
                documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection() { Id = "CourseCollection" });
            }
            return documentCollection;
        }
Beispiel #6
0
        private static DocumentCollection GetOrCreateCollection(DocumentClient client, string databaseSelfLink, string collectionName)
        {
            // Try to retrieve the collection (Microsoft.Azure.Documents.DocumentCollection) whose Id is equal to collectionName
            var collection = client.CreateDocumentCollectionQuery(databaseSelfLink)
                .Where(c => c.Id == collectionName)
                .ToArray()
                .FirstOrDefault()
                             ??
                             client.CreateDocumentCollectionAsync(databaseSelfLink,
                                 new DocumentCollection { Id = collectionName }).Result;

            if (collection == null)
            {
                collection = new DocumentCollection { Id = collectionName };
                collection.IndexingPolicy.IncludedPaths.Add(new IndexingPath { IndexType = IndexType.Range, NumericPrecision = 5, Path = "/" });

                collection = client.CreateDocumentCollectionAsync(databaseSelfLink, collection).Result;
            }
            return collection;
        }
        internal static DocumentCollection ReadOrCreateCollection(DocumentClient client, string databaseLink, string collectionId)
        {
            var collections = client.CreateDocumentCollectionQuery(databaseLink)
                            .Where(col => col.Id == collectionId).ToArray();

            if (collections.Any())
            {
                return collections.First();
            }

            var collection = new DocumentCollection { Id = collectionId };
            return client.CreateDocumentCollectionAsync(databaseLink, collection).Result;
        }
        private static DocumentCollection GetCollection(Microsoft.Azure.Documents.Client.DocumentClient client, Database database)
        {
            // Create a document collection.
            var documentCollection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == "LogEntries").ToArray().FirstOrDefault();

            if (documentCollection == null)
            {
                // Create the document collection.
                documentCollection = client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection {
                    Id = "LogEntries"
                }).Result;
            }
            return(documentCollection);
        }
        public async Task<bool>  WriteDocument(MessageType type, String jsonString)
        {
            var client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentServiceEndpoint"]), ConfigurationManager.AppSettings["DocumentKey"]);

            var dbName = ConfigurationManager.AppSettings["DocumentDatabase"];
            var database = client.CreateDatabaseQuery().Where(db => db.Id == dbName).AsEnumerable().FirstOrDefault() ??
                           await client.CreateDatabaseAsync(new Database{ Id = dbName});


            // Check to verify a document collection with the does not exist
            var docCollection = ConfigurationManager.AppSettings["DocumentCollection"];
            var documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == docCollection).AsEnumerable().FirstOrDefault() ??
                                     await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = docCollection });

            var id = Guid.NewGuid().ToString();

            var response = HttpStatusCode.Unused;
            switch (type)
            {
                case MessageType.Energy:
                    var energyDoc = JsonConvert.DeserializeObject<EnergyDocument>(jsonString);
                    energyDoc.id = id;
                    response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, energyDoc)).StatusCode;
                    break;
                case MessageType.Humidity:
                    var humidityDoc = JsonConvert.DeserializeObject<HumidityDocument>(jsonString);
                    humidityDoc.id = id;
                    response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, humidityDoc)).StatusCode;
                    break;
                case MessageType.Light:
                    var lightDoc = JsonConvert.DeserializeObject<LightDocument>(jsonString);
                    lightDoc.id = id;
                    response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, lightDoc)).StatusCode;
                    break;
                case MessageType.Temperature:
                    var tempDoc = JsonConvert.DeserializeObject<TemperatureDocument>(jsonString);
                    tempDoc.id = id;
                    response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, tempDoc)).StatusCode;
                    break;
            }

            return response == HttpStatusCode.Created;
        }
        public static async Task SaveTestResults(PerformanceTestResult testResults)
        {
            
            // Make sure to call client.Dispose() once you've finished all DocumentDB interactions
            // Create a new instance of the DocumentClient
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            // Check to verify a database with the id=FamilyRegistry does not exist
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "DistributedWebTest").AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                // Create a database
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = "DistributedWebTest"
                    });
            }
           
            // Check to verify a document collection with the id=FamilyCollection does not exist
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "DistributedTestResults").AsEnumerable().FirstOrDefault();

            if (documentCollection == null)
            {
                // Create a document collection using the lowest performance tier available (currently, S1)
                documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink,
                    new DocumentCollection { Id = "DistributedTestResults" },
                    new RequestOptions { OfferType = "S1" });
            }

            await client.CreateDocumentAsync(documentCollection.DocumentsLink, testResults);

  

        }
        public static DocumentCollection GetOrCreateDocumentCollection(DocumentClient client, string databaseLink,
            string collectionId, IndexingPolicy indexingPolicy)
        {
            IQueryable<DocumentCollection> collectionQuery =
                from coll in client.CreateDocumentCollectionQuery(databaseLink)
                where coll.Id == collectionId
                select coll;

            IEnumerable<DocumentCollection> enumerable = collectionQuery.AsEnumerable();
            if (!enumerable.Any())
            {
                DocumentCollection collection = new DocumentCollection() { Id = collectionId };

                if (indexingPolicy != null)
                {
                    collection.IndexingPolicy.Automatic = indexingPolicy.Automatic;
                    collection.IndexingPolicy.IndexingMode = indexingPolicy.IndexingMode;

                    foreach (var path in indexingPolicy.IncludedPaths)
                    {
                        collection.IndexingPolicy.IncludedPaths.Add(path);
                    }

                    foreach (var path in indexingPolicy.ExcludedPaths)
                    {
                        collection.IndexingPolicy.ExcludedPaths.Add(path);
                    }
                }

                return client.CreateDocumentCollectionAsync(databaseLink, collection).Result.Resource;
            }
            else
            {
                return enumerable.First();
            }
        }
Beispiel #12
0
        public static async Task<DocumentCollection> GetDC(DocumentClient client, Database database)
        {
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.SelfLink)
                .Where(c => c.Id == "LMSCollection")
                .AsEnumerable()
                .FirstOrDefault()
                                                    ??
                                                    await client.CreateDocumentCollectionAsync(database.CollectionsLink,
                                                        new DocumentCollection
                                                        {
                                                            Id = "LMSCollection"
                                                        });

            Console.WriteLine(documentCollection.SelfLink);
            return documentCollection;
        }
        public async void UploadFeedsToDocumentDB()
        {
          
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);  
            
            Database database = client.CreateDatabaseQuery()
                .Where(db => db.Id == databaseId)
                .AsEnumerable()
                .FirstOrDefault(); 
            if (database==null) 
            { 
                database = await client.CreateDatabaseAsync(new Database { Id = databaseId }); 
                Console.WriteLine("Created Database: id - {0} and selfLink - {1}", database.Id, database.SelfLink); 
            }


            DocumentCollection collectionBlog = client.CreateDocumentCollectionQuery(database.CollectionsLink)
                .Where(doccoll => doccoll.Id == collectionIdBlogs)
                .AsEnumerable()
                .FirstOrDefault();
            if (collectionBlog == null)
            {
                collectionBlog = await client.CreateDocumentCollectionAsync(database.SelfLink,
                    new DocumentCollection { Id = collectionIdBlogs });
                Console.WriteLine("Created Collection {0}.", collectionBlog);
            }

            DocumentCollection collectionPosts = client.CreateDocumentCollectionQuery(database.CollectionsLink)
                .Where(doccoll => doccoll.Id == collectionIdPost)
                .AsEnumerable()
                .FirstOrDefault();
            if (collectionPosts == null)
            {
                collectionPosts = await client.CreateDocumentCollectionAsync(database.SelfLink,
                    new DocumentCollection { Id = collectionIdPost });
                Console.WriteLine("Created Collection {0}.", collectionPosts);
            }

            foreach(var f in this.Feeds)
            {
                Console.WriteLine(f.Title);

                foreach (var post in f.Items)
                {
                    Console.Write(".");
                    try
                    {
                        await client.CreateDocumentAsync(collectionPosts.SelfLink, post);
                    }
                    catch(Exception ex)
                    { Console.WriteLine("X"); }
                }

                f.Items.Clear();
                await client.CreateDocumentAsync(collectionBlog.SelfLink, f);
                Console.WriteLine();
            }
        }
        private static async Task GetStartedDemo()
        {
            // Make sure to call client.Dispose() once you've finished all DocumentDB interactions
            // Create a new instance of the DocumentClient
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            // Check to verify a database with the id=FamilyRegistry does not exist
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                // Create a database
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = "FamilyRegistry"
                    });
            }
            else { Warn("database"); }

            // Check to verify a document collection with the id=FamilyCollection does not exist
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault();

            if (documentCollection == null)
            {
                // Create a document collection using the lowest performance tier available (currently, S1)
                documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink,
                    new DocumentCollection { Id = "FamilyCollection" },
                    new RequestOptions { OfferType = "S1" });
            }
            
            else { Warn("document collection"); }

            // Check to verify a document with the id=AndersenFamily does not exist
            Document document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault();

            if (document == null)
            {
                // Create the Andersen Family document
                Family AndersonFamily = new Family
                {
                    Id = "AndersenFamily",
                    LastName = "Andersen",
                    Parents = new Parent[] {
                        new Parent { FirstName = "Thomas" },
                        new Parent { FirstName = "Mary Kay"}
                    },
                    Children = new Child[] {
                        new Child
                        { 
                            FirstName = "Henriette Thaulow", 
                            Gender = "female", 
                            Grade = 5, 
                            Pets = new Pet[] {
                                new Pet { GivenName = "Fluffy" } 
                            }
                        } 
                    },
                    Address = new Address { State = "WA", County = "King", City = "Seattle" },
                    IsRegistered = true
                };

                await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersonFamily);
            }
            else { Warn("document"); }

            // Check to verify a document with the id=AndersenFamily does not exist
            document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault();

            if (document == null)
            {
                // Create the WakeField document
                Family WakefieldFamily = new Family
                {
                    Id = "WakefieldFamily",
                    Parents = new Parent[] {
                        new Parent { FamilyName= "Wakefield", FirstName= "Robin" },
                        new Parent { FamilyName= "Miller", FirstName= "Ben" }
                    },
                    Children = new Child[] {
                        new Child {
                            FamilyName= "Merriam", 
                            FirstName= "Jesse", 
                            Gender= "female", 
                            Grade= 8,
                            Pets= new Pet[] {
                                new Pet { GivenName= "Goofy" },
                                new Pet { GivenName= "Shadow" }
                            }
                        },
                        new Child {
                            FamilyName= "Miller", 
                            FirstName= "Lisa", 
                            Gender= "female", 
                            Grade= 1
                        }
                    },
                    Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
                    IsRegistered = false
                };

                await client.CreateDocumentAsync(documentCollection.DocumentsLink, WakefieldFamily);
            }
            else { Warn("document"); }


            // Query the documents using DocumentDB SQL for the Andersen family
            var families = client.CreateDocumentQuery(documentCollection.DocumentsLink,
                "SELECT * " +
                "FROM Families f " +
                "WHERE f.id = \"AndersenFamily\"");

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from SQL", family);
            }

            // Query the documents using LINQ for the Andersen family
            families =
                from f in client.CreateDocumentQuery(documentCollection.DocumentsLink)
                where f.Id == "AndersenFamily"
                select f;

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ", family);
            }

            // Query the documents using LINQ lambdas for the Andersen family
            families = client.CreateDocumentQuery(documentCollection.DocumentsLink)
                .Where(f => f.Id == "AndersenFamily")
                .Select(f => f);

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ query", family);
            }

            // Query the documents using DocumentSQl with one join
            var items = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink,
                "SELECT f.id, c.FirstName AS child " +
                "FROM Families f " +
                "JOIN c IN f.Children");

            foreach (var item in items.ToList())
            {
                Console.WriteLine(item);
            }

            // Query the documents using LINQ with one join
            items = client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink)
                .SelectMany(family => family.Children
                    .Select(children => new
                    {
                        family = family.Id,
                        child = children.FirstName
                    }));

            foreach (var item in items.ToList())
            {
                Console.WriteLine(item);
            }

            // Clean up/delete the database and client
            await client.DeleteDatabaseAsync(database.SelfLink);
            client.Dispose();
        }
Beispiel #15
0
        private static async Task CreateDatabase()
        {
            var client = new DocumentClient(new Uri(url), auth);

            // Create the database if it does not exist.
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "fProj")
                .AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                database = await client.CreateDatabaseAsync(new Database { Id = "fProj" });
            }
            else
            {
                Console.WriteLine("Your Database existed previously");
            }

            // Create the Document Collection if it does not exist.
            DocumentCollection col = client.CreateDocumentCollectionQuery
                (database.CollectionsLink)
                .Where(c => c.Id == "fpDocs")
                .AsEnumerable().FirstOrDefault();

            if (col == null)
            {
                col = await client.CreateDocumentCollectionAsync
                    (database.CollectionsLink, 
                    new DocumentCollection { Id = "fpDocs" },
                    new RequestOptions { OfferType = "S1" });
            }
            else
            {
                Console.WriteLine("Yo, you already had that collection");
            }

            // Create the first document
            Document doc = client.CreateDocumentQuery(col.DocumentsLink)
                .Where(d => d.Id == "1").AsEnumerable().FirstOrDefault();

            if (doc == null)
            {
                Restaurant doc1 = new Restaurant
                {
                    Id = "1",
                    RName = "Duck's Country Bunker",
                    UserId = "user1",
                    FName = "Phil",
                    LName = "McLovin",
                    MenuItems = new MenuItem[] { 
                        new MenuItem { Id = "1", ItemName = "Small Fries", Calories = 333, Price = .99M },
                        new MenuItem { Id = "2", ItemName = "Medium Fries", Calories = 444, Price = 1.99M },
                        new MenuItem { Id = "3", ItemName = "Large Fries", Calories = 555, Price = 2.99M },
                        new MenuItem { Id = "4", ItemName = "Small Beer", Calories = 5, Price = .99M },
                        new MenuItem { Id = "5", ItemName = "Medium Beer", Calories = 10, Price = 2.00M },
                        new MenuItem { Id = "6", ItemName = "Normal Sized Beer", Calories = 300, Price = 3.00M },
                        new MenuItem { Id = "7", ItemName = "Coffee", Calories = 50, Price = 1.00M }
                    },
                    Address = new Address
                    {
                        Id = "1",
                        StreetNumber = "1235 SE Brooklyn St.",
                        City = "Corvallis",
                        State = "Oregon",
                        ZipCode = "99775"
                    }
                };

                await client.CreateDocumentAsync(col.DocumentsLink, doc1);
            }

            // Create the second document
            doc = client.CreateDocumentQuery(col.DocumentsLink)
                .Where(d => d.Id == "2").AsEnumerable().FirstOrDefault();

            if (doc == null)
            {
                Restaurant doc2 = new Restaurant
                {
                    Id = "2",
                    RName = "Obi One",
                    UserId = "user1",
                    FName = "Allen",
                    LName = "Jones",
                    MenuItems = new MenuItem[] { 
                        new MenuItem { Id = "1", ItemName = "Cheeseburger", Calories = 75, Price = .99M },
                        new MenuItem { Id = "2", ItemName = "Hamburger", Calories = 50, Price = 1M },
                        new MenuItem { Id = "3", ItemName = "Regular Onion Rings", Calories = 100, Price = 1.50M },
                        new MenuItem { Id = "4", ItemName = "Large Onion Rings", Calories = 300, Price = 2M }
                    },
                    Address = new Address
                    {
                        Id = "2",
                        StreetNumber = "4949 N Broadway Ave",
                        City = "Eugene",
                        State = "Oregon",
                        ZipCode = "96709"
                    }
                };

                await client.CreateDocumentAsync(col.DocumentsLink, doc2);
            }

            doc = client.CreateDocumentQuery(col.DocumentsLink)
                .Where(d => d.Id == "3").AsEnumerable().FirstOrDefault();

            if (doc == null)
            {
                Restaurant doc3 = new Restaurant
                {
                    Id = "3",
                    RName = "Classy Chicken",
                    UserId = "user2",
                    FName = "Ash",
                    LName = "Awesome",
                    MenuItems = new MenuItem[] { 
                        new MenuItem { Id = "1", ItemName = "Small Chicken Dinner", Calories = 1111, Price = 11M },
                        new MenuItem { Id = "2", ItemName = "Medium Chicken Dinner", Calories = 2222, Price = 22M },
                        new MenuItem { Id = "3", ItemName = "Large Chicken Dinner", Calories = 3333, Price = 33M },
                        new MenuItem { Id = "4", ItemName = "Freedom Sized Chicken Dinner", Calories = 4444, Price = 44M },
                        new MenuItem { Id = "5", ItemName = "Small Chicken Wings", Calories = 500, Price = 5M },
                        new MenuItem { Id = "6", ItemName = "Medium Chicken Wings", Calories = 1000, Price = 7M },
                        new MenuItem { Id = "7", ItemName = "Large Chicken Wings", Calories = 1500, Price = 10M }
                    },
                    Address = new Address
                    {
                        Id = "3",
                        StreetNumber = "500 Midtown Ave",
                        City = "Los Angeles",
                        State = "California",
                        ZipCode = "90210"
                    }
                };

                await client.CreateDocumentAsync(col.DocumentsLink, doc3);
            }

            doc = client.CreateDocumentQuery(col.DocumentsLink)
                .Where(d => d.Id == "4").AsEnumerable().FirstOrDefault();

            if (doc == null)
            {
                Restaurant doc4 = new Restaurant
                {
                    Id = "4",
                    RName = "Four Stars",
                    UserId = "user2",
                    FName = "Ash",
                    LName = "Awesome",
                    MenuItems = new MenuItem[] { 
                        new MenuItem { Id = "1", ItemName = "Pretentious Meal #1", Calories = 1, Price = 100M },
                        new MenuItem { Id = "2", ItemName = "Pretentious Meal #2", Calories = 2, Price = 100M },
                        new MenuItem { Id = "3", ItemName = "Pretentious Meal #3", Calories = 3, Price = 300M },
                        new MenuItem { Id = "4", ItemName = "Small Gerbil Food", Calories = 4, Price = 400M },
                        new MenuItem { Id = "5", ItemName = "Medium Gerbil Food", Calories = 5, Price = 50M },
                        new MenuItem { Id = "6", ItemName = "Large Gerbil Food", Calories = 6, Price = 60M }
                    },
                    Address = new Address
                    {
                        Id = "4",
                        StreetNumber = "3001 SE Belmont St.",
                        City = "Portland",
                        State = "Oregon",
                        ZipCode = "97214"
                    }
                };

                await client.CreateDocumentAsync(col.DocumentsLink, doc4);
            }


            var items = client.CreateDocumentQuery(col.DocumentsLink, "SELECT r.id, r.rName FROM Restaurant r");

            // Query and check what I have entered is there.
            foreach(var rest in items)
            {
                Console.WriteLine(rest);
            }
            
            // Begin seeding of the collection with users
            Document user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user1")
             .AsEnumerable().FirstOrDefault();

            if (user == null)
            {
                Users user1 = new Users
                {
                    Id = "user1",
                    UserName = "******",
                    Password = "******"
                };

                await client.CreateDocumentAsync(col.DocumentsLink, user1);
            }

            user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user2")
                .AsEnumerable().FirstOrDefault();

            if (user == null)
            {
                Users user2 = new Users
                {
                    Id = "user2",
                    UserName = "******",
                    Password = "******"
                };

                await client.CreateDocumentAsync(col.DocumentsLink, user2);
            }

            // TODO: Try to query a user assosciated with a restaurant as a separate document.
            /*
            */

            //await client.DeleteDatabaseAsync(database.SelfLink);

            // Dispose of the client connection.
            client.Dispose();
        }
        private DocumentConnection CreateDocumentDbConnection()
        {
            var client = new DocumentClient(new Uri(EndpointUri), AccountKey);

            // get the database and if it doesn't exist create it

            Database database = client.CreateDatabaseQuery()
                .Where(db => db.Id == Database)
                .AsEnumerable()
                .FirstOrDefault();

            if (database == null)
            {
                Log.LogMessage(MessageImportance.Low, "The database {0} does not exist, will create it.", Database);
                var task = client.CreateDatabaseAsync(new Database { Id = Database });
                database = task.Result;
            }

            // get the document collection and if it doesn't exist create it

            DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink)
                .Where(c => c.Id == Collection)
                .AsEnumerable()
                .FirstOrDefault();

            if (collection == null)
            {
                Log.LogMessage(MessageImportance.Low, "The collection {0} does not exist, will create it.", Collection);
                var task = client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = Collection });
                collection = task.Result;
            }

            Log.LogMessage(MessageImportance.Normal, "Connected to DocumentDB database {0}, collection {1}.", Database, Collection);
            return new DocumentConnection(database, client, collection);
        }
        /// <summary>
        /// Initialize the DocumentDb settings and connections
        /// </summary>
        public void InitializeDocumentDb()
        {
            this.DocumentDbEndPointUrl = ConfigurationManager.AppSettings["DocumentDbEndPointUrl"];
            if (String.IsNullOrWhiteSpace(this.DocumentDbEndPointUrl))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbEndPointUrl");
            }

            this.DocumentDbAuthorizationKey = ConfigurationManager.AppSettings["DocumentDbAuthorizationKey"];
            if (String.IsNullOrWhiteSpace(this.DocumentDbAuthorizationKey))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbAuthorizationKey");
            }

            this.DocumentDbDatabase = ConfigurationManager.AppSettings["DocumentDbDatabase"];
            if (String.IsNullOrWhiteSpace(this.DocumentDbDatabase))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbDatabase");
            }

            this.DocumentDbCollection = ConfigurationManager.AppSettings["DocumentDbCollection"];
            if (String.IsNullOrWhiteSpace(this.DocumentDbCollection))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "DocumentDbCollection");
            }

            // Create a new instance of the DocumentClient
            documentClient = new DocumentClient(new Uri(this.DocumentDbEndPointUrl), this.DocumentDbAuthorizationKey);

            // Check to verify if database already exists
            Database database = documentClient.CreateDatabaseQuery().
                Where(db => db.Id == this.DocumentDbDatabase).AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                Context.Logger.Info("Creating a new DocumentDb database: {0}", this.DocumentDbDatabase);
                // Create a database
                var task = documentClient.CreateDatabaseAsync(
                    new Database
                    {
                        Id = this.DocumentDbDatabase
                    });

                task.Wait();
                database = task.Result;
            }
            else
            {
                Context.Logger.Info("Found an existing DocumentDb database: {0}", database.Id);
            }

            // Check to verify a document collection already exists
            documentCollection = documentClient.CreateDocumentCollectionQuery(database.CollectionsLink).
                Where(c => c.Id == this.DocumentDbCollection).AsEnumerable().FirstOrDefault();

            if (documentCollection == null)
            {
                Context.Logger.Info("Creating a new DocumentDb collection: {0}", this.DocumentDbCollection);
                // Create a document collection
                var task = documentClient.CreateDocumentCollectionAsync(database.CollectionsLink,
                    new DocumentCollection
                    {
                        Id = this.DocumentDbCollection,
                    });

                task.Wait();
                documentCollection = task.Result;
            }
            else
            {
                Context.Logger.Info("Found an existing DocumentDb collection: {0}", documentCollection.Id);
            }
        }
        private static async Task GetStartedDemo()
        {
            // Create a new instance of the DocumentClient
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            // Check to verify a database with the id=FamilyRegistry does not exist
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault();

            // If the database does not exist, create a new database
            if (database == null)
            {
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = "FamilyRegistry"
                    });

                WriteMessage("Created dbs/FamilyRegistry");
            }

            // Check to verify a document collection with the id=FamilyCollection does not exist
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault();

            // If the document collection does not exist, create a new collection
            if (documentCollection == null)
            {
                documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id,
                    new DocumentCollection
                    {
                        Id = "FamilyCollection"
                    });

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault();

            // If the document does not exist, create a new document
            if (document == null)
            {
                // Create the Andersen Family document
                Family andersonFamily = new Family
                {
                    Id = "AndersenFamily",
                    LastName = "Andersen",
                    Parents = new Parent[] {
                        new Parent { FirstName = "Thomas" , SSN = "111-11-1111"}.Seal(),
                        new Parent { FirstName = "Mary Kay", SSN = "222-22-2222"}.Seal()
                    },
                    Children = new Child[] {
                        new Child
                        { 
                            FirstName = "Henriette Thaulow", 
                            Gender = "female", 
                            Grade = 5, 
                            Pets = new Pet[] {
                                new Pet { GivenName = "Fluffy" } 
                            }
                        } 
                    },
                    Address = new Address { State = "WA", County = "King", City = "Seattle" },
                    IsRegistered = true,
                    GeneticCondition = "diabetes"
                };

                Crypteron.CipherObject.Seal(andersonFamily); // or andersonFamily.Seal()

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault();

            if (document == null)
            {
                // Create the WakeField document
                Family wakefieldFamily = new Family
                {
                    Id = "WakefieldFamily",
                    Parents = new Parent[] {
                        new Parent { FamilyName= "Wakefield", FirstName= "Robin" },
                        new Parent { FamilyName= "Miller", FirstName= "Ben" }
                    },
                    Children = new Child[] {
                        new Child {
                            FamilyName= "Merriam", 
                            FirstName= "Jesse", 
                            Gender= "female", 
                            Grade= 8,
                            Pets= new Pet[] {
                                new Pet { GivenName= "Goofy" },
                                new Pet { GivenName= "Shadow" }
                            }
                        },
                        new Child {
                            FamilyName= "Miller", 
                            FirstName= "Lisa", 
                            Gender= "female", 
                            Grade= 1
                        }
                    },
                    Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
                    IsRegistered = false,
                };

                Crypteron.CipherObject.Seal(wakefieldFamily); // or wakefieldFamily.Seal()                

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily");
            }

            // Query the documents using DocumentDB SQL for the Andersen family
            var families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id,
                "SELECT * " +
                "FROM Families f " +
                "WHERE f.id = \"AndersenFamily\"");

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from SQL", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented));
            }

            // Query the documents using LINQ for the Andersen family
            families =
                from f in client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                where f.Id == "AndersenFamily"
                select f;

            foreach (var family in families)
            {
                Console.WriteLine("Read {0} from LINQ", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented));
            }

            // Query the documents using LINQ lambdas for the Andersen family
            // Need to get results back in original class with Secure attributes
            // Dynamic JObject is not currently supported
            families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                .Where(f => f.Id == "AndersenFamily")
                .Select(f => f);

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ query", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented));
            }

            // Clean up/delete the database and client
            Console.WriteLine("Done. Press 'd' to delete database prior to exiting");
            var choice = Console.ReadKey().KeyChar;
            if (choice == 'd' || choice == 'D')
            {
                Console.WriteLine("\nDeleting database ...");
                await client.DeleteDatabaseAsync("dbs/" + database.Id);
            }
            client.Dispose();
        }
Beispiel #19
0
        private static DocumentCollection GetOrCreateCollection(DocumentClient client, string databaseLink, string collectionId)
        {
            var col = client.CreateDocumentCollectionQuery(databaseLink)
                              .Where(c => c.Id == collectionId)
                              .AsEnumerable()
                              .FirstOrDefault();

            if (col == null)
            {
                col = client.CreateDocumentCollectionAsync(databaseLink, new DocumentCollection { Id = collectionId }).Result;
            }

            return col;
        }
 /// <summary>
 /// Internal Member to get or return a Azure DocumentDB Collection
 /// </summary>
 /// <param name="client"></param>
 /// <param name="dbLink"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 private async Task<DocumentCollection> GetOrCreateCollectionAsync(DocumentClient client, string dbLink, string id)
 {
     DocumentCollection collection = client.CreateDocumentCollectionQuery(dbLink).Where(c => c.Id == id).ToArray().FirstOrDefault();
     if (collection == null)
     {
         collection = await client.CreateDocumentCollectionAsync(dbLink, new DocumentCollection { Id = id });
     }
     return collection;
 }
Beispiel #21
0
 /// <summary>
 /// Internal Member to get or return a Azure DocumentDB Collection
 /// </summary>
 /// <param name="client"></param>
 /// <param name="dbLink"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 private async Task<DocumentCollection> GetOrCreateCollectionAsync(DocumentClient client, string dbLink, string id)
 {
     DocumentCollection collection = client.CreateDocumentCollectionQuery(dbLink).Where(c => c.Id == id).ToArray().FirstOrDefault();
     if (collection == null)
     {
         collection = await client.CreateDocumentCollectionAsync(dbLink, new DocumentCollection { Id = id });
        Log.Info("AzureDocDbRequestManager.GetOrCreateCollectionAsync", "Created Document DB Collection {0}", dbLink);
     }
     return collection;
 }
        private static async Task GetStartedDemo()
        {
            // Create a new instance of the DocumentClient
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            // Check to verify a database with the id=FamilyRegistry does not exist
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault();

            // If the database does not exist, create a new database
            if (database == null)
            {
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = "FamilyRegistry"
                    });

                WriteMessage("Created dbs/FamilyRegistry");
            }

            // Check to verify a document collection with the id=FamilyCollection does not exist
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault();

            // If the document collection does not exist, create a new collection
            if (documentCollection == null)
            {
                documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id,
                    new DocumentCollection
                    {
                        Id = "FamilyCollection"
                    });

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault();

            // If the document does not exist, create a new document
            if (document == null)
            {
                // Create the Andersen Family document
                Family andersonFamily = new Family
                {
                    Id = "AndersenFamily",
                    LastName = "Andersen",
                    Parents = new Parent[] {
                        new Parent { FirstName = "Thomas" },
                        new Parent { FirstName = "Mary Kay"}
                    },
                    Children = new Child[] {
                        new Child
                        { 
                            FirstName = "Henriette Thaulow", 
                            Gender = "female", 
                            Grade = 5, 
                            Pets = new Pet[] {
                                new Pet { GivenName = "Fluffy" } 
                            }
                        } 
                    },
                    Address = new Address { State = "WA", County = "King", City = "Seattle" },
                    IsRegistered = true
                };

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault();

            if (document == null)
            {
                // Create the WakeField document
                Family wakefieldFamily = new Family
                {
                    Id = "WakefieldFamily",
                    Parents = new Parent[] {
                        new Parent { FamilyName= "Wakefield", FirstName= "Robin" },
                        new Parent { FamilyName= "Miller", FirstName= "Ben" }
                    },
                    Children = new Child[] {
                        new Child {
                            FamilyName= "Merriam", 
                            FirstName= "Jesse", 
                            Gender= "female", 
                            Grade= 8,
                            Pets= new Pet[] {
                                new Pet { GivenName= "Goofy" },
                                new Pet { GivenName= "Shadow" }
                            }
                        },
                        new Child {
                            FamilyName= "Miller", 
                            FirstName= "Lisa", 
                            Gender= "female", 
                            Grade= 1
                        }
                    },
                    Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
                    IsRegistered = false
                };

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily");
            }

            // Query the documents using DocumentDB SQL for the Andersen family
            var families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id,
                "SELECT * " +
                "FROM Families f " +
                "WHERE f.id = \"AndersenFamily\"");

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from SQL", family);
            }

            // Query the documents using LINQ for the Andersen family
            families =
                from f in client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                where f.Id == "AndersenFamily"
                select f;

            foreach (var family in families)
            {
                Console.WriteLine("Read {0} from LINQ", family);
            }

            // Query the documents using LINQ lambdas for the Andersen family
            families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                .Where(f => f.Id == "AndersenFamily")
                .Select(f => f);

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ query", family);
            }

            // Clean up/delete the database and client
            await client.DeleteDatabaseAsync("dbs/" + database.Id);
            client.Dispose();
        }