Exemplo n.º 1
0
        public static void LogInfo(string msg)
        {
            TableClient client = new TableClient(_TableName);

            Models.LogEntry l = new Models.LogEntry("0", Convert.ToString(Guid.NewGuid()));

            l.Level = "Info";
            l.Message = msg;
            l.Source = "System";
            client.InsertRow(l);
        }
Exemplo n.º 2
0
        public static MessageEntity GetMessage(string orgId, string messageId)
        {
            TableClient client = new TableClient(_TableName);

            TableOperation operation = TableOperation.Retrieve<MessageEntity>(orgId, messageId);

            // Execute the retrieve operation.
            TableResult tresult = client.Table.Execute(operation);

            Models.MessageEntity entity = (MessageEntity)tresult.Result;

            return entity;
        }
Exemplo n.º 3
0
        public static void CreateMessage(Models.MessageEntity entity)
        {
            Contracts.MessageContract contract = new Contracts.MessageContract(entity.RowKey, entity.PartitionKey);

            TableClient client = new TableClient(_TableName);
            QueueClient qclient = new QueueClient();

            Console.WriteLine("Inserting Entity");
            entity.ModifiedOn = System.DateTime.Now.ToString();
            client.InsertRow(entity);

            Console.WriteLine("Inserting Queue Msg");
            qclient.Send(contract);
        }
Exemplo n.º 4
0
        /// <summary>
        ///     Deletes all the underlying Service Bus entities.
        /// </summary>
        /// <param name="deleteInstanceStore">True if Azure Storage entities should also deleted, False otherwise.</param>
        public void DeleteHub(bool deleteInstanceStore)
        {
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            SafeDeleteQueue(namespaceManager, orchestratorEntityName);
            SafeDeleteQueue(namespaceManager, workerEntityName);
            SafeDeleteQueue(namespaceManager, trackingEntityName);

            if (deleteInstanceStore)
            {
                if (!string.IsNullOrEmpty(tableStoreConnectionString))
                {
                    var client = new TableClient(hubName, tableStoreConnectionString);
                    client.DeleteTableIfExists();
                }
            }
        }
        public async Task TableEntity_IfBoundToJObject_CanCall()
        {
            // Arrange
            await TableClient.AddEntityAsync(CreateTableEntity(PartitionKey, RowKey, "Value", "Foo"));

            await CallAsync <BindTableEntityToJObjectProgram>(arguments : new
            {
                table = TableName, // Test resolution
                pk1   = PartitionKey,
                rk1   = RowKey
            });

            // Assert
            SdkTableEntity entity = await TableClient.GetEntityAsync <SdkTableEntity>(PartitionKey, RowKey);

            Assert.NotNull(entity);
        }
Exemplo n.º 6
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.
            TableItem table = serviceClient.CreateTable(tableName);
            Console.WriteLine($"The created table's name is {table.TableName}.");
            #endregion

            #region Snippet:TablesSample1DeleteTable
            // Deletes the table made previously.
            serviceClient.DeleteTable(tableName);
            #endregion

            #region Snippet:TablesSample1GetTableClient
            tableName = "OfficeSupplies1p2";
            var tableClient = serviceClient.GetTableClient(tableName);
            #endregion

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

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

            #region Snippet:TablesSample1TableClientDeleteTable
            tableClient.Delete();
            #endregion
        }
        // Used as an alternative to binding to IQueryable.
        private async Task <JArray> CreateJArray(TableAttribute attribute, CancellationToken cancellation)
        {
            var table = GetTable(attribute);

            string filter = attribute.Filter;

            if (!string.IsNullOrEmpty(attribute.PartitionKey))
            {
                var partitionKeyPredicate = TableClient.CreateQueryFilter($"PartitionKey eq {attribute.PartitionKey}");
                if (!string.IsNullOrEmpty(filter))
                {
                    filter = $"{partitionKeyPredicate} and {filter}";
                }
                else
                {
                    filter = partitionKeyPredicate;
                }
            }

            int?maxPerPage = null;

            if (attribute.Take > 0)
            {
                maxPerPage = attribute.Take;
            }

            int countRemaining = attribute.Take;

            JArray entityArray = new JArray();
            var    entities    = table.QueryAsync <TableEntity>(
                filter: filter,
                maxPerPage: maxPerPage,
                cancellationToken: cancellation).ConfigureAwait(false);

            await foreach (var entity in entities)
            {
                countRemaining--;
                entityArray.Add(ConvertEntityToJObject(entity));
                if (countRemaining == 0)
                {
                    break;
                }
            }
            return(entityArray);
        }
Exemplo n.º 8
0
        public async Task <T> GetTableRow <T>(string tableName, string rowKey, string partitionKey = "default")
            where T : ValueWithEtag
        {
            TableClient tableClient = await this.GetTableClient(tableName);

            try
            {
                var res = await tableClient.GetEntityAsync <ContentDataEntity>(partitionKey, rowKey);

                T value = JsonConvert.DeserializeObject <T>(res.Value.Content);
                value.etag = res.Value.ETag;
                return(value);
            }
            catch (RequestFailedException e)
            {
                return(null);
            }
        }
Exemplo n.º 9
0
        public async Task ConnStringAuth()
        {
            string tableName        = "OfficeSupplies";
            string connectionString = $"DefaultEndpointsProtocol=https;AccountName={StorageAccountName};AccountKey={PrimaryStorageAccountKey};EndpointSuffix={StorageEndpointSuffix ?? DefaultStorageSuffix}";

            #region Snippet:TablesAuthConnString
            // Construct a new TableClient using a connection string.

            var client = new TableClient(
                connectionString,
                tableName);

            // Create the table if it doesn't already exist to verify we've successfully authenticated.

            await client.CreateIfNotExistsAsync();

            #endregion
        }
        public async Task TableQueryableComplexFilterWithCreateFilter()
        {
            var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);

            // Create the new entities.

            await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);

            var filter  = TableClient.CreateQueryFilter <ComplexEntity>(ent => (ent.RowKey == "0004" && ent.Int32 == 4) || ((ent.Int32 == 2) && (ent.String == "wrong string" || ent.Bool == true)) || (ent.LongPrimitiveN == (long)int.MaxValue + 50));
            var results = await client.QueryAsync <ComplexEntity>(filter).ToEnumerableAsync().ConfigureAwait(false);

            foreach (ComplexEntity ent in results)
            {
                Assert.IsTrue(ent.Int32 == 4 || ent.Int32 == 2);
            }

            Assert.That(results.Count, Is.EqualTo(2));
        }
Exemplo n.º 11
0
        private TableClient GetTableClient()
        {
            if (tableClient == null)
            {
                lock (tableClientLock)
                {
                    if (tableClient == null)
                    {
                        KeyVaultSecret secret           = secretClient.GetSecret(ConnectionStringSecretName);
                        var            connectionString = secret.Value;

                        tableClient = new TableClient(connectionString, PullRequestStateTableName);
                    }
                }
            }

            return(tableClient);
        }
Exemplo n.º 12
0
        public static HelpMetaData CalculateMetaData(TableClient client, ILogger log)
        {
            log.LogInformation("Calculating meta data on HelpTable");

            string filter   = TableServiceClient.CreateQueryFilter($"PartitionKey eq {CommandHelpPartitionKey}");
            var    select   = new string[] { "CommandName", "ModuleName" };
            var    entities = client.Query <HelpEntity>(filter: filter, select: select);

            var numAbout = entities
                           .Where(r => r
                                  .CommandName
                                  .StartsWith("about_", StringComparison.OrdinalIgnoreCase))
                           .Count();

            var moduleNames = entities
                              .Select(r => r.ModuleName)
                              .Where(moduleName => !string.IsNullOrEmpty(moduleName))
                              .Distinct();

            var helpMetaData = new HelpMetaData()
            {
                PartitionKey          = MetaDataPartitionKey,
                RowKey                = MetaDataRowKey,
                NumberOfAboutArticles = numAbout,
                NumberOfCommands      = entities.Count() - numAbout,
                NumberOfModules       = moduleNames.Count(),
                ModuleNames           = string.Join(',', moduleNames),
                LastPublished         = Helpers.GetBuildDate(Assembly.GetExecutingAssembly()).ToLongDateString()
            };

            var metaDataEntity = new HelpMetaData();

            try
            {
                metaDataEntity = client.GetEntity <HelpMetaData>(MetaDataPartitionKey, MetaDataRowKey);
                _ = client.UpsertEntity(helpMetaData);
            }
            catch (RequestFailedException)
            {
                _ = client.AddEntity(helpMetaData);
            }

            return(helpMetaData);
        }
        public async Task <ActionResult> AddToCart(Guid id, int quantity)
        {
            var shoppingCart = TableClient.GetTableReference("shoppingcart");

            shoppingCart.CreateIfNotExists();

            var retrieve = TableOperation.Retrieve <ProductCartEntity>(UserSession(), id.ToString());
            var result   = shoppingCart.Execute(retrieve);
            var item     = (ProductCartEntity)result.Result;

            if (item != null)
            {
                item.Quantity   = quantity;
                item.TotalPrice = quantity * item.UnitPrice;
            }
            else
            {
                var product = DocumentDbProducts().Where(xx => xx.id == id).ToList().First();
                item = new ProductCartEntity
                {
                    PartitionKey = UserSession()
                    ,
                    RowKey = id.ToString()
                    ,
                    CreateDate = DateTime.Now
                    ,
                    ProductDescription = product.Name
                    ,
                    Currency = "EUR"
                    ,
                    UnitPrice = (double)product.ListPrice
                    ,
                    TotalPrice = quantity * (double)product.ListPrice
                    ,
                    Quantity = quantity
                };
            }

            var upsert = TableOperation.InsertOrReplace(item);

            shoppingCart.Execute(upsert);

            return(RedirectToAction("ShoppingCart"));
        }
        public async Task TableEntity_IfUpdatesRowKey_Throws()
        {
            // Arrange
            await TableClient.AddEntityAsync(new TableEntity(PartitionKey, RowKey));

            // Act
            var       functionException = Assert.CatchAsync <FunctionInvocationException>(async() => await CallAsync <UpdatePocoRowKeyProgram>());
            Exception exception         = functionException.InnerException;

            // Assert
            Assert.NotNull(exception);
            Assert.IsInstanceOf <InvalidOperationException>(exception);
            Assert.AreEqual("Error while handling parameter entity after function returned:", exception.Message);
            Exception innerException = exception.InnerException;

            Assert.NotNull(innerException);
            Assert.IsInstanceOf <InvalidOperationException>(innerException);
            Assert.AreEqual("When binding to a table entity, the row key must not be changed.", innerException.Message);
        }
Exemplo n.º 15
0
        internal HttpStatusCode insertTableEntity(CloudStorageAccount pCloudStorageAccount, string pTable, TableEntity pTableEntity, out string pInsertETag)
        {
            //TableClient table = new TableClient(pCloudStorageAccount, caCerts, _timeZoneOffset, _debug, _debug_level);
            TableClient table = new TableClient(pCloudStorageAccount, caCerts, _debug, _debug_level);

            // To use Fiddler as WebProxy include the following line. Use the local IP-Address of the PC where Fiddler is running
            // see: -http://blog.devmobile.co.nz/2013/01/09/netmf-http-debugging-with-fiddler
            if (attachFiddler)
            {
                table.attachFiddler(true, fiddlerIPAddress, fiddlerPort);
            }

            var resultCode = table.InsertTableEntity(pTable, pTableEntity, TableClient.ContType.applicationIatomIxml, TableClient.AcceptType.applicationIjson, TableClient.ResponseType.dont_returnContent, useSharedKeyLite: false);

            pInsertETag = table.OperationResponseETag;
            //var body = table.OperationResponseBody;
            //Debug.Print("Entity inserted");
            return(resultCode);
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Creates all the underlying entities in Service bus and Azure Storage (if specified) for
        ///     the TaskHubWorker and TaskHubClient's operations. If TaskHub already existed then
        ///     it would be deleted and recreated. Instance store creation can be controlled via parameter.
        /// </summary>
        public void CreateHub(TaskHubDescription description, bool createInstanceStore)
        {
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            SafeDeleteQueue(namespaceManager, orchestratorEntityName);
            SafeDeleteQueue(namespaceManager, workerEntityName);
            SafeDeleteQueue(namespaceManager, trackingEntityName);

            CreateQueue(namespaceManager, orchestratorEntityName, true, description.MaxTaskOrchestrationDeliveryCount);
            CreateQueue(namespaceManager, workerEntityName, false, description.MaxTaskActivityDeliveryCount);
            CreateQueue(namespaceManager, trackingEntityName, true, description.MaxTrackingDeliveryCount);

            if (!string.IsNullOrEmpty(tableStoreConnectionString) && createInstanceStore)
            {
                var client = new TableClient(hubName, tableStoreConnectionString);
                client.DeleteTableIfExists();
                client.CreateTableIfNotExists();
            }
        }
Exemplo n.º 17
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
            });
        }
Exemplo n.º 18
0
        private static async Task <TableClient> InitTableAsync(ILogger logger)
        {
            try
            {
                var         tableCreationClient = GetCloudTableCreationClient(logger);
                TableClient tableRef            = tableCreationClient.GetTableClient(tableName);
                var         tableItem           = await tableRef.CreateIfNotExistsAsync();

                var didCreate = tableItem is not null;

                logger.LogInformation("{Verb} Azure storage table {TableName}", didCreate ? "Created" : "Attached to", tableName);
                return(tableRef);
            }
            catch (Exception exc)
            {
                logger.LogError(exc, "Could not initialize connection to storage table {TableName}", tableName);
                throw;
            }
        }
Exemplo n.º 19
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));
        }
        public async Task TableEntity_IfBoundToExistingPoco_BindsUsingNativeTableTypes()
        {
            // Arrange
            byte[] expectedValue = new byte[] { 0x12, 0x34 };

            await TableClient.AddEntityAsync(new TableEntity(PartitionKey, RowKey)
            {
                { "Value", (expectedValue) }
            });

            // Act
            var function = await CallAsync <BindToPocoWithByteArrayValueProgram>();

            var result = function.Entity;

            // Assert
            Assert.NotNull(result);
            Assert.AreEqual(expectedValue, result.Value);
        }
        public async Task <ActionResult> AddToCart(string productId, decimal unitPrice, int quantity)
        {
            var shoppingCart = TableClient.GetTableReference("shoppingcart");

            shoppingCart.CreateIfNotExists();

            var userSession = Membership.GetUser().UserName;

            var retrieve = TableOperation.Retrieve <ProductCartEntity>(userSession, productId);
            var result   = shoppingCart.Execute(retrieve);
            var item     = (ProductCartEntity)result.Result;

            if (item != null)
            {
                item.UnitPrice = unitPrice;
                item.Quantity  = quantity;
            }
            else
            {
                item = new ProductCartEntity
                {
                    PartitionKey = userSession
                    ,
                    RowKey = productId
                    ,
                    CreateDate = DateTime.Now
                    ,
                    Currency = "EUR"
                    ,
                    UnitPrice = unitPrice
                    ,
                    Quantity = quantity
                };
            }
            item.TotalPrice = item.UnitPrice * item.Quantity;

            var upsert = TableOperation.InsertOrReplace(item);

            shoppingCart.Execute(upsert);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 22
0
        internal AzureTableRepositoryBase(string connectionString, string tableName, bool createIfNotExists, ICompoundKeyCachingStrategy <T, string, string> cachingStrategy = null)
            : base(cachingStrategy)
        {
            var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);

            TableName = TypeName;

            if (!String.IsNullOrEmpty(tableName))
            {
                TableName = tableName;
            }

            TableClient = storageAccount.CreateCloudTableClient();
            Table       = TableClient.GetTableReference(TableName);

            if (createIfNotExists)
            {
                Table.CreateIfNotExists();
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// AddEntity Wrapper.
        /// </summary>
        /// <param name="tableName">TableName.</param>
        /// <param name="entity">Entity.</param>
        /// <param name="cancellationToken">CancellationToken.</param>
        /// <returns>Response</returns>
        public async Task <Azure.Response> AddEntityAsync(string tableName, TableEntity entity, CancellationToken cancellationToken = default)
        {
            TableClient tableClient;

            // Look for cache key.
            if (!this.memoryCache.TryGetValue(tableName, out tableClient))
            {
                await this.CreateTableIfNotExistsAsync(tableName).ConfigureAwait(false);

                tableClient = new TableClient(
                    this.tableStorageConfig.ConnectionString,
                    tableName);

                // Save data in cache.
                this.memoryCache.Set(tableName, tableClient);
            }

            Azure.Response res = tableClient.AddEntity(entity, cancellationToken);
            return(res);
        }
Exemplo n.º 24
0
        public async Task <List <T> > GetAllRowsAsync <T>(string tableName, string partitionKey)
            where T : ValueWithEtag
        {
            TableClient tableClient = await this.GetTableClient(tableName);

            try
            {
                var res = await tableClient.QueryAsync <ContentDataEntity>((item) => string.Equals(item.PartitionKey, partitionKey)).ToListAsync();

                return(res.ConvertAll(item => {
                    T value = JsonConvert.DeserializeObject <T>(item.Content);
                    value.etag = item.ETag;
                    return value;
                }));
            }
            catch (RequestFailedException e)
            {
                return(null);
            }
        }
        public async Task SharedKeyAuth()
        {
            string storageUri  = StorageUri;
            string accountName = StorageAccountName;
            string accountKey  = PrimaryStorageAccountKey;
            string tableName   = "OfficeSuppliesSharedKeyAuth" + _random.Next();

            #region Snippet:TablesAuthSharedKey

            // Construct a new TableClient using a TableSharedKeyCredential.
            var client = new TableClient(
                new Uri(storageUri),
                tableName,
                new TableSharedKeyCredential(accountName, accountKey));

            // Create the table if it doesn't already exist to verify we've successfully authenticated.
            await client.CreateIfNotExistsAsync();

            #endregion
        }
Exemplo n.º 26
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [Table(HelpTableName)] TableClient tableClient,
            ILogger log)
        {
            AnalysisResult analysisResult;
            string         requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            if (string.IsNullOrEmpty(requestBody))
            {
                return(ResponseHelper(HttpStatusCode.BadRequest, "Empty request. Pass powershell code in the request body for an AST analysis."));
            }

            var code = JsonConvert
                       .DeserializeObject <Code>(requestBody)
                       ?.PowershellCode;

            log.LogInformation("PowerShell code sent: " + code); // LogAnalytics does not log the body of requests, so we have to log this ourselves.

            ScriptBlockAst ast = Parser.ParseInput(code, out Token[] tokens, out ParseError[] parseErrors);
Exemplo n.º 27
0
        /// <inheritdoc />
        public async Task <IDictionary <DateTime, IList <string> > > RetrieveSiteNewsEntriesAsync()
        {
            TableClient tableClient = GetTableClient();

            // Group entities by date and sort by order in each group
            int currentOrder = 0;
            SortedDictionary <DateTime, SortedList <int, string> > entitiesByDate = new();
            AsyncPageable <TableEntity> results = tableClient.QueryAsync <TableEntity>();

            await foreach (TableEntity entity in results)
            {
                if (!DateTime.TryParse(entity.PartitionKey, out DateTime date))
                {
                    _telemetryClient.TrackInvalidTableEntry(entity);
                    continue;
                }

                if (!int.TryParse(entity.RowKey, out int order))
                {
                    order = currentOrder++;
                }

                if (!entitiesByDate.TryGetValue(date, out SortedList <int, string> entities))
                {
                    entities = new SortedList <int, string>();
                    entitiesByDate.Add(date, entities);
                }

                entities.Add(order, entity.GetString("Message"));
            }

            // Select only the messages
            SortedDictionary <DateTime, IList <string> > entries = new();

            foreach (KeyValuePair <DateTime, SortedList <int, string> > entities in entitiesByDate)
            {
                entries.Add(entities.Key, entities.Value.Values);
            }

            return(entries);
        }
Exemplo n.º 28
0
        private static HttpStatusCode queryTableEntities(CloudStorageAccount pCloudStorageAccount, X509Certificate[] pCaCerts, string tableName, string query, out ArrayList queryResult)
        {
            //table = new TableClient(pCloudStorageAccount, pCaCerts, _debug, _debug_level, wifi);
            table = new TableClient(pCloudStorageAccount, pCaCerts, _debug, _debug_level);


            // To use Fiddler as WebProxy include the  following line. Use the local IP-Address of the PC where Fiddler is running
            // see: -http://blog.devmobile.co.nz/2013/01/09/netmf-http-debugging-with-fiddler
            //if (attachFiddler)
            //{ table.attachFiddler(true, fiddlerIPAddress, fiddlerPort); }

            HttpStatusCode resultCode = table.QueryTableEntities(tableName, query, TableClient.ContType.applicationIatomIxml, TableClient.AcceptType.applicationIatomIxml, useSharedKeyLite: false);

            // now we can get the results by reading the properties: table.OperationResponse......
            queryResult = table.OperationResponseQueryList;
            // var body = table.OperationResponseBody;
            // this shows how to get a special value (here the RowKey)of the first entity
            // var entityHashtable = queryResult[0] as Hashtable;
            // var theRowKey = entityHashtable["RowKey"];
            return(resultCode);
        }
        protected virtual void Initialize(PersistedGrantStorageConfig config)
        {
            TableClient = Microsoft.Azure.Cosmos.Table.CloudStorageAccount.Parse(config.StorageConnectionString).CreateCloudTableClient();
            TableClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.Json;
            PersistedGrantTableName = config.PersistedGrantTableName;

            if (string.IsNullOrWhiteSpace(PersistedGrantTableName))
            {
                throw new ArgumentException($"PersistedGrantTableName cannot be null or empty, check your configuration.", nameof(config.PersistedGrantTableName));
            }

            PersistedGrantTable = TableClient.GetTableReference(PersistedGrantTableName);

            BlobClient        = new BlobServiceClient(config.StorageConnectionString);
            BlobContainerName = config.BlobContainerName;
            if (string.IsNullOrWhiteSpace(BlobContainerName))
            {
                throw new ArgumentException($"BlobContainerName cannot be null or empty, check your configuration.", nameof(config.BlobContainerName));
            }
            PersistedGrantBlobContainer = BlobClient.GetBlobContainerClient(BlobContainerName);
        }
Exemplo n.º 30
0
        public async Task SaveTableRow <T>(string tableName, string rowKey, string partitionKey, T entity)
            where T : ValueWithEtag
        {
            TableClient tableClient = await this.GetTableClient(tableName);

            ContentDataEntity entry = new ContentDataEntity
            {
                RowKey       = rowKey,
                PartitionKey = partitionKey,
                Content      = JsonConvert.SerializeObject(entity)
            };

            if (entity.etag == default)
            {
                await tableClient.UpsertEntityAsync(entry);
            }
            else
            {
                var res = await tableClient.UpdateEntityAsync(entry, entity.etag);
            }
        }
        public async Task CreateIfNotExists()
        {
            // Call CreateIfNotExists when the table already exists.
            Assert.That(async() => await CosmosThrottleWrapper(async() => await client.CreateIfNotExistsAsync().ConfigureAwait(false)), Throws.Nothing);

            // Call CreateIfNotExists when the table does not already exist.
            var         newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
            TableItem   table;
            TableClient tableClient = null;

            try
            {
                tableClient = service.GetTableClient(newTableName);
                table       = await CosmosThrottleWrapper(async() => await tableClient.CreateIfNotExistsAsync().ConfigureAwait(false));
            }
            finally
            {
                await tableClient.DeleteAsync().ConfigureAwait(false);
            }

            Assert.That(table.TableName, Is.EqualTo(newTableName));
        }
        public async Task TableEntity_IfBoundToExistingPoco_Binds()
        {
            // Arrange
            const string expectedValue = "abc";

            await TableClient.AddEntityAsync(new TableEntity(PartitionKey, RowKey)
            {
                { "Value", (expectedValue) }
            });

            // Act
            var function = await CallAsync <BindToPocoProgram>(arguments : new
            {
                newValue = expectedValue
            });

            var result = function.Entity;

            // Assert
            Assert.NotNull(result);
            Assert.AreEqual(expectedValue, result.Value);
        }
        public async Task InsertRowsAsync(
            TableName tableName,
            IEnumerable <BigtableByteString> rowKeys,
            string familyName = null,
            BigtableByteString?qualifierName = null,
            BigtableByteString?valuePrefix   = null,
            BigtableVersion?version          = null)
        {
            BigtableByteString rowKey = Guid.NewGuid().ToString();

            familyName    = familyName ?? ColumnFamily1;
            qualifierName = qualifierName ?? "row_index";
            valuePrefix   = valuePrefix ?? "";

            // TODO: Use cleaner API when available.
            int counter = 0;
            var request = new MutateRowsRequest
            {
                TableNameAsTableName = tableName,
                Entries =
                {
                    rowKeys.Select(k => new MutateRowsRequest.Types.Entry
                    {
                        RowKey    = k.Value,
                        Mutations =
                        {
                            Mutations.SetCell(
                                familyName,
                                qualifierName.Value,
                                valuePrefix.Value.Value.Concat(new BigtableByteString(counter++).Value),
                                version)
                        }
                    })
                }
            };

            var response = TableClient.MutateRows(request);

            while (await response.ResponseStream.MoveNext(default))
Exemplo n.º 34
0
 public static void UpdateMessage(Models.MessageEntity entity)
 {
     TableClient client = new TableClient(_TableName);
     entity.ModifiedOn = System.DateTime.Now.ToString();
     client.UpdateRow(entity);
 }
Exemplo n.º 35
0
        /// <summary>
        ///     Create a new TaskHubClient with given name, Service Bus and Azure Storage connection strings  with specified
        ///     settings.
        /// </summary>
        /// <param name="hubName">Name of the Task Hub</param>
        /// <param name="connectionString">Service Bus connection string</param>
        /// <param name="tableStoreConnectionString">Azure Storage connection string</param>
        /// <param name="settings">Client settings</param>
        public TaskHubClient(string hubName, string connectionString, string tableStoreConnectionString,
            TaskHubClientSettings settings)
        {
            this.hubName = hubName;
            this.connectionString = connectionString;
            messagingFactory = Utils.CreateMessagingFactory(connectionString);
            workerEntityName = string.Format(FrameworkConstants.WorkerEndpointFormat, this.hubName);
            orchestratorEntityName = string.Format(FrameworkConstants.OrchestratorEndpointFormat, this.hubName);
            defaultConverter = new JsonDataConverter();
            this.settings = settings;

            this.tableStoreConnectionString = tableStoreConnectionString;
            if (!string.IsNullOrEmpty(this.tableStoreConnectionString))
            {
                tableClient = new TableClient(this.hubName, this.tableStoreConnectionString);
            }
        }