예제 #1
0
        public void Table_IfBoundToIQueryableDynamicTableEntityAndExists_Binds()
        {
            // Arrange
            Guid            expectedValue = Guid.NewGuid();
            IStorageAccount account       = CreateFakeStorageAccount();
            IStorageQueue   triggerQueue  = CreateQueue(account, TriggerQueueName);

            triggerQueue.AddMessage(triggerQueue.CreateMessage("ignore"));
            IStorageTableClient client = account.CreateTableClient();
            IStorageTable       table  = client.GetTableReference(TableName);

            table.CreateIfNotExists();
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>
            {
                { PropertyName, new EntityProperty(expectedValue) }
            };

            table.Insert(new DynamicTableEntity(PartitionKey, RowKey, etag: null, properties: properties));

            // Act
            IQueryable <DynamicTableEntity> result = RunTrigger <IQueryable <DynamicTableEntity> >(account,
                                                                                                   typeof(BindToIQueryableDynamicTableEntityProgram),
                                                                                                   (s) => BindToIQueryableDynamicTableEntityProgram.TaskSource = s);

            // Assert
            Assert.NotNull(result);
            DynamicTableEntity[] entities = result.ToArray();
            Assert.Equal(1, entities.Length);
            DynamicTableEntity entity = entities[0];

            Assert.NotNull(entity);
            Assert.Equal(PartitionKey, entity.PartitionKey);
            Assert.Equal(RowKey, entity.RowKey);
            Assert.NotNull(entity.Properties);
            Assert.True(entity.Properties.ContainsKey(PropertyName));
            EntityProperty property = entity.Properties[PropertyName];

            Assert.NotNull(property);
            Assert.Equal(EdmType.Guid, property.PropertyType);
            Assert.Equal(expectedValue, property.GuidValue);
        }
예제 #2
0
            public async Task <GrainStateRecord> Read(string partitionKey, string rowKey)
            {
                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
                }
                try
                {
                    Tuple <DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false);

                    if (data == null || data.Item1 == null)
                    {
                        if (logger.IsEnabled(LogLevel.Trace))
                        {
                            logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
                        }
                        return(null);
                    }
                    DynamicTableEntity stateEntity = data.Item1;
                    var record = new GrainStateRecord {
                        Entity = stateEntity, ETag = data.Item2
                    };
                    if (logger.IsEnabled(LogLevel.Trace))
                    {
                        logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag);
                    }
                    return(record);
                }
                catch (Exception exc)
                {
                    if (AzureStorageUtils.TableStorageDataNotFound(exc))
                    {
                        if (logger.IsEnabled(LogLevel.Trace))
                        {
                            logger.Trace((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc));
                        }
                        return(null);  // No data
                    }
                    throw;
                }
            }
예제 #3
0
        /// <summary>
        /// Save the DTT square to batch.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="square">The square.</param>
        private void SaveDTTSquareToBatch(string tableName, DTTSquare square)
        {
            try
            {
                byte[] block = new byte[square.DttValues.Length * sizeof(int)];
                Buffer.BlockCopy(square.DttValues, 0, block, 0, block.Length);

                var stream = new MemoryStream();
                using (Stream ds = new GZipStream(stream, CompressionMode.Compress))
                {
                    ds.Write(block, 0, square.DttValues.Count() * sizeof(int));
                }

                byte[] compressed = stream.ToArray();

                DynamicTableEntity entity = new DynamicTableEntity();
                entity.Properties.Add("DataRecord", EntityProperty.GeneratePropertyForByteArray(compressed));
                entity.Properties.Add("Easting", EntityProperty.GeneratePropertyForInt(square.Easting));
                entity.Properties.Add("Northing", EntityProperty.GeneratePropertyForInt(square.Northing));
                entity.RowKey       = square.Northing.ToString().PadLeft(7, '0');
                entity.PartitionKey = square.Easting.ToString().PadLeft(7, '0');

                if (!batches.ContainsKey(entity.PartitionKey))
                {
                    batches[entity.PartitionKey] = new TableBatchOperation();
                }

                TableBatchOperation batchOperations = batches[entity.PartitionKey];
                batchOperations.Add(TableOperation.Insert(entity));

                if (batchOperations.Count >= 50)
                {
                    this.FlushBatch(tableName, batchOperations);
                    batchOperations.Clear();
                }
            }
            catch (Exception ex)
            {
                this.Logger.Log(TraceEventType.Error, LoggingMessageId.DttSyncGenericMessage, string.Format("Exception Occured in Table: {0}, Exception :{1}", tableName, ex.ToString()));
            }
        }
예제 #4
0
        public void EditSnippet(string sFileName, string sSnippet, string sTagList)
        {
            //List<string> lTags = sTagList.Split(',').ToList();

            // get prexisting tag list for this snippet
            TableOperation     pRetrieveInitialOperation = TableOperation.Retrieve <SnippetTableEntity>("SNIPPET", sFileName);
            TableResult        pInitialSnippetResult     = this.Table.Execute(pRetrieveInitialOperation);
            SnippetTableEntity pInitialSnippet           = (SnippetTableEntity)pInitialSnippetResult.Result;

            string        sPreviousTags = pInitialSnippet.TagList;
            List <string> lPreviousTags = sPreviousTags.Split(',').ToList();

            //List<TableOperation> lOperations = new List<TableOperation>();

            // 1. delete all tags for snippet that currently exist (query row key) INCLUDING THE SNIPPET PARTITION

            // delete every combination of tag partition key and the filename (rowkey)
            foreach (string sOldTag in lPreviousTags)
            {
                // referencing row entity with a dynamic table entity allows deletion by partition/row key without having to first manually retrieve the correct entity
                DynamicTableEntity pDynamicEntity = new DynamicTableEntity(sOldTag, sFileName);
                pDynamicEntity.ETag = "*";

                TableOperation pDeletionOperation = TableOperation.Delete(pDynamicEntity);
                this.Table.Execute(pDeletionOperation);
                //lOperations.Add(pDeletionOperation);
            }

            // delete the snippet from the SNIPPET partition
            TableOperation pInitialSnippetDeletion = TableOperation.Delete(pInitialSnippet);

            this.Table.Execute(pInitialSnippetDeletion);

            // 2. edit the snippets blob content
            CloudBlockBlob pBlob = this.Container.GetBlockBlobReference(sFileName);

            pBlob.UploadText(sSnippet);

            // 3. using same process as add snippet, add tags stuff
            this.AddTagsForSnippet(sFileName, sTagList);
        }
        public void UpdateEventSeats(Event eventObj)
        {
            string partitionKey  = eventObj.EventDate.Year.ToString();
            string rowKey        = eventObj.Id.ToString();
            var    eventToUpdate = new DynamicTableEntity()
            {
                PartitionKey = partitionKey, RowKey = rowKey, ETag = "*"
            };
            Dictionary <string, EntityProperty> newProperties = new Dictionary <string, EntityProperty>
            {
                { "AvailableSeats", new EntityProperty(eventObj.AvailableSeats) }
            };

            eventToUpdate.Properties = newProperties;
            TableOperation updateOperation = TableOperation.Merge(eventToUpdate);

            _tableEvents.Execute(updateOperation);


            _cacheService.InvalidateCache(GenerateLiveEventsKey(partitionKey));
        }
예제 #6
0
        public void Convert_IfOtherPropertyIsWriteOnly_PopulatesOtherProperty()
        {
            // Arrange
            int?expectedOtherProperty = 123;
            IConverter <ITableEntity, PocoWithWriteOnlyOtherProperty> product =
                CreateProductUnderTest <PocoWithWriteOnlyOtherProperty>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                Properties = new Dictionary <string, EntityProperty>
                {
                    { "OtherProperty", new EntityProperty(expectedOtherProperty) }
                }
            };

            // Act
            PocoWithWriteOnlyOtherProperty actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Equal(expectedOtherProperty, actual.ReadOtherProperty);
        }
예제 #7
0
        public void Convert_IfDictionaryContainsRowKey_PopulatesFromOfficialRowKey()
        {
            // Arrange
            const string expectedRowKey = "RK";
            IConverter <ITableEntity, PocoWithRowKey> product = CreateProductUnderTest <PocoWithRowKey>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                RowKey     = expectedRowKey,
                Properties = new Dictionary <string, EntityProperty>
                {
                    { "RowKey", new EntityProperty("UnexpectedRK") }
                }
            };

            // Act
            PocoWithRowKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedRowKey, actual.RowKey);
        }
예제 #8
0
        public async Task <object> DeleteUserAsync(string personGroupID, string username)
        {
            try
            {
                //Get reference to user table
                var table = await GetUserTableAsync();

                //Create a dynamic table entity using partition key and row key
                var entity = new DynamicTableEntity(personGroupID, username);
                entity.ETag = "*";

                //Delete the entity
                await table.ExecuteAsync(TableOperation.Delete(entity));

                return(table);
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
예제 #9
0
        private void RetrieveOrInsert(string SourceRepo, string branch, string sha, string TargetRepo)
        {
            TableQuery rangeQuery = new TableQuery().Where(TableQuery.CombineFilters(
                                                               TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, sha),
                                                               TableOperators.And,
                                                               TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, TargetRepo)));

            var commits = s_table.ExecuteQuery(rangeQuery);

            if (commits.Count() == 0)
            {
                DynamicTableEntity entity = new DynamicTableEntity(TargetRepo, sha);
                entity.Properties.Add("Branch", EntityProperty.GeneratePropertyForString(branch));
                entity.Properties.Add("PR", EntityProperty.GeneratePropertyForString(string.Empty));
                entity.Properties.Add("SourceRepo", EntityProperty.GeneratePropertyForString(SourceRepo));
                entity.Properties.Add("Mirrored", EntityProperty.GeneratePropertyForBool(false));

                TableOperation insertOperation = TableOperation.Insert(entity);
                s_table.Execute(insertOperation);
            }
        }
        public void TableToDynamicMeasurement()
        {
            // Arrange
            CountryTableEntity entity    = ObjectsFactory.GetTableCountry();
            Stopwatch          stopWatch = Stopwatch.StartNew();
            var dynamicTableEntity       = new DynamicTableEntity();

            // Act
            for (int i = 0; i < IteractionsCount; i++)
            {
                dynamicTableEntity.PartitionKey = entity.PartitionKey;
                dynamicTableEntity.RowKey       = entity.RowKey;
                dynamicTableEntity.Properties   = entity.WriteEntity(null);
            }

            stopWatch.Stop();

            Assert.NotNull(dynamicTableEntity);

            Console.WriteLine(ResultFormat, IteractionsCount, stopWatch.ElapsedMilliseconds);
        }
 internal static void VerifyEntityProperty <T>(
     DynamicTableEntity entity,
     string propertyName,
     string tableName,
     T[] validValues,
     T actualValue)
 {
     if (false == validValues.Contains(actualValue))
     {
         Utility.TraceSource.WriteError(
             AzureTableUploaderTest.TraceType,
             "Property {0} for entity with PK: {1}, RK: {2} in table {3} has invalid value {4}. Valid values: {5}.",
             propertyName,
             entity.PartitionKey,
             entity.RowKey,
             tableName,
             actualValue,
             String.Join(",", validValues));
         Verify.Fail("Invalid property value in table");
     }
 }
예제 #12
0
        public static void SetSelectionSetting(string selection_id, string board_list)
        {
            TableResult        result = Warehouse.SelectionListTable.Execute(TableOperation.Retrieve(selection_id, EMPTY_ROW_KEY));
            DynamicTableEntity entity = (DynamicTableEntity)result.Result;

            // if (entity != null)		// let it throw null reference exception.
            int ec = RevisionStore.IncreaseEditCount(entity);

            string partition_key = SandId.CombineId(Warehouse.SelectionListTable.Name, selection_id);

            RevisionStore.CreateHistory(entity, partition_key, ec, "selectionname", "boardlist");

            CreatorConverter.FillEntity(entity, CreatorConverter.Status.Editor, null);
            entity["boardlist"].StringValue = board_list;

            Warehouse.SelectionListTable.Execute(TableOperation.Replace(entity));                  // Throws StorageException ((412) Precondition Failed) if the entity is modified in between.
            //don't work for child action. //HttpResponse.RemoveOutputCacheItem("/boardlist");
            //don't work for child action. //HttpResponse.RemoveOutputCacheItem("/discussionlist/" + selection_id);
            //SelectionBoardListResult.Invalidate();
            Warehouse.BsMapPond.Notify();
        }
예제 #13
0
        public RegisterViewModel(string eventKey)
        {
            using (EventsContext context = new EventsContext())
            {
                this.Event = context.Events.SingleOrDefault(e => e.EventKey == eventKey);
            }

            string connectionString = ConfigurationManager.AppSettings["Microsoft.WindowsAzure.Storage.ConnectionString"];
            var    storageAccount   = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("EventRegistrations");

            string partitionKey = String.Format("Stub_{0}", eventKey);
            string filter       = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);

            TableQuery         query       = new TableQuery().Where(filter);
            DynamicTableEntity tableEntity = table.ExecuteQuery(query).SingleOrDefault();

            this.RegistrationStub = DynamicEntity.GenerateDynamicItem(tableEntity);
        }
예제 #14
0
        public void ConfirmTicket(Ticket ticket)
        {
            string partitionKey   = ticket.Attendee;
            string rowKey         = ticket.Id.ToString();
            var    ticketToUpdate = new DynamicTableEntity()
            {
                PartitionKey = partitionKey, RowKey = rowKey, ETag = "*"
            };
            Dictionary <string, EntityProperty> newProperties = new Dictionary <string, EntityProperty>
            {
                { "TicketStatus", new EntityProperty("Paid") }
            };

            ticketToUpdate.Properties = newProperties;
            TableOperation updateOperation = TableOperation.Merge(ticketToUpdate);

            _tableTickets.Execute(updateOperation);

            //Todo : Invalido el cache
            _cacheService.InvalidateCache(GenerateMyTicketsKey(ticket.Attendee));
        }
예제 #15
0
        public void AddOrUpdate(string partition_key, string row_key, DynamicTableEntity entity)
        {
            string cache_key = key(partition_key);
            ConcurrentDictionary <string, T> obj = (ConcurrentDictionary <string, T>)HttpRuntime.Cache.Get(cache_key);

            if (obj != null)
            {
                obj.AddOrUpdate(row_key,
                                rk =>
                {
                    T t = new T();
                    t.Initialize(entity);
                    return(t);
                },
                                (rk, t) =>
                {
                    t.Initialize(entity);
                    return(t);
                });
            }
        }
예제 #16
0
        private DynamicTableEntity GetDynamicEntity(StorageEntity entity)
        {
            if (!entity.CreatedOn.HasValue)
            {
                entity.CreatedOn = DateTime.UtcNow;
            }

            OperationContext context = new OperationContext();
            IDictionary <string, EntityProperty> properties = TableEntity.Flatten(entity, context);

            properties.Remove("PartitionKey");
            properties.Remove("RowKey");

            DynamicTableEntity dynamicEntity = new DynamicTableEntity(entity.PartitionKey, entity.RowKey)
            {
                ETag       = "*",
                Properties = properties
            };

            return(dynamicEntity);
        }
        public void DynamicToTableMeasurement()
        {
            // Arrange
            DynamicTableEntity dynamicTableEntity = ObjectsFactory.GetCountryDynamicTableEntity();
            Stopwatch          stopWatch          = Stopwatch.StartNew();
            var tableEntity = new CountryTableEntity();

            // Act
            for (int i = 0; i < IteractionsCount; i++)
            {
                tableEntity.PartitionKey = dynamicTableEntity.PartitionKey;
                tableEntity.RowKey       = dynamicTableEntity.RowKey;
                tableEntity.ReadEntity(dynamicTableEntity.Properties, null);
            }

            stopWatch.Stop();

            Assert.NotNull(tableEntity);

            Console.WriteLine(ResultFormat, IteractionsCount, stopWatch.ElapsedMilliseconds);
        }
예제 #18
0
        public static DynamicTableEntity ToTableEntity(CounterRecord record, string pk, string rk)
        {
            DynamicTableEntity entity = new DynamicTableEntity(pk, rk);

            entity.Properties["Key"]       = new EntityProperty(record.Key);
            entity.Properties["Timestamp"] = new EntityProperty(DateTimeOffset.UtcNow);

            //Serialize ComplexValue Value
            using (MemoryStream mstream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(mstream, record.Value);
                byte[] bin = mstream.ToArray();

                if (!Utils.AttachBin2Entity(entity, bin))
                {
                    throw new CounterTooLargeException();
                }
            }

            return(entity);
        }
예제 #19
0
        public static void CopyEntity(DynamicTableEntity src_entity, Status src_status,
                                      DynamicTableEntity dst_entity, Status dst_status)
        {
            try
            {
                dst_entity[names[(int)dst_status, 0]] = new EntityProperty(src_entity.GetString(names[(int)src_status, 0], null));
                dst_entity[names[(int)dst_status, 1]] = new EntityProperty(src_entity[names[(int)src_status, 1]].DateTimeOffsetValue);
                dst_entity[names[(int)dst_status, 2]] = new EntityProperty(src_entity[names[(int)src_status, 2]].Int32Value);
                dst_entity[names[(int)dst_status, 3]] = new EntityProperty(src_entity[names[(int)src_status, 3]].StringValue);

                dst_entity[names[(int)dst_status, 4]] = new EntityProperty(src_entity.GetString(names[(int)src_status, 4], null));
                dst_entity[names[(int)dst_status, 5]] = new EntityProperty(src_entity.GetString(names[(int)src_status, 5], null));

                dst_entity[names[(int)dst_status, 6]] = new EntityProperty(src_entity.GetString(names[(int)src_status, 6], null));
            }
            catch (KeyNotFoundException ex)
            {
                // TODO: inspect why this happens. this happens when a letter is 檢舉 then 先斬後奏.
                // version is not zero, but the entity is creator instead of last editor.
            }
        }
        public void ConvertToEntityWithNameMapping()
        {
            // Arrange
            var converter   = new TableEntityConverter <LogEntry>();
            var tableEntity = new DynamicTableEntity
            {
                PartitionKey = "My partiton key",
                Properties   = new Dictionary <string, EntityProperty>
                {
                    { "OldMessage", new EntityProperty("My message") }
                }
            };

            // Act
            LogEntry entity = converter.GetEntity(tableEntity);

            // Assert
            Assert.Equal(entity.Id, tableEntity.PartitionKey);
            Assert.Null(tableEntity.RowKey);
            Assert.Equal(entity.Message, tableEntity.Properties["OldMessage"].StringValue);
        }
예제 #21
0
        /// <summary>
        /// Update value, if not contain key then add value.
        /// </summary>
        /// <param name="key">The key to add or update.</param>
        /// <param name="value">The value to add or update.</param>
        /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for a task to complete.</param>
        /// <returns>A Microsoft.WindowsAzure.Storage.Table.TableResult object.</returns>
        public Task <TableResult> AddOrUpdateAsync(string key, object value, CancellationToken?cancellationToken = null)
        {
            key.ValidateTableDictionaryPropertyValue();

            return(Task.Run(() =>
            {
                if (this._dictionaryKeyIgnoreCase)
                {
                    key = key.ToLowerInvariant();
                }

                key = RowKeyPrefix + key;

                var entity = new DynamicTableEntity();

                entity[ValueKey] = value.ToEntityProperty();

                return this._tableStorage.InsertOrReplaceAsync(entity, this._dictionaryPartitionKey, key, cancellationToken);
            },
                            cancellationToken ?? CancellationToken.None));
        }
예제 #22
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        public void GetModificationDate(CloudTable table, DynamicTableEntity entity)
        {
            testContextInstance.WriteLine("{0}", entity.Timestamp);
            for (int i = 0; i < recentSongs.Length; i++)
            {
                if (recentSongs[i] == null)
                {
                    recentSongs[i] = entity;
                    return;
                }
                else if (recentSongs[i].Timestamp.CompareTo(entity.Timestamp) < 0)
                {
                    for (int x = recentSongs.Length - 2; x > i; x--)
                    {
                        recentSongs[x + 1] = recentSongs[x];
                    }
                    recentSongs[i] = entity;
                    return;
                }
            }
        }
        public async Task <bool> UpdateUrl(string email, string url)
        {
            var table = await _getTableObject();

            var entity = new DynamicTableEntity(email, email);

            entity.ETag = "*";
            entity.Properties.Add("VSO_Url", new EntityProperty(url));
            var mergeOperation = TableOperation.Merge(entity);

            try
            {
                await table.ExecuteAsync(mergeOperation);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #24
0
        public static FigureInfoEntity GetFigure(string room_name, string figure_name)
        {
            string partition_key = Config.ROOM_NAME_KEY_PREFIX + room_name.ToLowerInvariant() + Config.NAME_CONCAT +
                                   Config.FIGURE_KEY_PREFIX + figure_name.ToLowerInvariant();

            TableOperation op     = TableOperation.Retrieve(partition_key, Config.EMPTY_KEY);
            TableResult    result = Warehouse.FiguresTable.Execute(op);                         // StorageException: 遠端伺服器傳回一個錯誤: (400) 不正確的要求。 if partition_key is invalid.

            DynamicTableEntity entity = (DynamicTableEntity)result.Result;

            if (entity != null)
            {
                int figure_id = (int)entity["figureid"].Int32Value;

                return(getFigure(room_name, figure_id));
            }
            else
            {
                return(null);
            }
        }
예제 #25
0
        public void Convert_IfDictionaryContainsETag_PopulatesFromOfficialETag()
        {
            // Arrange
            const string expectedETag = "ETag";
            IConverter <ITableEntity, PocoWithETag> product = CreateProductUnderTest <PocoWithETag>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                ETag       = expectedETag,
                Properties = new Dictionary <string, EntityProperty>
                {
                    { "ETag", new EntityProperty("UnexpectedETag") }
                }
            };

            // Act
            PocoWithETag actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedETag, actual.ETag);
        }
        public void CloudAnalyticsClientPopulateCapacityQuery()
        {
            Blob.CloudBlobClient   blobClient      = CloudAnalyticsClientTests.GenerateCloudBlobClient();
            Table.CloudTableClient tableClient     = CloudAnalyticsClientTests.GenerateCloudTableClient();
            CloudAnalyticsClient   analyticsClient = new CloudAnalyticsClient(blobClient.StorageUri, tableClient.StorageUri, tableClient.Credentials);

            CapacityEntity     capacityEntity = analyticsClient.CreateCapacityQuery().Execute().First();
            DynamicTableEntity dynamicEntity  = tableClient.GetTableReference("$MetricsCapacityBlob").CreateQuery <DynamicTableEntity>().Execute().First();

            IDictionary <string, EntityProperty> capacityEntityDictionary = capacityEntity.WriteEntity(null);
            IDictionary <string, EntityProperty> dynamicEntityDictionary  = dynamicEntity.Properties;

            // Note that the other direction will fail because the PartitionKey/RowKey are not present in dtEntityDictionary
            foreach (KeyValuePair <string, EntityProperty> pair in capacityEntityDictionary)
            {
                EntityProperty propertyValue;
                bool           propertyExists = dynamicEntityDictionary.TryGetValue(pair.Key, out propertyValue);
                Assert.IsTrue(propertyExists);
                Assert.AreEqual(propertyValue, pair.Value);
            }
        }
예제 #27
0
        public void Convert_IfExtraPropertyIsPresentInDictionary_Ignores()
        {
            // Arrange
            const string expectedPartitionKey = "PK";
            IConverter <ITableEntity, PocoWithPartitionKey> product = CreateProductUnderTest <PocoWithPartitionKey>();
            DynamicTableEntity entity = new DynamicTableEntity
            {
                PartitionKey = expectedPartitionKey,
                Properties   = new Dictionary <string, EntityProperty>
                {
                    { "ExtraProperty", new EntityProperty("abc") }
                }
            };

            // Act
            PocoWithPartitionKey actual = product.Convert(entity);

            // Assert
            Assert.NotNull(actual);
            Assert.Same(expectedPartitionKey, actual.PartitionKey);
        }
예제 #28
0
        public static Lesson ToLesson(this DynamicTableEntity entry)
        {
            var days = new[] {
                JsonConvert.DeserializeObject <Day>(entry.Properties["One"].StringValue),
                JsonConvert.DeserializeObject <Day>(entry.Properties["Two"].StringValue),
                JsonConvert.DeserializeObject <Day>(entry.Properties["Three"].StringValue),
                JsonConvert.DeserializeObject <Day>(entry.Properties["Four"].StringValue),
                JsonConvert.DeserializeObject <Day>(entry.Properties["Five"].StringValue),
                JsonConvert.DeserializeObject <Day>(entry.Properties["Six"].StringValue),
            };

            return(new Lesson
            {
                Culture = entry.PartitionKey,
                Id = entry.RowKey,
                Name = entry.Properties["Name"].StringValue,
                ////AudioUrl = entry["AudioUrl"].StringValue,
                MemoryVerse = entry.Properties["MemoryVerse"].StringValue,
                DayQuestions = days.ToList(),
            });
        }
예제 #29
0
        /// <summary>
        /// Converts a DynamicTableEntity to a JObject
        /// This will automatically include the ETag, Timestamp, and RowKey field (as ID)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static JObject ToJObject(this DynamicTableEntity entity)
        {
            var entityList = entity.Properties.Select(x => new JProperty(x.Key, x.Value.PropertyAsObject)).ToArray();
            var obj        = new JObject(entityList);

            //Add in our tracking properties
            if (obj.Value <string>(nameof(entity.ETag)) == null)
            {
                obj.AddFirst(new JProperty(nameof(entity.ETag), entity.ETag));
            }
            if (obj.Value <string>(nameof(entity.Timestamp)) == null)
            {
                obj.AddFirst(new JProperty(nameof(entity.Timestamp), entity.Timestamp.UtcDateTime));
            }
            if (obj.Value <string>(nameof(entity.RowKey)) == null)
            {
                obj.AddFirst(new JProperty(JObjectRowKeyFieldName, entity.RowKey));
            }

            return(obj);
        }
        public void BetweenAnHourWithGraceOf3ThereIs57()
        {
            var lockStore = new Mock <ILockStore>();

            lockStore.Setup(
                x => x.TryLockAsync(It.IsAny <LockToken>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(true));
            var config    = new Mock <IConfigurationValueProvider>();
            var scheduler = new MinuteTableShardScheduler(config.Object);
            var entity    = new DynamicTableEntity("dd", "fff");

            entity.Properties.Add("GracePeriodMinutes", EntityProperty.GeneratePropertyForInt(3));
            entity.Properties.Add("IsActive", EntityProperty.GeneratePropertyForBool(true));
            var source = new DiagnosticsSource(entity);

            source.LastOffsetPoint = DateTimeOffset.UtcNow.AddHours(-1).DropSecondAndMilliseconds().ToString("O");
            source.LastScheduled   = DateTimeOffset.UtcNow.AddDays(-1);

            var result = scheduler.TryScheduleAsync(source).Result;

            Assert.Equal(57, result.Item1.Count());
        }