示例#1
0
        public Table(string accountName, string accountKey, string tableName, string repoTableName)
        {
            var tableServiceClient = new TableServiceClient("DefaultEndpointsProtocol=https;AccountName=" + accountName + ";AccountKey=" + accountKey + ";TableEndpoint=https://" + accountName + ".table.cosmosdb.azure.com:443/;");

            CommitTable = tableServiceClient.GetTableClient(tableName);
            RepoTable   = tableServiceClient.GetTableClient(repoTableName);
        }
示例#2
0
        public FokkersDbService(TableServiceClient dbClient, string connectionString)
        {
            _connectionString    = connectionString;
            this._catchContainer = dbClient.GetTableClient("Catches");
            this._fishContainer  = dbClient.GetTableClient("Fish");

            this._catchContainer.CreateIfNotExists();
            this._fishContainer.CreateIfNotExists();
        }
示例#3
0
        public async Task <Sensor> GetByBoxIdAndTypeAsync(string boxId, SensorType type)
        {
            var table = _client.GetTableClient(_tableName);
            await table.CreateIfNotExistsAsync();

            var sensorTypeString = type.ToString("G");
            var entityPages      = table.QueryAsync <TableEntity>(x => x.PartitionKey == boxId && x.RowKey == sensorTypeString);

            return((await entityPages.AsPages().FirstOrDefaultAsync())?.Values.Select(SensorMapper.Map).FirstOrDefault());
        }
示例#4
0
        public async Task <SensorAlarm> GetBySensorBoxIdAndSensorTypeAndStatusAsync(string sensorBoxId, SensorType sensorType, AlarmStatus status)
        {
            var table = _client.GetTableClient(_tableName);
            await table.CreateIfNotExistsAsync();

            var sensorTypeString  = sensorType.ToString("G");
            var alarmStatusString = status.ToString("G");
            var entityPages       = table.QueryAsync <TableEntity>($"{nameof(TableEntity.PartitionKey)} eq '{sensorBoxId}' and {nameof(SensorAlarm.SensorType)} eq '{sensorTypeString}' and {nameof(SensorAlarm.Status)} eq '{alarmStatusString}'");

            return((await entityPages.AsPages().FirstOrDefaultAsync())?.Values.Select(SensorAlarmMapper.Map).FirstOrDefault());
        }
 public TableStorage(IOptions <TableStorageOptions> options, ILogger <TableStorage> log, TableServiceClient serviceClient)
 {
     _log = log;
     _transactionTable = serviceClient.GetTableClient($"{options.Value.Namespace}transactions");
     _dataTable        = serviceClient.GetTableClient($"{options.Value.Namespace}transactiondata");
     _hashDataTable    = serviceClient.GetTableClient($"{options.Value.Namespace}hashdata");
     _cachePurgeTable  = serviceClient.GetTableClient($"{options.Value.Namespace}cachepurge");
     _transactionTable.CreateIfNotExists();
     _dataTable.CreateIfNotExists();
     _hashDataTable.CreateIfNotExists();
     _cachePurgeTable.CreateIfNotExists();
 }
示例#6
0
        public async Task <SyncState> ReadAsync(CancellationToken cancellationToken = default)
        {
            TableClient tableClient = _tableServiceClient.GetTableClient(Constants.SyncStateTableName);

            try
            {
                var entity = await tableClient.GetEntityAsync <SyncStateEntity>(Constants.SyncStatePartitionKey, Constants.SyncStateRowKey, cancellationToken : cancellationToken);

                return(new SyncState(entity.Value.SyncedSequence, entity.Value.Timestamp.Value));
            }
            catch (RequestFailedException)
            {
                return(SyncState.CreateInitialSyncState());
            }
        }
示例#7
0
        public void CreateDeleteTable()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies1p1";

            #region Snippet:TablesSample1CreateClient
            // Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));
            #endregion

            #region Snippet:TablesSample1CreateTable
            // Create a new table. The <see cref="TableItem" /> class stores properties of the created table.
#if SNIPPET
            string tableName = "OfficeSupplies1p1";
#endif
            TableItem table = serviceClient.CreateTable(tableName);
            Console.WriteLine($"The created table's name is {table.Name}.");
            #endregion

            #region Snippet:TablesSample1DeleteTable
            // Deletes the table made previously.
#if SNIPPET
            string tableName = "OfficeSupplies1p1";
#endif
            serviceClient.DeleteTable(tableName);
            #endregion

            #region Snippet:TablesSample1GetTableClient
#if SNIPPET
            string tableName = "OfficeSupplies1p2";
#else
            tableName = "OfficeSupplies1p2";
#endif
            var tableClient = serviceClient.GetTableClient(tableName);
            #endregion

            #region Snippet:TablesSample1CreateTableClient
#if SNIPPET
            var tableClient = new TableClient(
#else
            tableClient = new TableClient(
#endif
                new Uri(storageUri),
                tableName,
                new TableSharedKeyCredential(accountName, storageAccountKey));
            #endregion

            #region Snippet:TablesSample1TableClientCreateTable
            tableClient.Create();
            #endregion

            #region Snippet:TablesSample1TableClientDeleteTable
            tableClient.Delete();
                               #endregion
        }
示例#8
0
        /// <summary>
        /// Connects to, or creates and initializes a new Azure table if it does not already exist.
        /// </summary>
        /// <returns>Completion promise for this operation.</returns>
        public async Task InitTableAsync()
        {
            const string operation = "InitTable";
            var          startTime = DateTime.UtcNow;

            try
            {
                TableServiceClient tableCreationClient = await GetCloudTableCreationClientAsync();

                var table     = tableCreationClient.GetTableClient(TableName);
                var tableItem = await table.CreateIfNotExistsAsync();

                var didCreate = tableItem is not null;

                Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName);

                Table = table;
            }
            catch (TimeoutException te)
            {
                var errorMsg = $"Unable to create or connect to the Azure table in {this.StoragePolicyOptions.CreationTimeout}";
                this.Logger.Error((int)Utilities.ErrorCode.AzureTable_TableNotCreated, errorMsg, te);
                throw new OrleansException(errorMsg, te);
            }
            catch (Exception exc)
            {
                Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc);
                throw;
            }
            finally
            {
                CheckAlertSlowAccess(startTime, operation);
            }
        }
示例#9
0
        /// <summary>
        /// Requesting Metrics from azure tables for each node in scale-set
        /// </summary>
        internal List <WadMetric> GetMetricsFromTable(string StorageAccountConnectionString, int LookupTimeInMinutes, string TablePrefix)
        {
            List <WadMetric> resultList = new List <WadMetric>();

            var serviceClient = new TableServiceClient(StorageAccountConnectionString);
            var table         = serviceClient.GetTableClient(TablePrefix);

            if (table == null)
            {
                throw new SystemException("There is no table in storage account with prefix:" + TablePrefix);
            }

            //CloudTable table = tableClient.GetTableReference(TableName);

            //Timeback in mins
            var            minutesBack = TimeSpan.FromMinutes(LookupTimeInMinutes);
            var            timeInPast  = DateTime.UtcNow.Subtract(minutesBack);
            DateTimeOffset qdate       = new DateTimeOffset(timeInPast);



            //TODO add ROWKEY to encrease performance.
            var result = table.Query <WadMetric>(wad => wad.PartitionKey == scalesetid.Replace("/", ":002F").Replace("-", ":002D").Replace(".", ":002E") &&
                                                 wad.Timestamp >= qdate && (wad.CounterName == CpuMetricName || wad.CounterName == DiskMetricName));

            foreach (var entity in result)
            {
                resultList.Add(entity);
            }

            return(resultList);
        }
            async Task <TableClient> InitializeAndCacheTableAsync(string tableName, CancellationToken cancellationToken)
            {
                try
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("CloudTableClient has not been initialized");
                    }

                    InternalLogger.Debug("AzureDataTablesTarget: Initializing table: {0}", tableName);

                    var tableExists = await _client.CreateTableIfNotExistsAsync(tableName, cancellationToken).ConfigureAwait(false);

                    var table = _client.GetTableClient(tableName);

                    if (tableExists != null)
                    {
                        InternalLogger.Debug("AzureDataTablesTarget: Created new table: {0}", tableName);
                    }
                    else
                    {
                        InternalLogger.Debug("AzureDataTablesTarget: Opened existing table: {0}", tableName);
                    }

                    _table = table;
                    return(table);
                }
                catch (Exception exception)
                {
                    InternalLogger.Error(exception, "AzureDataTablesTarget: Failed to initialize table={0}", tableName);
                    throw;
                }
            }
    public async Task InsertAsync(AggregatedSensorData aggregatedSensorData)
    {
        var table = _client.GetTableClient(_tableName);
        await table.CreateIfNotExistsAsync();

        await table.UpsertEntityAsync(SensorDataMapper.Map(aggregatedSensorData));
    }
示例#12
0
            public override TableClient GetTableClient(string tableName)
            {
                var client = _client.GetTableClient(tableName);

                client.SetBatchGuids(_recording.Random.NewGuid(), _recording.Random.NewGuid());
                return(client);
            }
        public async Task UpdateUpsertEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies5p2" + _random.Next();
            string partitionKey      = "Stationery";
            string rowKey            = "A1";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            var tableClient = serviceClient.GetTableClient(tableName);

            #region Snippet:TablesSample5UpsertEntityAsync
            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Markers" },
                { "Price", 5.00 },
                { "Brand", "myCompany" }
            };

            // Entity doesn't exist in table, so invoking UpsertEntity will simply insert the entity.
            await tableClient.UpsertEntityAsync(entity);

            #endregion

            #region Snippet:TablesSample5UpsertWithReplaceAsync
            // Delete an entity property.
            entity.Remove("Brand");

            // Entity does exist in the table, so invoking UpsertEntity will update using the given UpdateMode, which defaults to Merge if not given.
            // Since UpdateMode.Replace was passed, the existing entity will be replaced and delete the "Brand" property.
            await tableClient.UpsertEntityAsync(entity, TableUpdateMode.Replace);

            #endregion

            #region Snippet:TablesSample5UpdateEntityAsync
            // Get the entity to update.
            TableEntity qEntity = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey);

            qEntity["Price"] = 7.00;

            // Since no UpdateMode was passed, the request will default to Merge.
            await tableClient.UpdateEntityAsync(qEntity, qEntity.ETag);

            TableEntity updatedEntity = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey);

            Console.WriteLine($"'Price' before updating: ${entity.GetDouble("Price")}");
            Console.WriteLine($"'Price' after updating: ${updatedEntity.GetDouble("Price")}");
            #endregion

            await serviceClient.DeleteTableAsync(tableName);
        }
示例#14
0
 public StorageManager(IOptions <StorageOptions> options, ILogger <StorageManager> logger)
 {
     _options          = options.Value;
     _connectionString = _options.StorageAccount;
     _logger           = logger;
     _serviceClient    = new TableServiceClient(_connectionString);
     _dishTable        = _serviceClient.GetTableClient("dish");
     _dishTable.CreateIfNotExists();
 }
示例#15
0
        async Task <IDictionary <string, object> > IAzureTableStoreClient.ReadRecordAsync(string tableName, string partitionKey, string rowKey, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }
            if (string.IsNullOrWhiteSpace(partitionKey))
            {
                throw new ArgumentNullException(nameof(partitionKey));
            }
            if (string.IsNullOrWhiteSpace(rowKey))
            {
                throw new ArgumentNullException(nameof(rowKey));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var managedIdentityCredential = new DefaultAzureCredential();

            var tableClientOptions = GetTableClientOptions(_geoRedundantServiceUrl);

            var tableServiceClient = new TableServiceClient(_primaryServiceUrl, managedIdentityCredential, tableClientOptions);

            var tableClient = tableServiceClient.GetTableClient(tableName);

            try
            {
                var result = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey, cancellationToken : cancellationToken);

                using var response = result.GetRawResponse();

                if (!IsSuccessStatusCode(response?.Status ?? int.MinValue))
                {
                    Debug.Assert(response is not null);

                    _logger?.LogDebug("Unable to read a record from table storage '{TableName}'.  {ClientRequestId} - Reported '{ReasonPhrase}' with status code: '{StatusCode} {StatusCodeName}'", response.ClientRequestId, tableName, response.ReasonPhrase, response.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(response.Status, CultureInfo.InvariantCulture)));

                    // TODO - Add custom table storage exception

                    throw new ApplicationException($"{response.ClientRequestId}: Unable to read a record from table storage '{tableName}'.  Please consult log files for more information");
                }

                return(result.Value);
            }
            catch (AuthenticationFailedException ex)
            {
                _logger?.LogError(ex, "Unable to authenticate with the Azure Table Storage service using the default credentials.  Please ensure the user account this application is running under has permissions to access the Blob Storage account we are targeting");

                throw;
            }
            catch (RequestFailedException ex)
            {
                _logger?.LogError(ex, "Unable to access the Table Storage endpoint as the Read request failed: '{StatusCode} {StatusCodeName}'", ex.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(ex.Status, CultureInfo.InvariantCulture)));

                throw;
            }
        }
        private async Task <TableClient> RetrieveTable()
        {
            var serviceClient = new TableServiceClient(connectionString);

            await serviceClient.CreateTableIfNotExistsAsync(TableName);

            var tableClient = serviceClient.GetTableClient(TableName);

            return(tableClient);
        }
        public void AccountNameAndNameForConnStringCtor(string connString, string accountName)
        {
            var client = new TableServiceClient(connString, new TableClientOptions());

            Assert.AreEqual(accountName, client.AccountName);

            var tableClient = client.GetTableClient("someTable");

            Assert.AreEqual(accountName, tableClient.AccountName);
        }
示例#18
0
        /// <inheritdoc/>
        public async Task WriteExceptionAsync(ChangeFeedEntry changeFeedEntry, Exception exceptionToStore, ErrorType errorType, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(changeFeedEntry, nameof(changeFeedEntry));

            string tableName = errorType switch
            {
                ErrorType.FhirError => Constants.FhirExceptionTableName,
                ErrorType.DicomError => Constants.DicomExceptionTableName,
                ErrorType.DicomValidationError => Constants.DicomValidationTableName,
                ErrorType.TransientFailure => Constants.TransientFailureTableName,
                _ => null,
            };

            if (tableName == null)
            {
                return;
            }

            DicomDataset dataset            = changeFeedEntry.Metadata;
            string       studyInstanceUid   = dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string       seriesInstanceUid  = dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
            string       sopInstanceUid     = dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
            long         changeFeedSequence = changeFeedEntry.Sequence;

            var tableClient = _tableServiceClient.GetTableClient(tableName);
            var entity      = new IntransientEntity(studyInstanceUid, seriesInstanceUid, sopInstanceUid, changeFeedSequence, exceptionToStore);

            try
            {
                await tableClient.UpsertEntityAsync(entity, cancellationToken : cancellationToken);

                _logger.LogInformation("Error when processing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyInstanceUid}, SeriesUID: {SeriesInstanceUid}, InstanceUID: {SopInstanceUid}. Stored into table: {Table} in table storage.", changeFeedSequence, studyInstanceUid, seriesInstanceUid, sopInstanceUid, tableName);
            }
            catch
            {
                _logger.LogInformation("Error when processing changefeed entry: {ChangeFeedSequence} for DICOM instance with StudyUID: {StudyInstanceUid}, SeriesUID: {SeriesInstanceUid}, InstanceUID: {SopInstanceUid}. Failed to store to table storage.", changeFeedSequence, studyInstanceUid, seriesInstanceUid, sopInstanceUid);
                throw;
            }
        }
        public async Task Insert <T>(T entity) where T : AzureTableEntity, new()
        {
            var client = serviceClient.GetTableClient(typeof(T).Name);
            await client.CreateIfNotExistsAsync();

            try
            {
                await client.UpsertEntityAsync(entity);
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
示例#20
0
    private async Task <TableClient> GetTableClientForTime(DateTimeOffset dt)
    {
        var bucketId  = GetBucketNameForTimeSpan(dt);
        var tableName = GetTableName(bucketId);

        _logger.LogInformation("Getting client for table: [{tableName}]", tableName);

        var tc = _tableServiceClient.GetTableClient(tableName);
        await Task.WhenAll(
            tc.CreateIfNotExistsAsync(),
            DeleteExpiredTables(DateTimeOffset.UtcNow)
            );

        return(tc);
    }
示例#21
0
        public async Task EntitiyCanBeUpserted()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            const string       rowKeyValue       = "1";
            const string       propertyName      = "SomeStringProperty";
            const string       originalValue     = "This is the original";
            const string       updatedValue      = "This is new and improved!";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                var         entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { propertyName, originalValue }
                };

                // Insert the new entity.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                var entityToUpdate = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                entityToUpdate[propertyName] = updatedValue;
                await client.UpsertAsync(entityToUpdate).ConfigureAwait(false);

                // Fetch the updated entity from the service.

                var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
示例#22
0
        public override async Task StartTestRecordingAsync()
        {
            await base.StartTestRecordingAsync();

            TableName     = GetRandomTableName();
            ServiceClient = InstrumentClient(
                new TableServiceClient(
                    UseCosmos ? TestEnvironment.CosmosConnectionString : TestEnvironment.StorageConnectionString,
                    InstrumentClientOptions(new TableClientOptions())));

            TableClient = ServiceClient.GetTableClient(TableName);
            if (_createTable)
            {
                await TableClient.CreateAsync();
            }
        }
示例#23
0
    /// <summary>
    /// Create the table client
    /// </summary>
    /// <param name="connectionString">The connection string</param>
    /// <param name="tableName">The name of the table</param>
    /// <param name="retries">Number of retries</param>
    /// <param name="retryWaitTimeInSeconds">Wait time between retries in seconds</param>
    /// <returns>The table client</returns>
    private static (TableServiceClient serviceClient, TableClient tableClient) CreateTableClient(string connectionString, string tableName, int retries, double retryWaitTimeInSeconds)
    {
        var options = new TableClientOptions
        {
            Retry =
            {
                MaxRetries = retries,
                Delay      = TimeSpan.FromSeconds(retryWaitTimeInSeconds),
                Mode       = Azure.Core.RetryMode.Exponential
            }
        };

        var serviceClient = new TableServiceClient(connectionString, options);
        var tableClient   = serviceClient.GetTableClient(tableName);

        return(serviceClient, tableClient);
    }
        public Task <IValueProvider> BindAsync(BindingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            TableEntityPath    boundPath     = _path.Bind(context.BindingData);
            var                table         = _client.GetTableClient(boundPath.TableName);
            TableEntityContext entityContext = new TableEntityContext
            {
                Table        = table,
                PartitionKey = boundPath.PartitionKey,
                RowKey       = boundPath.RowKey
            };

            return(BindEntityAsync(entityContext, context.ValueContext));
        }
        /// <inheritdoc/>
        public async Task PerformTestAsync(CancellationToken cancellationToken = default)
        {
            await _testServiceClient.CreateTableIfNotExistsAsync(TestTable, cancellationToken : cancellationToken);

            var tableClient = _testServiceClient.GetTableClient(TestTable);
            var entity      = new HealthEntity(TestPartitionKey, TestRowKey)
            {
                Data = TestData
            };

            await tableClient.UpsertEntityAsync(entity, cancellationToken : cancellationToken);

            await tableClient.GetEntityAsync <HealthEntity>(TestPartitionKey, TestRowKey, cancellationToken : cancellationToken);

            await tableClient.DeleteEntityAsync(TestPartitionKey, TestRowKey, cancellationToken : cancellationToken);

            await _testServiceClient.DeleteTableAsync(TestTable, cancellationToken);
        }
示例#26
0
        public async Task <IActionResult> GetFileAsync(string fileId)
        {
            // TODO: Verify that user is allowed to get files for this chat/call

            // Prepare Table Storage clients
            TableServiceClient tableServiceClient = new TableServiceClient(_storageAccountConnectionString);
            TableClient        tableClient        = tableServiceClient.GetTableClient(_tableName);

            tableClient.CreateIfNotExists();

            // Get file info from Table Storage
            Azure.Response <TableEntity> getTableEntityResponse;
            try
            {
                getTableEntityResponse = await tableClient.GetEntityAsync <TableEntity>(fileId, fileId);
            }
            catch (Azure.RequestFailedException e)
            {
                if (e.Status == 404)
                {
                    return(NotFound());
                }

                return(BadRequest("Couldn't get file from storage"));
            }

            var fileName = getTableEntityResponse.Value.GetString("FileName");

            // Prepare Blob Storage clients and container
            BlobContainerClient containerClient = new BlobContainerClient(_storageAccountConnectionString, _blobContainerName);

            containerClient.CreateIfNotExists();
            BlobClient blob = containerClient.GetBlobClient(fileId);

            // MemoryStream blobStream = new MemoryStream();
            // var downloadResult = await blob.DownloadToAsync(blobStream);
            var blobStream = await blob.OpenReadAsync();

            return(new FileStreamResult(blobStream, "application/octet-stream")
            {
                FileDownloadName = fileName
            });
        }
示例#27
0
        public async Task <IActionResult> GetAsync()
        {
            // TODO: Verify that user is allowed to get files for this chat/call

            // Get file info from Table Storage
            TableServiceClient tableServiceClient = new TableServiceClient(_storageAccountConnectionString);
            TableClient        tableClient        = tableServiceClient.GetTableClient(_tableName);

            tableClient.CreateIfNotExists();
            var tableEntities = tableClient.Query <TableEntity>();
            var files         = tableEntities.Select(tableEntity => new FileMetadata
            {
                Id             = tableEntity.GetString("FileId"),
                Name           = tableEntity.GetString("FileName"),
                UploadDateTime = tableEntity.GetDateTimeOffset("UploadDateTime").Value,
            });

            return(Ok(files));
        }
示例#28
0
        public static async Task Main(string[] args)
        {
            var serviceClient = new TableServiceClient(
                new Uri("https://pakrym0test0storage.table.core.windows.net"),
                new StorageSharedKeyCredential("pakrym0test0storage", args[0]));

            await foreach (var table in serviceClient.GetTablesAsync())
            {
                Console.WriteLine(table.TableName);
            }

            var tableClient = serviceClient.GetTableClient("mytesttable2");

            var currentTime = DateTimeOffset.Now;
            var timestamp   = currentTime.Ticks.ToString();

            Console.WriteLine("Type in a message:");

            var message = Console.ReadLine();

            Console.WriteLine("Type in a number:");

            var number = int.Parse(Console.ReadLine());

            await tableClient.InsertAsync(new Dictionary <string, object>()
            {
                { "Number", number },
                { "Time", currentTime },
                { "Message", message },
                { "PartitionKey", timestamp },
                { "RowKey", timestamp }
            });

            Console.WriteLine("What number do you want?");

            var filter = int.Parse(Console.ReadLine());

            await foreach (var entity in tableClient.QueryAsync(select: "Time,Message", filter: $"Number eq {filter}"))
            {
                Console.WriteLine($"{entity["Time"]} {entity["Message"]}");
            }
        }
示例#29
0
        public TableEntityContext Convert(string input)
        {
            TableEntityPath path;

            // For convenience, treat an an empty string as a request for the default value (when valid).
            if (String.IsNullOrEmpty(input) && _defaultPath.IsBound)
            {
                path = _defaultPath.Bind(null);
            }
            else
            {
                path = TableEntityPath.ParseAndValidate(input);
            }

            return(new TableEntityContext
            {
                Table = _client.GetTableClient(path.TableName),
                PartitionKey = path.PartitionKey,
                RowKey = path.RowKey
            });
        }
        public async Task <TableClient> GetTableAsync(string tablename)
        {
            Console.Write("Checking storage...");

            var serviceClient = new TableServiceClient(_storageConnectionString);

            var result = await serviceClient.CreateTableIfNotExistsAsync(tablename);

            if (result != null)
            {
                Console.WriteLine("table '{0}' created", tablename);
            }
            else
            {
                Console.WriteLine("table '{0}' exists", tablename);
            }

            var table = serviceClient.GetTableClient(tablename);



            return(table);
        }