public async Task InsertAsync(string tinyUrlKey, string originalUrl)
 {
     var tinyUrlMapEntity = new TinyUrlMapEntity(tinyUrlKey, originalUrl);
     var insertOperation  = TableOperation.Insert(tinyUrlMapEntity);
     await _myTinyUrlsTable.ExecuteAsync(insertOperation);
 }
示例#2
0
        private async void ProcessCloudQueue(object sender, object e)
        {
            queue.Tick -= ProcessCloudQueue;

            // Create the table client.

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();;

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("myroomcommands");

            // Construct the query operation for all customer entities where PartitionKey="Smith".
            TableQuery <RoomCommand> query = new TableQuery <RoomCommand>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "ROOM1"));


            // Print the fields for each customer.
            // Initialize the continuation token to null to start from the beginning of the table.
            TableContinuationToken continuationToken = null;

            do
            {
                // Retrieve a segment (up to 1,000 entities).
                TableQuerySegment <RoomCommand> tableQueryResult =
                    await table.ExecuteQuerySegmentedAsync(query, continuationToken);

                // Assign the new continuation token to tell the service where to
                // continue on the next iteration (or null if it has reached the end).
                continuationToken = tableQueryResult.ContinuationToken;

                foreach (RoomCommand cmd in tableQueryResult)
                {
                    TableOperation deleteOperation = TableOperation.Delete(cmd);
                    if (cmd.RelayId == "RELAY1" && cmd.State == true)
                    {
                        FAN.Fill       = greenBrush;
                        StateText.Text = "Fan On";
                        TurnRelay1On();
                    }
                    else if (cmd.RelayId == "RELAY1" && cmd.State == false)
                    {
                        FAN.Fill       = grayBrush;
                        StateText.Text = "Fan Off";
                        TurnRelay1Off();
                    }
                    else if (cmd.RelayId == "RELAY2" && cmd.State == true)
                    {
                        LIGHT.Fill          = greenBrush;
                        StateTextlight.Text = "Light On";
                        TurnRelay2On();
                    }
                    else if (cmd.RelayId == "RELAY2" && cmd.State == false)
                    {
                        LIGHT.Fill          = grayBrush;
                        StateTextlight.Text = "Light Off";
                        TurnRelay2Off();
                    }
                    else
                    {
                        FAN.Fill       = grayBrush;
                        LIGHT.Fill     = grayBrush;
                        StateText.Text = StateTextlight.Text = "Invalid Operation";
                    }
                    // Execute the operation.
                    await table.ExecuteAsync(deleteOperation);
                }
            } while (continuationToken != null);

            queue.Tick    += ProcessCloudQueue;
            queue.Interval = TimeSpan.FromMilliseconds(1000);
            queue.Start();
        }
示例#3
0
        public async Task AddTableEntity(ITableEntity entity)
        {
            CloudTable table = this.GetStorageTable();

            await table.ExecuteAsync(TableOperation.Insert(entity));
        }
 public Product GetProduct(string id)
 {
     return((Product)_table.ExecuteAsync(TableOperation.Retrieve <Product>(PartitionKey, id)).Result.Result);
 }
示例#5
0
        public static async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log, [Table("dselbtable")] CloudTable loadbalancerconfigTable)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            TableQuerySegment <UpdateLoadBalancerEntity> segment = null;
            TableBatchOperation batchOperation = new TableBatchOperation();

            log.LogInformation($"Deleting all resources for {loadbalancerconfigTable.Name}");
            while (segment == null || segment.ContinuationToken != null)
            {
                segment = await loadbalancerconfigTable.ExecuteQuerySegmentedAsync(new TableQuery <UpdateLoadBalancerEntity>().Take(500), segment?.ContinuationToken);

                Parallel.ForEach(segment.Results, async entity =>
                {
                    await loadbalancerconfigTable.ExecuteAsync(TableOperation.Delete(entity));
                });
            }
            if (batchOperation.Count > 0)
            {
                await loadbalancerconfigTable.ExecuteBatchAsync(batchOperation);
            }

            //Get Token
            string token = AuthHelper.GetTokenAsync().Result;

            log.LogInformation($"Token Received: {token}");

            string        subscriptionsUri = "https://management.azure.com/subscriptions?api-version=2016-06-01";
            Subscriptions subscriptions    = await ResilientRestClient.GetAsync <Subscriptions>(subscriptionsUri, token);

            log.LogInformation($"Subs Received");

            //Query SubscriptionIDs which has Gateway Connections
            string query = "where type =~ 'microsoft.network/connections'| distinct subscriptionId ";
            Dictionary <string, int> options = new Dictionary <string, int>();

            options["$skip"] = 0;
            Dictionary <string, object> requestBodyObj = new Dictionary <string, object>();
            List <string> subscriptionIds = subscriptions.value.Select(subs => subs.subscriptionId).ToList();

            requestBodyObj.Add("subscriptions", subscriptionIds);
            requestBodyObj.Add("query", query);
            requestBodyObj.Add("options", options);
            string        resourceGraphUri = "https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2018-09-01-preview";
            List <string> expressRouteConnectedSubscriptions = new List <string>();
            //TEST CASE
            string subId = Environment.GetEnvironmentVariable("TestSubscriptionID", EnvironmentVariableTarget.Process);

            expressRouteConnectedSubscriptions.Add(subId);
            //Commenting for test
            // ResourceGraphResponse resourcesubs = ResilientRestClient.PostAsync<ResourceGraphResponse>(resourceGraphUri, token, requestBodyObj).Result;
            // foreach (List<string> row in resourcesubs.data.rows)
            // {
            //     expressRouteConnectedSubscriptions.Add(row[0]);
            // }
            // log.LogInformation($"The number of subs are {expressRouteConnectedSubscriptions.Count}");

            //TODO ADD Logic to clear the table or after automation job completion trigger an update to remove the upgraded LB from table

            //Query for Load Balancers
            string lbquery = "where type =~ 'Microsoft.Network/loadbalancers'| where tostring(sku.name) =='Basic' | project id, subscriptionId, resourceGroup, name, location";
            Dictionary <string, int> lboptions = new Dictionary <string, int>();

            options["$skip"] = 0;
            Dictionary <string, object> lbrequestBodyObj = new Dictionary <string, object>();

            lbrequestBodyObj.Add("subscriptions", expressRouteConnectedSubscriptions);
            lbrequestBodyObj.Add("query", lbquery);
            lbrequestBodyObj.Add("options", lboptions);

            List <LoadBalancerObj> loadBalancers = new List <LoadBalancerObj>();

            ResourceGraphResponse lbs = ResilientRestClient.PostAsync <ResourceGraphResponse>(resourceGraphUri, token, lbrequestBodyObj).Result;
            int i = 1;

            foreach (List <string> row in lbs.data.rows)
            {
                LoadBalancerObj lb = new LoadBalancerObj
                {
                    ResourceId     = row[0],
                    SubscriptionId = row[1],
                    ResourceGroup  = row[2],
                    Name           = row[3],
                    Location       = row[4]
                };
                loadBalancers.Add(lb);
            }
            while (lbs.skipToken != null)
            {
                log.LogInformation(i.ToString());
                Dictionary <string, int> nextSkip = new Dictionary <string, int>();
                nextSkip["$skip"] = i * 1000;
                Dictionary <string, object> updatedrequestBodyObj = new Dictionary <string, object>();
                updatedrequestBodyObj["subscriptions"] = expressRouteConnectedSubscriptions;
                updatedrequestBodyObj["query"]         = lbquery;
                updatedrequestBodyObj["$skipToken"]    = lbs.skipToken;
                updatedrequestBodyObj["options"]       = nextSkip;
                lbs = ResilientRestClient.PostAsync <ResourceGraphResponse>(resourceGraphUri, token, updatedrequestBodyObj).Result;
                foreach (List <string> row in lbs.data.rows)
                {
                    LoadBalancerObj lb = new LoadBalancerObj
                    {
                        ResourceId     = row[0],
                        SubscriptionId = row[1],
                        ResourceGroup  = row[2],
                        Name           = row[3],
                        Location       = row[4]
                    };
                    loadBalancers.Add(lb);
                }
                i++;
            }

            Parallel.ForEach(loadBalancers, async lb =>
            {
                UpdateLoadBalancerEntity loadBalancerEntity = new UpdateLoadBalancerEntity
                {
                    PartitionKey  = lb.SubscriptionId,
                    RowKey        = lb.Name,
                    Location      = lb.Location,
                    ResourceGroup = lb.ResourceGroup,
                    ResourceId    = lb.ResourceId
                };
                TableOperation insertOperation = TableOperation.InsertOrMerge(loadBalancerEntity);
                await loadbalancerconfigTable.ExecuteAsync(insertOperation);
            });
        }
示例#6
0
        protected Task <TableResult> InsertDataAsync <T>(CloudTable table, T data) where T : BaseTable
        {
            TableOperation insertOperation = TableOperation.Insert(data);

            return(table.ExecuteAsync(insertOperation));
        }
示例#7
0
 public async Task SaveServiceClient(ServerClient serverClient)
 {
     await _serviceClientsTable.ExecuteAsync(TableOperation.InsertOrReplace(serverClient));
 }
        public async Task <TableResult> CreateOrUpdateAsync(T entity)
        {
            var insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

            return(await cloudTable.ExecuteAsync(insertOrMergeOperation));
        }
        static void CreateMessage(CloudTable table, EmailEntity newemail)
        {
            TableOperation insert = TableOperation.Insert(newemail);

            table.ExecuteAsync(insert);
        }
示例#10
0
 public async Task <StreamOpenResult> ExecuteAsync()
 {
     return(Result(await table.ExecuteAsync(Prepare())));
 }
示例#11
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Table("User")] CloudTable cloudTable,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger {nameof(CreateProfile)} function processed a request.");


            var privateKey = Utils.ParseToken(req);

            if (privateKey == null)
            {
                return(new UnauthorizedResult());
            }

            User user = null;

            try
            {
                var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                user = JsonConvert.DeserializeObject <User>(requestBody);
            }
            catch (Exception ex)
            {
                log.LogWarning("Unable to deserialize user: "******"Invalid data to process request"));
            }
            var encryptedFriendCode = string.Empty;

            try
            {
                encryptedFriendCode = Cipher.Encrypt(user.FriendCode, Utils.FriendCodePassword, user.PublicKey);
            }
            catch (Exception ex)
            {
                log.LogError("Unable to decrypt friendcode: " + ex.Message);
            }
            var userEntity = new UserEntity(user.PublicKey, privateKey)
            {
                Name                = user.Name,
                IslandName          = user.IslandName,
                Fruit               = user.Fruit,
                TimeZone            = user.TimeZone,
                Status              = user.Status ?? string.Empty,
                TurnipUpdateTimeUTC = DateTime.UtcNow,
                FriendCode          = encryptedFriendCode,
                GateClosesAtUTC     = DateTime.UtcNow
            };

            try
            {
#if DEBUG
                userEntity.ETag = "*";
#endif
                // Create the InsertOrReplace table operation
                var insertOrMergeOperation = TableOperation.InsertOrMerge(userEntity);

                // Execute the operation.
                var result = await cloudTable.ExecuteAsync(insertOrMergeOperation);

                var insertedCustomer = result.Result as UserEntity;
            }
            catch (Exception ex)
            {
                log.LogError($"Error {nameof(CreateProfile)} - Error: " + ex.Message);
                return(new InternalServerErrorResult());
            }

            return(new OkObjectResult("User Created"));
        }
示例#12
0
 public async Task Add(T item)
 {
     await TableClient.ExecuteAsync(TableOperation.Insert(item));
 }
        /// <summary>
        /// Gets the <see cref="PoisonMessage"/>.
        /// </summary>
        private async Task <PoisonMessage> GetPoisonMessageAsync()
        {
            var tr = await _poisonTable.ExecuteAsync(TableOperation.Retrieve <PoisonMessage>(_storagePartitionKey, _storageRowKey)).ConfigureAwait(false);

            return((PoisonMessage)tr.Result);
        }
示例#14
0
        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("virtualroomconfig");

            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 <VirtualRoomConfig>(partitionKey, rowKey);

                var query = await table.ExecuteAsync(getRoom);

                var currRoomConfig = (VirtualRoomConfig)query.Result;

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

                    currRoomConfig = (VirtualRoomConfig)(await table.ExecuteAsync(getRoom)).Result;
                }

                var operation = req.Query["operation"].ToString().ToLower();
                var updated   = false;

                if (!string.IsNullOrEmpty(operation))
                {
                    if (operation.Equals("reset"))
                    {
                        currRoomConfig.LoadDefaultConfig();
                        updated = true;
                    }
                    else if (operation.Equals("turn"))
                    {
                        var item     = req.Query["item"].ToString().ToLower();
                        var instance = req.Query["instance"].ToString().ToLower();
                        var value    = req.Query["value"].ToString().ToLower();

                        bool?valueBool = (value.Equals("on") || value.Equals("open")) ? true : ((value.Equals("off") || value.Equals("close")) ? (bool?)false : null);

                        if (valueBool == null)
                        {
                            updated = false;
                        }
                        else if (item.Equals("lights"))
                        {
                            if (instance.Equals("all"))
                            {
                                if (currRoomConfig.Lights_bathroom == (bool)valueBool && currRoomConfig.Lights_room == (bool)valueBool)
                                {
                                    currRoomConfig.Message = $"All lights already {value}";
                                }
                                else
                                {
                                    currRoomConfig.Lights_bathroom = (bool)valueBool;
                                    currRoomConfig.Lights_room     = (bool)valueBool;
                                    currRoomConfig.Message         = $"Ok, turning all the lights {value}";
                                }
                                updated = true;
                            }
                            else if (instance.Equals("room"))
                            {
                                if (currRoomConfig.Lights_room == (bool)valueBool)
                                {
                                    currRoomConfig.Message = $"Room light already {value}";
                                }
                                else
                                {
                                    currRoomConfig.Lights_room = (bool)valueBool;
                                    currRoomConfig.Message     = $"Ok, turning {value} the room light";
                                }
                                updated = true;
                            }
                            else if (instance.Equals("bathroom"))
                            {
                                if (currRoomConfig.Lights_bathroom == (bool)valueBool)
                                {
                                    currRoomConfig.Message = $"Bathroom light already {value}";
                                }
                                else
                                {
                                    currRoomConfig.Lights_bathroom = (bool)valueBool;
                                    currRoomConfig.Message         = $"Ok, turning {value} the bathroom light";
                                }
                                updated = true;
                            }
                        }
                        else if (item.Equals("tv"))
                        {
                            if (currRoomConfig.Television == (bool)valueBool)
                            {
                                currRoomConfig.Message = $"TV already {value}";
                            }
                            else
                            {
                                currRoomConfig.Television = (bool)valueBool;
                                currRoomConfig.Message    = $"Ok, turning the TV {value}";
                            }
                            updated = true;
                        }
                        else if (item.Equals("blinds"))
                        {
                            if (currRoomConfig.Blinds == (bool)valueBool)
                            {
                                currRoomConfig.Message = (bool)valueBool ? "Blinds already opened" : "Blinds already closed";
                            }
                            else
                            {
                                currRoomConfig.Blinds  = (bool)valueBool;
                                currRoomConfig.Message = (bool)valueBool ? "All right, opening the blinds" : "All right, closing the blinds";
                            }
                            updated = true;
                        }
                        else if (item.Equals("ac"))
                        {
                            if (currRoomConfig.AC == (bool)valueBool)
                            {
                                currRoomConfig.Message = $"AC already {value}";
                            }
                            else
                            {
                                currRoomConfig.AC      = (bool)valueBool;
                                currRoomConfig.Message = $"Ok, turning the AC {value}";
                            }
                            updated = true;
                        }
                    }
                    else if (operation.Equals("settemperature"))
                    {
                        currRoomConfig.Temperature = int.Parse(req.Query["value"]);
                        currRoomConfig.Message     = "set temperature to " + req.Query["value"];
                        updated = true;
                    }
                    else if (operation.Equals("increasetemperature"))
                    {
                        currRoomConfig.Temperature += int.Parse(req.Query["value"]);
                        currRoomConfig.Message      = "raised temperature by " + req.Query["value"] + " degrees";
                        updated = true;
                    }
                    else if (operation.Equals("decreasetemperature"))
                    {
                        currRoomConfig.Temperature -= int.Parse(req.Query["value"]);
                        currRoomConfig.Message      = "decreased temperature by " + req.Query["value"] + " degrees";
                        updated = true;
                    }
                }

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

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

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(currRoomConfig, 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
        /// <summary>
        /// Uploads results to GitHub/Azure Table Storage
        /// </summary>
        /// <param name="scorecards">List of Scorecard instances to be uploaded</param>
        /// <param name="githubClient">An authenticated Octokit.GitHubClient instance</param>
        /// <param name="storageAccountKey">Key to the rollout scorecards storage account</param>
        /// <param name="githubConfig">GitHubConfig object representing config</param>
        public async static Task UploadResultsAsync(List <Scorecard> scorecards, GitHubClient githubClient, string storageAccountKey, GithubConfig githubConfig, bool skipPr = false)
        {
            // We batch the scorecards by date so they can be sorted into markdown files properly
            IEnumerable <ScorecardBatch> scorecardBatches = scorecards
                                                            .GroupBy(s => s.Date).Select(g => new ScorecardBatch {
                Date = g.Key, Scorecards = g.ToList()
            });

            const string TargetBranch = "main";

            if (!skipPr)
            {
                Reference targetBranch = await githubClient.Git.Reference
                                         .Get(githubConfig.ScorecardsGithubOrg, githubConfig.ScorecardsGithubRepo, "heads/" + TargetBranch);

                string    newBranchName = $"{DateTime.Today:yyyy-MM-dd}-Scorecard-Update";
                string    newBranchRef  = $"heads/{newBranchName}";
                Reference newBranch;

                // If this succeeds than the branch exists and we should update it directly
                try
                {
                    newBranch = await githubClient.Git.Reference.Get(githubConfig.ScorecardsGithubOrg,
                                                                     githubConfig.ScorecardsGithubRepo, newBranchRef);
                }
                // If not, we've got to create the new branch
                catch (NotFoundException)
                {
                    newBranch = await githubClient.Git.Reference.CreateBranch(githubConfig.ScorecardsGithubOrg,
                                                                              githubConfig.ScorecardsGithubRepo, newBranchName, targetBranch);
                }

                TreeResponse currentTree = await githubClient.Git.Tree.Get(githubConfig.ScorecardsGithubOrg,
                                                                           githubConfig.ScorecardsGithubRepo, newBranchRef);

                NewTree newTree = new NewTree
                {
                    BaseTree = currentTree.Sha,
                };

                // We loop over the batches and generate a markdown file for each rollout date
                foreach (ScorecardBatch scorecardBatch in scorecardBatches)
                {
                    List <RepoMarkdown> repoMarkdowns = scorecardBatch.Scorecards.Select(s => CreateRepoMarkdown(s)).ToList();

                    string scorecardBatchMarkdown = $"# {scorecardBatch.Date.Date:dd MMMM yyyy} Rollout Summaries\n\n" +
                                                    $"{string.Join('\n', repoMarkdowns.Select(md => md.Summary))}\n" +
                                                    $"# Itemized Scorecard\n\n" +
                                                    $"{string.Join('\n', repoMarkdowns.Select(md => md.Breakdown))}";

                    string scorecardBatchFilePath =
                        $"{githubConfig.ScorecardsDirectoryPath}Scorecard_{scorecardBatch.Date.Date:yyyy-MM-dd}.md";

                    NewTreeItem markdownBlob = new NewTreeItem
                    {
                        Path    = scorecardBatchFilePath,
                        Mode    = _gitFileBlobMode,
                        Type    = TreeType.Blob,
                        Content = scorecardBatchMarkdown,
                    };
                    newTree.Tree.Add(markdownBlob);
                }

                TreeResponse treeResponse = await githubClient.Git.Tree.Create(githubConfig.ScorecardsGithubOrg, githubConfig.ScorecardsGithubRepo, newTree);

                // Commit the new response to the new branch
                NewCommit newCommit = new NewCommit("Add scorecards for " +
                                                    string.Join(", ", scorecardBatches.Select(s => s.Date.Date.ToString("yyyy-MM-dd"))),
                                                    treeResponse.Sha,
                                                    newBranch.Object.Sha);
                Commit commit = await githubClient.Git.Commit
                                .Create(githubConfig.ScorecardsGithubOrg, githubConfig.ScorecardsGithubRepo, newCommit);

                ReferenceUpdate update     = new ReferenceUpdate(commit.Sha);
                Reference       updatedRef = await githubClient.Git.Reference.Update(githubConfig.ScorecardsGithubOrg,
                                                                                     githubConfig.ScorecardsGithubRepo, newBranchRef, update);

                PullRequestRequest prRequest = new PullRequestRequest
                {
                    Base  = TargetBranch,
                    Head  = newBranchName,
                    State = ItemStateFilter.Open,
                };
                // If an open PR exists already, we shouldn't try to create a new one
                List <PullRequest> prs =
                    (await githubClient.PullRequest.GetAllForRepository(githubConfig.ScorecardsGithubOrg, githubConfig.ScorecardsGithubRepo)).ToList();
                if (!prs.Any(pr => pr.Head.Ref == newBranchName))
                {
                    NewPullRequest newPullRequest = new NewPullRequest(newCommit.Message, newBranchName, TargetBranch);
                    await githubClient.PullRequest.Create(githubConfig.ScorecardsGithubOrg, githubConfig.ScorecardsGithubRepo, newPullRequest);
                }
            }

            // Upload the results to Azure Table Storage (will overwrite previous entries with new data if necessary)
            CloudTable table = Utilities.GetScorecardsCloudTable(storageAccountKey);

            foreach (Scorecard scorecard in scorecards)
            {
                ScorecardEntity scorecardEntity = new ScorecardEntity(scorecard.Date, scorecard.Repo.Repo)
                {
                    TotalScore           = scorecard.TotalScore,
                    TimeToRolloutSeconds = scorecard.TimeToRollout.TotalSeconds,
                    CriticalIssues       = scorecard.CriticalIssues,
                    Hotfixes             = scorecard.Hotfixes,
                    Rollbacks            = scorecard.Rollbacks,
                    DowntimeSeconds      = scorecard.Downtime.TotalSeconds,
                    Failure             = scorecard.Failure,
                    TimeToRolloutScore  = scorecard.TimeToRolloutScore,
                    CriticalIssuesScore = scorecard.CriticalIssueScore,
                    HotfixScore         = scorecard.HotfixScore,
                    RollbackScore       = scorecard.RollbackScore,
                    DowntimeScore       = scorecard.DowntimeScore,
                };
                await table.ExecuteAsync(TableOperation.InsertOrReplace(scorecardEntity));
            }
        }
示例#16
0
 public async Task UpdateCounter(CloudTable cloudTable, Counter counter)
 {
     await cloudTable.ExecuteAsync(TableOperation.InsertOrReplace(counter));
 }
示例#17
0
        public async Task <ActionResult> PostAsync()
        {
            string input = null;

            // If not data came in, then return
            if (this.Request.Body == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict)));
            }

            // Read the input claims from the request body
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                input = await reader.ReadToEndAsync();
            }

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into IdentityClaims object
            IdentityClaims inputClaims = IdentityClaims.Parse(input);

            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.signInName))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'signInName' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.password))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'password' is null or empty", HttpStatusCode.Conflict)));
            }

            // Create or reference an existing table
            CloudTable table = await Common.CreateTableAsync("identities");

            var identityEntity = new IdentityEntity(inputClaims.signInName);

            identityEntity.displayName = inputClaims.displayName;
            identityEntity.password    = inputClaims.password;
            identityEntity.givenName   = inputClaims.givenName;
            identityEntity.surName     = inputClaims.surName;

            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(identityEntity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            }
            catch (StorageException e)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel(e.Message, HttpStatusCode.Conflict)));
            }
            return(Ok());
        }
示例#18
0
 public void Add(ActivityEntity entity)
 {
     activityTable.ExecuteAsync(TableOperation.Insert(entity)).Wait();
 }
示例#19
0
 public static async Task InsertOrMergeAsync(CloudTable table, MessageBatchTableEntity entity)
 {
     var operation = TableOperation.InsertOrMerge(entity);
     await table.ExecuteAsync(operation);
 }
示例#20
0
        public static async Task <HttpResponseMessage> ShortenUrl(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req,
            [Table(Utility.TABLE, Utility.PARTITIONKEY, Utility.KEY, Take = 1)] UrlKey keyTable,
            [Table(Utility.TABLE)] CloudTable tableOut,
            TraceWriter log)
        {
            log.Info($"C# triggered function called with req: {req}");

            if (req == null)
            {
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.NotFound
                });
            }

            var result = new ShortResponse
            {
                url        = string.Empty,
                short_code = string.Empty,
                error      = string.Empty
            };

            try
            {
                ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>();

                if (input == null)
                {
                    log.Error("Input payload is null.");
                    return(new HttpResponseMessage {
                        StatusCode = HttpStatusCode.NotFound
                    });
                }

                if (string.IsNullOrWhiteSpace(input.url))
                {
                    log.Error("No URL found.");
                    return(new HttpResponseMessage {
                        StatusCode = HttpStatusCode.BadRequest
                    });
                }

                if (!Uri.TryCreate(input.url, UriKind.Absolute, out Uri uri))
                {
                    log.Error($"Input URL ({input.url}) is invalid format.");
                    return(req.CreateResponse(HttpStatusCode.BadRequest));
                }

                if (keyTable == null)
                {
                    keyTable = new UrlKey
                    {
                        PartitionKey = Utility.PARTITIONKEY,
                        RowKey       = Utility.KEY,
                        Id           = 1
                    };
                    var addKey = TableOperation.Insert(keyTable);
                    await tableOut.ExecuteAsync(addKey);
                }

                var idx  = keyTable.Id;
                var code = Utility.Encode(idx);

                var url = new UrlEntity
                {
                    PartitionKey = $"{code[0]}",
                    RowKey       = code,
                    Url          = input.url
                };

                log.Info($"ShortCode={code} for URL {url.Url}");
                result.url = $"https://{Utility.BASEURL}/{code}";

                keyTable.Id++;
                var operation = TableOperation.Replace(keyTable);
                await tableOut.ExecuteAsync(operation);

                operation = TableOperation.Insert(url);
                await tableOut.ExecuteAsync(operation);

                result.short_code = code;

                var response = new HttpResponseMessage
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result))
                };

                return(response);
            }
            catch (Exception ex)
            {
                log.Error("Error processing link", ex);
                result.error = ex.Message;
                var response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.Conflict,
                    Content    = new StringContent(JsonConvert.SerializeObject(result))
                };
                return(response);
            }
        }
示例#21
0
 public async Task SaveClient(Client client)
 {
     await _clientsTable.ExecuteAsync(TableOperation.InsertOrReplace(client));
 }
        public async Task CreateNewStudent(StudentEntity student)
        {
            var insertOperation = TableOperation.Insert(student);

            await _studentsTable.ExecuteAsync(insertOperation);
        }
示例#23
0
        public static async Task <TableResult> Delete(this CloudTable table, ITableEntity rec)
        {
            TableOperation operation = TableOperation.Delete(rec);

            return(await table.ExecuteAsync(operation));
        }
        public void postNewUser(User newUserObject)
        {
            CloudTable table = tableClient.GetTableReference("UserAccounts");

            table.ExecuteAsync(TableOperation.InsertOrReplace(newUserObject));
        }
示例#25
0
        /// <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>
        internal static async Task TestTableSAS(string sasUri, UserEntity 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 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.
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <UserEntity>(customer.PartitionKey, customer.RowKey);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                UserEntity customerRead = result.Result as UserEntity;
                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
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <UserEntity>(customer.PartitionKey, customer.RowKey);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                UserEntity customerDelete = result.Result as UserEntity;
                if (customerDelete != null)
                {
                    await DeleteEntityAsync(table, customerDelete);
                }

                Console.WriteLine("Delete operation succeeded for SAS {0}", sasUri);
                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();
        }
示例#26
0
        public static async Task Run(
            [ServiceBusTrigger(QueueNames.StatusLoop, Connection = "ServiceBusConnectionString")] Message msg,
            [ServiceBus(QueueNames.StatusLoop, Connection = "ServiceBusConnectionString")] IAsyncCollector <Message> statusLoop,
            [ServiceBus(QueueNames.StatusMessage, Connection = "ServiceBusConnectionString")] IAsyncCollector <Message> statusMessages,
            [Table(TableNames.Status, PartitionKeys.Status, "{CorrelationId}")] ImportStatusEntity status,
            [Table(TableNames.Status)] CloudTable table,
            [Table(TableNames.StatusProcess)] CloudTable statusProcTable,
            string correlationId,
            ILogger log)
        {
            await statusProcTable.CreateIfNotExistsAsync();

            await table.CreateIfNotExistsAsync();

            if (string.IsNullOrWhiteSpace(correlationId))
            {
                correlationId = Guid.NewGuid().ToString();
                log.LogWarning("CorrelationID is empty, generating a new one ({correlationId})", correlationId);
                return;
            }

            if (status == null)
            {
                log.LogWarning("Oops, the status entry of import ({correlationId}) could not be found", correlationId);
                return;
            }

            var statusUpdateCommand = msg.Convert <ImportStatusReportCommand>();
            var updateCounts        = await GetProcessingCountsAsync(correlationId, statusProcTable);

            status.TotalSucceeded    += updateCounts.Item1;
            status.TotalFailed       += updateCounts.Item2;
            status.LastModificationOn = DateTimeOffset.UtcNow;
            if (!status.CompletedOn.HasValue && status.TotalEntries == status.TotalFailed + status.TotalSucceeded)
            {
                status.CompletedOn = DateTimeOffset.UtcNow;
            }

            var operation = TableOperation.Replace(status);
            await table.ExecuteAsync(operation);

            try
            {
                var importStatus = new ImportStatusMessageDto
                {
                    TotalEntries  = status.TotalEntries,
                    ErrorMessage  = status.ErrorMessage,
                    CompletedOn   = status.CompletedOn,
                    CorrelationId = correlationId,
                    Failed        = status.TotalFailed,
                    StartedOn     = status.CreatedOn,
                    Succeeded     = status.TotalSucceeded
                };
                await statusMessages.AddAsync(importStatus.Convert(correlationId));

                if (updateCounts.Item1 > 0 || updateCounts.Item2 > 0)
                {
                    statusUpdateCommand.StopReportingAt = DateTimeOffset.UtcNow.AddMinutes(30);
                }

                if (!status.CompletedOn.HasValue && statusUpdateCommand.StopReportingAt.CompareTo(DateTimeOffset.UtcNow) > 0)
                {
                    await statusLoop.AddAsync(statusUpdateCommand.Convert(correlationId, 1));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Failed to send message to status update queueu");
            }

            await statusMessages.FlushAsync();

            await statusLoop.FlushAsync();

            log.LogInformation($"C# ServiceBus queue trigger function processed message: {msg}");
        }
示例#27
0
        private async void ProcessCloudSchedules(object sender, object e)
        {
            schedule.Tick -= ProcessCloudSchedules;
            // Create the table client.
            CloudTableClient scheduleTableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable scheduleTable = scheduleTableClient.GetTableReference("myschedules");

            // Create the table query.
            TableQuery <ScheduleCommand> scheduleQuery = new TableQuery <ScheduleCommand>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "ROOM1"));

            // Print the fields for each customer.
            // Initialize the continuation token to null to start from the beginning of the table.
            TableContinuationToken continuationToken = null;

            do
            {
                // Retrieve a segment (up to 1,000 entities).
                TableQuerySegment <ScheduleCommand> tableQueryResult =
                    await scheduleTable.ExecuteQuerySegmentedAsync(scheduleQuery, continuationToken);

                // Assign the new continuation token to tell the service where to
                // continue on the next iteration (or null if it has reached the end).
                continuationToken = tableQueryResult.ContinuationToken;

                foreach (ScheduleCommand entity in tableQueryResult)
                {
                    //Added 3 hours as offset between pi and est
                    if (entity.ScheduledTime <= DateTime.Now.AddHours(3))
                    {
                        TableOperation deleteOperation = TableOperation.Delete(entity);
                        if (entity.RelayId == "RELAY1" && entity.State == true)
                        {
                            FAN.Fill       = greenBrush;
                            StateText.Text = "Fan On";
                            TurnRelay1On();
                        }
                        else if (entity.RelayId == "RELAY1" && entity.State == false)
                        {
                            FAN.Fill       = grayBrush;
                            StateText.Text = "Fan Off";
                            TurnRelay1Off();
                        }
                        else if (entity.RelayId == "RELAY2" && entity.State == true)
                        {
                            LIGHT.Fill          = greenBrush;
                            StateTextlight.Text = "Light On";
                            TurnRelay2On();
                        }
                        else if (entity.RelayId == "RELAY2" && entity.State == false)
                        {
                            LIGHT.Fill          = grayBrush;
                            StateTextlight.Text = "Light Off";
                            TurnRelay2Off();
                        }
                        else
                        {
                            FAN.Fill            = redBrush;
                            LIGHT.Fill          = redBrush;
                            StateText.Text      = "Invalid Operation";
                            StateTextlight.Text = "Invalid Operation";
                        }
                        // Execute the operation.
                        await scheduleTable.ExecuteAsync(deleteOperation);
                    }
                }
            } while (continuationToken != null);


            schedule.Tick    += ProcessCloudSchedules;
            schedule.Interval = TimeSpan.FromMilliseconds(30000);
            schedule.Start();
        }
        public static async Task TemperatureCopAsync(
            [TimerTrigger("0 */10 * * * 1-5")] TimerInfo myTimer,
            [Table("ThermostatData", Connection = "StorageConnectionAppSetting")] CloudTable temperatureTable,
            [Table("ReportsTable", Connection = "StorageConnectionAppSetting")] CloudTable reportsTable,
            [Blob(ContainerName + "/" + TokenFileName, FileAccess.Read, Connection = "StorageConnectionAppSetting")] Stream inputBlob,
            TraceWriter log,
            ExecutionContext context)
        {
            log.Info($"Temperature Cop Timer trigger function executed at: {DateTime.Now}");

            IConfigurationRoot configurationRoot = ReadConfiguration(context);

            int    temperatureCheckRangeMinutes     = int.Parse(configurationRoot["RunCheckRangeMinutes"]);
            int    temperatureReportingRangeMinutes = int.Parse(configurationRoot["RunReportingRangeMinutes"]);
            double targetTemp   = double.Parse(configurationRoot["TargetValue"]);
            double comfortRange = double.Parse(configurationRoot["ComfortRange"]);

            double comfortMaxTemp = targetTemp + comfortRange;
            double comfortMinTemp = targetTemp - comfortRange;

            var dateFrom = DateTime.UtcNow.AddMinutes(-temperatureCheckRangeMinutes).ToString(DateTimeFormat);

            foreach (var device in configurationRoot["Nest.Devices"].Split(','))
            {
                // Get the latests lectures
                var query = new TableQuery <ThermostatData>()
                            .Where(
                    TableQuery.CombineFilters(
                        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, device),
                        TableOperators.And,
                        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, dateFrom)));

                var result = await temperatureTable.ExecuteQueryAsync <ThermostatData>(query);

                if (result != null && result.Any())
                {
                    // If all readings are below/above comfort temperature
                    var tooHot  = result.All(x => x.AmbientTemperatureC > comfortMaxTemp);
                    var tooCold = result.All(x => x.AmbientTemperatureC < comfortMinTemp);

                    if (tooHot || tooCold)
                    {
                        var currentTemp = result.OrderBy(x => x.RowKey).Last().AmbientTemperatureC;
                        var message     = new TemperatureNotification()
                        {
                            DeviceId                = device,
                            NotificationType        = tooHot ? TemperatureNotificationType.Hot : TemperatureNotificationType.Cold,
                            ComfortTemperatureMax   = comfortMaxTemp,
                            ComfortTemperatureMin   = comfortMinTemp,
                            CurrentTemperature      = currentTemp,
                            EvaluationPeriodMinutes = temperatureReportingRangeMinutes,
                            RowKey       = DateTime.UtcNow.ToString(DateTimeFormat),
                            PartitionKey = device
                        };

                        // Check if a report has recently sent in the last minutes
                        var notificationType = Enum.GetName(typeof(TemperatureNotificationType), message.NotificationType);

                        log.Info($"Temperature out of range detected for device {message.DeviceId}, Notification Type {notificationType}.");

                        var reportDateFrom     = DateTime.UtcNow.AddMinutes(-temperatureReportingRangeMinutes).ToString(DateTimeFormat);
                        var latestReportsQuery = new TableQuery <TemperatureNotification>()
                                                 .Where(
                            TableQuery.CombineFilters(
                                TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, device),
                                TableOperators.And,
                                TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, dateFrom)));

                        var latestReports = await reportsTable.ExecuteQueryAsync <TemperatureNotification>(latestReportsQuery);

                        if (!latestReports.Any(x => x.NotificationType == message.NotificationType))
                        {
                            await ReportTemperatureIssue(configurationRoot, message, log);

                            await reportsTable.ExecuteAsync(TableOperation.Insert(message));
                        }
                        else
                        {
                            log.Info($"Temperature {notificationType} has been already reported in the last {temperatureReportingRangeMinutes} minutes.");
                        }
                    }
                }
            }
        }
        public async Task <ImageModel> GetAsync(string id)
        {
            TableResult tableResult = await cloudTable.ExecuteAsync(TableOperation.Retrieve <ImageModel>(this.userNameProvider.UserName, id));

            return((ImageModel)tableResult.Result);
        }
示例#30
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(
                 AuthorizationLevel.Function,
                 "post",
                 Route = "categories/add/{login}/")
            ] HttpRequestMessage req,
            string login,
            [Table("ExpensesApp")] CloudTable table,
            [Table("ExpensesApp", "user_{login}", "user_{login}")] UserLogInData entity,
            TraceWriter log)
        {
            if (entity == null)
            {
                log.Info($"AddCategory response: BadRequest - no such user");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "User with given login does not exist"
                           ));
            }


            AddCategoryDto dto = null;

            try
            {
                dto = await req.Content.ReadAsDeserializedJson <AddCategoryDto>();
            }
            catch
            {
                log.Info("AddCategory response: BadRequest - cannot read dto object");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "Please pass a valid dto object in the request content"));
            }


            var newCategory = new Category()
            {
                Name   = dto.Name,
                Factor = dto.Factor
            };

            var householdId = entity.HouseholdId;
            var retrieveHouseholdOperation = TableOperation.Retrieve <Household>(householdId, householdId);
            var householdResult            = await table.ExecuteAsync(retrieveHouseholdOperation);

            if (householdResult.Result != null)
            {
                var household = householdResult.Result as Household;

                if (newCategory.Factor == null)
                {
                    var members = JsonConvert.DeserializeObject <List <Member> >(household.Members);
                    var factor  = new Dictionary <string, double>();
                    foreach (var member in members)
                    {
                        if (member.Login == login)
                        {
                            factor.Add(member.Login, 100);
                        }
                        else
                        {
                            factor.Add(member.Login, 0);
                        }
                    }
                    newCategory.Factor = factor;
                }

                var categories = JsonConvert.DeserializeObject <List <Category> >(household.CategoriesAggregated);
                categories.Add(newCategory);
                household.CategoriesAggregated = JsonConvert.SerializeObject(categories);
                var updateTableOperation = TableOperation.Replace(household);
                await table.ExecuteAsync(updateTableOperation);
            }
            else
            {
                var retrieveUsersOwnCategories = TableOperation.Retrieve <UserDetails>(householdId, entity.PartitionKey);
                var userDetailsResult          = await table.ExecuteAsync(retrieveUsersOwnCategories);

                if (userDetailsResult.Result != null)
                {
                    var userDetails = userDetailsResult.Result as UserDetails;
                    var categories  = JsonConvert.DeserializeObject <List <Category> >(userDetails.Categories);

                    if (newCategory.Factor == null)
                    {
                        newCategory.Factor = new Dictionary <string, double>()
                        {
                            { login, 100 }
                        };
                    }

                    categories.Add(newCategory);
                    userDetails.Categories = JsonConvert.SerializeObject(categories);
                    var updateTableOperation = TableOperation.Replace(userDetails);
                    await table.ExecuteAsync(updateTableOperation);
                }
                else
                {
                    log.Info($"AddCategory response: InternalServerError - user does not have categories neither in household nor in user detailed info");
                    return(req.CreateResponse(
                               statusCode: HttpStatusCode.InternalServerError,
                               value: "Cannot get categories"
                               ));
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }