public TableWrapper( CloudStorageAccount storageAccount, string tableName) { var tableClient = storageAccount?.CreateCloudTableClient() ?? throw new ArgumentNullException(nameof(storageAccount)); _table = tableClient.GetTableReference(tableName); }
/// <summary> /// Tries to resolve a table in the storage defined by the given connection string and table name. /// </summary> /// <param name="connectionString">The Azure storage connection string.</param> /// <param name="tableName">The name of the table to resolve and return.</param> /// <returns>The resolved table or null in case of an error.</returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="FormatException"></exception> public static CloudTable GetTable(string connectionString, string tableName) { CloudStorageAccount cloudStorageAccount = null; try { cloudStorageAccount = CloudStorageAccount.Parse(connectionString); } catch { throw; } CloudTableClient cloudTableClient = cloudStorageAccount?.CreateCloudTableClient(); return(cloudTableClient?.GetTableReference(tableName)); }
protected async void Button4_Click(object sender, EventArgs e) { CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount; CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("Urunler"); TableBatchOperation batchOperation = new TableBatchOperation(); for (int i = 0; i < 100; i++) { batchOperation.InsertOrMerge(new Urun() { PartitionKey = "Musteri" + i.ToString(), RowKey = (new Random().Next(1, 100)).ToString(), Adi = "Deneme", Aciklama = "Açıklama" }); } IList <TableResult> results = await table.ExecuteBatchAsync(batchOperation); foreach (var res in results) { var eklenenUrun = res.Result as Urun; } }
public static async Task <IActionResult> GetTimeRace( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "LeaderboardTimeRace")] HttpRequest req, ILogger log) { try { string connectionstring = Environment.GetEnvironmentVariable("tablestorageconnection"); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionstring); CloudTableClient cloudTableClient = cloudStorageAccount.CreateCloudTableClient(); CloudTable table = cloudTableClient.GetTableReference("LeaderboardTimeRace"); TableQuery <timelogEntity> rangeQuery = new TableQuery <timelogEntity>(); var queryResult = await table.ExecuteQuerySegmentedAsync <timelogEntity>(rangeQuery, null); List <timelog> points = new List <timelog>(); foreach (var reg in queryResult.Results) { points.Add(new timelog() { name = reg.PartitionKey, timestamp = reg.Timestamp, isFinished = reg.isFinished, totalTime = reg.totalTime }); } return(new OkObjectResult(points)); } catch (Exception ex) { log.LogError(ex.Message); return(new StatusCodeResult(500)); } }
public static async Task SaveData([ActivityTrigger] DurableActivityContext context) { // retrieves a list of books from the Orchestrator function var books = context.GetInput <List <Book> >(); // create a table storage client var client = account.CreateCloudTableClient(); var table = client.GetTableReference("Books"); await table.CreateIfNotExistsAsync(); TableBatchOperation tableBatchOperations = new TableBatchOperation(); for (int i = 0; i < books.Count; i++) { tableBatchOperations.Add(TableOperation.InsertOrMerge( new BookRepository(books[i].Id) { Name = books[i].Name })); } await table.ExecuteBatchAsync(tableBatchOperations); }
private CloudTable CreateTableClient(IConfiguration configuration, IHealthReporter healthReporter) { string accountConnectionString = configuration["StorageAccountConnectionString"]; string sasToken = configuration["StorageAccountSasToken"]; if (string.IsNullOrWhiteSpace(sasToken) && string.IsNullOrWhiteSpace(accountConnectionString)) { healthReporter.ReportProblem($"{nameof(TableStorageSender)}: configuration must specify either the storage account connection string ('StorageAccountConnectionString' parameter) or SAS token ('StorageAccountSasToken' paramteter)"); return(null); } string storageTableName = configuration["StorageTableName"]; if (string.IsNullOrWhiteSpace(storageTableName)) { healthReporter.ReportProblem($"{nameof(TableStorageSender)}: configuration must specify the target storage name ('storageTableName' parameter)"); return(null); } CloudStorageAccount storageAccount = string.IsNullOrWhiteSpace(sasToken) ? CloudStorageAccount.Parse(accountConnectionString) : new CloudStorageAccount(new StorageCredentials(sasToken), useHttps: true); var cloudTable = storageAccount.CreateCloudTableClient().GetTableReference(storageTableName); try { cloudTable.CreateIfNotExists(); } catch (Exception e) { healthReporter.ReportProblem($"{nameof(TableStorageSender)}: could not ensure that destination Azure storage table exists{Environment.NewLine}{e.ToString()}"); throw; } return(cloudTable); }
public static async Task <CloudTable> CreateTableAsync(string tableName) { string storageConnectionString = AppSettings.LoadAppSettings().StorageConnectionString; CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration()); Console.WriteLine("Create table for demo"); CloudTable table = tableClient.GetTableReference(tableName); if (await table.CreateIfNotExistsAsync()) { Console.WriteLine("Created Table named: {0}", tableName); } else { Console.WriteLine("Table {0} already exists", tableName); } Console.WriteLine(); return(table); }
public IHttpActionResult GetUserInfo() { // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse( WebConfigurationManager.AppSettings.Get("StorageConnectionString")); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "userInfo" table. CloudTable table = tableClient.GetTableReference("userInfo"); // Construct the query operation for all user entities. TableQuery <UserEntity> query = new TableQuery <UserEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "userInfo")); List <String> list = new List <string>(); foreach (UserEntity entity in table.ExecuteQuery(query)) { list.Add(entity.firstName + " " + entity.lastName); } return(Ok(list)); }
/// <summary> /// Define a new worker instance of Common Runtime for Applications (CRA) /// </summary> /// <param name="workerInstanceName">Name of the worker instance</param> /// <param name="address">IP address</param> /// <param name="port">Port</param> /// <param name="storageConnectionString">Storage account to store metadata</param> /// <param name="streamsPoolSize">Maximum number of stream connections will be cached in the CRA client</param> /// <param name="descriptor">Secure stream connection callbacks</param> public CRAWorker(string workerInstanceName, string address, int port, string storageConnectionString, ISecureStreamConnectionDescriptor descriptor = null, int streamsPoolSize = 0) { Console.WriteLine("Starting CRA Worker instance [http://github.com/Microsoft/CRA]"); Console.WriteLine(" Instance Name: " + workerInstanceName); Console.WriteLine(" IP address: " + address); Console.WriteLine(" Port: " + port); Console.WriteLine(" Azure connection string: " + storageConnectionString); if (descriptor != null) { Console.WriteLine(" Secure network connections: Enabled using assembly " + descriptor.GetType().FullName); } else { Console.WriteLine(" Secure network connections: Disabled"); } _craClient = new CRAClientLibrary(storageConnectionString, this); _workerinstanceName = workerInstanceName; _address = address; _port = port; _streamsPoolSize = streamsPoolSize; _storageConnectionString = storageConnectionString; _storageAccount = CloudStorageAccount.Parse(_storageConnectionString); _blobClient = _storageAccount.CreateCloudBlobClient(); _tableClient = _storageAccount.CreateCloudTableClient(); _workerInstanceTable = CreateTableIfNotExists("cravertextable"); _connectionTable = CreateTableIfNotExists("craconnectiontable"); if (descriptor != null) { _craClient.SecureStreamConnectionDescriptor = descriptor; } }
public CloudTable GetCloudTable(CloudStorageAccount storageAccount, string storageTableName, bool bypassTableCreationValidation) { if (_cloudTable == null) { var cloudTableClient = storageAccount.CreateCloudTableClient(); _cloudTable = cloudTableClient.GetTableReference(storageTableName); // In some cases (e.g.: SAS URI), we might not have enough permissions to create the table if // it does not already exists. So, if we are in that case, we ignore the error as per bypassTableCreationValidation. try { _cloudTable.CreateIfNotExistsAsync().SyncContextSafeWait(_waitTimeoutMilliseconds); } catch (Exception ex) { Debugging.SelfLog.WriteLine($"Failed to create table: {ex}"); if (!bypassTableCreationValidation) { throw; } } } return(_cloudTable); }
/// <summary> /// Make azure call to write to Table /// </summary> /// <param name="count">no of calls to be made</param> public static void MakeAzureCallToWriteTableWithSdk(int count) { // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the table if it doesn't exist. CloudTable table = tableClient.GetTableReference("people"); table.CreateIfNotExists(); // Create the batch operation. TableBatchOperation batchOperation = new TableBatchOperation(); // Create a customer entity and add it to the table. CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff" + DateTime.UtcNow.Ticks); customer1.Email = "*****@*****.**"; customer1.PhoneNumber = "425-555-0104"; // Create another customer entity and add it to the table. CustomerEntity customer2 = new CustomerEntity("Smith", "Ben" + DateTime.UtcNow.Ticks); customer2.Email = "*****@*****.**"; customer2.PhoneNumber = "425-555-0102"; // Add both customer entities to the batch insert operation. batchOperation.Insert(customer1); batchOperation.Insert(customer2); // Execute the batch operation. table.ExecuteBatch(batchOperation); }
public AzureEventLogReader(CloudStorageAccount account, string tableName, ITextSerializer serializer) { if (account == null) { throw new ArgumentNullException("account"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (string.IsNullOrWhiteSpace(tableName)) { throw new ArgumentException("tableName"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } this.account = account; this.tableName = tableName; tableClient = account.CreateCloudTableClient(); this.serializer = serializer; }
public static async Task <CloudTable> CreateTableAsync(string tableName) { // Retrieve storage account information from connection string. CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CONNECTION_STRING); // Create a table client for interacting with the table service CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); Debug.WriteLine("Create a Table for the demo"); // Create a table client for interacting with the table service CloudTable table = tableClient.GetTableReference(tableName); if (await table.CreateIfNotExistsAsync()) { Debug.WriteLine("Created Table named: {0}", tableName); } else { Debug.WriteLine("Table {0} already exists", tableName); } return(table); }
public RegisterViewModel(string eventKey) { using (EventsContext context = new EventsContext()) { this.Event = context.Events.SingleOrDefault(e => e.EventKey == eventKey); } string connectionstring = ConfigurationManager.AppSettings.Get("Microsoft.WindowsAzure.Storage.ConnectionString"); CloudStorageAccount account = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionstring); var client = account.CreateCloudTableClient(); var table = client.GetTableReference("EventRegistrations"); table.CreateIfNotExists(); string partitionKey = $"Stub_{eventKey}"; string filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey); var query = new TableQuery().Where(filter); IEnumerable <DynamicTableEntity> tableEntities = table.ExecuteQuery(query); DynamicTableEntity tableEntity = tableEntities.SingleOrDefault(); this.RegistrationStub = DynamicEntity.GenerateDynamicItem(tableEntity); }
// Constructor public TableManager(string _CloudTableName) { if (string.IsNullOrEmpty(_CloudTableName)) { throw new ArgumentNullException("Table", "Table Name can't be empty"); } try { string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=dotnetdevsa;AccountKey=k3Ih0Uc7ipsd7tvsG/LZ3wE5+zI5zHiHS86yclnEr7EOERiiWcSRbnPxUrrCdyk2a59DoVCv4z+hblfaQbXIhg==;EndpointSuffix=core.windows.net"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); table = tableClient.GetTableReference(_CloudTableName); table.CreateIfNotExists(); } catch (StorageException StorageExceptionObj) { throw StorageExceptionObj; } catch (Exception ExceptionObj) { throw ExceptionObj; } }
public static async Task <IActionResult> CrearProducto([HttpTrigger(AuthorizationLevel.Function, "post", Route = "usuarios")] HttpRequest req, TraceWriter log) { var body = await new StreamReader(req.Body).ReadToEndAsync(); Producto data = JsonConvert.DeserializeObject <Producto>(body as string); if (data == null) { throw new ArgumentNullException("entity"); } try { // Create the InsertOrReplace table operation TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(data); // Execute the operation. var acc = new CloudStorageAccount( new StorageCredentials("123459876", "X9XmzmV0xX6AG/WYCXSA8BrrrCF0M4j3X4zFDgJZ5g9hRwPafsIjAWk2kgjLZmj6YSxJGIikJDsLmvxgEfGWTQ=="), true); var tableClient = acc.CreateCloudTableClient(); var table = tableClient.GetTableReference("misProductos"); TableResult result = await table.ExecuteAsync(insertOrMergeOperation); Producto insertedCustomer = result.Result as Producto; return(new OkObjectResult(insertedCustomer)); } catch (StorageException e) { Console.WriteLine(e.Message); Console.ReadLine(); throw; } }
public static async Task <List <Request> > GetRequests( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get-requests/{user}/{isApproved}")] HttpRequestMessage request, string user, string isApproved, ILogger log) { log.LogInformation("GetRequests"); //addition CloudTable table = null; CloudTableClient client = null; Boolean isAdmin = false; try { StorageCredentials creds = new StorageCredentials(Environment.GetEnvironmentVariable("accountName"), Environment.GetEnvironmentVariable("accountKey")); CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true); client = account.CreateCloudTableClient(); table = client.GetTableReference("Requests"); await table.CreateIfNotExistsAsync(); Console.WriteLine(table.Uri.ToString()); } catch (Exception ex) { Console.WriteLine(ex); } if (user.Equals("admin")) { //must be chaaaaaaange isAdmin = true; } return(await GetRequests(table, user, isAdmin, isApproved)); }
private static Func <ValueTask <HealthCheckResult> > CheckTableStorageConnectivity(string name, CloudStorageAccount storageAccount) { return(async() => { var result = true; try { var tableStorageClient = storageAccount.CreateCloudTableClient(); await tableStorageClient.GetServicePropertiesAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.ErrorException($"{name} failed.", ex); result = false; } return result ? HealthCheckResult.Healthy($"OK. '{storageAccount.BlobStorageUri}' is available.") : HealthCheckResult.Unhealthy($"Failed. '{storageAccount.BlobStorageUri}' is unavailable."); }); }
public async Task <CatalogEntity> SaveToTableAsync(CatalogItem item) { CatalogEntity catalogEntity = new CatalogEntity(item.Name, item.Id) { ImageUrl = item.ImageUrl, ReorderLevel = item.ReorderLevel, Quantity = item.Quantity, Price = item.Price, ManufacturingDate = item.ManufacturingDate }; // for save into blob storage //tableClient = storageAccount.CreateCloudTableClient(); //for store in CosmosDB table storage account tableClient = tableStorageAccount.CreateCloudTableClient(); var catalogtable = tableClient.GetTableReference("catalog"); await catalogtable.CreateIfNotExistsAsync(); TableOperation operation = TableOperation.InsertOrMerge(catalogEntity); var tableResult = await catalogtable.ExecuteAsync(operation); return(tableResult.Result as CatalogEntity); }
public async Task AddPlayedTracksAsync(List <PlayedTrackViewModel> playedTrackViewModels) { // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_settings.Value.StorageConnectionString); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); var tableName = "playedtracks" + DateTime.Now.ToString("yyyyMMddTHHmmssZ"); // Retrieve a reference to the table. var playedTracksTable = tableClient.GetTableReference(tableName); // Create the table if it doesn't exist. await playedTracksTable.CreateIfNotExistsAsync(); foreach (var track in playedTrackViewModels) { // Create the TableOperation that inserts the customer entity. TableOperation insertOperation = TableOperation.Insert(track); // Execute the insert operation. await playedTracksTable.ExecuteAsync(insertOperation); } }
public TableHelperTests() { config = new ConfigurationBuilder() .AddJsonFile("appSettings.json") .Build(); var section = config.GetSection("storageAccount"); accountName = section["name"]; accountKey = section["key"]; tableName = section["table"]; ValidateConfig(); storageAccount = new CloudStorageAccount( new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials( accountName, accountKey), true); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); v1Table = tableClient.GetTableReference(tableName); helper = new TableHelper(accountName, accountKey, tableName); helper.Delete(DateTime.Now).GetAwaiter().GetResult(); }
public static string GetFromMapping(string Partition, string Row) { CloudStorageAccount storageAccount = GetCloudStorageAccount(); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); //CloudTable mappingTable = tableClient.GetTableReference("mappingTable");//table name //TableOperation retrieveOperation = TableOperation.Retrieve<MappingEntity>(Partition, Row); //TableResult retrievedResult = mappingTable.Execute(retrieveOperation); //MappingEntity ResultEntity = (MappingEntity)retrievedResult.Result; CloudTable MappingTable = tableClient.GetTableReference("mappingTable"); TableOperation retrieveOperation = TableOperation.Retrieve <MappingEntity>(Partition, Row); MappingTable.CreateIfNotExists(); TableResult Query = MappingTable.Execute(retrieveOperation); MappingEntity ResultEntity = (MappingEntity)Query.Result; string Result = ""; if (ResultEntity != null) { Result = ResultEntity.Value; } return(Result); }
static void Main(string[] args) { // if you need to create a table first in the sqlite database. //CreateTable(); #region Just for demo insertions to Azure Storage Table CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureStorageConnectionString); _tableClient = storageAccount.CreateCloudTableClient(); _table = _tableClient.GetTableReference("demotable"); _table.CreateIfNotExistsAsync().Wait(); #endregion _sqliteHelper = new SqliteHelper(sqlitefile); while (true) { // Write: When you want to pre-populate the sqlite database with the dummy data. //ProcessWriteMany(); // Read: When we start reading. This is what we do in the distributed processing setup from multiple containers. ProcessReadOnce(); } }
public static async Task <int> GetNumberOfPlaces( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get-places-number/")] HttpRequestMessage request, ILogger log) { log.LogInformation("GetNumberOfPlaces"); //addition CloudTable table = null; CloudTableClient client = null; try { StorageCredentials creds = new StorageCredentials(Environment.GetEnvironmentVariable("accountName"), Environment.GetEnvironmentVariable("accountKey")); CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true); client = account.CreateCloudTableClient(); table = client.GetTableReference("Garage"); await table.CreateIfNotExistsAsync(); Console.WriteLine(table.Uri.ToString()); } catch (Exception ex) { Console.WriteLine(ex); } /*get the avaliable places*/ TableQuery <availablePlaces> idQuery = new TableQuery <availablePlaces>() .Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, "places")); TableQuerySegment <availablePlaces> queryResult = await table.ExecuteQuerySegmentedAsync(idQuery, null); availablePlaces places = queryResult.FirstOrDefault(); Console.Out.WriteLine("RowKey" + places.RowKey); return(int.Parse(places.numOfPlaces)); }
public AzureBootCampTicketsCloudContext(ICacheService cacheService) { _cacheService = cacheService; _storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); _tableClient = _storageAccount.CreateCloudTableClient(); //TODO : 01 - Agrego politicas de re-intento _tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromMilliseconds(200), 3); _tableTickets = _tableClient.GetTableReference("TicketsRead"); _tableEvents = _tableClient.GetTableReference("EventsRead"); _tableMyEvents = _tableClient.GetTableReference("MyEventsRead"); _queueClient = _storageAccount.CreateCloudQueueClient(); _ordersQueue = _queueClient.GetQueueReference("tickets"); try { _tableTickets.CreateIfNotExists(); _tableEvents.CreateIfNotExists(); _tableMyEvents.CreateIfNotExists(); } catch (StorageException e) { throw; } }
public async Task <SwingLoggerEntity[]> GetRegisterdLoggers() { var tableClient = _storageAccount.CreateCloudTableClient(); var loggerTable = tableClient.GetTableReference("SwingLogger"); var tableQuery = new TableQuery <SwingLoggerEntity>(); tableQuery.FilterString = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "0"); var result = new List <SwingLoggerEntity>(); TableContinuationToken token = null; do { var entities = await loggerTable.ExecuteQuerySegmentedAsync(tableQuery, token); result.AddRange(entities); token = entities.ContinuationToken; } while (token != null); return(result.ToArray()); }
public static async Task <bool> InsertIntoTable <T>(string tableName, string partitionId, string keyId, T rowEntity) where T : ITableEntity { // Create the table client. CloudTableClient tableClient = _cloudStorageAccount.CreateCloudTableClient(); // Retrieve a reference to the table. CloudTable table = tableClient.GetTableReference(tableName); // Create the table if it doesn't exist. if (!_createdTables.ContainsKey(tableName)) { _createdTables.TryAdd(tableName, true); await table.CreateIfNotExistsAsync(); } rowEntity.PartitionKey = partitionId; rowEntity.RowKey = keyId; // Create the TableOperation object that inserts the row entity. TableOperation insertOperation = TableOperation.Insert(rowEntity, true); Debug.WriteLine("Inserting line!"); // Execute the insert operation. TableResult result; try { result = await table.ExecuteAsync(insertOperation); } catch (Exception ex) { Debug.WriteLine("Error while inserting element into table." + ex.ToString()); throw; } return(result.HttpStatusCode == 201); }
internal bool CheckDiagnosticsTable(string storageAccountName, string resId, string host, string waitChar, string osType, int TimeoutinMinutes = 15) { var tableExists = true; StorageAccount account = null; if (!String.IsNullOrEmpty(storageAccountName)) { account = this.GetStorageAccountFromCache(storageAccountName); } if (account != null) { var endpoint = this.GetCoreEndpoint(storageAccountName); var key = this.GetAzureStorageKeyFromCache(storageAccountName); var credentials = new StorageCredentials(storageAccountName, key); var cloudStorageAccount = new CloudStorageAccount(credentials, endpoint, true); var tableClient = cloudStorageAccount.CreateCloudTableClient(); var checkStart = DateTime.Now; var searchTime = DateTime.UtcNow.AddMinutes(-5); foreach (var tableName in AEMExtensionConstants.WADTablesV2[osType]) { var query = TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("DeploymentId", QueryComparisons.Equal, resId), TableOperators.And, TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("Host", QueryComparisons.Equal, host), TableOperators.And, TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, searchTime))); var perfCounterTable = tableClient.GetTableReference(tableName); bool wait = true; while (wait) { var results = perfCounterTable.ExecuteQuery(new TableQuery() { FilterString = query }); if (results.Count() > 0) { tableExists &= true; break; } else { WriteHost(waitChar, newLine: false); TestMockSupport.Delay(5000); } wait = ((DateTime.Now) - checkStart).TotalMinutes < TimeoutinMinutes; } if (!wait) { WriteVerbose("PerfCounter Table " + tableName + " not found"); tableExists = false; break; } } } return(tableExists); }
internal bool CheckTableAndContent(string StorageAccountName, string TableName, string FilterString, string WaitChar, bool UseNewTableNames, int TimeoutinMinutes = 15) { var tableExists = false; StorageAccount account = null; if (!String.IsNullOrEmpty(StorageAccountName)) { account = this.GetStorageAccountFromCache(StorageAccountName); } if (account != null) { var endpoint = this.GetCoreEndpoint(StorageAccountName); var key = this.GetAzureStorageKeyFromCache(StorageAccountName); var credentials = new StorageCredentials(StorageAccountName, key); var cloudStorageAccount = new CloudStorageAccount(credentials, endpoint, true); var tableClient = cloudStorageAccount.CreateCloudTableClient(); var checkStart = DateTime.Now; var wait = true; CloudTable table = null; if (UseNewTableNames) { try { table = tableClient.ListTables().FirstOrDefault(tab => tab.Name.StartsWith("WADMetricsPT1M")); } catch { } //#table name should be sorted } else { try { table = tableClient.GetTableReference(TableName); } catch { } } while (wait) { if (table != null && table.Exists()) { TableQuery query = new TableQuery(); query.FilterString = FilterString; var results = table.ExecuteQuery(query); if (results.Count() > 0) { tableExists = true; break; } } WriteHost(WaitChar, newLine: false); TestMockSupport.Delay(5000); if (UseNewTableNames) { try { table = tableClient.ListTables().FirstOrDefault(tab => tab.Name.StartsWith("WADMetricsPT1M")); } catch { } //#table name should be sorted } else { try { table = tableClient.GetTableReference(TableName); } catch { } } wait = ((DateTime.Now) - checkStart).TotalMinutes < TimeoutinMinutes; } } return(tableExists); }
public override void Initialize(string name, NameValueCollection config) { // Verify that config isn't null if (config == null) { throw new ArgumentNullException("config"); } // Assign the provider a default name if it doesn't have one if (String.IsNullOrEmpty(name)) { name = "TableServiceSessionStateProvider"; } // Add a default "description" attribute to config if the // attribute doesn't exist or is empty if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Session state provider using table storage"); } // Call the base class's Initialize method base.Initialize(name, config); bool allowInsecureRemoteEndpoints = Configuration.GetBooleanValue(config, "allowInsecureRemoteEndpoints", false); // structure storage-related properties _applicationName = Configuration.GetStringValueWithGlobalDefault(config, "applicationName", Configuration.DefaultProviderApplicationNameConfigurationString, Configuration.DefaultProviderApplicationName, false); _tableName = Configuration.GetStringValueWithGlobalDefault(config, "sessionTableName", Configuration.DefaultSessionTableNameConfigurationString, Configuration.DefaultSessionTableName, false); _containerName = Configuration.GetStringValueWithGlobalDefault(config, "containerName", Configuration.DefaultSessionContainerNameConfigurationString, Configuration.DefaultSessionContainerName, false); if (!SecUtility.IsValidContainerName(_containerName)) { throw new ProviderException("The provider configuration for the TableStorageSessionStateProvider does not contain a valid container name. " + "Please refer to the documentation for the concrete rules for valid container names." + "The current container name is: " + _containerName); } config.Remove("allowInsecureRemoteEndpoints"); config.Remove("containerName"); config.Remove("applicationName"); config.Remove("sessionTableName"); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) { throw new ProviderException ("Unrecognized attribute: " + attr); } } CloudStorageAccount account = null; try { account = Configuration.GetStorageAccount(Configuration.DefaultStorageConfigurationString); SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, account.Credentials, account.TableEndpoint); SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, account.Credentials, account.BlobEndpoint); _tableStorage = account.CreateCloudTableClient(); _tableStorage.RetryPolicy = _tableRetry; lock (thisLock) { _tableStorage.CreateTableIfNotExist <SessionRow>(_tableName); } _blobProvider = new BlobProvider(account.Credentials, account.BlobEndpoint, _containerName); } catch (SecurityException) { throw; } // catch InvalidOperationException as well as StorageException catch (Exception e) { string exceptionDescription = Configuration.GetInitExceptionDescription(account.Credentials, account.TableEndpoint, account.BlobEndpoint); string tableName = (_tableName == null) ? "no session table name specified" : _tableName; string containerName = (_containerName == null) ? "no container name specified" : _containerName; Log.Write(EventKind.Error, "Initialization of data service structures (tables and/or blobs) failed!" + exceptionDescription + Environment.NewLine + "Configured blob container: " + containerName + Environment.NewLine + "Configured table name: " + tableName + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace); throw new ProviderException("Initialization of data service structures (tables and/or blobs) failed!" + "The most probable reason for this is that " + "the storage endpoints are not configured correctly. Please look at the configuration settings " + "in your .cscfg and Web.config files. More information about this error " + "can be found in the logs when running inside the hosting environment or in the output " + "window of Visual Studio.", e); } Debug.Assert(_blobProvider != null); }
public void TableSASConstructors() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); TableServiceContext context = tableClient.GetTableServiceContext(); context.AddObject(table.Name, new BaseEntity("PK", "RK")); context.SaveChangesWithRetries(); // Prepare SAS authentication with full permissions string sasToken = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null /* accessPolicyIdentifier */, null /* startPk */, null /* startRk */, null /* endPk */, null /* endRk */); CloudStorageAccount sasAccount; StorageCredentials sasCreds; CloudTableClient sasClient; CloudTable sasTable; TableServiceContext sasContext; Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); int count; // SAS via connection string parse sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken)); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); // SAS via account constructor sasCreds = new StorageCredentials(sasToken); sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri, null); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); // SAS via client constructor URI + Creds sasCreds = new StorageCredentials(sasToken); sasClient = new CloudTableClient(baseUri, sasCreds); sasContext = sasClient.GetTableServiceContext(); count = sasContext.CreateQuery<BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count(); Assert.AreEqual(1, count); } finally { table.DeleteIfExists(); } }
public void CloudStorageAccountClientUriVerify() { StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true); CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("container1"); Assert.AreEqual(cloudStorageAccount.BlobEndpoint.ToString() + "container1", container.Uri.ToString()); CloudQueueClient queueClient = cloudStorageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("queue1"); Assert.AreEqual(cloudStorageAccount.QueueEndpoint.ToString() + "queue1", queue.Uri.ToString()); CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("table1"); Assert.AreEqual(cloudStorageAccount.TableEndpoint.ToString() + "table1", table.Uri.ToString()); }
private CloudTableClient TableClient() { if (this._storageAccount == null) { this._storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting(this.Attributes[_azureStorageCnnAttributeName])); this._tableClient = _storageAccount.CreateCloudTableClient(); } return this._tableClient; }
public async Task TableSASConstructorsAsync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { await table.CreateAsync(); await table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK"))); // Prepare SAS authentication with full permissions string sasToken = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null /* accessPolicyIdentifier */, null /* startPk */, null /* startRk */, null /* endPk */, null /* endRk */); CloudStorageAccount sasAccount; StorageCredentials sasCreds; CloudTableClient sasClient; CloudTable sasTable; Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); // SAS via connection string parse sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken)); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery<BaseEntity>(), null)).Results.Count()); // SAS via account constructor sasCreds = new StorageCredentials(sasToken); sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri, null); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery<BaseEntity>(), null)).Results.Count()); // SAS via client constructor URI + Creds sasCreds = new StorageCredentials(sasToken); sasClient = new CloudTableClient(baseUri, sasCreds); Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery<BaseEntity>(), null)).Results.Count()); // SAS via CloudTable constructor Uri + Client sasCreds = new StorageCredentials(sasToken); sasTable = new CloudTable(table.Uri, tableClient.Credentials); sasClient = sasTable.ServiceClient; Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery<BaseEntity>(), null)).Results.Count()); } finally { table.DeleteIfExistsAsync().AsTask().Wait(); } }
public async Task TableSasUriTestAsync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { await table.CreateAsync(); BaseEntity entity = new BaseEntity("PK", "RK"); BaseEntity entity1 = new BaseEntity("PK", "RK1"); await table.ExecuteAsync(TableOperation.Insert(entity)); await table.ExecuteAsync(TableOperation.Insert(entity1)); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete, }; string sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null); StorageCredentials creds = new StorageCredentials(sasToken); CloudStorageAccount sasAcc = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */); CloudTableClient client = sasAcc.CreateCloudTableClient(); CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri)); await sasTable.ExecuteAsync(TableOperation.Delete(entity)); CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken)); await sasTable2.ExecuteAsync(TableOperation.Delete(entity1)); } finally { table.DeleteIfExistsAsync().AsTask().Wait(); } }
public void CloudStorageAccountClientMethods() { CloudStorageAccount account = new CloudStorageAccount(TestBase.StorageCredentials, false); CloudBlobClient blob = account.CreateCloudBlobClient(); CloudQueueClient queue = account.CreateCloudQueueClient(); CloudTableClient table = account.CreateCloudTableClient(); // check endpoints Assert.AreEqual(account.BlobEndpoint, blob.BaseUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueEndpoint, queue.BaseUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableEndpoint, table.BaseUri, "Table endpoint doesn't match account"); // check storage uris Assert.AreEqual(account.BlobStorageUri, blob.StorageUri, "Blob endpoint doesn't match account"); Assert.AreEqual(account.QueueStorageUri, queue.StorageUri, "Queue endpoint doesn't match account"); Assert.AreEqual(account.TableStorageUri, table.StorageUri, "Table endpoint doesn't match account"); // check creds Assert.AreEqual(account.Credentials, blob.Credentials, "Blob creds don't match account"); Assert.AreEqual(account.Credentials, queue.Credentials, "Queue creds don't match account"); Assert.AreEqual(account.Credentials, table.Credentials, "Table creds don't match account"); }
public void CloudStorageAccountWithStorageUri() { StorageUri blobEndpoint = new StorageUri( new Uri("http://" + AccountName + BlobService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + BlobService + EndpointSuffix)); StorageUri queueEndpoint = new StorageUri( new Uri("http://" + AccountName + QueueService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + QueueService + EndpointSuffix)); StorageUri tableEndpoint = new StorageUri( new Uri("http://" + AccountName + TableService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + TableService + EndpointSuffix)); StorageUri fileEndpoint = new StorageUri( new Uri("http://" + AccountName + FileService + EndpointSuffix), new Uri("http://" + AccountName + SecondarySuffix + FileService + EndpointSuffix)); #if WINDOWS_RT || ASPNET_K CloudStorageAccount account = CloudStorageAccount.Create(new StorageCredentials(), blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); #else CloudStorageAccount account = new CloudStorageAccount(new StorageCredentials(), blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); #endif Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); account = new CloudStorageAccount(new StorageCredentials(AccountName, TestBase.StorageCredentials.ExportBase64EncodedKey()), false); Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); account = CloudStorageAccount.Parse(string.Format("DefaultEndpointsProtocol=http;AccountName={0};AccountKey=", AccountName)); Assert.IsTrue(blobEndpoint.Equals(account.BlobStorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.QueueStorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.TableStorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.FileStorageUri)); Assert.IsTrue(blobEndpoint.Equals(account.CreateCloudBlobClient().StorageUri)); Assert.IsTrue(queueEndpoint.Equals(account.CreateCloudQueueClient().StorageUri)); Assert.IsTrue(tableEndpoint.Equals(account.CreateCloudTableClient().StorageUri)); Assert.IsTrue(fileEndpoint.Equals(account.CreateCloudFileClient().StorageUri)); Assert.IsTrue(blobEndpoint.PrimaryUri.Equals(account.BlobEndpoint)); Assert.IsTrue(queueEndpoint.PrimaryUri.Equals(account.QueueEndpoint)); Assert.IsTrue(tableEndpoint.PrimaryUri.Equals(account.TableEndpoint)); Assert.IsTrue(fileEndpoint.PrimaryUri.Equals(account.FileEndpoint)); }