Beispiel #1
0
        private async Task InitializeDatabase()
        {
            try
            {
                await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_databaseId));
            }
            catch (DocumentClientException dce)
            {
                if (dce.StatusCode == HttpStatusCode.NotFound)
                {
                    await _client.CreateDatabaseAsync(new Database { Id = _databaseId });

                    return;
                }

                throw;
            }
        }
 private static async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = databaseName });
         }
         else
         {
             throw;
         }
     }
 }
 private async Task CreateDataBaseIfNotExists(DocumentClient documentClient)
 {
     try
     {
         await documentClient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(CloudConfigurationManager.GetSetting(AzureRelatedNames.DatabaseName)));
     }
     catch (DocumentClientException de)
     {
         if (de.StatusCode == HttpStatusCode.NotFound)
         {
             await documentClient.CreateDatabaseAsync(new Database { Id = CloudConfigurationManager.GetSetting(AzureRelatedNames.DatabaseName) });
         }
         else
         {
             throw;
         }
     }
 }
        private async Task <DocumentCollection> SetupSingleCollectionScenario()
        {
            DocumentClient client = TestCommon.CreateClient(true);
            await TestCommon.DeleteAllDatabasesAsync();

            Database database             = (await client.CreateDatabaseAsync(new Database {
                Id = this.DatabaseName
            })).Resource;
            DocumentCollection collection = (await client.CreateDocumentCollectionIfNotExistsAsync(database.SelfLink, new DocumentCollection {
                Id = this.CollectionName
            }, new RequestOptions {
                OfferThroughput = 10000
            })).Resource;

            //   await Task.Delay(30000);

            return(collection);
        }
Beispiel #5
0
 private async Task CreateDatabaseIfNotExists()
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(dbName));
     }
     catch (DocumentClientException de)
     {
         if (de.StatusCode == HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = dbName });
         }
         else
         {
             logger.Error(de);
         }
     }
 }
 private async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_databaseId));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = _databaseId });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #7
0
 private async Task CreateDatabaseIfNotExists()
 {
     try
     {
         await Client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseName));
     }
     catch (DocumentClientException ex)
     {
         if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await Client.CreateDatabaseAsync(new Database { Id = DatabaseName });
         }
         else
         {
             throw ex;
         }
     }
 }
Beispiel #8
0
        async Task <Database> GetDatabase()
        {
            var dbs = from db in Cosmos.CreateDatabaseQuery()
                      where db.Id == DatabaseName
                      select db;

            var dbr = dbs.ToList().First();

            if (dbr == null)
            {
                dbr = await Cosmos.CreateDatabaseAsync(new Database()
                {
                    Id = DatabaseName
                });
            }

            return(dbr);
        }
Beispiel #9
0
 //method for creating database if it doesnot exist
 public static async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {//read from already created database
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {//if not found then create a new database
             await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #10
0
 private async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
     }
     catch (DocumentClientException docEx)
     {
         if (docEx.StatusCode == HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #11
0
 async Task createDatabaseAsync(DocumentClient client, string id)
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(id));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = id });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #12
0
 public async Task CreateDatabaseIfNotExistsAsync(CancellationToken cancellationToken)
 {
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_builder.Database));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = _builder.Database });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #13
0
 private async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(ConfigSettings.Database));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = ConfigSettings.Database });
         }
         else
         {
             throw;
         }
     }
 }
#pragma warning disable 1591 // Xml Comments
        public void Initialize(IContainer container)
        {
            Client = new DocumentClient(new Uri(_configuration.Url), _configuration.AuthorizationKey);

            Client.ReadDatabaseFeedAsync()
            .ContinueWith(a => Database = a.Result.Where(d => d.Id == _configuration.DatabaseId).SingleOrDefault())
            .Wait();

            if (Database == null)
            {
                this.Database = new Database {
                    Id = _configuration.DatabaseId
                };
                Client.CreateDatabaseAsync(Database)
                .ContinueWith(d => Database = d.Result.Resource)
                .Wait();
            }
        }
        private async Task <Database> InitialiseDatabase()
        {
            // Check to verify a database with the id=FamilyRegistry does not exist
            var database = _documentClient.CreateDatabaseQuery()
                           .Where(db => db.Id == "AssociateRecords")
                           .AsEnumerable()
                           .FirstOrDefault();

            if (database == null)
            {
                database = await _documentClient.CreateDatabaseAsync(
                    new Database
                {
                    Id = "AssociateRecords"
                });
            }
            return(database);
        }
Beispiel #16
0
 private async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_config.GetValue <string>("Values:COSMOSDB_DATABASE_NAME")));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = _config.GetValue <string>("Values:COSMOSDB_DATABASE_NAME") });
         }
         else
         {
             throw;
         }
     }
 }
        private async Task InitDocDbClient()
        {
            using (var client = new DocumentClient(new Uri(_cloudConfig.DocDbUri), _cloudConfig.DocDbKey))
            {
                await client.OpenAsync();

                //This code is not as efficient as storing the selfLink in the config, but
                //I wanted to keep it easy to configure.

                var dynamicDb =
                    client.CreateDatabaseQuery("select * from root r where r.id = '" + _cloudConfig.DocDbDatabaseName +
                                               "'")
                    .AsEnumerable().FirstOrDefault();

                string dbSelfLink;
                if (dynamicDb == null)
                {
                    var db = new Database {
                        Id = _cloudConfig.DocDbDatabaseName
                    };
                    db = await client.CreateDatabaseAsync(db);

                    dbSelfLink = db.SelfLink;
                }
                else
                {
                    dbSelfLink = dynamicDb._self;
                }

                var collectionFeed = await client.ReadDocumentCollectionFeedAsync(dbSelfLink);

                var collection = collectionFeed.SingleOrDefault(x => x.Id == DataTableName);
                if (collection == null)
                {
                    collection = new DocumentCollection {
                        Id = DataTableName
                    };
                    collection = await client.CreateDocumentCollectionAsync(dbSelfLink, collection);
                }

                //Caching the selfLink will help avoid querying the collections excessively
                CollectionSelfLink = collection.SelfLink;
            }
        }
        static void Main()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile($"appsettings.json");
            var configuration = builder.Build();

            Console.WriteLine("Obter configurações de acesso...");
            DocumentClient client = new DocumentClient(
                new Uri(configuration.GetSection("DBCatalogo:EndpointUri").Value),
                configuration.GetSection("DBCatalogo:PrimaryKey").Value);

            Console.WriteLine("Criar banco de dados...");
            client.CreateDatabaseAsync(
                new Database {
                Id = "DBCatalogo"
            }).Wait();

            Console.WriteLine("Criar coleção...");
            DocumentCollection collectionInfo = new DocumentCollection();

            collectionInfo.Id = "Catalogo";

            collectionInfo.IndexingPolicy =
                new IndexingPolicy(new RangeIndex(DataType.String)
            {
                Precision = -1
            });

            client.CreateDocumentCollectionAsync(
                UriFactory.CreateDatabaseUri("DBCatalogo"),
                collectionInfo,
                new RequestOptions {
                OfferThroughput = 400
            }).Wait();

            Console.WriteLine("Incluir produtos...");
            Carga.InserirDadosProdutos(client);

            Console.WriteLine("Incluir serviços...");
            Carga.InserirDadosServicos(client);

            Console.WriteLine("Finalizado!");
        }
Beispiel #19
0
 protected virtual async Task CreateDatabaseIfNotExistsAsync()
 {
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_config.DatabaseId))
         .ConfigureAwait(false);
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = _config.DatabaseId }).ConfigureAwait(false);
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #20
0
 private async Task CreateDatabaseIfNotExists()
 {
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DbName));
     }
     catch (DocumentClientException de)
     {
         // If the database does not exist, create a new database
         if (de.StatusCode == HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = DbName });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #21
0
        private static async Task SetupEnvironmentAsync(string dbUri, string key, string collectionName)
        {
            var client   = new DocumentClient(new Uri(dbUri), key);
            var database = new Database()
            {
                Id = DbName
            };
            await client.CreateDatabaseAsync(database);

            await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(DbName), new DocumentCollection()
            {
                Id = collectionName
            });

            await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(DbName), new DocumentCollection()
            {
                Id = $"{collectionName}.Lease.ConsoleApp"
            });
        }
        /// <summary>
        /// Create database if it does not exist
        /// </summary>
        /// <returns></returns>
        private static async Task CreateNewDatabaseAsync()
        {
            try
            {
                await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));

                await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
            }
            catch (DocumentClientException e)
            {
                // If we receive an error other than database not found, fail
                if (e.StatusCode != System.Net.HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            await client.CreateDatabaseAsync(new Database { Id = databaseName });
        }
Beispiel #23
0
        public async Task ResourceResponseStreamingTest()
        {
            using (DocumentClient client = TestCommon.CreateClient(true))
            {
                Database db             = (await client.CreateDatabaseAsync(new Database()
                {
                    Id = Guid.NewGuid().ToString()
                })).Resource;
                DocumentCollection coll = await TestCommon.CreateCollectionAsync(client, db, new DocumentCollection()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = new PartitionKeyDefinition()
                    {
                        Paths = new System.Collections.ObjectModel.Collection <string>()
                        {
                            "/id"
                        }
                    }
                });

                ResourceResponse <Document> doc = await client.CreateDocumentAsync(coll.SelfLink, new Document()
                {
                    Id = Guid.NewGuid().ToString()
                });

                Assert.AreEqual(doc.ResponseStream.Position, 0);

                StreamReader streamReader = new StreamReader(doc.ResponseStream);
                string       text         = streamReader.ReadToEnd();

                Assert.AreEqual(doc.ResponseStream.Position, doc.ResponseStream.Length);

                try
                {
                    doc.Resource.ToString();
                    Assert.Fail("Deserializing Resource here should throw exception since the stream was already read");
                }
                catch (JsonReaderException ex)
                {
                    Console.WriteLine("Expected exception while deserializing Resource: " + ex.Message);
                }
            }
        }
Beispiel #24
0
        private async Task <CosmosContainerSettings> SetupSingleCollectionScenario()
        {
            DocumentClient client = TestCommon.CreateClient(true);

            TestCommon.DeleteAllDatabasesAsync(client).Wait();

            CosmosDatabaseSettings database    = (await client.CreateDatabaseAsync(new CosmosDatabaseSettings {
                Id = this.DatabaseName
            })).Resource;
            CosmosContainerSettings collection = (await client.CreateDocumentCollectionIfNotExistsAsync(database.SelfLink, new CosmosContainerSettings {
                Id = this.CollectionName
            }, new RequestOptions {
                OfferThroughput = 10000
            })).Resource;

            //   await Task.Delay(30000);

            return(collection);
        }
 public static async Task CreateDatabaseIfNotExistsAsync(
     this DocumentClient client, string databaseId)
 {
     try
     {
         await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseId));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await client.CreateDatabaseAsync(new Database { Id = databaseId }).ConfigureAwait(false);
         }
         else
         {
             throw;
         }
     }
 }
 private async Task CreateDatabaseIfNotExistsAsync()
 {
     // TODO: Create db with shared 400 RU/s across all containers
     try
     {
         await _client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(_databaseId));
     }
     catch (DocumentClientException e)
     {
         if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             await _client.CreateDatabaseAsync(new Database { Id = _databaseId });
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #27
0
        public void ValidateVersionHeader()
        {
            string correctVersion = HttpConstants.Versions.CurrentVersion;

            try
            {
                DocumentClient client = TestCommon.CreateClient(true);
                var            db     = client.CreateDatabaseAsync(new Database()
                {
                    Id = Guid.NewGuid().ToString()
                }).Result.Resource;
                var coll = client.CreateDocumentCollectionAsync(db.SelfLink, new DocumentCollection()
                {
                    Id = Guid.NewGuid().ToString()
                }).Result.Resource;
                var doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                client = TestCommon.CreateClient(true);
                doc    = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                HttpConstants.Versions.CurrentVersion = "2015-01-01";
                client = TestCommon.CreateClient(true);
                try
                {
                    doc = client.CreateDocumentAsync(coll.SelfLink, new Document()).Result.Resource;
                    Assert.Fail("Should have faild because of version error");
                }
                catch (AggregateException exception)
                {
                    var dce = exception.InnerException as DocumentClientException;
                    if (dce != null)
                    {
                        Assert.AreEqual(dce.StatusCode, HttpStatusCode.BadRequest);
                    }
                    else
                    {
                        Assert.Fail("Should have faild because of version error with DocumentClientException BadRequest");
                    }
                }
            }
            finally
            {
                HttpConstants.Versions.CurrentVersion = correctVersion;
            }
        }
        internal void TestEtagOnUpsertOperation(DocumentClient client)
        {
            Database db = client.CreateDatabaseAsync(new Database()
            {
                Id = Guid.NewGuid().ToString()
            }).Result.Resource;
            DocumentCollection coll = TestCommon.CreateCollectionAsync(client, db, new DocumentCollection()
            {
                Id = Guid.NewGuid().ToString()
            }).Result;

            LinqGeneralBaselineTests.Book myBook = new LinqGeneralBaselineTests.Book();
            myBook.Id    = Guid.NewGuid().ToString();
            myBook.Title = "Azure DocumentDB 101";

            Document doc = client.CreateDocumentAsync(coll.SelfLink, myBook).Result.Resource;

            myBook.Title = "Azure DocumentDB 201";
            client.ReplaceDocumentAsync(doc.SelfLink, myBook).Wait();

            AccessCondition condition = new AccessCondition();

            condition.Type      = AccessConditionType.IfMatch;
            condition.Condition = doc.ETag;

            RequestOptions requestOptions = new RequestOptions();

            requestOptions.AccessCondition = condition;

            myBook.Title = "Azure DocumentDB 301";

            try
            {
                client.UpsertDocumentAsync(coll.SelfLink, myBook, requestOptions).Wait();
                Assert.Fail("Upsert Document should fail since the Etag is not matching.");
            }
            catch (Exception ex)
            {
                var innerException = ex.InnerException as DocumentClientException;
                Assert.IsTrue(innerException.StatusCode == HttpStatusCode.PreconditionFailed, "Invalid status code");
            }
        }
Beispiel #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            // make sure the database exists!
            Database db = client.CreateDatabaseQuery().Where(d => d.Id == databaseId).AsEnumerable().FirstOrDefault()
                          ?? client.CreateDatabaseAsync(new Database {
                Id = databaseId
            }).Result;

            // add Identity Server with DocumentDB stores (will store data in collections "users" and "roles")
            // services.AddIdentityWithDocumentDBStoresUsingCustomTypes<MyUser, MyRole>(client, databaseLink);

            // variant 2:
            services.AddIdentity <MyUser, MyRole>()
            .RegisterDocumentDBStores <MyUser, MyRole>(client, (p) => new DocumentCollection {
                Id = "userCollection"
            });
        }
        /// <summary>
        /// Get a Database by id, or create a new one if one with the id provided doesn't exist.
        /// </summary>
        /// <param name="client">The DocumentDB client instance.</param>
        /// <param name="id">The id of the Database to search for, or create.</param>
        /// <returns>The matched, or created, Database object</returns>
        private static async Task <Database> GetOrCreateDatabaseAsync(DocumentClient client, string id)
        {
            // Get the database by name, or create a new one if one with the name provided doesn't exist.
            // Create a query object for database, filter by name.
            IEnumerable <Database> query = from db in client.CreateDatabaseQuery()
                                           where db.Id == id
                                           select db;

            // Run the query and get the database (there should be only one) or null if the query didn't return anything.
            // Note: this will run synchronously. If async exectution is preferred, use IDocumentServiceQuery<T>.ExecuteNextAsync.
            Database database = query.FirstOrDefault();

            if (database == null)
            {
                // Create the database.
                database = await client.CreateDatabaseAsync(new Database { Id = id });
            }

            return(database);
        }