示例#1
0
        public static async Task <IActionResult> PostOrchestrationFunction(
            // Using /a/p/i route prefix, to let Functions Host distinguish api methods from statics
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "a/p/i/orchestrations('{instanceId}')/{action?}")] HttpRequest req,
            string instanceId,
            string action,
            [DurableClient(TaskHub = "%DFM_HUB_NAME%")] IDurableClient durableClient,
            ILogger log)
        {
            // Checking that the call is authenticated properly
            try
            {
                await Auth.ValidateIdentityAsync(req.HttpContext.User, req.Headers);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Failed to authenticate request");
                return(new UnauthorizedResult());
            }

            string bodyString = await req.ReadAsStringAsync();

            switch (action)
            {
            case "purge":
                await durableClient.PurgeInstanceHistoryAsync(instanceId);

                break;

            case "rewind":
                await durableClient.RewindAsync(instanceId, bodyString);

                break;

            case "terminate":
                await durableClient.TerminateAsync(instanceId, bodyString);

                break;

            case "raise-event":
                dynamic bodyObject = JObject.Parse(bodyString);
                string  eventName  = bodyObject.name;
                JObject eventData  = bodyObject.data;

                await durableClient.RaiseEventAsync(instanceId, eventName, eventData);

                break;

            case "set-custom-status":

                string connectionString = Environment.GetEnvironmentVariable(EnvVariableNames.AzureWebJobsStorage);
                string hubName          = Environment.GetEnvironmentVariable(EnvVariableNames.DFM_HUB_NAME);

                // Updating the table directly, as there is no other known way
                var tableClient = CloudStorageAccount.Parse(connectionString).CreateCloudTableClient();
                var table       = tableClient.GetTableReference($"{hubName}Instances");

                var orcEntity = (await table.ExecuteAsync(TableOperation.Retrieve(instanceId, string.Empty))).Result as DynamicTableEntity;

                if (string.IsNullOrEmpty(bodyString))
                {
                    orcEntity.Properties.Remove("CustomStatus");
                }
                else
                {
                    // Ensuring that it is at least a valid JSON
                    string customStatus = JObject.Parse(bodyString).ToString();
                    orcEntity.Properties["CustomStatus"] = new EntityProperty(customStatus);
                }

                await table.ExecuteAsync(TableOperation.Replace(orcEntity));

                break;

            case "restart":
                bool restartWithNewInstanceId = ((dynamic)JObject.Parse(bodyString)).restartWithNewInstanceId;

                await durableClient.RestartAsync(instanceId, restartWithNewInstanceId);

                break;

            default:
                return(new NotFoundResult());
            }

            return(new OkResult());
        }
示例#2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            log.LogTrace("C# HTTP trigger function processed a request.");

            dynamic body = await req.Content.ReadAsStringAsync();

            string CompanyName;
            Guid?  CompanyId;
            string json = null;

            try
            {
                var data = JsonConvert.DeserializeObject <Company>(body as string);
                CompanyId   = data?.CompanyId;
                CompanyName = data?.CompanyName;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // parse query parameter

            string connectionstring2 = "DefaultEndpointsProtocol=https;AccountName=spassessservices20190227;AccountKey=KLx/VDJ279oOZ2Z2wELr90GauiVlEN4pr8r2ss2xAiokZJGAi4PF6eGz0nI0Vz0IieEwtKxqkgoM+ukeVoWxMw==;EndpointSuffix=core.windows.net";

            if (CompanyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a company id"));
            }

            try
            {
                //this code will do a insert and do a check for the id
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionstring2);
                CloudTableClient    tableClient    = storageAccount.CreateCloudTableClient();

                CloudTable cloudTable = tableClient.GetTableReference("company");

                TableOperation tableOperation = TableOperation.Retrieve <Company>(CompanyId.Value.ToString(), CompanyName);

                TableResult tableResult = await cloudTable.ExecuteAsync(tableOperation);

                Company company = tableResult.Result as Company;



                if (company != null)
                {
                    // add the code here to pass the id back to the client
                    json = JsonConvert.SerializeObject(company, Newtonsoft.Json.Formatting.None,
                                                       new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });;

                    //change this to return the companyid
                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(json, Encoding.UTF8, "application/json")
                    });
                }
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
            }
            catch (StorageException se)
            {
                log.LogTrace(se.Message);
            }
            catch (Exception ex)
            {
                log.LogTrace(ex.Message);
            }


            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
示例#3
0
        protected override T GetQuery(string key, string key2)
        {
            var result = Table.Execute(TableOperation.Retrieve <T>(key, key2));

            return(result.Result as T);
        }
示例#4
0
 private static TableOperation GetOperation(string serviceName, string environmentName, string version)
 {
     return(TableOperation.Retrieve <ConfigurationItem>(environmentName, $"{serviceName}_{version}"));
 }
示例#5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "rescan/resourceId=/SUBSCRIPTIONS/{subId}/RESOURCEGROUPS/{resourceGroup}/PROVIDERS/MICROSOFT.NETWORK/NETWORKSECURITYGROUPS/{nsgName}/y={blobYear}/m={blobMonth}/d={blobDay}/h={blobHour}/m={blobMinute}/macAddress={mac}/PT1H.json")]
//            [Table("checkpoints", Connection = "AzureWebJobsStorage")] CloudTable checkpointToReset,
            HttpRequest req,
            Binder checkpointsBinder,
            Binder nsgDataBlobBinder,
            string subId, string resourceGroup, string nsgName, string blobYear, string blobMonth, string blobDay, string blobHour, string blobMinute, string mac,
            ILogger log)
        {
            string nsgSourceDataAccount = Util.GetEnvironmentVariable("nsgSourceDataAccount");

            if (nsgSourceDataAccount.Length == 0)
            {
                log.LogError("Value for nsgSourceDataAccount is required.");
                throw new System.ArgumentNullException("nsgSourceDataAccount", "Please provide setting.");
            }

            string AzureWebJobsStorage = Util.GetEnvironmentVariable("AzureWebJobsStorage");

            if (AzureWebJobsStorage.Length == 0)
            {
                log.LogError("Value for AzureWebJobsStorage is required.");
                throw new System.ArgumentNullException("AzureWebJobsStorage", "Please provide setting.");
            }

            string blobContainerName = Util.GetEnvironmentVariable("blobContainerName");

            if (blobContainerName.Length == 0)
            {
                log.LogError("Value for blobContainerName is required.");
                throw new System.ArgumentNullException("blobContainerName", "Please provide setting.");
            }

            var blobName    = $"resourceId=/SUBSCRIPTIONS/{subId}/RESOURCEGROUPS/{resourceGroup}/PROVIDERS/MICROSOFT.NETWORK/NETWORKSECURITYGROUPS/{nsgName}/y={blobYear}/m={blobMonth}/d={blobDay}/h={blobHour}/m={blobMinute}/macAddress={mac}/PT1H.json";
            var blobDetails = new BlobDetails(subId, resourceGroup, nsgName, blobYear, blobMonth, blobDay, blobHour, blobMinute, mac);

            var tableAttributes = new Attribute[]
            {
                new TableAttribute("checkpoints"),
                new StorageAccountAttribute("AzureWebJobsStorage")
            };

            try
            {
                CloudTable CheckpointTable = await checkpointsBinder.BindAsync <CloudTable>(tableAttributes);

                TableOperation getOperation = TableOperation.Retrieve <Checkpoint>(blobDetails.GetPartitionKey(), blobDetails.GetRowKey());
                TableResult    result       = await CheckpointTable.ExecuteAsync(getOperation);

                Checkpoint c = (Checkpoint)result.Result;
                c.CheckpointIndex = 1;
                TableOperation putOperation = TableOperation.InsertOrReplace(c);
                await CheckpointTable.ExecuteAsync(putOperation);
            }
            catch (Exception ex)
            {
                log.LogError(string.Format("Error binding checkpoints table: {0}", ex.Message));
                throw ex;
            }

            var attributes = new Attribute[]
            {
                new BlobAttribute(string.Format("{0}/{1}", blobContainerName, blobName)),
                new StorageAccountAttribute(nsgSourceDataAccount)
            };

            try
            {
                CloudBlockBlob blob = await nsgDataBlobBinder.BindAsync <CloudBlockBlob>(attributes);

                await blob.FetchAttributesAsync();

                var metadata = blob.Metadata;
                if (metadata.ContainsKey("rescan"))
                {
                    int numberRescans = Convert.ToInt32(metadata["rescan"]);
                    metadata["rescan"] = (numberRescans + 1).ToString();
                }
                else
                {
                    metadata.Add("rescan", "1");
                }
                await blob.SetMetadataAsync();
            }
            catch (Exception ex)
            {
                log.LogError(string.Format("Error binding blob input: {0}", ex.Message));
                throw ex;
            }

            return((ActionResult) new OkObjectResult($"NSG flow logs for {blobName} were requested."));
        }
示例#6
0
        public static async Task Run(
            [TimerTrigger("0 */30 * * * *", RunOnStartup = true)] TimerInfo timerInfo,
            [Table("installation")] CloudTable installationTable,
            [Queue("openprmessage")] CloudQueue openPrQueue,
            [Queue("openprmessage-poison")] CloudQueue openPrPoisonQueue,
            ILogger logger,
            ExecutionContext context)
        {
            for (var i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(1000);

                var topQueueMessage = await openPrPoisonQueue.GetMessageAsync();

                if (topQueueMessage == null)
                {
                    continue;
                }

                // pre-emptively delete the message from the queue we are pulling from
                await openPrPoisonQueue.DeleteMessageAsync(topQueueMessage);

                var topMessage = JsonConvert.DeserializeObject <OpenPrMessage>(topQueueMessage.AsString);

                try
                {
                    var installation = (Installation)(await installationTable.ExecuteAsync(
                                                          TableOperation.Retrieve <Installation>(topMessage.InstallationId.ToString(), topMessage.RepoName)))
                                       .Result;

                    if (installation == null)
                    {
                        logger.LogInformation("Not listed in installation table");
                        continue;
                    }

                    logger.LogInformation($"https://github.com/{installation.Owner}/{installation.RepoName}");

                    var installationTokenParameters = new InstallationTokenParameters
                    {
                        AccessTokensUrl = string.Format(KnownGitHubs.AccessTokensUrlFormat, topMessage.InstallationId),
                        AppId           = KnownGitHubs.AppId,
                    };

                    var installationToken = await InstallationToken.GenerateAsync(
                        installationTokenParameters,
                        File.OpenText(Path.Combine(context.FunctionDirectory, $"../{KnownGitHubs.AppPrivateKey}")));

                    var appClient = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("MyApp"))
                    {
                        Credentials = new Octokit.Credentials(installationToken.Token, Octokit.AuthenticationType.Bearer)
                    };

                    var limits = await appClient.Miscellaneous.GetRateLimits();

                    logger.LogInformation("Ratelimits:\n");
                    logger.LogInformation(JsonConvert.SerializeObject(limits));

                    // check if an 'imgbot' branch is open
                    var branches = await appClient.Repository.Branch.GetAll(installation.Owner, installation.RepoName);

                    var imgbotBranches = branches.Where(x => x.Name == "imgbot");

                    if (imgbotBranches.Count() == 0)
                    {
                        // we have no open imgbot branches right now, let's just leave
                        continue;
                    }
                    else
                    {
                        logger.LogInformation("Open 'imgbot' branch found");
                    }

                    // check for ImgBot PRs
                    var prs = await appClient.Repository.PullRequest.GetAllForRepository(installation.Owner, installation.RepoName);

                    var imgbotPrs = prs.Where(x => x.Head.Ref == "imgbot");

                    if (imgbotPrs.Count() > 0)
                    {
                        // we have an open imgbot PR right now, let's just leave
                        continue;
                    }
                    else
                    {
                        logger.LogInformation("Open 'imgbot' PR not found, do we need to open one?");
                    }

                    // query for closed ImgBot PRs
                    var searchRequest = new Octokit.SearchIssuesRequest("imgbot")
                    {
                        Type  = Octokit.IssueTypeQualifier.PullRequest,
                        Repos = new Octokit.RepositoryCollection {
                            installation.Owner + "/" + installation.RepoName
                        }
                    };

                    var imgbotIssues = await appClient.Search.SearchIssues(searchRequest);

                    if (imgbotIssues.TotalCount == 0)
                    {
                        // no imgbot prs in history, let's queue a message to get the pr open
                        await openPrQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(topMessage)));
                    }
                    else
                    {
                        // this is the case where an 'imgbot' branch exists, but there are closed imgbot prs
                        var latestClosedPr  = imgbotIssues.Items.OrderByDescending(x => x.ClosedAt).First();
                        var potentialBranch = branches.First(x => x.Name == "imgbot");

                        var commitInImgbotBranch = await appClient.Repository.Commit
                                                   .Get(installation.Owner, installation.RepoName, potentialBranch.Commit.Sha);

                        if (commitInImgbotBranch.Commit.Author.Date > latestClosedPr.ClosedAt)
                        {
                            // if the branch is newer than the last closed imgbot PR then we should queue a message to get the pr open
                            await openPrQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(topMessage)));
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.LogError(e, "ERROR!");

                    // add it back to the poison queue
                    await openPrPoisonQueue.AddMessageAsync(topQueueMessage);
                }
            }
        }
示例#7
0
        private async Task <Result> UpdateProducerDeliveryCountAsync(Guid producerId, Guid deliveryId, DateTimeOffset expectedDeliveryDate, TimeSpan from, TimeSpan to, int maxPurchaseOrders, int change, CancellationToken token)
        {
            var table = _cloudStorageAccount.CreateCloudTableClient().GetTableReference(_storageOptions.Tables.CapingDeliveries);
            await table.CreateIfNotExistsAsync(token);

            var    concurrentUpdateError = false;
            string partitionKey          = GetPartitionKey(producerId, deliveryId, expectedDeliveryDate);
            string rowkey = GetRowKey(from, to);

            var retry = 0;

            do
            {
                try
                {
                    var tableResults = await table.ExecuteAsync(TableOperation.Retrieve <CapingDeliveryTableEntity>(partitionKey, rowkey), token);

                    var results = (CapingDeliveryTableEntity)tableResults.Result;
                    if (results != null)
                    {
                        results.Count += change;
                        if (!_storageOptions.RequireEtag)
                        {
                            results.ETag = "*";
                        }

                        await table.ExecuteAsync(TableOperation.Replace(results), token);
                    }
                    else
                    {
                        await table.ExecuteAsync(TableOperation.Insert(new CapingDeliveryTableEntity
                        {
                            PartitionKey = partitionKey,
                            RowKey       = rowkey,
                            Count        = change < 0 ? 0 : 1,
                            ProducerId   = producerId,
                            DeliveryId   = deliveryId,
                            ExpectedDate = expectedDeliveryDate,
                            From         = from.TotalSeconds,
                            To           = to.TotalSeconds,
                        }), token);
                    }

                    concurrentUpdateError = false;
                }
                catch (StorageException e)
                {
                    retry++;
                    if (retry <= 10 && (e.RequestInformation.HttpStatusCode == 412 || e.RequestInformation.HttpStatusCode == 409))
                    {
                        concurrentUpdateError = true;
                    }
                    else
                    {
                        throw;
                    }
                }
            } while (concurrentUpdateError);

            return(Success());
        }
        public async Task <IHttpActionResult> GetCollection(string q)
        {
            if (String.IsNullOrWhiteSpace(q))
            {
                return(BadRequest("Empty query."));
            }
            var collectionName = GeneralUtils.SanitizeSpaceSeparatedWords(q);

            // Try to find the picture collection for the query in the internal Table storage.
            var    table     = AzureStorageUtils.GetCloudTable(AzureStorageUtils.TableNames.GamePicapick);
            var    operation = TableOperation.Retrieve <GamePickapicEntity>(collectionName, String.Empty);
            var    entity    = (await table.ExecuteAsync(operation)).Result as GamePickapicEntity;
            string json      = entity != null ? entity.Json : null;

            // If the data not found in our internal Table, query the YouTube API.
            if (json == null)
            {
                // We do not use the Google API Client library to materialize result as a POCO. Anyway the API itself is RESTful, and JSON can be parsed easily. Avoid overhead, overkill, bloatware etc.
                // +https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.search.list

                var youtubeParams = HttpUtility.ParseQueryString(String.Empty); // returns System.Web.HttpValueCollection: System.Collections.Specialized.NameValueCollection
                youtubeParams["key"]        = ConfigurationManager.AppSettings["YoutubeApiKey"];
                youtubeParams["part"]       = "snippet";
                youtubeParams["type"]       = "video";
                youtubeParams["maxResults"] = "50";
                youtubeParams["q"]          = collectionName;
                youtubeParams["fields"]     = "items(id,snippet(thumbnails(high)))";
                var youtubeQueryString = youtubeParams.ToString();

                var url = "https://www.googleapis.com/youtube/v3/search?" + youtubeQueryString;

                var handler = new HttpClientHandler();
                if (handler.SupportsAutomaticDecompression)
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                }

                string response = null;
                using (var client = new HttpClient(handler))
                {
                    // If User-Agent is not sent, the server ignores "Accept-Encoding: gzip, deflate" and does not compress the response. The observed compression is 10kB -> 1kB.
                    client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "google-api-dotnet-client/1.8.1.31685 (gzip)");

                    response = await client.GetStringAsync(url);
                }

                var urls = JObject.Parse(response)
                           .GetValue("items")
                           .Children()
                           .Select(i => i["snippet"]["thumbnails"]["high"]["url"].Value <string>())
                           .OrderBy(i => Guid.NewGuid()) // Shuffle
                           .ToArray();

                var controlNumber = Math.Abs(String.Join(String.Empty, urls).GetHashCode()) % 100;
                json   = JsonUtils.SerializeAsJson(new { CollectionName = collectionName, ControlNumber = controlNumber, Urls = urls, });
                entity = new GamePickapicEntity(collectionName, json);
                await AzureStorageUtils.InsertEntityAsync(AzureStorageUtils.TableNames.GamePicapick, entity);
            }

            return(new RawStringResult(this, json, RawStringResult.TextMediaType.Json));
        }
        public async Task Run([ServiceBusTrigger("student", Connection = "ServiceBusConnection")]
                              string myQueueItem,
                              [Table("student")] CloudTable cloudTable,
                              ILogger log)
        {
            log.LogInformation("C# AddStudentQueueTrigger HTTP trigger function processed a request.");

            var msg = JsonConvert.DeserializeObject <Message>(myQueueItem);

            var msgType = msg.Type;
            var student = msg.Student;

            if (msgType.Equals("add"))
            {
                //Add
                var newStudent = new Student
                {
                    PartitionKey = "Student",
                    RowKey       = Guid.NewGuid().ToString(),
                    FirstName    = student.FirstName,
                    LastName     = student.LastName,
                    Email        = student.Email,
                    Address      = student.Address,
                    City         = student.City,
                    Zip          = student.Zip,
                    Phone        = student.Phone
                };

                var insertOperation = TableOperation.Insert(newStudent);
                await cloudTable.ExecuteAsync(insertOperation);

                //return new OkObjectResult(newStudent);
                //await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }
            else
            {
                //Update
                var findOperation = TableOperation.Retrieve <Student>("Student", student.RowKey);
                var findResult    = await cloudTable.ExecuteAsync(findOperation);

                if (findResult.Result == null)
                {
                    //return new NotFoundResult();
                    log.LogError("NotFoundResult =>" + myQueueItem);
                    return;
                }

                var existingRow = (Student)findResult.Result;

                existingRow.FirstName = student.FirstName;
                existingRow.LastName  = student.LastName;
                existingRow.Email     = student.Email;
                existingRow.Address   = student.Address;
                existingRow.City      = student.City;
                existingRow.Zip       = student.Zip;
                existingRow.Phone     = student.Phone;

                var replaceOperation = TableOperation.Replace(existingRow);
                await cloudTable.ExecuteAsync(replaceOperation);

                //return new OkObjectResult(existingRow);
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            // Step 1 :- Create a connection with the storage account
            CloudStorageAccount storageAccount
                = CloudStorageAccount.Parse(@"DefaultEndpointsProtocol=https;AccountName=arena11storage;AccountKey=jV1YbiOkX06nmDyNkyJvl5raNMeGa+URoQc+g7BaY5CAMv4gRWer5hwhgvjrI/8VhuSgCtZvRiTekjqFZWxv1Q==;EndpointSuffix=core.windows.net");
            // Step 2 :-- Table client
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            // Step 3 :- Get reference to hospital management table
            CloudTable table1 = tableClient.GetTableReference("HospitalManagementSystem");



            // get the object to be updated
            TableOperation retrieveOperation = TableOperation.
                                               Retrieve <Patient>("Patient", "P1001");
            TableResult retrievedResult = table1.Execute(retrieveOperation);

            Patient updateEntity = (Patient)retrievedResult.Result;

            updateEntity.PatientName = "PK";
            // attach this object with the operation
            TableOperation updateOperation = TableOperation.Replace(updateEntity);

            //TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
            // execute thate operation using the table
            table1.Execute(updateOperation);


            //TableBatchOperation batchOperation = new TableBatchOperation();

            // Create a customer entity and add it to the table.
            //CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff");
            //customer1.Email = "*****@*****.**";
            //customer1.PhoneNumber = "425-555-0104";

            //// Create another customer entity and add it to the table.
            //CustomerEntity customer2 = new CustomerEntity("Smith", "Ben");
            //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);


            ////prepare the object --create
            //Patient newpat = new Patient();
            //newpat.PatientName = "newpat2";
            //newpat.RowKey = "P1001";
            //newpat.PartitionKey = "Patient";
            //newpat.PaitentAge = "40";
            //newpat.Medication = "Tablets";
            //// you will attach it to a operation
            //TableOperation insertoperation = TableOperation.Insert(newpat);
            //// send this operation to the table
            //table1.Execute(insertoperation);

            // Step 4 :- Create table Query where we will filter
            // only patient partition
            TableQuery <Patient> MyQuery = new TableQuery <Patient>().
                                           Where(
                TableQuery.CombineFilters(
                    TableQuery
                    .GenerateFilterCondition("PartitionKey",
                                             QueryComparisons.Equal
                                             , "Patient"),
                    TableOperators.And,
                    TableQuery
                    .GenerateFilterCondition("RowKey",
                                             QueryComparisons.Equal
                                             , "P1001")));

            // Step 5 :- Fire the query and loop through collection.
            foreach (Patient x in table1.ExecuteQuery <Patient>(MyQuery))
            {
                Console.WriteLine(x.PatientName + "  " + x.Medication);
            }
            Console.Read();
        }
        public async Task <IFeatureBitDefinition> GetByNameAsync(string featureBitName)
        {
            var tableResult = await _table.ExecuteAsync(TableOperation.Retrieve <FeatureBitTableDefinition>(_table.Name, featureBitName));

            return((IFeatureBitDefinition)tableResult.Result);
        }
        /// <summary>
        /// Helper method for retrieving a single entity
        /// </summary>
        /// <param name="rowKey"></param>
        /// <returns></returns>
        private TableResult RetrieveCategory(string rowKey)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve <Category>("Category", rowKey);

            return(categories.Execute(retrieveOperation));
        }
示例#13
0
        private Task <TableResult> RetrieveTableEntityAsync(string partitionKey, string rowKey, List <string> selectColumns, TableRequestOptions tableRequestOptions, OperationContext operationContext)
        {
            var operation = TableOperation.Retrieve <TEntity>(partitionKey, rowKey, selectColumns);

            return(this.CloudTable.ExecuteAsync(operation, tableRequestOptions, operationContext));
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string connectionsJson = File.ReadAllText(Path.Combine(context.FunctionAppDirectory, "Connections.json"));

            JObject ConnectionsObject = JObject.Parse(connectionsJson);

            string connectionString = ConnectionsObject["AZURE_STORAGE_URL"].ToString();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference("AutomotiveData");

            await table.CreateIfNotExistsAsync();

            var room = req.Headers["room"];

            if (string.IsNullOrEmpty(room))
            {
                room = req.Query["room"];
            }

            if (string.IsNullOrEmpty(room))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Please pass a room name on the query string or in the header")
                });
            }

            var partitionKey = "Demo";
            var rowKey       = room;

            try
            {
                // get the room from the table
                var getRoom = TableOperation.Retrieve <AutomotiveData>(partitionKey, rowKey);

                var query = await table.ExecuteAsync(getRoom);

                var currentAutomotiveData = (AutomotiveData)query.Result;

                // if room not exist, create a record using default data
                if (currentAutomotiveData == null)
                {
                    var defaultRoom = new AutomotiveData(partitionKey, rowKey);
                    var createRoom  = TableOperation.Insert(defaultRoom);
                    await table.ExecuteAsync(createRoom);

                    currentAutomotiveData = (AutomotiveData)(await table.ExecuteAsync(getRoom)).Result;
                }

                string operation = req.Query["operation"].ToString().ToLower();
                string strValue  = req.Query["value"].ToString().ToLower();
                int.TryParse(strValue, out int intValue);
                bool updated = false;

                if (!string.IsNullOrEmpty(operation))
                {
                    if (operation.Equals("reset"))
                    {
                        currentAutomotiveData.LoadDefaultData();
                        currentAutomotiveData.Message = "Okay, reset to default state.";
                        updated = true;
                    }
                    else if (operation.Equals("help"))
                    {
                        currentAutomotiveData.Help    = true;
                        currentAutomotiveData.Message = "You're in a virtual car and able to control features with your voice. Try saying \"Turn on the seat warmers\" or \"Set the temperature to 73 degrees\"";
                        updated = true;
                    }
                    else
                    {
                        currentAutomotiveData.Help = false;

                        if (operation.Equals("settemperature"))
                        {
                            currentAutomotiveData.Temperature = intValue;
                            currentAutomotiveData.Message     = $"Okay, set temperature to {intValue} degrees";
                            updated = true;
                        }
                        else if (operation.Equals("increasetemperature"))
                        {
                            currentAutomotiveData.Temperature += intValue;
                            currentAutomotiveData.Message      = $"All right, raise the temperature by {intValue} degrees";
                            updated = true;
                        }
                        else if (operation.Equals("decreasetemperature"))
                        {
                            currentAutomotiveData.Temperature -= intValue;
                            currentAutomotiveData.Message      = $"All right, lower the temperature by {intValue} degrees";
                            updated = true;
                        }
                        else if (operation.Equals("defrost") || operation.Equals("seatwarmer"))
                        {
                            bool?valueBool = (strValue.Equals("on")) ? true : ((strValue.Equals("off")) ? (bool?)false : null);

                            if (valueBool == null)
                            {
                                updated = false;
                            }
                            else if (operation.Equals("defrost"))
                            {
                                if (currentAutomotiveData.Defrost == (bool)valueBool)
                                {
                                    currentAutomotiveData.Message = $"Defrost already {strValue}";
                                }
                                else
                                {
                                    currentAutomotiveData.Defrost = (bool)valueBool;
                                    currentAutomotiveData.Message = $"Ok, turn defroster {strValue}";
                                }
                                updated = true;
                            }
                            else if (operation.Equals("seatwarmer"))
                            {
                                if (currentAutomotiveData.SeatWarmers == (bool)valueBool)
                                {
                                    currentAutomotiveData.Message = $"Seat warmer already {strValue}";
                                }
                                else
                                {
                                    currentAutomotiveData.SeatWarmers = (bool)valueBool;
                                    currentAutomotiveData.Message     = $"Ok, turn seat warmer {strValue}";
                                }
                                updated = true;
                            }
                        }
                        else
                        {
                            currentAutomotiveData.Help = true;
                        }
                    }
                }

                if (updated)
                {
                    var updateRoom = TableOperation.Replace(currentAutomotiveData as AutomotiveData);
                    await table.ExecuteAsync(updateRoom);

                    log.LogInformation("successfully updated the record");
                }

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(currentAutomotiveData, Formatting.Indented), Encoding.UTF8, "application/json")
                });
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Failed to process request")
                });
            }
        }
示例#15
0
 private TableResult DoRetrieve(string pKey, string rKey)
 {
     return(s.Execute(TableOperation.Retrieve <TestEntity>(pKey, rKey)));
 }
示例#16
0
        public void ReplaceUsingLargerViewId()
        {
            long currentViewId = 100;
            long futureViewId  = currentViewId + 1;

            this.UpdateConfiguration(replicas, 0, false, currentViewId);

            string firstName = "FirstName02";
            string lastName  = "LastName02";
            string email     = "*****@*****.**";
            string phone     = "1-800-123-0001";

            // Insert entity
            CustomerEntity newCustomer = new CustomerEntity(firstName, lastName);

            newCustomer.Email       = email;
            newCustomer.PhoneNumber = phone;

            TableOperation operation = TableOperation.Insert(newCustomer);
            TableResult    result    = this.repTable.Execute(operation);

            Assert.AreNotEqual(null, result, "result = null");
            ReplicatedTableEntity row = (ReplicatedTableEntity)result.Result;

            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "result.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, result.Result, "result.Result = null");
            Assert.AreEqual("1", result.Etag, "result.Etag mismatch");
            Assert.AreEqual(false, row._rtable_RowLock, "row._rtable_RowLock mismatch");
            Assert.AreEqual(1, row._rtable_Version, "row._rtable_Version mismatch");
            Assert.AreEqual(false, row._rtable_Tombstone, "row._rtable_Tombstone mismatch");
            Assert.AreEqual(currentViewId, row._rtable_ViewId, "row._rtable_ViewId mismatch");
            Console.WriteLine("Successfully created an entity");

            // Retrieve entity
            operation = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);
            TableResult retrievedResult = this.repTable.Execute(operation);

            Assert.AreNotEqual(null, retrievedResult, "retrievedResult = null");
            CustomerEntity customer = (CustomerEntity)retrievedResult.Result;

            Assert.AreEqual((int)HttpStatusCode.OK, retrievedResult.HttpStatusCode, "retrievedResult.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, retrievedResult.Result, "retrievedResult.Result = null");
            Assert.AreEqual("1", retrievedResult.Etag, "retrievedResult.Etag mismatch");
            Assert.AreEqual(false, customer._rtable_RowLock, "customer._rtable_RowLock mismatch");
            Assert.AreEqual(1, customer._rtable_Version, "customer._rtable_Version mismatch");
            Assert.AreEqual(false, customer._rtable_Tombstone, "customer._rtable_Tombstone mismatch");
            Assert.AreEqual(currentViewId, customer._rtable_ViewId, "customer._rtable_ViewId mismatch");
            Assert.AreEqual(newCustomer.PhoneNumber, customer.PhoneNumber, "customer.PhoneNumber mismatch");
            Assert.AreEqual(newCustomer.Email, customer.Email, "customer.Email mismatch");
            Console.WriteLine("Successfully retrieved the entity");

            //
            // Call ModifyConfigurationBlob to change the viewId of the wrapper to a larger value
            //
            Console.WriteLine("Changing the viewId to futureViewId {0}", futureViewId);
            this.UpdateConfiguration(replicas, 0, false, futureViewId);

            //
            // Replace entity
            //
            Console.WriteLine("\nCalling Replace with larger viewId...");
            email                = "*****@*****.**";
            phone                = "1-800-123-0002";
            customer.Email       = email;
            customer.PhoneNumber = phone;
            operation            = TableOperation.Replace(customer);
            result               = repTable.Execute(operation);
            Assert.AreNotEqual(null, result, "result = null");

            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "result.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, result.Result, "result.Result = null");

            // Retrieve Entity
            Console.WriteLine("\nCalling Retrieve() with larger viewId...");
            operation       = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);
            retrievedResult = repTable.Execute(operation);
            Assert.AreNotEqual(null, retrievedResult, "retrievedResult = null");
            CustomerEntity customer2 = (CustomerEntity)retrievedResult.Result;

            Assert.AreEqual((int)HttpStatusCode.OK, retrievedResult.HttpStatusCode, "retrievedResult.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, retrievedResult.Result, "retrievedResult.Result = null");
            Assert.AreEqual("2", retrievedResult.Etag, "retrievedResult.Etag mismatch");
            Assert.AreEqual(false, customer2._rtable_RowLock, "customer2._rtable_RowLock mismatch");
            Assert.AreEqual(2, customer2._rtable_Version, "customer2._rtable_Version mismatch");
            Assert.AreEqual(false, customer2._rtable_Tombstone, "customer2._rtable_Tombstone mismatch");
            Assert.AreEqual(futureViewId, customer2._rtable_ViewId, "customer2._rtable_ViewId mismatch");
            Assert.AreEqual(phone, customer2.PhoneNumber, "customer2.PhoneNumber mismatch");
            Assert.AreEqual(email, customer2.Email, "customer2.Email mismatch");
            Console.WriteLine("Successfully retrieved the entity");

            //
            // Delete entity
            //
            Console.WriteLine("\nCalling Delete with larger viewId...");
            operation = TableOperation.Delete(customer);
            TableResult deleteResult = repTable.Execute(operation);

            Assert.AreNotEqual(null, deleteResult, "deleteResult = null");
            Assert.AreEqual((int)HttpStatusCode.NoContent, deleteResult.HttpStatusCode, "deleteResult.HttpStatusCode mismatch");
            Assert.IsNotNull(deleteResult.Result, "deleteResult.Result = null");

            // Retrieve
            Console.WriteLine("Calling TableOperation.Retrieve() after Delete() was called...");
            operation = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);
            TableResult retrievedResult2 = repTable.Execute(operation);

            Assert.AreEqual((int)HttpStatusCode.NotFound, retrievedResult2.HttpStatusCode, "retrievedResult2.HttpStatusCode mismatch");
            Assert.IsNull(retrievedResult2.Result, "retrievedResult2.Result != null");
        }
示例#17
0
 private TableResult DoRetrieveSnapshot(int ssid, string pKey, string rKey)
 {
     return(s.RetrieveFromSnapshot(TableOperation.Retrieve <TestEntity>(pKey, rKey), ssid));
 }
示例#18
0
        public void MergeUsingLargerViewId()
        {
            long currentViewId   = 100;
            long futureViewId    = currentViewId + 1;
            int  expectedVersion = 1;

            this.UpdateConfiguration(replicas, 0, false, currentViewId);

            // Insert Entity
            DynamicReplicatedTableEntity baseEntity = new DynamicReplicatedTableEntity("merge test02", "foo02");

            baseEntity.Properties.Add("prop1", new EntityProperty("value1"));
            Console.WriteLine("Calling TableOperation.Insert()...");
            TableResult result = this.repTable.Execute(TableOperation.Insert(baseEntity));

            Assert.AreNotEqual(null, result, "Insert(): result = null");
            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "Insert(): result.HttpStatusCode mismatch");

            //
            // Call ModifyConfigurationBlob to change the viewId of the wrapper to a larger value
            //
            Console.WriteLine("Changing the viewId to futureViewId {0}", futureViewId);
            this.UpdateConfiguration(replicas, 0, false, futureViewId);

            //
            // Merge
            //
            DynamicReplicatedTableEntity mergeEntity = new DynamicReplicatedTableEntity(baseEntity.PartitionKey, baseEntity.RowKey)
            {
                ETag = result.Etag
            };

            mergeEntity.Properties.Add("prop2", new EntityProperty("value2"));
            Console.WriteLine("\nCalling TableOperation.Merge() with a larger viewId...");
            result = this.repTable.Execute(TableOperation.Merge(mergeEntity));
            expectedVersion++;
            Assert.AreNotEqual(null, result, "Merge(): result = null");
            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "Merge(): result.HttpStatusCode mismatch");

            //
            // InsertOrMerge
            //
            DynamicReplicatedTableEntity mergeEntity2 = new DynamicReplicatedTableEntity(baseEntity.PartitionKey, baseEntity.RowKey)
            {
                ETag = result.Etag
            };

            mergeEntity2.Properties.Add("prop3", new EntityProperty("value3"));
            Console.WriteLine("\nCalling TableOperation.InsertOrMerge() with a larger viewId...");
            result = this.repTable.Execute(TableOperation.InsertOrMerge(mergeEntity2));
            expectedVersion++;
            Assert.AreNotEqual(null, result, "InsertOrMerge(): result = null");
            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "InsertOrMerge(): result.HttpStatusCode mismatch");

            // Retrieve Entity & Verify Contents
            Console.WriteLine("\nCalling TableOperation.Retrieve() with a larger viewId...");
            result = this.repTable.Execute(TableOperation.Retrieve <DynamicReplicatedTableEntity>(baseEntity.PartitionKey, baseEntity.RowKey));
            Assert.AreNotEqual(null, result, "Retrieve(): result = null");
            DynamicReplicatedTableEntity retrievedEntity = result.Result as DynamicReplicatedTableEntity;

            Assert.IsNotNull(retrievedEntity, "retrievedEntity = null");
            Assert.AreEqual(3, retrievedEntity.Properties.Count, "Properties.Count mismatch");
            Assert.AreEqual(baseEntity.Properties["prop1"], retrievedEntity.Properties["prop1"], "Properties[prop1] mismatch");
            Assert.AreEqual(mergeEntity.Properties["prop2"], retrievedEntity.Properties["prop2"], "Properties[prop2] mismatch");
            Assert.AreEqual(mergeEntity2.Properties["prop3"], retrievedEntity.Properties["prop3"], "Properties[prop3] mismatch");
            Assert.AreEqual(futureViewId, retrievedEntity._rtable_ViewId, "retrievedEntity._rtable_ViewId mismatch");
            Assert.AreEqual(expectedVersion, retrievedEntity._rtable_Version, "retrievedEntity._rtable_Version mismatch");
        }
示例#19
0
        public async Task <T> FindAsync <T>(string partitionKey, string rowKey) where T : TableEntity
        {
            var res = await m_table.ExecuteAsync(TableOperation.Retrieve <T>(partitionKey, rowKey));

            return(res.Result as T);
        }
示例#20
0
        public void ExceptionWhenUsingSmallerViewId()
        {
            long currentViewId = 100;
            long badViewId     = currentViewId - 1;

            this.UpdateConfiguration(replicas, 0, false, currentViewId);

            string firstName = "FirstName01";
            string lastName  = "LastName01";
            string email     = "*****@*****.**";
            string phone     = "1-800-123-0001";

            // Insert entity
            CustomerEntity newCustomer = new CustomerEntity(firstName, lastName);

            newCustomer.Email       = email;
            newCustomer.PhoneNumber = phone;

            TableOperation operation = TableOperation.Insert(newCustomer);
            TableResult    result    = this.repTable.Execute(operation);

            Assert.AreNotEqual(null, result, "result = null");
            ReplicatedTableEntity row = (ReplicatedTableEntity)result.Result;

            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "result.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, result.Result, "result.Result = null");
            Assert.AreEqual("1", result.Etag, "result.Etag mismatch");
            Assert.AreEqual(false, row._rtable_RowLock, "row._rtable_RowLock mismatch");
            Assert.AreEqual(1, row._rtable_Version, "row._rtable_Version mismatch");
            Assert.AreEqual(false, row._rtable_Tombstone, "row._rtable_Tombstone mismatch");
            Assert.AreEqual(currentViewId, row._rtable_ViewId, "row._rtable_ViewId mismatch");
            Console.WriteLine("Successfully created an entity");

            // Retrieve entity
            operation = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);
            TableResult retrievedResult = this.repTable.Execute(operation);

            Assert.AreNotEqual(null, retrievedResult, "retrievedResult = null");
            CustomerEntity customer = (CustomerEntity)retrievedResult.Result;

            Assert.AreEqual((int)HttpStatusCode.OK, retrievedResult.HttpStatusCode, "retrievedResult.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, retrievedResult.Result, "retrievedResult.Result = null");
            Assert.AreEqual("1", retrievedResult.Etag, "retrievedResult.Etag mismatch");
            Assert.AreEqual(false, customer._rtable_RowLock, "customer._rtable_RowLock mismatch");
            Assert.AreEqual(1, customer._rtable_Version, "customer._rtable_Version mismatch");
            Assert.AreEqual(false, customer._rtable_Tombstone, "customer._rtable_Tombstone mismatch");
            Assert.AreEqual(currentViewId, customer._rtable_ViewId, "customer._rtable_ViewId mismatch");
            Assert.AreEqual(newCustomer.PhoneNumber, customer.PhoneNumber, "customer.PhoneNumber mismatch");
            Assert.AreEqual(newCustomer.Email, customer.Email, "customer.Email mismatch");
            Console.WriteLine("Successfully retrieved the entity");

            //
            // Call RefreshRTableEnvJsonConfigBlob to change the viewId of the wrapper to an older value
            //
            Console.WriteLine("Changing the viewId to badViewId {0}", badViewId);
            this.UpdateConfiguration(replicas, 0, false, badViewId);

            //
            // Retrieve with bad viewId
            //
            Console.WriteLine("\nCalling Retrieve with badViewId...");
            operation = TableOperation.Retrieve <CustomerEntity>(firstName, lastName);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("Retrieve() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }

            //
            // Replace with bad viewId
            //
            Console.WriteLine("\nCalling Replace with badViewId...");
            operation = TableOperation.Replace(customer);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("Replace() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }

            //
            // InsertOrMerge with bad viewId
            //
            Console.WriteLine("\nCalling InsertOrMerge with badViewId...");
            operation = TableOperation.InsertOrMerge(customer);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("InsertOrMerge() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }

            //
            // InsertOrReplace with bad viewId
            //
            Console.WriteLine("\nCalling InsertOrReplace with badViewId...");
            operation = TableOperation.InsertOrReplace(customer);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("InsertOrReplace() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }

            //
            // Merge with bad viewId
            //
            Console.WriteLine("\nCalling Merge with badViewId...");
            operation = TableOperation.Merge(customer);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("Merge() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }

            //
            // Delete with bad viewId
            //
            Console.WriteLine("\nCalling Delete with badViewId...");
            operation = TableOperation.Delete(customer);
            try
            {
                retrievedResult = this.repTable.Execute(operation);
                Assert.Fail("Delete() is expected to get an RTableStaleViewException but did not get it.");
            }
            catch (ReplicatedTableStaleViewException ex)
            {
                Console.WriteLine("Get this RTableStaleViewException: {0}", ex.Message);
                Assert.IsTrue(ex.Message.Contains(string.Format("current _rtable_ViewId {0} is smaller than", badViewId)), "Got unexpected exception message");
            }
        }
        /// <summary>
        /// Tests a table SAS to determine which operations it allows.
        /// </summary>
        /// <param name="sasUri">A string containing a URI with a SAS appended.</param>
        /// <param name="customer">The customer entity.</param>
        /// <returns>A Task object</returns>
        private static async Task TestTableSAS(string sasUri, CustomerEntity customer)
        {
            // Try performing table operations with the SAS provided.
            // Note that the storage account credentials are not required here; the SAS provides the necessary
            // authentication information on the URI.

            // Return a reference to the table using the SAS URI.
            CloudTable table = new CloudTable(new Uri(sasUri));

            // Upsert (add/update) operations: insert an entity.
            // This operation requires both add and update permissions on the SAS.
            try
            {
                // Insert the new entity.
                customer = await SamplesUtils.InsertOrMergeEntityAsync(table, customer);

                Console.WriteLine("Add operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Add operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Read operation: query an entity.
            // This operation requires read permissions on the SAS.
            CustomerEntity customerRead = null;

            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>(customer.PartitionKey, customer.RowKey);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                customerRead = result.Result as CustomerEntity;
                if (customerRead != null)
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customerRead.PartitionKey, customerRead.RowKey, customerRead.Email, customerRead.PhoneNumber);
                }

                Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Read operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Delete operation: delete an entity.
            try
            {
                Console.WriteLine("Delete an entity? [Y]es or [N]o ");
                var delete = Console.ReadKey();
                if (delete.ToString().ToUpper() == "Y")
                {
                    if (customerRead != null)
                    {
                        await SamplesUtils.DeleteEntityAsync(table, customerRead);
                    }

                    Console.WriteLine("Delete operation succeeded for SAS {0}", sasUri);
                }
                else
                {
                    Console.WriteLine("The operation was not done!");
                }
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Delete operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            Console.WriteLine();
        }
        public void TableBatchAddQueryAndOneMoreOperationShouldThrow()
        {
            TableBatchOperation batch     = new TableBatchOperation();
            TableOperation      operation = TableOperation.Retrieve <DynamicReplicatedTableEntity>("foo", "bar");

            try
            {
                batch.Add(operation);
                Assert.IsTrue(batch.Contains(operation));
                batch.Add(TableOperation.Insert(GenerateRandomEnitity("foo")));
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // no op
            }
            catch (Exception)
            {
                Assert.Fail();
            }

            batch.Clear();
            Assert.IsFalse(batch.Contains(operation));

            try
            {
                batch.Add(TableOperation.Insert(GenerateRandomEnitity("foo")));
                batch.Add(TableOperation.Retrieve <DynamicReplicatedTableEntity>("foo", "bar"));
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // no op
            }
            catch (Exception)
            {
                Assert.Fail();
            }

            batch.Clear();

            try
            {
                batch.Add(TableOperation.Retrieve <DynamicReplicatedTableEntity>("foo", "bar"));
                batch.Insert(0, TableOperation.Insert(GenerateRandomEnitity("foo")));

                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // no op
            }
            catch (Exception)
            {
                Assert.Fail();
            }

            try
            {
                batch.Insert(0, TableOperation.Insert(GenerateRandomEnitity("foo")));
                batch.Insert(0, TableOperation.Retrieve <DynamicReplicatedTableEntity>("foo", "bar"));

                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // no op
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
        /// <summary>
        /// Fetches orchestration instance history directly from XXXHistory table
        /// Tries to mimic this algorithm: https://github.com/Azure/azure-functions-durable-extension/blob/main/src/WebJobs.Extensions.DurableTask/ContextImplementations/DurableClient.cs#L718
        /// Intentionally returns IEnumerable<>, because the consuming code not always iterates through all of it.
        /// </summary>
        public static IEnumerable <HistoryEvent> GetHistoryDirectlyFromTable(IDurableClient durableClient, string connName, string hubName, string instanceId)
        {
            var tableClient = TableClient.GetTableClient(connName);

            // Need to fetch executionId first

            var instanceEntity = tableClient.ExecuteAsync($"{hubName}Instances", TableOperation.Retrieve(instanceId, string.Empty))
                                 .Result.Result as DynamicTableEntity;

            string executionId = instanceEntity.Properties.ContainsKey("ExecutionId") ?
                                 instanceEntity.Properties["ExecutionId"].StringValue :
                                 null;

            var instanceIdFilter = TableQuery.CombineFilters
                                   (
                TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, instanceId),
                TableOperators.And,
                TableQuery.GenerateFilterCondition("ExecutionId", QueryComparisons.Equal, executionId)
                                   );

            // Fetching _all_ correlated events with a separate parallel query. This seems to be the only option.
            var correlatedEventsQuery = new TableQuery <HistoryEntity>().Where
                                        (
                TableQuery.CombineFilters
                (
                    instanceIdFilter,
                    TableOperators.And,
                    TableQuery.GenerateFilterConditionForInt("TaskScheduledId", QueryComparisons.GreaterThanOrEqual, 0)
                )
                                        );

            var correlatedEventsTask = tableClient.GetAllAsync($"{hubName}History", correlatedEventsQuery)
                                       .ContinueWith(t => t.Result.ToDictionary(e => e.TaskScheduledId));

            // Memorizing 'ExecutionStarted' event, to further correlate with 'ExecutionCompleted'
            HistoryEntity executionStartedEvent = null;

            // Fetching the history
            var query = new TableQuery <HistoryEntity>().Where(instanceIdFilter);

            foreach (var evt in tableClient.GetAll($"{hubName}History", query))
            {
                switch (evt.EventType)
                {
                case "TaskScheduled":
                case "SubOrchestrationInstanceCreated":

                    // Trying to match the completion event
                    correlatedEventsTask.Result.TryGetValue(evt.EventId, out var correlatedEvt);
                    if (correlatedEvt != null)
                    {
                        yield return(correlatedEvt.ToHistoryEvent
                                     (
                                         evt._Timestamp,
                                         evt.Name,
                                         correlatedEvt.EventType == "GenericEvent" ? evt.EventType : null,
                                         evt.InstanceId
                                     ));
                    }
                    else
                    {
                        yield return(evt.ToHistoryEvent());
                    }

                    break;

                case "ExecutionStarted":

                    executionStartedEvent = evt;

                    yield return(evt.ToHistoryEvent(null, evt.Name));

                    break;

                case "ExecutionCompleted":
                case "ExecutionFailed":
                case "ExecutionTerminated":

                    yield return(evt.ToHistoryEvent(executionStartedEvent?._Timestamp));

                    break;

                case "ContinueAsNew":
                case "TimerCreated":
                case "TimerFired":
                case "EventRaised":
                case "EventSent":

                    yield return(evt.ToHistoryEvent());

                    break;
                }
            }
        }
        public void RTableRepairRowDelete()
        {
            // Insert entity
            Assert.IsTrue(this.repTable.Exists(), "RTable does not exist");

            View fullView = configurationWrapper.GetWriteView();
            List <ReplicaInfo> fullViewReplicas = new List <ReplicaInfo>();

            for (int i = 0; i <= fullView.TailIndex; i++)
            {
                fullViewReplicas.Add(fullView.GetReplicaInfo(i));
            }

            List <ReplicaInfo> newReplicas = new List <ReplicaInfo>();

            for (int i = 1; i <= fullView.TailIndex; i++)
            {
                newReplicas.Add(fullView.GetReplicaInfo(i));
            }

            SampleRTableEntity newCustomer = new SampleRTableEntity("firstName1", "lastName1", "*****@*****.**");

            TableOperation operation = TableOperation.Insert(newCustomer);
            TableResult    result    = repTable.Execute(operation);

            Assert.AreNotEqual(null, result, "result = null");
            ReplicatedTableEntity row = (ReplicatedTableEntity)result.Result;

            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "result.HttpStatusCode mismatch");
            Assert.AreNotEqual(null, result.Result, "result.Result = null");
            Assert.AreEqual("1", result.Etag, "result.Etag mismatch");
            Assert.AreEqual(false, row._rtable_RowLock, "row._rtable_RowLock mismatch");
            Assert.AreEqual(1, row._rtable_Version, "row._rtable_Version mismatch");
            Assert.AreEqual(false, row._rtable_Tombstone, "row._rtable_Tombstone mismatch");
            Assert.AreEqual(configurationWrapper.GetWriteView().ViewId, row._rtable_ViewId, "row._rtable_ViewId mismatch");

            ReadFromIndividualAccountsDirectly(newCustomer.PartitionKey, newCustomer.RowKey, true);

            // remove replica from the head
            this.UpdateConfiguration(newReplicas, 0);
            Assert.IsTrue(configurationWrapper.IsViewStable());

            // delete row
            TableOperation deleteOperation = TableOperation.Delete(newCustomer);

            result = repTable.Execute(deleteOperation);
            Assert.AreNotEqual(null, result, "result = null");
            Assert.AreEqual((int)HttpStatusCode.NoContent, result.HttpStatusCode, "result.HttpStatusCode mismatch");

            //Add replica at head
            this.UpdateConfiguration(fullViewReplicas, 1);

            // repair row on the new head
            Console.WriteLine("Calling repair row");
            result = repTable.RepairRow(row.PartitionKey, row.RowKey, null);
            Assert.AreNotEqual(null, result, "result = null");

            // Retrieve Entity
            Console.WriteLine("Calling TableOperation.Retrieve<SampleRtableEntity>(firstName, lastName)...");
            operation = TableOperation.Retrieve <SampleRTableEntity>("firstname1", "lastName1");
            TableResult retrievedResult = repTable.Execute(operation);

            Assert.AreNotEqual(null, retrievedResult, "retrievedResult = null");

            Assert.AreEqual((int)HttpStatusCode.NotFound, retrievedResult.HttpStatusCode,
                            "retrievedResult.HttpStatusCode mismatch");

            ReadFromIndividualAccountsDirectly(newCustomer.PartitionKey, newCustomer.RowKey, true);
        }
示例#25
0
        public string By(string firstQueryElement, string seccondQueryElement)
        {
            string queryResult = null;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("" +
                                                                           "DefaultEndpointsProtocol=https;AccountName=egovtestbotae3a;AccountKey=HMZbdHjseB8xd8kc8bJgn1ch9R3h2glxFlVZRJCUrnDWtmcZyE11BHD5rkRM6WfjoqrTlS0TJ2GJ8fjKOXSNdA==;EndpointSuffix=core.windows.net");

            CloudTableClient tableClient       = storageAccount.CreateCloudTableClient();
            CloudTable       table             = tableClient.GetTableReference("botdata");
            TableOperation   retrieveOperation = TableOperation.Retrieve <GetInfoFromTable>("Servicii", seccondQueryElement);


            TableResult retrievedResult = table.Execute(retrieveOperation);

            if (retrievedResult.Result != null)
            {
                switch (firstQueryElement)
                {
                case "Cerereonline":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).CerereOnline);
                    break;

                case "Adresa si datele de contact":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).Adresa + "" + ((GetInfoFromTable)retrievedResult.Result).Contact);
                    break;

                case "Costul prestarii serviciului":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).Costul);
                    break;

                case "Informatie generala":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).Descrierea);
                    break;

                case "Documentele necesare":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).Documente);
                    break;

                case "Program de lucru":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).Programul);
                    break;

                case "TipPersoana":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).TipPersoana);
                    break;

                case "Acte normative":
                    queryResult = (((GetInfoFromTable)retrievedResult.Result).TipPersoana);
                    break;

                default:
                    queryResult = "Și uaiiiiiiii!";
                    break;
                }
                return(queryResult);
            }
            else
            {
                return("Nu am gasit așa informație ");
            }
        }
示例#26
0
        private Index ReadIndex()
        {
            var response = _tableRef.Execute(TableOperation.Retrieve <Index>(IndexPartitionKey, IndexRowKey));

            return((Index)response.Result);
        }
 // Get specific entity
 public async Task <T> GetEntityAsync <T>(CloudTable table, string partitionKey, string rowKey)
     where T : TableEntity
 {
     return((await table.ExecuteAsync(TableOperation.Retrieve <T>(partitionKey, rowKey))).Result as T);
 }
示例#28
0
        public ActionResult Delete(DeleteDataset model)
        {
            try
            {
                CloudTable        endPoints = Azure.GetCloudTable(model.DataStorageName, model.DataStorageKey, Azure.Table.AvailableEndpoints);
                AvailableEndpoint catalog   = endPoints.ExecuteQuery(new TableQuery <AvailableEndpoint>()).SingleOrDefault(x => x.alias == model.Catalog);

                CloudTable tableMetadata = Azure.GetCloudTable(catalog.storageaccountname, catalog.storageaccountkey, Azure.Table.TableMetadata);
                if (!tableMetadata.Exists())
                {
                    return(Json(new { Error = string.Format(Messages.TableDoesNotExist, Azure.Table.TableMetadata) }));
                }

                TableOperation retrieveOperation = TableOperation.Retrieve <TableMetadata>(model.PartitionKey, (model.RowKey ?? string.Empty));
                TableResult    retrievedResult   = tableMetadata.Execute(retrieveOperation);
                if (retrievedResult.Result == null)
                {
                    return(Json(new { Error = Messages.DatasetNotFound }));
                }

                TableMetadata entity    = retrievedResult.Result as TableMetadata;
                string        entitySet = entity.entityset;

                // Deleting row in TableMetadata
                tableMetadata.Execute(TableOperation.Delete(entity));

                // Deleting rows in TableColumnsMetadata
                CloudTable tableColumnsMetadata = Azure.GetCloudTable(catalog.storageaccountname, catalog.storageaccountkey, Azure.Table.TableColumnsMetadata);
                if (tableColumnsMetadata.Exists())
                {
                    TableQuery <TableColumnsMetadata> rangeQuery = new TableQuery <TableColumnsMetadata>().Where(TableQuery.GenerateFilterCondition("entityset", QueryComparisons.Equal, entitySet));
                    foreach (TableColumnsMetadata tmpEntity in tableColumnsMetadata.ExecuteQuery(rangeQuery))
                    {
                        tableColumnsMetadata.Execute(TableOperation.Delete(tmpEntity));
                    }
                }

                // Deleting rows in EntityMetadata
                CloudTable entityMetadata = Azure.GetCloudTable(catalog.storageaccountname, catalog.storageaccountkey, Azure.Table.EntityMetadata);
                if (entityMetadata.Exists())
                {
                    TableQuery <EntityMetadata> rangeQuery = new TableQuery <EntityMetadata>().Where(TableQuery.GenerateFilterCondition("entityset", QueryComparisons.Equal, entitySet));
                    foreach (EntityMetadata tmpEntity in entityMetadata.ExecuteQuery(rangeQuery))
                    {
                        entityMetadata.Execute(TableOperation.Delete(tmpEntity));
                    }
                }

                // Deleting rows in ProcessorParams
                CloudTable processorParams = Azure.GetCloudTable(catalog.storageaccountname, catalog.storageaccountkey, Azure.Table.ProcessorParams);
                if (processorParams.Exists())
                {
                    TableQuery <ProcessorParams> rangeQuery = new TableQuery <ProcessorParams>().Where(TableQuery.GenerateFilterCondition("entityset", QueryComparisons.Equal, entitySet));
                    foreach (ProcessorParams tmpEntity in processorParams.ExecuteQuery(rangeQuery))
                    {
                        processorParams.Execute(TableOperation.Delete(tmpEntity));
                    }
                }

                // Deleting the data table
                Azure.GetCloudTable(catalog.storageaccountname, catalog.storageaccountkey, entitySet).DeleteIfExists();

                return(Json(new { Result = string.Empty }));
            }
            catch (Exception ex)
            {
                return(Json(new { Error = ex.Message }));
            }
        }
示例#29
0
        public static async Task Run(
            [QueueTrigger("submissions", Connection = "AzureWebJobsStorage")] string username,
            [Table("users", "{queueTrigger}", "{queueTrigger}", Connection = "AzureWebJobsStorage")] UserEntity user,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {username}");

            // Check if already run in last x amount of time
            if (user?.Timestamp > DateTime.Now.Subtract(Constants.UserExpiry))
            {
                log.LogInformation($"Username '{username}' was updated in last hour. Exit early.");
                return;
            }

            // Check if we've hit rate limit
            string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process);
            var    storageAccount   = CloudStorageAccount.Parse(connectionString);
            var    tableClient      = storageAccount.CreateCloudTableClient();
            var    table            = tableClient.GetTableReference("rateLimit");

            table.CreateIfNotExists();

            RateLimitReset rateReset = null;
            var            utc       = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            var            query     = table.Execute(TableOperation.Retrieve <RateLimitReset>("pk", "rk"));

            if (query.Result is RateLimitReset tmp)
            {
                rateReset = tmp;
                if (utc.AddSeconds(rateReset.ResetTime) > DateTime.UtcNow)
                {
                    log.LogInformation($"Have not reached rate limit timestamp of {utc.AddSeconds(rateReset.ResetTime)}. Current: {DateTime.UtcNow}.");
                    throw new HttpResponseException((HttpStatusCode)429);
                }
            }

            // Lookup data from Twitter
            List <Status> result, likes;
            TwitterUser   userDetails;

            try
            {
                result = await TwitterClient.FetchUserActivityInPastYear(username, log);

                likes = await TwitterClient.FetchUserLikesInPastYear(username, log);

                userDetails = await TwitterClient.FetchUserDetails(username, log);
            }
            catch (HttpResponseException e)
            {
                if (e.Response.StatusCode == (HttpStatusCode)429)
                {
                    if (rateReset == null)
                    {
                        rateReset = new RateLimitReset();
                        rateReset.PartitionKey = "pk";
                        rateReset.RowKey       = "rk";
                    }
                    if (e.Response.Headers.TryGetValues("x-rate-limit-reset", out IEnumerable <string> resetTime))
                    {
                        var newTime = Double.Parse(resetTime.First());
                        if (newTime > rateReset.ResetTime)
                        {
                            rateReset.ResetTime = newTime;
                            table.Execute(TableOperation.InsertOrReplace(rateReset));
                            log.LogInformation("Updated rateLimit to " + newTime);
                        }
                    }
                }

                throw;
            }

            var hashset = new Dictionary <string, DaySummary>();

            foreach (Status status in result)
            {
                string date = status.CreatedAt.ToString("yyyy-MM-dd");
                if (!hashset.TryGetValue(date, out DaySummary summary))
                {
                    summary = new DaySummary {
                        Date = date
                    };
                }
                summary.StatusCount++;
                hashset[date] = summary;
            }

            foreach (Status status in likes)
            {
                string date = status.CreatedAt.ToString("yyyy-MM-dd");
                if (!hashset.TryGetValue(date, out DaySummary summary))
                {
                    summary = new DaySummary {
                        Date = date
                    };
                }
                summary.LikeCount++;
                hashset[date] = summary;
            }

            // Write results to storage. Bindings don't support update, apparently :/
            table = tableClient.GetTableReference("users");
            table.CreateIfNotExists();

            if (user == null)
            {
                user = new UserEntity();
                user.PartitionKey = username;
                user.RowKey       = username;
            }

            user.Timestamp = DateTime.Now;
            user.Entity    = JsonConvert.SerializeObject(new UserSummary
            {
                Summary     = hashset.Values.ToList(),
                UserDetails = userDetails
            });
            table.Execute(TableOperation.InsertOrReplace(user));
        }
示例#30
0
        /// <summary>
        /// Gets the specified job
        /// </summary>
        /// <param name="job"></param>
        /// <returns>Indicates whether the operation was successful</returns>
        public Job GetJob(Guid jobId, string version)
        {
            var retrieveOperation = TableOperation.Retrieve <Job>(jobId.ToString(), version);

            return(JobsTable.Execute(retrieveOperation).Result as Job);
        }