Beispiel #1
0
        public async Task CreateDropAutoscaleDatabaseStreamApi()
        {
            string databaseId = Guid.NewGuid().ToString();

            using (ResponseMessage response = await this.cosmosClient.CreateDatabaseStreamAsync(
                       new DatabaseProperties(databaseId),
                       ThroughputProperties.CreateAutoscaleThroughput(5000)))
            {
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            }

            DatabaseCore       database  = (DatabaseInlineCore)this.cosmosClient.GetDatabase(databaseId);
            ThroughputResponse autoscale = await database.ReadThroughputAsync(requestOptions : null);

            Assert.IsNotNull(autoscale);
            Assert.AreEqual(5000, autoscale.Resource.MaxAutoscaleThroughput);

            ThroughputResponse autoscaleReplaced = await database.ReplaceThroughputAsync(
                ThroughputProperties.CreateAutoscaleThroughput(10000));

            Assert.IsNotNull(autoscaleReplaced);
            Assert.AreEqual(10000, autoscaleReplaced.Resource.MaxAutoscaleThroughput);

            await database.DeleteAsync();
        }
Beispiel #2
0
        public async Task CreateDropAutoscaleAutoUpgradeDatabase()
        {
            DatabaseCore database = (DatabaseInlineCore)await this.cosmosClient.CreateDatabaseAsync(
                nameof(CreateDropAutoscaleAutoUpgradeDatabase) + Guid.NewGuid(),
                ThroughputProperties.CreateAutoscaleThroughput(
                    maxAutoscaleThroughput: 5000,
                    autoUpgradeMaxThroughputIncrementPercentage: 10));

            // Container is required to validate database throughput upgrade scenarios
            Container container = await database.CreateContainerAsync("Test", "/id");

            ThroughputResponse autoscale = await database.ReadThroughputAsync(requestOptions : null);

            Assert.IsNotNull(autoscale);
            Assert.AreEqual(5000, autoscale.Resource.MaxAutoscaleThroughput);
            Assert.AreEqual(10, autoscale.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            ThroughputResponse autoscaleReplaced = await database.ReplaceThroughputAsync(
                ThroughputProperties.CreateAutoscaleThroughput(6000));

            Assert.IsNotNull(autoscaleReplaced);
            Assert.AreEqual(6000, autoscaleReplaced.Resource.MaxAutoscaleThroughput);
            Assert.IsNull(autoscaleReplaced.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            ThroughputResponse autoUpgradeReplace = await database.ReplaceThroughputAsync(
                ThroughputProperties.CreateAutoscaleThroughput(
                    maxAutoscaleThroughput: 7000,
                    autoUpgradeMaxThroughputIncrementPercentage: 20));

            Assert.IsNotNull(autoUpgradeReplace);
            Assert.AreEqual(7000, autoUpgradeReplace.Resource.MaxAutoscaleThroughput);
            Assert.AreEqual(20, autoUpgradeReplace.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            await database.DeleteAsync();
        }
Beispiel #3
0
        public async Task CreateDropFixedDatabase()
        {
            DatabaseCore database = (DatabaseInlineCore)await this.cosmosClient.CreateDatabaseAsync(
                nameof(CreateDropAutoscaleDatabase) + Guid.NewGuid().ToString(),
                ThroughputProperties.CreateManualThroughput(5000));

            ThroughputResponse fixedDatabaseThroughput = await database.ReadThroughputAsync(requestOptions : null);

            Assert.IsNotNull(fixedDatabaseThroughput);
            Assert.AreEqual(5000, fixedDatabaseThroughput.Resource.Throughput);
            Assert.IsNull(fixedDatabaseThroughput.Resource.MaxAutoscaleThroughput);
            Assert.IsNull(fixedDatabaseThroughput.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            ThroughputResponse fixedReplaced = await database.ReplaceThroughputAsync(
                ThroughputProperties.CreateManualThroughput(6000));

            Assert.IsNotNull(fixedReplaced);
            Assert.AreEqual(6000, fixedReplaced.Resource.Throughput);
            Assert.IsNull(fixedReplaced.Resource.MaxAutoscaleThroughput);
            Assert.IsNull(fixedReplaced.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            ThroughputResponse fixedReplacedIfExists = await database.ReplaceThroughputPropertiesIfExistsAsync(
                ThroughputProperties.CreateManualThroughput(7000));

            Assert.IsNotNull(fixedReplacedIfExists);
            Assert.AreEqual(7000, fixedReplacedIfExists.Resource.Throughput);
            Assert.IsNull(fixedReplacedIfExists.Resource.MaxAutoscaleThroughput);
            Assert.IsNull(fixedReplacedIfExists.Resource.AutoUpgradeMaxThroughputIncrementPercentage);

            await database.DeleteAsync();
        }
Beispiel #4
0
        [Ignore] // Not currently working with emulator
        public async Task CreateDropAutoscaleContainer()
        {
            DatabaseCore database = (DatabaseInlineCore)await this.cosmosClient.CreateDatabaseAsync(
                Guid.NewGuid().ToString());

            ThroughputResponse databaseThroughput = await database.ReadThroughputIfExistsAsync(requestOptions : null);

            Assert.IsNotNull(databaseThroughput);
            Assert.AreEqual(HttpStatusCode.NotFound, databaseThroughput.StatusCode);

            ContainerCore container = (ContainerInlineCore)await database.CreateContainerAsync(
                new ContainerProperties(Guid.NewGuid().ToString(), "/pk"),
                ThroughputProperties.CreateAutoscaleProvionedThroughput(5000));

            Assert.IsNotNull(container);

            ThroughputResponse autoscale = await container.ReadThroughputAsync(requestOptions : null);

            Assert.IsNotNull(autoscale);
            Assert.AreEqual(5000, autoscale.Resource.MaxAutoscaleThroughput);

            ThroughputResponse autoscaleReplaced = await container.ReplaceThroughputPropertiesAsync(
                ThroughputProperties.CreateAutoscaleProvionedThroughput(10000));

            Assert.IsNotNull(autoscaleReplaced);
            Assert.AreEqual(10000, autoscaleReplaced.Resource.MaxAutoscaleThroughput);

            await database.DeleteAsync();
        }
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            Mock <CosmosClient> mockClient = new Mock <CosmosClient>();

            mockClient.Setup(x => x.Endpoint).Returns(new Uri("http://localhost"));

            CosmosClientContext context = new ClientContextCore(
                client: mockClient.Object,
                clientOptions: new CosmosClientOptions(),
                userJsonSerializer: null,
                defaultJsonSerializer: null,
                sqlQuerySpecSerializer: null,
                cosmosResponseFactory: null,
                requestHandler: null,
                documentClient: null);

            DatabaseCore db = new DatabaseCore(context, databaseId);

            Assert.AreEqual(db.LinkUri.OriginalString, "dbs/" + databaseId);

            ContainerCore container = new ContainerCore(context, db, crId);

            Assert.AreEqual(container.LinkUri.OriginalString, "dbs/" + databaseId + "/colls/" + crId);
        }
        public void InitializeBatchExecutorForContainer_NotNull_WhenAllowBulk_True()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            Mock <CosmosClient> mockClient = new Mock <CosmosClient>();

            mockClient.Setup(x => x.Endpoint).Returns(new Uri("http://localhost"));

            CosmosClientContext context = new ClientContextCore(
                client: mockClient.Object,
                clientOptions: new CosmosClientOptions()
            {
                AllowBulkExecution = true
            },
                userJsonSerializer: null,
                defaultJsonSerializer: null,
                sqlQuerySpecSerializer: null,
                cosmosResponseFactory: null,
                requestHandler: null,
                documentClient: null);

            DatabaseCore  db        = new DatabaseCore(context, databaseId);
            ContainerCore container = new ContainerCore(context, db, crId);

            Assert.IsNotNull(container.BatchExecutor);
        }
        public async Task SingleTaskScheduler_ExecutorTest()
        {
            CosmosClientContext context = this.MockClientContext();

            DatabaseCore db = new DatabaseCore(context, "test");

            List <Task <ContainerCore> > tasks = new List <Task <ContainerCore> >();

            for (int i = 0; i < 20; i++)
            {
                tasks.Add(
                    Task.Factory.StartNew(() => new ContainerCore(context, db, "test"),
                                          CancellationToken.None,
                                          TaskCreationOptions.None,
                                          new SingleTaskScheduler()));
            }

            await Task.WhenAll(tasks);

            BatchAsyncContainerExecutor firstExecutor = tasks[0].Result.BatchExecutor;

            Assert.IsNotNull(firstExecutor);
            for (int i = 1; i < 20; i++)
            {
                BatchAsyncContainerExecutor otherExecutor = tasks[i].Result.BatchExecutor;
                Assert.AreEqual(firstExecutor, otherExecutor);
            }
        }
Beispiel #8
0
        public async Task DatabaseContractTest()
        {
            DatabaseResponse response = await this.CreateDatabaseHelper();

            Assert.IsNotNull(response);
            Assert.IsTrue(response.RequestCharge > 0);
            Assert.IsNotNull(response.Headers);
            Assert.IsNotNull(response.Headers.ActivityId);

            DatabaseProperties databaseSettings = response.Resource;

            Assert.IsNotNull(databaseSettings.Id);
            Assert.IsNotNull(databaseSettings.ResourceId);
            Assert.IsNotNull(databaseSettings.ETag);
            Assert.IsTrue(databaseSettings.LastModified.HasValue);
            Assert.IsTrue(databaseSettings.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), databaseSettings.LastModified.Value.ToString());

            DatabaseCore databaseCore = response.Database as DatabaseInlineCore;

            Assert.IsNotNull(databaseCore);
            Assert.IsNotNull(databaseCore.LinkUri);
            Assert.IsFalse(databaseCore.LinkUri.ToString().StartsWith("/"));

            response = await response.Database.DeleteAsync(cancellationToken : this.cancellationToken);

            Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
        }
Beispiel #9
0
        public async Task EncryptionResourceTokenAuth()
        {
            User user = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(user.Id);

            PermissionProperties permission = await user.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.container));

            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient resourceTokenBasedClient = new CosmosClientBuilder(endpoint, permission.Token)
                                                    .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                                    .Build();

            DatabaseCore databaseForTokenClient  = (DatabaseInlineCore)resourceTokenBasedClient.GetDatabase(EncryptionTests.databaseCore.Id);
            Container    containerForTokenClient = databaseForTokenClient.GetContainer(EncryptionTests.container.Id);

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 databaseForTokenClient.GetDataEncryptionKey(EncryptionTests.dekId).ReadAsync(), "DEK.ReadAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemStreamAsync(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemStreamAsync");
        }
        public async Task AllowBatchingRequestsSendsToExecutor_Delete()
        {
            CosmosClient      cosmosClient      = MockCosmosUtil.CreateMockCosmosClient();
            ClientContextCore clientContextCore = new ClientContextCore(
                cosmosClient,
                new CosmosClientOptions()
            {
                AllowBulkExecution = true
            },
                new CosmosJsonDotNetSerializer(),
                new CosmosJsonDotNetSerializer(),
                null,
                cosmosClient.ResponseFactory,
                null,
                new MockDocumentClient()
                );

            DatabaseCore          db        = new DatabaseCore(clientContextCore, "test");
            ExecutorContainerCore container = new ExecutorContainerCore(clientContextCore, db, "test");

            dynamic testItem = new
            {
                id = Guid.NewGuid().ToString(),
                pk = "FF627B77-568E-4541-A47E-041EAC10E46F",
            };

            Cosmos.PartitionKey    partitionKey = new Cosmos.PartitionKey(testItem.pk);
            ItemResponse <dynamic> response     = await container.DeleteItemAsync <dynamic>(
                partitionKey : partitionKey,
                id : testItem.id);

            container.MockedExecutor.Verify(c => c.AddAsync(It.IsAny <ItemBatchOperation>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>()), Times.Once);
        }
Beispiel #11
0
        public async Task EncryptionBulkCrud()
        {
            TestDoc docToReplace = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToReplace.NonSensitive = Guid.NewGuid().ToString();
            docToReplace.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToUpsert = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToUpsert.NonSensitive = Guid.NewGuid().ToString();
            docToUpsert.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToDelete = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            CosmosClient clientWithBulk = new CosmosClientBuilder(endpoint, authKey)
                                          .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                          .WithBulkExecution(true)
                                          .Build();

            DatabaseCore  databaseWithBulk  = (DatabaseInlineCore)clientWithBulk.GetDatabase(EncryptionTests.databaseCore.Id);
            ContainerCore containerWithBulk = (ContainerInlineCore)databaseWithBulk.GetContainer(EncryptionTests.container.Id);

            List <Task> tasks = new List <Task>();

            tasks.Add(EncryptionTests.CreateItemAsync(containerWithBulk, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, TestDoc.Create(), EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.Created));
            tasks.Add(EncryptionTests.ReplaceItemAsync(containerWithBulk, docToReplace, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, docToUpsert, EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.OK));
            tasks.Add(EncryptionTests.DeleteItemAsync(containerWithBulk, docToDelete));
            await Task.WhenAll(tasks);
        }
Beispiel #12
0
        public async Task AllowBatchingRequestsSendsToExecutor_ReadStream()
        {
            ClientContextCore clientContextCore = this.CreateMockBulkClientContextCore();

            DatabaseCore          db        = new DatabaseCore(clientContextCore, "test");
            ExecutorContainerCore container = new ExecutorContainerCore(clientContextCore, db, "test");

            dynamic testItem = new
            {
                id = Guid.NewGuid().ToString(),
                pk = "FF627B77-568E-4541-A47E-041EAC10E46F",
            };

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                ItemRequestOptions  itemRequestOptions = new ItemRequestOptions();
                Cosmos.PartitionKey partitionKey       = new Cosmos.PartitionKey(testItem.pk);
                using (ResponseMessage streamResponse = await container.ReadItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id))
                {
                    container.MockedExecutor.Verify(c => c.AddAsync(It.IsAny <ItemBatchOperation>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>()), Times.Once);
                }
            }
        }
Beispiel #13
0
        [TestCategory("Quarantine")] // Not currently working with emulator
        public async Task CreateDropAutoscaleContainerStreamApi()
        {
            DatabaseCore database = (DatabaseInlineCore)await this.cosmosClient.CreateDatabaseAsync(
                Guid.NewGuid().ToString());

            ThroughputResponse databaseThroughput = await database.ReadThroughputIfExistsAsync(requestOptions : null);

            Assert.IsNotNull(databaseThroughput);
            Assert.AreEqual(HttpStatusCode.NotFound, databaseThroughput.StatusCode);

            string streamContainerId = Guid.NewGuid().ToString();

            using (ResponseMessage response = await database.CreateContainerStreamAsync(
                       new ContainerProperties(streamContainerId, "/pk"),
                       ThroughputProperties.CreateAutoscaleThroughput(5000)))
            {
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                ContainerCore      streamContainer   = (ContainerInlineCore)database.GetContainer(streamContainerId);
                ThroughputResponse autoscaleIfExists = await streamContainer.ReadThroughputIfExistsAsync(requestOptions : null);

                Assert.IsNotNull(autoscaleIfExists);
                Assert.AreEqual(5000, autoscaleIfExists.Resource.MaxAutoscaleThroughput);
            }
        }
Beispiel #14
0
        public async Task ShouldContinueUntilResponseOk()
        {
            // Setting 3 ranges, first one returns a 304, second returns Ok
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(new Uri("/dbs/test/colls/test", UriKind.Relative));

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";
            ResponseMessage secondResponse = new ResponseMessage(HttpStatusCode.OK);

            secondResponse.Headers.ETag = "SecondContinuation";

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <Uri>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerCore>(),
                                          It.IsAny <PartitionKey?>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse))
            .Returns(Task.FromResult(secondResponse));

            DatabaseCore databaseCore = new DatabaseCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object, new ContainerCore(mockContext.Object, databaseCore, "myColl"), null, 10, new ChangeFeedRequestOptions());
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should contain the second continuation");
            Assert.AreEqual(HttpStatusCode.OK, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <Uri>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerCore>(),
                                   It.IsAny <PartitionKey?>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
Beispiel #15
0
 public ExecutorContainerCore(
     CosmosClientContext clientContext,
     DatabaseCore database,
     string containerId) : base(clientContext, database, containerId)
 {
     this.MockedExecutor
     .Setup(e => e.AddAsync(It.IsAny <ItemBatchOperation>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>()))
     .ReturnsAsync(new TransactionalBatchOperationResult(HttpStatusCode.OK));
 }
        public void Null_When_OptionsOff()
        {
            CosmosClientContext context = this.MockClientContext(allowBulkExecution: false);

            DatabaseCore  db        = new DatabaseCore(context, "test");
            ContainerCore container = new ContainerCore(context, db, "test");

            Assert.IsNull(container.BatchExecutor);
        }
 public ExecutorWithThrottlingContainerCore(
     CosmosClientContext clientContext,
     DatabaseCore database,
     string containerId) : base(clientContext, database, containerId)
 {
     this.MockedExecutor
     .SetupSequence(e => e.AddAsync(It.IsAny <ItemBatchOperation>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>()))
     .ReturnsAsync(new BatchOperationResult((HttpStatusCode)StatusCodes.TooManyRequests))
     .ReturnsAsync(new BatchOperationResult(HttpStatusCode.OK));
 }
Beispiel #18
0
        public static async Task ClassInitialize(TestContext context)
        {
            EncryptionTests.client       = EncryptionTests.GetClient();
            EncryptionTests.databaseCore = (DatabaseInlineCore)await EncryptionTests.client.CreateDatabaseAsync(Guid.NewGuid().ToString());

            EncryptionTests.container = await EncryptionTests.databaseCore.CreateContainerAsync(Guid.NewGuid().ToString(), "/PK", 400);

            EncryptionTests.containerCore = (ContainerInlineCore)EncryptionTests.container;
            EncryptionTests.dekProperties = await CreateDekAsync(EncryptionTests.databaseCore, EncryptionTests.dekId);
        }
Beispiel #19
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (ContextFactory.ConnectionString == null)
            {
                DatabaseCore.SetDatabaseConnection();
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            optionsBuilder.UseLoggerFactory(DatabaseCore.GetLoggerFactory(LogLevel.Error)).UseMySql(ContextFactory.ConnectionString);
        }
        public void InitializeBatchExecutorForContainer_Null_WhenAllowBulk_False()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            CosmosClientContext context   = this.CreateMockClientContext();
            DatabaseCore        db        = new DatabaseCore(context, databaseId);
            ContainerCore       container = new ContainerCore(context, db, crId);

            Assert.IsNull(container.BatchExecutor);
        }
Beispiel #21
0
        public static void TestProvider(DataProviderType providerType)
        {
            DatabaseCore db = DatabaseCore.Create(providerType, @"Data Source=(localdb)\MSSQLLocalDB;Database=ZKTecoTime;User ID=manuel.ortiz;Password=1910Skynet;Pooling=true;Encrypt=False;TrustServerCertificate=False;Trusted_Connection=Yes;");

            using (var cn = db.CreateOpenConnection())
            {
                cn.Open();
                cn.Close();
                cn.Dispose();
            }
        }
Beispiel #22
0
        public AppCore(MainWindow wi)
        {
            if (dCore == null)
            {
                dCore = new DatabaseCore(DatabasePath);
            }

            wi = Wi;
            dCore.OpenDataBase();
            databaseOpened = true;
        }
        /// <summary>
        /// 获得所有类别名
        /// </summary>
        /// <returns>所有类别名</returns>
        public List <string> GetPartNames()
        {
            DatabaseCore  dc     = new DatabaseCore(_sqlCon);
            DataTable     dt     = dc.SelectData("dbo.Parts", null);
            List <string> result = new List <string>();

            foreach (DataRow dr in dt.Rows)
            {
                result.Add(dr["PartName"].ToString());
            }
            return(result);
        }
Beispiel #24
0
        public void Fresh(DatabaseCore accessor)
        {
            if (accessor == null)
            {
                return;
            }
            var data = Fetch(accessor);

            if (data != null)
            {
                Value = data;
            }
        }
Beispiel #25
0
        /// <summary>
        /// 将数据写入数据库
        /// </summary>
        /// <param name="dataString"></param>
        private static void WriteIntoDatabase(byte[] dataByte, DateTime dateTime, OleDbConnection oleDbCon)
        {
            DatabaseCore dataCore = new DatabaseCore(oleDbCon);

            //数据库列名
            string[] colName = { "ID",                    "Year",                  "Month",                 "Day", "Hour", "Minute", "Second",
                                 "WindSpeed(m/s)",        "AirTemperayure",        "Rasiation(W/m2)",
                                 "WindDirection",         "Humidity(%RH)",
                                 "Component2Temperature", "Component3Temperature",
                                 "Component4Temperature", "Component5Temperature", "Component6Temperature", };
            //string colString = "Year, Month, Day, Hour, Minute, Second, WindSpeed(m/s), AirTemperayure, Rasiation(W/m2), WindDirection, Humidity(%RH), Component1Temperature, Component2Temperature, Component3Temperature,Component4Temperature, Component5Temperature, Component6Temperature";
            //string valueString = "";//要插入的语句
            Dictionary <string, string> QXdataDic = new Dictionary <string, string>();

            //添加日期数据
            int year   = dateTime.Year;
            int month  = dateTime.Month;
            int day    = dateTime.Day;
            int hour   = dateTime.Hour;
            int minute = dateTime.Minute;
            int second = dateTime.Second;

            int[] time = { year, month, day, hour, minute, second };
            for (int i = 0; i < time.Length; i++)
            {
                QXdataDic.Add(colName[i + 1], time[i].ToString());                                                              //第一列不添加
            }

            //添加气象仪数据
            int[]    index     = { 1, 3, 6, 7, 9, 11, 12, 13, 14, 15 };                                 //有效通道
            double[] precision = { 0.1, 0.1, 1.0, 1.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, };                 //每个有效通道数值的精度
            for (int i = 0; i < index.Length; i++)
            {
                int k     = (index[i] + 1) * 2;                                         //前面两个字内容无效, 所以+2 , 但由于dataByte的下标从零开始, 所以要-1 即: (index[i]-1+2),  每个数据占两个字节, 所以*2
                int value = (dataByte[k] << 8) + dataByte[k + 1];                       //高位左移8位地位  =  实际值
                if (value >> 15 == 1)                                                   //如果最高位为1, 则取补,  否则不改变
                {
                    value = -(0x10000 - value);
                }
                double dvalue = value * precision[i];                                           //取精度
                QXdataDic.Add(colName[i + 7], dvalue.ToString());
            }
            try
            {
                dataCore.InsertData("MeteorologicalData", QXdataDic);                   //插入数据
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #26
0
        public Class1()
        {
            _databaseCore = new DatabaseCore();

            var serviceCollection = new ServiceCollection();

            _databaseCore.OnResourceStartHandler(() =>
            {
                _serviceProvider = serviceCollection
                                   .AddSingleton(ContextFactory.Instance)
                                   .BuildServiceProvider();
                LoadServices();
            });
        }
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            CosmosClientContext context = this.CreateMockClientContext();
            DatabaseCore        db      = new DatabaseCore(context, databaseId);

            Assert.AreEqual(db.LinkUri.OriginalString, "dbs/" + databaseId);

            ContainerCore container = new ContainerCore(context, db, crId);

            Assert.AreEqual(container.LinkUri.OriginalString, "dbs/" + databaseId + "/colls/" + crId);
        }
Beispiel #28
0
        public async Task UserTests(bool directMode)
        {
            CosmosClient  client     = directMode ? DirectCosmosClient : GatewayCosmosClient;
            DatabaseCore  database   = (DatabaseInlineCore)client.GetDatabase(DatabaseId);
            List <string> createdIds = new List <string>();

            try
            {
                UserResponse userResponse = await database.CreateUserAsync("BasicQueryUser1");

                createdIds.Add(userResponse.User.Id);

                userResponse = await database.CreateUserAsync("BasicQueryUser2");

                createdIds.Add(userResponse.User.Id);

                userResponse = await database.CreateUserAsync("BasicQueryUser3");

                createdIds.Add(userResponse.User.Id);

                //Read All
                List <UserProperties> results = await this.ToListAsync(
                    database.GetUserQueryStreamIterator,
                    database.GetUserQueryIterator <UserProperties>,
                    null,
                    CosmosBasicQueryTests.RequestOptions
                    );

                CollectionAssert.IsSubsetOf(createdIds, results.Select(x => x.Id).ToList());

                //Basic query
                List <UserProperties> queryResults = await this.ToListAsync(
                    database.GetUserQueryStreamIterator,
                    database.GetUserQueryIterator <UserProperties>,
                    "select * from T where STARTSWITH(T.id, \"BasicQueryUser\")",
                    CosmosBasicQueryTests.RequestOptions
                    );

                CollectionAssert.AreEquivalent(createdIds, queryResults.Select(x => x.Id).ToList());
            }
            finally
            {
                foreach (string id in createdIds)
                {
                    await database.GetUser(id).DeleteAsync();
                }
            }
        }
Beispiel #29
0
        private static async Task <DataEncryptionKeyProperties> CreateDekAsync(DatabaseCore databaseCore, string dekId)
        {
            DataEncryptionKeyResponse dekResponse = await databaseCore.CreateDataEncryptionKeyAsync(
                dekId,
                CosmosEncryptionAlgorithm.AE_AES_256_CBC_HMAC_SHA_256_RANDOMIZED,
                EncryptionTests.metadata1);

            Assert.AreEqual(HttpStatusCode.Created, dekResponse.StatusCode);
            Assert.IsTrue(dekResponse.RequestCharge > 0);
            Assert.IsNotNull(dekResponse.ETag);

            DataEncryptionKeyProperties dekProperties = dekResponse.Resource;

            Assert.AreEqual(dekResponse.ETag, dekProperties.ETag);
            Assert.AreEqual(dekId, dekProperties.Id);
            return(dekProperties);
        }
Beispiel #30
0
        private void OnMainStudentFormClosing(object sender, FormClosingEventArgs e)
        {
            MessageDialog messageDialog = new MessageDialog(@"Bạn thực sự muốn thoát?", MessageDialog.DialogType.YesNo);

            messageDialog.SendValueDelegate = delegate(MessageDialog.DialogResultType result)
            {
                if (result == MessageDialog.DialogResultType.No)
                {
                    e.Cancel = true;
                }
                else if (result == MessageDialog.DialogResultType.Yes)
                {
                    DatabaseCore.ReleaseConnect();
                }
            };
            messageDialog.ShowDialog();
        }