Пример #1
0
        public Editor(
            ICommandService commandService,
            IControlHostService controlHostService,
            IDocumentService documentService,
            IDocumentRegistry documentRegistry,
            IFileDialogService fileDialogService
            )
        {
            m_commandService = commandService;
            m_controlHostService = controlHostService;
            m_documentService = documentService;
            m_documentRegistry = documentRegistry;
            m_fileDialogService = fileDialogService;

            // create a document client for each file type
            m_txtDocumentClient = new DocumentClient(this, ".txt");
            m_csDocumentClient = new DocumentClient(this, ".cs");
            m_luaDocumentClient = new DocumentClient(this, ".lua");
            m_nutDocumentClient = new DocumentClient(this, ".nut");
            m_pyDocumentClient = new DocumentClient(this, ".py");
            m_xmlDocumentClient = new DocumentClient(this, ".xml");
            m_daeDocumentClient = new DocumentClient(this, ".dae");
            m_cgDocumentClient = new DocumentClient(this, ".cg");

        }
Пример #2
0
 public TerminalRepository(DocumentClient client)
 {
     this._client = client;
 }
Пример #3
0
 public MeasureRepository(DocumentClient documentClient, Uri documentCollectionUri)
 {
     _documentClient        = documentClient;
     _documentCollectionUri = documentCollectionUri;
 }
Пример #4
0
 private static Database GetDatabaseIfExists(DocumentClient client, string databaseName)
 {
     return(client.CreateDatabaseQuery().Where(d => d.Id == databaseName).AsEnumerable().FirstOrDefault());
 }
Пример #5
0
 public void Initialize()
 {
     client = new DocumentClient(new Uri(_cosmosDbEndpoint), _cosmosDbKey);
     CreateDatabaseIfNotExistsAsync().Wait();
     CreateCollectionIfNotExistsAsync().Wait();
 }
 /// <summary>
 /// A method to create the cosmos client
 /// </summary>
 /// <remarks>
 /// Setting this property after sending any request won't have any effect.
 /// </remarks>
 internal virtual CosmosClient Build(DocumentClient documentClient)
 {
     DefaultTrace.TraceInformation($"CosmosClientBuilder.Build(DocumentClient) with configuration: {this.clientOptions.GetSerializedConfiguration()}");
     return(new CosmosClient(this.accountEndpoint, this.accountKey, this.clientOptions, documentClient));
 }
Пример #7
0
 public static void AddDocumentDbRepo(DocumentClient client, string dbName, string collectionName)
 {
     Repos.Add(collectionName, new DocumentDbRepo(dbName, collectionName, client));
 }
Пример #8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "GetDailyItems")] HttpRequestMessage req,
            [DocumentDB(Constants.CosmosDbName, Constants.ItemsCollectionName, ConnectionStringSetting = Constants.ConnectionStringSettingName)] DocumentClient client,
            TraceWriter log)
        {
            log.Info($"GetDailyItems begin");

            try
            {
                string playFabId = await PlayFab.AuthenticateUserAsync(req, log);

                string date = DateTime.Now.ToString(Constants.DateFormat);

                if (string.IsNullOrEmpty(playFabId))
                {
                    return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }

                // Get the list of items for today
                Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, Constants.ItemsCollectionName);
                IOrderedQueryable <DailyItems> query         = client.CreateDocumentQuery <DailyItems>(collectionUri);
                IQueryable <DailyItems>        dailyItemsDoc =
                    from di in query
                    where di.Date == date
                    select di;
                DailyItems[] dailyItemsArray = dailyItemsDoc.ToArray();
                if (dailyItemsArray.Length == 0)
                {
                    log.Error($"No daily items found for {date}");
                    return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, $"No daily items found for {date}"));
                }

                // and pull back just today's items
                DailyItems dailyItems = dailyItemsArray.Single();

                // get all items a user has found for today
                Uri foundUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, Constants.FoundItemsCollectionName);
                IOrderedQueryable <FoundItem> foundQuery    = client.CreateDocumentQuery <FoundItem>(foundUri);
                IQueryable <FoundItem>        foundItemsDoc =
                    from found in foundQuery
                    where found.PlayFabId == playFabId && found.Date == date
                    select found;

                FoundItem[] foundItems = foundItemsDoc.ToArray();

                // mark all found items by enumerating through both arrays
                foreach (Item i in dailyItems.Items)
                {
                    foreach (FoundItem fi in foundItems)
                    {
                        if (fi.Item.Id == i.Id)
                        {
                            i.Found = true;
                            break;
                        }
                    }
                }

                log.Info($"GetDailyItems complete");

                return(req.CreateResponse(HttpStatusCode.OK, dailyItems));
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return(req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Пример #9
0
 public GraphProjectionObserverFactory(DocumentClient client, DocumentCollection collectionInfo, ISerializationTypeMap typeMap)
 {
     this.client         = client;
     this.collectionInfo = collectionInfo;
     this.typeMap        = typeMap;
 }
 public TeamServiceContext(DocumentClient documentClient)
 {
     _documentClient = documentClient;
 }
Пример #11
0
 public DbCollectionOperationsRepository()
 {
     docClient = new DocumentClient(new Uri(EndPoint), Key);
     CreateDatabaseIfNotExistsAsync().Wait();
     CreateCollectionIfNotExistsAsync().Wait();
 }
 public DocumentDBRepository()
 {
     this.client = new DocumentClient(new Uri(Endpoint), Key);
     CreateDatabaseIfNotExistsAsync().Wait();
     CreateCollectionIfNotExistsAsync().Wait();
 }
Пример #13
0
        async public Task <bool> Open()
        {
            try
            {
                _client = new DocumentClient(
                    new Uri(ConnectionString.ExtractConnectionStringParameter("AccountEndpoint")),
                    ConnectionString.ExtractConnectionStringParameter("AccountKey"));

                var database = _client.CreateDatabaseQuery()
                               .Where(db => db.Id == ConnectionString.ExtractConnectionStringParameter("Database"))
                               .AsEnumerable()
                               .FirstOrDefault();

                if (database == null)
                {
                    throw new Exception($"Database {ConnectionString.ExtractConnectionStringParameter("Database")} not exits");
                }

                _spatialCollectionRef = _client.CreateDocumentCollectionQuery(database.SelfLink)
                                        .Where(col => col.Id == SpatialCollectionRefName)
                                        .AsEnumerable()
                                        .FirstOrDefault();

                if (_spatialCollectionRef == null)
                {
                    var partitionKey = new PartitionKeyDefinition();
                    partitionKey.Paths.Add("/name");

                    var response = await _client.CreateDocumentCollectionAsync(
                        database.SelfLink,
                        new DocumentCollection()
                    {
                        Id           = SpatialCollectionRefName,
                        PartitionKey = partitionKey
                    });

                    _spatialCollectionRef = response.Resource;
                }

                #region Points Collection

                _featureCollection_points = _client.CreateDocumentCollectionQuery(database.SelfLink)
                                            .Where(col => col.Id == FeatureCollectionNamePoints)
                                            .AsEnumerable()
                                            .FirstOrDefault();

                if (_featureCollection_points == null)
                {
                    IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
                    {
                        IncludedPaths = new System.Collections.ObjectModel.Collection <IncludedPath>()
                        {
                            new IncludedPath
                            {
                                Path    = "/*",
                                Indexes = new System.Collections.ObjectModel.Collection <Index>()
                                {
                                    new SpatialIndex(DataType.Point),
                                    new RangeIndex(DataType.Number)
                                    {
                                        Precision = -1
                                    },
                                    new RangeIndex(DataType.String)
                                    {
                                        Precision = -1
                                    }
                                }
                            }
                        }
                    };

                    var partitionKey = new PartitionKeyDefinition();
                    partitionKey.Paths.Add("/_fc");


                    var response = await _client.CreateDocumentCollectionAsync(
                        database.SelfLink,
                        new DocumentCollection()
                    {
                        Id             = FeatureCollectionNamePoints,
                        PartitionKey   = partitionKey,
                        IndexingPolicy = indexingPolicyWithSpatialEnabled
                    });

                    // ToDo: Create Spatial Index

                    _featureCollection_points = response.Resource;
                }

                #endregion

                #region Lines Collection

                _featureCollection_lines = _client.CreateDocumentCollectionQuery(database.SelfLink)
                                           .Where(col => col.Id == FeatureCollectionNameLines)
                                           .AsEnumerable()
                                           .FirstOrDefault();

                if (_featureCollection_lines == null)
                {
                    IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
                    {
                        IncludedPaths = new System.Collections.ObjectModel.Collection <IncludedPath>()
                        {
                            new IncludedPath
                            {
                                Path    = "/*",
                                Indexes = new System.Collections.ObjectModel.Collection <Index>()
                                {
                                    new SpatialIndex(DataType.LineString),
                                    new RangeIndex(DataType.Number)
                                    {
                                        Precision = -1
                                    },
                                    new RangeIndex(DataType.String)
                                    {
                                        Precision = -1
                                    }
                                }
                            }
                        }
                    };

                    var partitionKey = new PartitionKeyDefinition();
                    partitionKey.Paths.Add("/_fc");


                    var response = await _client.CreateDocumentCollectionAsync(
                        database.SelfLink,
                        new DocumentCollection()
                    {
                        Id             = FeatureCollectionNameLines,
                        PartitionKey   = partitionKey,
                        IndexingPolicy = indexingPolicyWithSpatialEnabled
                    });

                    _featureCollection_lines = response.Resource;
                }

                #endregion

                #region Polygons Collection

                _featureCollection_polygons = _client.CreateDocumentCollectionQuery(database.SelfLink)
                                              .Where(col => col.Id == FeatureCollectionNamePolygons)
                                              .AsEnumerable()
                                              .FirstOrDefault();

                if (_featureCollection_polygons == null)
                {
                    IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
                    {
                        IncludedPaths = new System.Collections.ObjectModel.Collection <IncludedPath>()
                        {
                            new IncludedPath
                            {
                                Path    = "/*",
                                Indexes = new System.Collections.ObjectModel.Collection <Index>()
                                {
                                    new SpatialIndex(DataType.Point),
                                    new SpatialIndex(DataType.Polygon),
                                    new RangeIndex(DataType.Number)
                                    {
                                        Precision = -1
                                    },
                                    new RangeIndex(DataType.String)
                                    {
                                        Precision = -1
                                    }
                                }
                            }
                        }
                    };

                    var partitionKey = new PartitionKeyDefinition();
                    partitionKey.Paths.Add("/_fc");


                    var response = await _client.CreateDocumentCollectionAsync(
                        database.SelfLink,
                        new DocumentCollection()
                    {
                        Id             = FeatureCollectionNamePolygons,
                        PartitionKey   = partitionKey,
                        IndexingPolicy = indexingPolicyWithSpatialEnabled
                    });

                    _featureCollection_polygons = response.Resource;
                }

                #endregion

                _spatialReference = SpatialReference.FromID("epsg:4326");
            }
            catch (Exception ex)
            {
                this.LastErrorMessage = ex.Message;
                return(false);
            }
            return(true);
        }
Пример #14
0
 private TodoItemManager()
 {
     client = new DocumentClient(new System.Uri(accountURL), accountKey);
 }
Пример #15
0
        public async Task TestStartTime()
        {
            var collectionUri = UriFactory.CreateDocumentCollectionUri(this.ClassData.monitoredCollectionInfo.DatabaseName, this.ClassData.monitoredCollectionInfo.CollectionName);

            using (var client = new DocumentClient(this.ClassData.monitoredCollectionInfo.Uri, this.ClassData.monitoredCollectionInfo.MasterKey, this.ClassData.monitoredCollectionInfo.ConnectionPolicy))
            {
                await client.CreateDocumentAsync(collectionUri, JsonConvert.DeserializeObject("{\"id\": \"doc1\"}"));

                // In worst case (long transaction, heavy load, the atomicity of StartTime is 5 sec).
                // For this case (different transactions) it's OK to wait timestamp precision time.
                await Task.Delay(TimeSpan.FromSeconds(1));

                DateTime timeInBeweeen = DateTime.Now;
                await Task.Delay(TimeSpan.FromSeconds(1));

                await client.CreateDocumentAsync(collectionUri, JsonConvert.DeserializeObject("{\"id\": \"doc2\"}"));

                int partitionCount = await Helper.GetPartitionCount(this.ClassData.monitoredCollectionInfo);

                var allDocsProcessed = new ManualResetEvent(false);

                var processedDocs   = new List <Document>();
                var observerFactory = new TestObserverFactory(
                    null,
                    null,
                    (context, docs) =>
                {
                    processedDocs.AddRange(docs);
                    foreach (var doc in docs)
                    {
                        if (doc.Id == "doc2")
                        {
                            allDocsProcessed.Set();
                        }
                    }
                    return(Task.CompletedTask);
                });

                var host = new ChangeFeedEventHost(
                    Guid.NewGuid().ToString(),
                    this.ClassData.monitoredCollectionInfo,
                    this.LeaseCollectionInfo,
                    new ChangeFeedOptions {
                    StartTime = timeInBeweeen
                },
                    new ChangeFeedHostOptions());
                await host.RegisterObserverFactoryAsync(observerFactory);

                var isStartOk = allDocsProcessed.WaitOne(
                    Debugger.IsAttached ? IntegrationTest.changeWaitTimeout + IntegrationTest.changeWaitTimeout : IntegrationTest.changeWaitTimeout);

                try
                {
                    Assert.IsTrue(isStartOk, "Timed out waiting for docs to process");
                    Assert.AreEqual(1, processedDocs.Count, "Wrong processed count");
                    Assert.AreEqual("doc2", processedDocs[0].Id, "Wrong doc.id");
                }
                finally
                {
                    await host.UnregisterObserversAsync();
                }
            }
        }
Пример #16
0
 public CosmosDbHealthCheck(Uri uri, string masterKey)
 {
     documentClient = new DocumentClient(uri, masterKey);
 }
Пример #17
0
        private async Task GetStartedDemo()
        {
            // Create a new instance of the DocumentClient
            this.client = new DocumentClient(new Uri(Connection.EndpointUrl), Connection.PrimaryKey);

            await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" });

            await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("FamilyDB"), new DocumentCollection { Id = "FamilyCollection" });

            // Insert a document, here we create a Family object
            Family andersenFamily = new Family
            {
                Id       = "Andersen.2",
                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"
                            }
                        }
                    }
                },
                District = "WA5",
                Address  = new Address {
                    State = "WA", County = "King", City = "Seattle"
                },
                IsRegistered = true
            };

            await this.CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", andersenFamily);

            Family andersonFamilyDocument = await this.client.ReadDocumentAsync <Family>(UriFactory.CreateDocumentUri("FamilyDB", "FamilyCollection", andersenFamily.Id));

            Console.WriteLine("\nRead family {0}", andersonFamilyDocument.Id);

            this.WriteToConsoleAndPromptToContinue("{0}", andersonFamilyDocument);

            Family wakefieldFamily = new Family
            {
                Id       = "Wakefield.2",
                LastName = "Wakefield",
                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
                    }
                },
                District = "NY23",
                Address  = new Address {
                    State = "NY", County = "Manhattan", City = "NY"
                },
                IsRegistered = false
            };

            await this.CreateFamilyDocumentIfNotExists("FamilyDB", "FamilyCollection", wakefieldFamily);

            Family wakefieldFamilyDocument = await this.client.ReadDocumentAsync <Family>(UriFactory.CreateDocumentUri("FamilyDB", "FamilyCollection", wakefieldFamily.Id));

            Console.WriteLine("\nRead family {0}", wakefieldFamilyDocument.Id);

            this.WriteToConsoleAndPromptToContinue("{0}", wakefieldFamilyDocument);

            this.ExecuteSimpleQuery("FamilyDB", "FamilyCollection");

            // Clean up/delete the database and client
            // await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB"));
        }
Пример #18
0
 public static void Initialize()
 {
     client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
     CreateDatabaseIfNotExistsAsync().Wait();
     CreateCollectionIfNotExistsAsync().Wait();
 }
Пример #19
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "user")] HttpRequest req,
            [CosmosDB(databaseName: Constants.DATABASE_NAME,
                      collectionName: Constants.USERS_COLLECTION_NAME,
                      ConnectionStringSetting = Constants.CONNECTION_STRING)] DocumentClient client,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.DATABASE_NAME, Constants.USERS_COLLECTION_NAME);

            //Also works : req.Headers.TryGetValue("X-MS-CLIENT-PRINCIPAL-NAME", out var principalName) = Isabelle Riverain
            //req.Headers.TryGetValue("X-MS-CLIENT-PRINCIPAL-ID", out var principalId) = AccountInfo.LocalAccountId

            string searchValue = null;
            var    userReq     = req.HttpContext.User;

            if (userReq == null)
            {
                log.LogInformation($"User from context is null");
            }
            else
            {
                searchValue = userReq.GetDisplayName();
                log.LogInformation($"searchedValue is {searchValue}");
            }

            string name = req.Query["name"];

            var option = new FeedOptions {
                EnableCrossPartitionQuery = true
            };

            IDocumentQuery <DatabaseUser> query = client.CreateDocumentQuery <DatabaseUser>(collectionUri, option)
                                                  .Where(p => p.UserName == searchValue)
                                                  .AsDocumentQuery();

            List <DatabaseUser> result = new List <DatabaseUser>();

            while (query.HasMoreResults)
            {
                foreach (DatabaseUser user in await query.ExecuteNextAsync())
                {
                    result.Add(user);
                }
            }

            if (result.Count > 1)
            {
                log.LogError($"Found several users with userName {searchValue}");
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            ReturnedUser returnUser;

            if (result.Count == 0)
            {
                returnUser = null;
            }
            else
            {
                returnUser = new ReturnedUser {
                    Id = result[0].Id, Login = result[0].Login, Score = result[0].Score
                };
            }

            return(new OkObjectResult(returnUser));
        }
Пример #20
0
        /// <summary>
        /// Run samples for Order By queries.
        /// </summary>
        /// <returns>a Task object.</returns>
        private async Task <RunSummary> ExecuteAsync(BenchmarkConfig config, string accountKey)
        {
            using (CosmosClient cosmosClient = config.CreateCosmosClient(accountKey))
            {
                if (config.CleanupOnStart)
                {
                    Microsoft.Azure.Cosmos.Database database = cosmosClient.GetDatabase(config.Database);
                    await database.DeleteStreamAsync();
                }

                ContainerResponse containerResponse = await Program.CreatePartitionedContainerAsync(config, cosmosClient);

                Container container = containerResponse;

                int?currentContainerThroughput = await container.ReadThroughputAsync();

                Console.WriteLine($"Using container {config.Container} with {currentContainerThroughput} RU/s");

                int taskCount = config.GetTaskCount(currentContainerThroughput.Value);

                Console.WriteLine("Starting Inserts with {0} tasks", taskCount);
                Console.WriteLine();

                string partitionKeyPath = containerResponse.Resource.PartitionKeyPath;
                int    opsPerTask       = config.ItemCount / taskCount;

                // TBD: 2 clients SxS some overhead
                RunSummary runSummary;
                using (DocumentClient documentClient = config.CreateDocumentClient(accountKey))
                {
                    Func <IBenchmarkOperatrion> benchmarkOperationFactory = this.GetBenchmarkFactory(
                        config,
                        partitionKeyPath,
                        cosmosClient,
                        documentClient);

                    if (config.DisableCoreSdkLogging)
                    {
                        // Do it after client initialization (HACK)
                        Program.ClearCoreSdkListeners();
                    }

                    IExecutionStrategy execution = IExecutionStrategy.StartNew(config, benchmarkOperationFactory);
                    runSummary = await execution.ExecuteAsync(taskCount, opsPerTask, config.TraceFailures, 0.01);
                }

                if (config.CleanupOnFinish)
                {
                    Console.WriteLine($"Deleting Database {config.Database}");
                    Microsoft.Azure.Cosmos.Database database = cosmosClient.GetDatabase(config.Database);
                    await database.DeleteStreamAsync();
                }

                runSummary.WorkloadType = config.WorkloadType;
                runSummary.id           = $"{DateTime.UtcNow.ToString("yyyy-MM-dd:HH-mm")}-{config.CommitId}";
                runSummary.Commit       = config.CommitId;
                runSummary.CommitDate   = config.CommitDate;
                runSummary.CommitTime   = config.CommitTime;

                runSummary.Date        = DateTime.UtcNow.ToString("yyyy-MM-dd");
                runSummary.Time        = DateTime.UtcNow.ToString("HH-mm");
                runSummary.BranchName  = config.BranchName;
                runSummary.TotalOps    = config.ItemCount;
                runSummary.Concurrency = taskCount;
                runSummary.Database    = config.Database;
                runSummary.Container   = config.Container;
                runSummary.AccountName = config.EndPoint;
                runSummary.pk          = config.ResultsPartitionKeyValue;

                string consistencyLevel = config.ConsistencyLevel;
                if (string.IsNullOrWhiteSpace(consistencyLevel))
                {
                    AccountProperties accountProperties = await cosmosClient.ReadAccountAsync();

                    consistencyLevel = accountProperties.Consistency.DefaultConsistencyLevel.ToString();
                }
                runSummary.ConsistencyLevel = consistencyLevel;


                if (config.PublishResults)
                {
                    Container resultsContainer = cosmosClient.GetContainer(config.Database, config.ResultsContainer);
                    await resultsContainer.CreateItemAsync(runSummary, new PartitionKey(runSummary.pk));
                }

                return(runSummary);
            }
        }
Пример #21
0
 /// <summary>
 /// Initializes a new instance of the ChangeFeedViewer class
 /// </summary>
 /// <param name="sourceClient">Document Client</param>
 public ChangeFeedViewer(DocumentClient sourceClient, DocumentClient destClient)
 {
     SourceClient = sourceClient;
     DestClient   = destClient;
 }
Пример #22
0
 public DocumentDbTeardown(DocumentClient client, string databaseId)
 {
     _client     = client;
     _databaseId = databaseId;
 }
Пример #23
0
 public string UpdateFamilyDocument(DocumentClient client, string databaseName, string collectionName, string familyID, Family familyDetails)
 {
     client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, familyID), familyDetails);
     return(familyDetails.Id);
 }
Пример #24
0
        private static async Task <DocumentCollection> CreateCollectionIfNotExistsAsync(DocumentClient client)
        {
            if (Program.GetDatabaseIfExists(client, Program.DatabaseName) == null)
            {
                return(null);
            }

            DocumentCollection collection = null;

            try
            {
                collection = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(Program.DatabaseName, Program.DataCollectionName));
            }
            catch (DocumentClientException exception)
            {
                if (exception.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            if (collection == null)
            {
                return(await client.CreateDocumentCollectionAsync(
                           UriFactory.CreateDatabaseUri(Program.DatabaseName),
                           new DocumentCollection()
                {
                    Id = Program.DataCollectionName
                },
                           new RequestOptions { OfferThroughput = 1000 }));
            }

            return(collection);
        }
Пример #25
0
 public string DeleteFamilyDocument(DocumentClient client, string databaseName, string collectionName, string id)
 {
     client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, id));
     return(id);
 }
Пример #26
0
 public CosmosDbRepository(CosmosDbSettings cosmosDbSettings, DocumentClient client)
 {
     _client       = client;
     _databaseName = cosmosDbSettings.DatabaseName;
 }
        public async Task <int> ExecuteAsync()
        {
            Console.WriteLine($"Importing {DatasetUrl}");

            using (var httpClient = new HttpClient())
            {
                var result = await httpClient.GetAsync(DatasetUrl);

                result.EnsureSuccessStatusCode();
                var dataset = JsonConvert.DeserializeObject <DatasetStorageItem>(await result.Content.ReadAsStringAsync());

                Console.WriteLine($"Found Doc: {dataset.Id} - {dataset.Name}");

                var storageCredentials = new StorageCredentials(StorageOptions.Account, StorageOptions.Key);
                var storageAccount     = new CloudStorageAccount(storageCredentials, true);
                var blobClient         = storageAccount.CreateCloudBlobClient();

                var containerRef = blobClient.GetContainerReference(StorageName);

                using (var client =
                           new DocumentClient(
                               new Uri($"https://{CosmosOptions.Endpoint}.documents.azure.com/"),
                               CosmosOptions.Key,
                               new ConnectionPolicy
                {
                    ConnectionMode = ConnectionMode.Direct,
                    ConnectionProtocol = Protocol.Tcp
                },
                               ConsistencyLevel.Session))
                {
                    await client.OpenAsync();

                    var license = await client.ReadDocumentAsync <LicenseStorageItem>(
                        UriFactory.CreateDocumentUri(CosmosOptions.Database, CosmosOptions.DatasetsCollection, dataset.LicenseId.ToString()),
                        new RequestOptions
                    {
                        PartitionKey = new PartitionKey(WellKnownIds.LicenseDatasetId.ToString())
                    });

                    // Attachment details
                    var blob = new
                    {
                        StorageType = "blob",
                        StorageOptions.Account,
                        Container = StorageName,
                        MediaLink = containerRef.Uri.ToString(),
                    };

                    // Convert Dataset to Nomination
                    var nomination = DatasetConvert.DatasetToNomination(dataset, ContactOptions, license);
                    Console.WriteLine(JsonConvert.SerializeObject(dataset, Formatting.Indented));
                    Console.WriteLine(JsonConvert.SerializeObject(nomination, Formatting.Indented));
                    Console.WriteLine(JsonConvert.SerializeObject(blob, Formatting.Indented));

                    // Add the nomination document
                    var uri = UriFactory.CreateDocumentCollectionUri(
                        CosmosOptions.Database,
                        CosmosOptions.UserDataCollection);
                    var options = new RequestOptions
                    {
                        PartitionKey = new PartitionKey(nomination.DatasetId.ToString())
                    };
                    var newDoc = await client.UpsertDocumentAsync(uri, nomination, options);

                    // Add the attachment to the nomination (with blob storage details)
                    var datasetRecordLink = new Attachment
                    {
                        Id          = "Content",
                        ContentType = "x-azure-blockstorage",
                        MediaLink   = blob.MediaLink,
                    };
                    datasetRecordLink.SetPropertyValue("storageType", "blob");
                    datasetRecordLink.SetPropertyValue("container", blob.Container);
                    datasetRecordLink.SetPropertyValue("account", blob.Account);
                    await client.UpsertAttachmentAsync(newDoc.Resource.SelfLink, datasetRecordLink, options);

                    Console.WriteLine($"Added nomination document.");
                }
            }

            return(0);
        }
Пример #28
0
 public static void InitializeDocumentClient(DocumentClient client)
 {
     documentClient = client;
     InitializeDocumentDataBase();
     InitializeDocumentCollection();
 }
Пример #29
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequest req,
            [CosmosDB("ProjetWeb", "Products", ConnectionStringSetting = "CosmosDB")]
            DocumentClient client,
            ILogger log
            )
        {
            log.LogInformation("GetAllProducts");

            var collectionUri = UriFactory.CreateDocumentCollectionUri("ProjetWeb", "Products");
            IDocumentQuery <Models.Product> query;

            if (req.Method == HttpMethods.Post)
            {
                var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                var filter      = JsonConvert.DeserializeObject <ProductFilter>(requestBody);

                var queryOptions = new FeedOptions {
                    EnableCrossPartitionQuery = true
                };
                query = client.CreateDocumentQuery <Models.Product>(collectionUri, queryOptions)
                        .Where(
                    p => filter == null ||
                    (string.IsNullOrEmpty(filter.Keyword) || p.Title.ToLower()
                     .Contains(string.IsNullOrEmpty(filter.Keyword)
                                      ? string.Empty
                                      : filter.Keyword.ToLower()) ||
                     p.Description.ToLower().Contains(string.IsNullOrEmpty(filter.Keyword)
                                  ? string.Empty
                                  : filter.Keyword.ToLower())) &&
                    (filter.LowerPriceLimit == 0 || p.Price >= filter.LowerPriceLimit) &&
                    (filter.UpperPriceLimit == 0 || p.Price <= filter.UpperPriceLimit) &&
                    (filter.LowerHorsepowerLimit == 0 || p.HorsePower >= filter.LowerHorsepowerLimit) &&
                    (filter.UpperHorsepowerLimit == 0 || p.HorsePower <= filter.UpperHorsepowerLimit)
                    )
                        .AsDocumentQuery();
            }
            else
            {
                query = client.CreateDocumentQuery <Models.Product>(collectionUri).AsDocumentQuery();
            }

            var everyProducts = req.Method == HttpMethods.Post
                ? client
                                .CreateDocumentQuery <Models.Product>(collectionUri)
                                .AsDocumentQuery()
                                .ExecuteNextAsync <Models.Product>().Result.ToList()
                : query
                                .ExecuteNextAsync <Models.Product>()
                                .Result
                                .ToList();

            var minimumPrice      = everyProducts.Min(x => x.Price);
            var maximumPrice      = everyProducts.Max(x => x.Price);
            var minimumHorsepower = everyProducts.Min(x => x.HorsePower);
            var maximumHorsepower = everyProducts.Max(x => x.HorsePower);

            return(new OkObjectResult(
                       new BaseResponse <ProductResponse <List <Models.Product> > >(new ProductResponse <List <Models.Product> >(
                                                                                        query.ExecuteNextAsync <Models.Product>().Result.ToList(), minimumPrice,
                                                                                        maximumPrice, minimumHorsepower, maximumHorsepower))));
        }
Пример #30
0
        public void TestStoredProcedure()
        {
            // Create a document client with a customer json serializer settings
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();

            serializerSettings.Converters.Add(new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_)));
            ConnectionPolicy connectionPolicy = new ConnectionPolicy {
                ConnectionMode = ConnectionMode.Gateway
            };
            ConsistencyLevel defaultConsistencyLevel = ConsistencyLevel.Session;
            DocumentClient   client = CreateDocumentClient(
                this.hostUri,
                this.masterKey,
                serializerSettings,
                connectionPolicy,
                defaultConsistencyLevel);

            // Create a simple stored procedure
            var scriptId = "bulkImportScript";
            var sproc    = new StoredProcedure
            {
                Id   = scriptId,
                Body = @"
function bulkImport(docs) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error(""The array is undefined or null."");

    var docsLength = docs.length;
            if (docsLength == 0)
            {
                getContext().getResponse().setBody(0);
            }

            // Call the CRUD API to create a document.
            tryCreate(docs[count], callback);

            // Note that there are 2 exit conditions:
            // 1) The createDocument request was not accepted. 
            //    In this case the callback will not be called, we just call setBody and we are done.
            // 2) The callback was called docs.length times.
            //    In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done.
            function tryCreate(doc, callback) {
            // If you are sure that every document will contain its own (unique) id field then
            // disable the option to auto generate ids.
            // by leaving this on, the entire document is parsed to check if there is an id field or not
            // by disabling this, parsing of the document is skipped because you're telling DocumentDB 
            // that you are providing your own ids.
            // depending on the size of your documents making this change can have a significant 
            // improvement on document creation. 
            var options = {
            disableAutomaticIdGeneration: true
        };

        var isAccepted = collection.createDocument(collectionLink, doc, options, callback);

        // If the request was accepted, callback will be called.
        // Otherwise report current count back to the client, 
        // which will call the script again with remaining set of docs.
        // This condition will happen when this stored procedure has been running too long
        // and is about to get cancelled by the server. This will allow the calling client
        // to resume this batch from the point we got to before isAccepted was set to false
        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done and the document has been persisted.
    function callback(err, doc, options)
    {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength)
        {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        }
        else
        {
            // Create next document.
            tryCreate(docs[count], callback);
        }
    }
}
"
            };

            sproc = client.CreateStoredProcedureAsync(collectionUri, sproc).Result.Resource;

            var doc = new MyObject(1);

            var args = new dynamic[] { new dynamic[] { doc } };

            RequestOptions requestOptions = ApplyRequestOptions(new RequestOptions {
                PartitionKey = new PartitionKey("value")
            }, serializerSettings);

            StoredProcedureResponse <int> scriptResult = client.ExecuteStoredProcedureAsync <int>(
                sproc.SelfLink,
                requestOptions,
                args).Result;

            var docUri  = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.id);
            var readDoc = client.ReadDocumentAsync <MyObject>(docUri, requestOptions).Result.Document;

            Assert.IsNotNull(readDoc.SerializedObject);
            Assert.AreEqual(doc.SerializedObject.Name, readDoc.SerializedObject.Name);
        }
Пример #31
0
 public CosmosDataAdapter(ICosmosConnection connection, IConfiguration config)
 {
     _accountUrl = config.GetValue <string>("Cosmos:AccountURL");
     _primarykey = config.GetValue <string>("Cosmos:AuthKey");
     _client     = new DocumentClient(new Uri(_accountUrl), _primarykey);
 }