// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "SupervisorApi", Version = "v1" }); }); services.AddSingleton <IRepositoryService>(provider => { var connectionString = Configuration["StorageConnectionString"]; var queueClient = new QueueClient(connectionString, Names.QueueName); // Create the queue queueClient.CreateIfNotExists(); var tableClient = new TableClient(connectionString, Names.TableName); // Create the table tableClient.CreateIfNotExists(); var repositoryService = new RepositoryService(queueClient, tableClient); return(repositoryService); }); }
public void CreateTableConflict() { string tableName = "OfficeSupplies"; string connectionString = $"DefaultEndpointsProtocol=https;AccountName={StorageAccountName};AccountKey={PrimaryStorageAccountKey};EndpointSuffix={StorageEndpointSuffix ?? DefaultStorageSuffix}"; #region Snippet:CreateDuplicateTable // Construct a new TableClient using a connection string. var client = new TableClient( connectionString, tableName); // Create the table if it doesn't already exist. client.CreateIfNotExists(); // Now attempt to create the same table unconditionally. try { client.Create(); } catch (RequestFailedException ex) when(ex.Status == (int)HttpStatusCode.Conflict) { Console.WriteLine(ex.ToString()); } #endregion }
public TaskStore(IOptions <TaskStoreOptions> options) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _client = new TableClient(_options.ConnectionString, _options.TableName); _client.CreateIfNotExists(); }
/// <summary> /// Creates a table on the service. /// </summary> /// <param name="tableName"></param> /// <param name="cancellationToken">A CancellationToken controlling the request lifetime.</param> /// <returns>True if table was created; otherwise, false.</returns> public bool CreateTableIfNotExists(string tableName, CancellationToken cancellationToken) { this.EnsureTableServiceClient(); TableClient tableClient = this.tableServiceClient.GetTableClient(tableName); Response <TableItem> response = tableClient.CreateIfNotExists(cancellationToken); return(response != null); }
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(); }
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(); }
public async Task CustomizeSerialization() { string storageUri = StorageUri; string tableName = "OfficeSupplies" + _random.Next(); #region Snippet:CustomSerialization // Construct a new TableClient using a TokenCredential. var client = new TableClient( new Uri(storageUri), tableName, #if SNIPPET new DefaultAzureCredential()); #else new ClientSecretCredential( GetVariable("TENANT_ID"), GetVariable("CLIENT_ID"), GetVariable("CLIENT_SECRET"))); #endif // Create the table if it doesn't already exist. client.CreateIfNotExists(); // Create a new entity with our customization attributes. var entity = new CustomSerializationEntity { PartitionKey = "CustomInventory", RowKey = "special stock", Product = "Fancy Marker", Price = 1.00, Quantity = 42, IgnoreMe = "nothing to see here", RenameMe = "This property will be saved to the table as 'rename_me'" }; // Add the entity to the table. It will be serialized according to our customizations. await client.AddEntityAsync(entity); // Fetch the entity as a TableEntity so that we can verify that things were serialized as expected. var fetchedEntity = await client.GetEntityAsync <TableEntity>(entity.PartitionKey, entity.RowKey); // Print each property name to the console. foreach (string propertyName in fetchedEntity.Value.Keys) { Console.WriteLine(propertyName); } #endregion }
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 }); }
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)); }
public async Task <IActionResult> PostAsync([FromForm] SendFileRequestBody body) { if (body.File == null && body.Image == null) { return(BadRequest("Invalid file")); } if (string.IsNullOrWhiteSpace(body.FileName)) { return(BadRequest("Invalid file name")); } // TODO: Verify that user is allowed to upload files for this chat/call // bool isUserInThread = await this.VerifyUserInThread(chatClient, body.ThreadId); // if (!isUserInThread) // { // return this.Unauthorized(); // } // Prepare Blob Storage clients and container string blobName = Guid.NewGuid().ToString(); BlobContainerClient containerClient = new BlobContainerClient(_storageAccountConnectionString, _blobContainerName); containerClient.CreateIfNotExists(); BlobClient blob = containerClient.GetBlobClient(blobName); Azure.Response <BlobContentInfo> uploadResponse; if (body.File != null) { Console.WriteLine($"Got file length: {body.File.Length}"); uploadResponse = await blob.UploadAsync(body.File.OpenReadStream()); } else { Console.WriteLine($"Got image length: {body.Image.Length}"); var bytes = Convert.FromBase64String(body.Image); using (var stream = new MemoryStream(bytes)) { uploadResponse = await blob.UploadAsync(stream); } } Console.WriteLine($"Uploaded blob: {blobName}"); // Store file info in Table Storage TableServiceClient tableServiceClient = new TableServiceClient(_storageAccountConnectionString); TableClient tableClient = tableServiceClient.GetTableClient(_tableName); tableClient.CreateIfNotExists(); var entity = new TableEntity(blobName, blobName) { { "FileId", blobName }, { "FileName", body.FileName }, { "UploadDateTime", DateTimeOffset.UtcNow } }; tableClient.AddEntity(entity); Console.WriteLine("Added file data to table"); return(this.Ok()); }
static void Main(string[] args) { Console.WriteLine(hiMessage); try { // Get the connection string from app settings string connectionString = ConfigurationManager.AppSettings[storageConnectionString]; // Instantiate a QueueClient which will be used to create and manipulate the queue var queueClient = new QueueClient(connectionString, Names.QueueName); // Create the queue queueClient.CreateIfNotExists(); if (!queueClient.Exists()) { Console.WriteLine("Cannot create Queue. Make sure the storage emulator running and try again."); } // Instantiate a TableClient which will be used to create and manipulate the table var tableClient = new TableClient(connectionString, Names.TableName); // Create the table tableClient.CreateIfNotExists(); for (;;) { // Get the next message QueueMessage retrievedMessage = queueClient.ReceiveMessage(); if (null == retrievedMessage) { Thread.Sleep(numberOfMilliseconds); continue; } var order = JsonSerializer.Deserialize <Order>(retrievedMessage.MessageText); if (order.RandomNumber == magicNumber) { Console.WriteLine(numberFoundMessage); break; } // Process the message Console.WriteLine(receivedOrderMessage, order.OrderId); var confirmation = new Confirmation() { OrderId = order.OrderId, AgentId = agentId, OrderStatus = orderStatusProcessed, RowKey = order.OrderId.ToString(), PartitionKey = agentId.ToString() }; tableClient.AddEntity(confirmation); // Delete the message queueClient.DeleteMessage(retrievedMessage.MessageId, retrievedMessage.PopReceipt); } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}\n\n"); Console.WriteLine("Make sure the storage emulator running and try again."); } }
static void Main(string[] args) { // Configure the app to use the appsettings.json file // That's where the connection string is var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); // Check the syntax if (args.Length < 1) { System.Console.WriteLine("Usage: LensesApp <Operation>"); return; } Console.WriteLine(args[0]); // Connect to the service, using the connection string in the appsettings.json file string tableConnectionString = configuration.GetConnectionString("LensesDatabase"); TableClient tableClient = new TableClient(tableConnectionString, "lensestable"); // Find out what the user wants to do. if (args[0] == "PopulateTable") { // Create and populate the table Console.WriteLine("Creating the Lenses table..."); tableClient.CreateIfNotExists(); Console.WriteLine("Table created. Populating..."); insertEntity(tableClient, new Lens() { LensType = "Prime", PartNumber = "X5018", FocalLength = "50mm", Aperture = "f1.8" }); insertEntity(tableClient, new Lens() { LensType = "Zoom", PartNumber = "X357035", FocalLength = "35-70mm", Aperture = "f3.5" }); insertEntity(tableClient, new Lens() { LensType = "Macro", PartNumber = "X10028", FocalLength = "100mm", Aperture = "f2.8" }); Console.WriteLine("Tables created and populated."); return; } else if (args[0] == "DisplayTable") { // Read the table and display it here. Console.WriteLine("Reading the contents of the Lenses table..."); Console.WriteLine("| {0, 10} | {1, 30} | {2, 10} | {3, 10} |", "Lens Type", "Part Number", "Focal Length", "Aperture"); Pageable <TableEntity> results = tableClient.Query <TableEntity>(); foreach (TableEntity entity in results) { string lensType = entity.PartitionKey; string partNumber = entity.RowKey; object focalLength = entity["FocalLength"]; object aperture = entity["Aperture"]; Console.WriteLine("| {0, 10} | {1, 30} | {2, 10} | {3, 10} |", lensType, partNumber, focalLength, aperture); } return; } else if (args[0] == "AddLens") { // Check the syntax. if (args.Length != 5) { System.Console.WriteLine("Usage: LensesApp AddLens <LensType> <PartNumber> <FocalLength> <Aperture>"); return; } // Add a lens Lens newLens = new Lens() { LensType = args[1], PartNumber = args[2], FocalLength = args[3], Aperture = args[4] }; Console.WriteLine("Adding your {0} lens...", newLens.FocalLength); insertEntity(tableClient, newLens); Console.WriteLine("Lens added."); return; } }
public void CreateDeleteTable() { string storageUri = StorageUri; string accountName = StorageAccountName; string storageAccountKey = PrimaryStorageAccountKey; string tableName = "OfficeSupplies1p1"; #region Snippet:TablesSample1CreateClient // Construct a new "TableServiceClient using a TableSharedKeyCredential. var serviceClient = new TableServiceClient( new Uri(storageUri), new TableSharedKeyCredential(accountName, storageAccountKey)); #endregion #region Snippet:TablesSample1CreateTable // Create a new table. The TableItem class stores properties of the created table. #if SNIPPET string tableName = "OfficeSupplies1p1"; #endif TableItem table = serviceClient.CreateTableIfNotExists(tableName); Console.WriteLine($"The created table's name is {table.Name}."); #endregion #region Snippet:TablesMigrationCreateTableWithClient // Get a reference to the TableClient from the service client instance. var tableClient = serviceClient.GetTableClient(tableName); // Create the table if it doesn't exist. tableClient.CreateIfNotExists(); #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"; var tableClient = serviceClient.GetTableClient(tableName); #else tableName = "OfficeSupplies1p2"; tableClient = serviceClient.GetTableClient(tableName); #endif #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.CreateIfNotExists(); #endregion #region Snippet:TablesSample1TableClientDeleteTable tableClient.Delete(); #endregion }
/// <summary> /// Create the table /// </summary> public void CreateTable() { CloudTable.CreateIfNotExists(); }