public static Task SaveState_BindToJObject_AllFields(
     JObject saveStateParameters,
     [DaprState("{saveStateParameters.stateStore}")] IAsyncCollector <JObject> state)
 {
     return(state.AddAsync(saveStateParameters));
 }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = Config.Http.Route)] HttpRequestMessage req,
            [CosmosDBTrigger(Config.Cosmos.Db, Config.Cosmos.Events.Collection,
                             ConnectionStringSetting = Config.Cosmos.DbConnectionStringSetting)] IAsyncCollector <Command> commandsOut,

            ILogger log)
        {
            var correlationId = Guid.NewGuid().ToString();
            // Deserialize & Validate
            UpdateRequest request = null;

            try
            {
                request = await req.Content.ReadAsAsync <UpdateRequest>();

                log.LogInformation(Config.Logging.GetEventId(Config.Logging.EventType.ValidationSucceeded),
                                   Config.Logging.Template,
                                   Config.Logging.Trigger.Http.ToString(),
                                   correlationId,
                                   nameof(UpdateRequest),
                                   null,
                                   $"CreateWineEntryRequest {JsonConvert.SerializeObject(request)}");
            }
            catch (Exception ex)
            {
                log.LogError(Config.Logging.GetEventId(Config.Logging.EventType.ValidationSucceeded),
                             ex,
                             Config.Logging.Template,
                             Config.Logging.Trigger.Http.ToString(),
                             correlationId,
                             nameof(UpdateRequest),
                             null,
                             $"CreateWineEntryRequest {JsonConvert.SerializeObject(request)}");
            }

            // Convert to commands
            Command command = null;

            try
            {
                command = new Command(Guid.NewGuid(), 0, EventName.WineEntryCreated, new JObject(request));
                log.LogInformation(Config.Logging.GetEventId(Config.Logging.EventType.ProcessingSucceeded),
                                   Config.Logging.Template,
                                   Config.Logging.Trigger.Http.ToString(),
                                   correlationId,
                                   nameof(Command),
                                   command.AggregateId,
                                   $"Command {JsonConvert.SerializeObject(command)}");

                // Write commands to data store
                await commandsOut.AddAsync(command);
            }
            catch (Exception ex)
            {
                log.LogError(Config.Logging.GetEventId(Config.Logging.EventType.ProcessingFailedUnhandledException),
                             ex,
                             Config.Logging.Template,
                             Config.Logging.Trigger.Http.ToString(),
                             correlationId,
                             nameof(Command),
                             command?.AggregateId,
                             ex.Message);
            }

            // return
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
        public Task Send(Message message)
        {
            LogContext.Debug?.Log("Sending message: {MessageId}", message.MessageId);

            return(_collector.AddAsync(message, _cancellationToken));
        }
        private static async Task <IActionResult> GetMethod(
            IAsyncCollector <string> console,
            IDurableClient client,
            string name,
            string target)
        {
            if (string.IsNullOrEmpty(target))
            {
                await console.AddAsync($"User {name} tried to get nothing.");

                return(new BadRequestObjectResult("Target is required."));
            }
            var room = await name.GetEntityForUserOrThrow <Room>(client);

            if (room.InventoryList.Contains(target))
            {
                // room loses inventory
                await client.SignalEntityAsync <IRoomOperations>(
                    name.AsEntityIdFor <Room>(),
                    operation => operation.RemoveInventory(target));

                // user gains inventory
                await client.SignalEntityAsync <IUserOperations>(
                    name.AsEntityIdFor <User>(),
                    operation => operation.AddInventory(target));

                // inventory moves to user
                await client.SignalEntityAsync <IInventoryOperations>(
                    name.AsEntityIdFor <Inventory>(target),
                    operation => operation.SetUser());

                var list = await name.GetEntityForUserOrThrow <InventoryList>(client);

                var inventoryList = await list.DeserializeListForUserWithClient(name, client);

                var inventory = inventoryList.Where(i => i.Name == target)
                                .Select(i => i).First();

                await console.AddAsync($"User {name} successfully grabbed {target}.");

                if (inventory.IsTreasure)
                {
                    await console.AddAsync($"User {name} nabbed the treasure.");

                    var gameMonitor = await Global.FindJob(
                        client,
                        DateTime.UtcNow,
                        nameof(MonitorFunctions.GameMonitorWorkflow),
                        name,
                        true,
                        false);

                    if (gameMonitor != null)
                    {
                        await client.RaiseEventAsync(gameMonitor.InstanceId,
                                                     MonitorFunctions.GOTTREASURE);
                    }
                }
                return(new OkResult());
            }
            else
            {
                await console.AddAsync($"User {name} tried to get a {target} that wasn't there.");

                return(new BadRequestObjectResult("Target not found."));
            }
        }
Exemple #5
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [Table("TemperatureHumidity")] out TemperatureHumidityReading output,
            [SignalR(HubName = "climate")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            req.FixCorsHeaders();

            output = null;

            string requestBody;

            try
            {
                requestBody = new StreamReader(req.Body).ReadToEnd();
            }
            catch (Exception e)
            {
                log.LogWarning(e, "Could not read the body of the request");
                return(new BadRequestObjectResult("Could not read the body of the request"));
            }

            TemperatureHumidityInput input;

            try
            {
                input = JsonConvert.DeserializeObject <TemperatureHumidityInput>(requestBody);
            }
            catch (Exception e)
            {
                log.LogWarning(e, "The received json data ({Json}) could not be parsed", requestBody);
                return(new BadRequestObjectResult("The received json data could not be parsed"));
            }

            if (string.IsNullOrWhiteSpace(input.SensorId))
            {
                log.LogWarning("Sensor id missing");
                return(new BadRequestObjectResult("Sensor id missing"));
            }

            var readAtUtc = DateTimeOffset.UtcNow;

            output = new TemperatureHumidityReading
            {
                PartitionKey = input.SensorId,
                RowKey       = readAtUtc.ToRowKey(),
                ReadAtUtc    = readAtUtc,
                Temperature  = input.Temperature,
                Humidity     = input.Humidity
            };

            signalRMessages.AddAsync(
                new SignalRMessage
            {
                Target    = "notifyTemperatureHumidityUpdated",
                Arguments = new object[] { new
                                           {
                                               sensorId      = input.SensorId,
                                               timestampWest = DateTimeOffsetHelper.ConvertToWest(readAtUtc),
                                               temperature   = input.Temperature,
                                               humidity      = input.Humidity
                                           } }
            }).Wait();

            return(new OkResult());
        }
 public static void SendAsyncCollectorString([FakeQueue] IAsyncCollector <string> collector)
 {
     collector.AddAsync("first").Wait();
     collector.AddAsync("second").Wait();
 }
Exemple #7
0
        public async Task RunAsync(
            DateTime importStartDate,
            DateTime importEndDate,
            IAsyncCollector <DayInfo> changesPerDayCollection,
            IAsyncCollector <ProcessDayInfoForTitlesJobWorkerData> outputTitleWorkerStorage,
            IAsyncCollector <ProcessDayInfoForTitlesJob> outputTitleQueue,
            TraceWriter log)
        {
            // TODO: improve
            // https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
            // https://developer.github.com/v3/#timezones
            var commits = await _gitHubClient.Repository.Commit.GetAll(GitHubOwner, GitHubRepName,
                                                                       new CommitRequest { Since = importStartDate, Until = importEndDate }
                                                                       );

            log.Info($"Processing {commits.Count} commits");

            var commitsPerDays = commits.GroupBy(_ => _.Commit.Committer.Date.UtcDateTime.Date);

            log.Info($"Processing {commitsPerDays.Count()} days");

            foreach (var commitsPerDay in commitsPerDays)
            {
                var dayInfo = new DayInfo
                {
                    Id                 = commitsPerDay.Key,
                    Date               = commitsPerDay.Key,
                    DocChanges         = new List <DocChange>(),
                    DeepLinksGenerated = true
                };


                foreach (var commitOverview in commitsPerDay)
                {
                    var commitDetail = await _gitHubClient.Repository.Commit.Get(GitHubOwner, GitHubRepName, commitOverview.Sha);

                    foreach (var file in commitDetail.Files)
                    {
                        AddOrModifyFileChange(commitDetail.Sha, commitDetail.Parents.FirstOrDefault()?.Sha, file, dayInfo.DocChanges, commitOverview.Commit.Committer.Date.UtcDateTime, log);
                    }
                }

                if (dayInfo.DocChanges.Count > 0)
                {
                    await changesPerDayCollection.AddAsync(dayInfo);

                    var filesToProcess = GetAllFiles(dayInfo);
                    if (filesToProcess.Count > 0)
                    {
                        await outputTitleWorkerStorage.AddAsync(new ProcessDayInfoForTitlesJobWorkerData
                        {
                            DayInfoId      = dayInfo.Date,
                            FilesToProcess = filesToProcess,
                        });

                        await outputTitleQueue.AddAsync(new ProcessDayInfoForTitlesJob()
                        {
                            DayInfoId = dayInfo.Date
                        });
                    }

                    log.Info($"Processed {dayInfo.DocChanges.Count} DocChanges for {dayInfo.Date}");
                }
                else
                {
                    log.Info($"No DocChanges for {dayInfo.Date}");
                }
            }

            await changesPerDayCollection.FlushAsync();
        }
Exemple #8
0
        public static async Task Run([TimerTrigger("0 0 0 * * *")] TimerInfo myTimer,
                                     [CosmosDB(
                                          databaseName: "Shared-Free",
                                          collectionName: "V1-pmdboard",
                                          ConnectionStringSetting = "CosmosDBConnection",
                                          Id = "internal-Pokémon-Blue-Rescue-Team",
                                          PartitionKey = "internal-Pokémon-Blue-Rescue-Team"
                                          )] V1GameMetadata runInfo,
                                     [CosmosDB(
                                          databaseName: "Shared-Free",
                                          collectionName: "V1-pmdboard",
                                          ConnectionStringSetting = "CosmosDBConnection"
                                          )] IAsyncCollector <V1CombinedRuns> entries,
                                     ILogger log)
        {
            log.LogInformation($"BRT Updater function started execution at: {DateTime.Now}");

            var gameInfo = new V1CombinedRuns
            {
                id         = "gameinfo-BRT",
                Title      = "Pokémon Mystery Dungeon: Blue Rescue Team",
                Categories = new List <Category>()
            };

            //Category format: xxxxxxxx-Category Name
            //Platform format: xxxxxxxx-Platform Name
            //Language format: xxxxxxxx-ENG/JPN
            foreach (var category in runInfo.Categories)
            {
                var categoryInfo     = category.Split('-');
                var internalCategory = new Category
                {
                    Name = categoryInfo[1],
                    Runs = new List <InternalRun>()
                };

                foreach (var platform in runInfo.Platforms)
                {
                    var platformInfo = platform.Split('-');

                    foreach (var language in runInfo.Languages)
                    {
                        var languageInfo = language.Split('-');

                        string url = $"https://speedrun.com/api/v1/leaderboards/{runInfo.GameID}/category/{categoryInfo[0]}?var-{runInfo.PlatformID}={platformInfo[0]}&var-{runInfo.LanguageID}={languageInfo[0]}&top=1&embed=players";
                        log.LogInformation(url);

                        var response = await FunctionHttpClient.httpClient.GetAsync(url);

                        var resStream = await response.Content.ReadAsStreamAsync();

                        Response result = await JsonSerializer.DeserializeAsync <Response>(resStream);

                        if (response.IsSuccessStatusCode)
                        {
                            if (result.ResponseBody.Players.PlayerList.Count > 0 && result.ResponseBody.RunList.Count > 0)
                            {
                                // Check whether the player is a guest or not
                                string playerName;
                                if (string.Equals(result.ResponseBody.Players.PlayerList[0].Role, "guest", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    var jsonString = await response.Content.ReadAsStringAsync();

                                    playerName = Utils.GetGuestUser(jsonString);
                                }
                                else
                                {
                                    playerName = !string.IsNullOrEmpty(result.ResponseBody.Players.PlayerList[0].Names.Name) ?
                                                 result.ResponseBody.Players.PlayerList[0].Names.Name :
                                                 result.ResponseBody.Players.PlayerList[0].Names.NameJP;
                                }

                                var runTime = result.ResponseBody.RunList[0].Run.Times.PrimaryTime;
                                var runDate = result.ResponseBody.RunList[0].Run.RunDate;
                                var srcID   = result.ResponseBody.RunList[0].Run.Id;

                                var internalRow = new InternalRun
                                {
                                    Platform = platformInfo[1],
                                    Language = languageInfo[1],
                                    Version  = string.Empty,
                                    Runner   = playerName,
                                    RunDate  = runDate,
                                    RunTime  = runTime,
                                    SRCLink  = srcID
                                };
                                internalCategory.Runs.Add(internalRow);
                            }
                        }
                        else
                        {
                            log.LogError($"Request to {url} failed. Error code: {response.StatusCode}");
                        }
                    }
                }
                gameInfo.Categories.Add(internalCategory);
            }
            await entries.AddAsync(gameInfo);
        }
Exemple #9
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "UserInformation",
                 collectionName: "UserInformation",
                 ConnectionStringSetting = "UserInformationDBConnection")] DocumentClient outputTable,
            [Queue("NewUserInformations")] IAsyncCollector <KeyValuePair <string, string> > outputQueue,
            ILogger log)
        {
            log.LogInformation("Try to add a new question.");
            Shared.Models.UserInformation userToSave = null;
            try
            {
                userToSave = await System.Text.Json.JsonSerializer.DeserializeAsync <Shared.Models.UserInformation>(req.Body,
                                                                                                                    new JsonSerializerOptions()
                {
                    AllowTrailingCommas = true,
                }
                                                                                                                    );
            }
            catch (System.Text.Json.JsonException ex)
            {
                return(new BadRequestObjectResult($"There was an error in the provided json: {ex.Message} -> {ex.InnerException.Message}"));
            }
            if (userToSave.RiskScore != null)
            {
                userToSave.RiskScore = null;
            }
            userToSave.Token  = TokenGenerator.GenerateToken();
            userToSave.Source = "covapp.charite";
            await outputTable.CreateDatabaseIfNotExistsAsync(new Database()
            {
                Id = "UserInformation"
            });

            await outputTable.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("UserInformation"), new DocumentCollection()
            {
                Id           = "UserInformation",
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string>()
                    {
                        "/Source"
                    }
                },
                UniqueKeyPolicy = new UniqueKeyPolicy()
                {
                    UniqueKeys = new Collection <UniqueKey>()
                    {
                        new UniqueKey()
                        {
                            Paths = new Collection <string>()
                            {
                                "/Token"
                            }
                        }
                    }
                }
            });

            await outputTable.CreateDocumentAsync("dbs/UserInformation/colls/UserInformation", userToSave);

            await outputQueue.AddAsync(userToSave.GetIdentifier());

            return(new OkObjectResult(userToSave.Token));
        }
        //[return: ServiceBus("fundingallocationqueue", Connection = "ServiceBusConnection")]
        //public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                                                     [ServiceBus("logappfundingallocationqueue", Connection = "ServiceBusConnection")] IAsyncCollector <dynamic> logicAppOutputQueue,
                                                     [ServiceBus("fundingallocationqueue", Connection = "ServiceBusConnection")] IAsyncCollector <dynamic> bizTalkOutputQueue,
                                                     ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string id = req.Query["id"];
            //string issueType = req.Query["issueType"];
            //string issueDescription = req.Query["issueDescription"];
            //string geoLatCoordinate = req.Query["geoLatCoordinate"];
            //string geoLongCoordinate = req.Query["geoLongCoordinate"];
            //string uploadUserName = req.Query["uploadUserName"];
            //string sendToBizTalk = req.Query["sendToBizTalk"];

            string  requestBody   = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data          = JsonConvert.DeserializeObject(requestBody);
            string  id            = data.id;
            bool    sendToBizTalk = data.sendToBizTalk;

            //issueType = issueType ?? data?.issueType;
            //issueDescription = issueDescription ?? data?.issueDescription;
            //geoLatCoordinate = geoLatCoordinate ?? data?.geoLatCoordinate;
            //geoLongCoordinate = geoLongCoordinate ?? data?.geoLongCoordinate;
            //uploadUserName = uploadUserName ?? data?.uploadUserName;

            ImageMetadata imageData         = new ImageMetadata();
            string        sourceStorage     = Environment.GetEnvironmentVariable("NewImageSourceStorage");
            string        destStorage       = Environment.GetEnvironmentVariable("ValidImageDestStorage");
            string        metaContainerName = Environment.GetEnvironmentVariable("ImageMetadataContainer");

            string metaname = id + ".json";

            try
            {
                CloudStorageAccount sourceStorageAccount = CloudStorageAccount.Parse(sourceStorage);
                CloudBlobClient     metaBlobClient       = sourceStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer  metaContainer        = metaBlobClient.GetContainerReference(metaContainerName);
                CloudBlockBlob      metaBlob             = metaContainer.GetBlockBlobReference(metaname);
                bool metaBlobExists = await metaBlob.ExistsAsync();

                if (metaBlobExists)
                {
                    string jsonMetaData = await metaBlob.DownloadTextAsync();

                    imageData = JsonConvert.DeserializeObject <ImageMetadata>(jsonMetaData);
                    log.LogInformation("Image Metadata timestamp: " + imageData.timestamp + " uploadedFileName: " + imageData.uploadedFileName);
                }
                else
                {
                    log.LogInformation("No Metadata exists for uploaded image. Exiting Process.");
                    throw new System.InvalidOperationException("Image has not yet been validated");
                }

                string blobName = imageData.uploadedFileName;

                string             imageContainerName = Environment.GetEnvironmentVariable("ImageContainerName");
                CloudBlobClient    imageBlobClient    = sourceStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer imageContainer     = imageBlobClient.GetContainerReference(imageContainerName);
                CloudBlockBlob     imageBlob          = imageContainer.GetBlockBlobReference(blobName);
                bool imageBlobExists = await imageBlob.ExistsAsync();

                if (imageBlobExists)
                {
                    log.LogInformation("Moving Blob: " + blobName + " to ProcessedImages container for further actions.");
                    CloudStorageAccount destStorageAccount = CloudStorageAccount.Parse(destStorage);
                    CloudBlobClient     destBlobClient     = destStorageAccount.CreateCloudBlobClient();
                    string             destContainerName   = Environment.GetEnvironmentVariable("ValidImageDestContainer");
                    CloudBlobContainer destContainer       = destBlobClient.GetContainerReference(destContainerName);
                    await destContainer.CreateIfNotExistsAsync();

                    string         ext          = Path.GetExtension(blobName);
                    CloudBlockBlob newImageBlob = destContainer.GetBlockBlobReference(imageData.id + ext);
                    await newImageBlob.StartCopyAsync(imageBlob);

                    string blobUrl = newImageBlob.StorageUri.PrimaryUri.AbsoluteUri;
                    log.LogInformation("Blob Url: " + blobUrl);
                    await imageBlob.DeleteIfExistsAsync();

                    imageData.blobUrl           = blobUrl;
                    imageData.issueType         = data.issueType;
                    imageData.issueDescription  = data.issueDescription;
                    imageData.geoLatCoordinate  = data.geoLatCoordinate;
                    imageData.geoLongCoordinate = data.geoLongCoordinate;
                    imageData.uploadUserName    = data.uploadUserName;

                    string issueType = data.issueType;
                    imageData.issueComplexity = getIssueComplexity(blobUrl, issueType);
                    imageData.issueUrgency    = getIssueUrgency(blobUrl, issueType);

                    string metaJson = System.Text.Json.JsonSerializer.Serialize <ImageMetadata>(imageData);
                    await metaBlob.UploadTextAsync(metaJson);
                }
                else
                {
                    throw new FileNotFoundException("Blob: " + blobName + " does not exist in container: " + imageContainer + ".");
                }
            }
            catch (Exception ex)
            {
                log.LogInformation($"Error! Something went wrong: {ex.Message}");
            }

            log.LogInformation($"sendToBizTalk Value: {sendToBizTalk}");

            if (sendToBizTalk == true)
            {
                log.LogInformation("Sending to BizTalk FundingAllocationQueue");
                await bizTalkOutputQueue.AddAsync(imageData);
            }
            else
            {
                log.LogInformation("Sending to LogicApp ValidImageQueue");
                await logicAppOutputQueue.AddAsync(imageData);
            }

            string responseMessage = "Ok";

            //return imageData;
            return(new OkObjectResult(responseMessage));
        }
        public static async Task Run([ServiceBusTrigger(Utils.PURGE_QUEUE_NAME, Connection = "ServiceBusConnection")] Message message, MessageReceiver messageReceiver, string lockToken,
                                     [ServiceBus(Utils.PURGE_QUEUE_NAME, Connection = "ServiceBusConnection", EntityType = EntityType.Queue)] IAsyncCollector <Message> queueCollector,
                                     [ServiceBus(Utils.REGISTRATION_QUEUE_NAME, Connection = "ServiceBusConnection", EntityType = EntityType.Queue)] IAsyncCollector <Message> registrationQueueCollector,
                                     ILogger log)
        {
            var feedStateItem = FeedState.DecodeFromMessage(message);

            log.LogInformation($"Purge Trigger Started: {feedStateItem.name}");

            try
            {
                int itemCount = 0;

                var sw = new Stopwatch();
                sw.Start();

                using (var db = new Database(SqlUtils.SqlDatabaseConnectionString, DatabaseType.SqlServer2012, SqlClientFactory.Instance))
                {
                    itemCount = await db.ExecuteAsync("DELETE_SOURCE @0", feedStateItem.name);
                }

                sw.Stop();

                log.LogWarning($"PURGE TIMER {feedStateItem.name}: Deleted {itemCount} items from source '{feedStateItem.name}' in {sw.ElapsedMilliseconds} ms");

                feedStateItem.purgedItems = itemCount;

                if (itemCount < 1000)
                {
                    log.LogInformation($"Purge complete for '{feedStateItem.name}'");

                    // Check lock exists, as close to a transaction as we can get
                    if (await messageReceiver.RenewLockAsync(lockToken) != null)
                    {
                        await messageReceiver.CompleteAsync(lockToken);

                        // Attempt re-registration unless the proxy cache is being cleared
                        if (Environment.GetEnvironmentVariable("ClearProxyCache")?.ToString() != "true")
                        {
                            feedStateItem.ResetCounters();
                            feedStateItem.totalPurgeCount++;
                            await registrationQueueCollector.AddAsync(feedStateItem.EncodeToMessage(1));
                        }
                        else
                        {
                            log.LogWarning($"Purge Successfully Cleaned: {feedStateItem.name}");
                        }
                    }
                }
                else
                {
                    feedStateItem.purgedItems += itemCount;

                    // Check lock exists, as close to a transaction as we can get
                    if (await messageReceiver.RenewLockAsync(lockToken) != null)
                    {
                        await messageReceiver.CompleteAsync(lockToken);

                        await queueCollector.AddAsync(feedStateItem.EncodeToMessage(1));
                    }
                }
            }
            catch (SqlException ex)
            {
                log.LogError($"Error during DELETE_SOURCE stored procedure {ex.Number}: " + ex.ToString());

                feedStateItem.lastError = ex.ToString();

                feedStateItem.purgeRetries++;

                TimeSpan timeSpan   = new TimeSpan(1, 0, 0);
                Random   randomTest = new Random();
                TimeSpan newSpan    = TimeSpan.FromMinutes(randomTest.Next(0, (int)timeSpan.TotalMinutes));

                int delaySeconds = (int)newSpan.TotalSeconds;

                log.LogWarning($"Unexpected error purging items: Retrying '{feedStateItem.name}' attempt {feedStateItem.purgeRetries} in {delaySeconds} seconds");

                // Check lock exists, as close to a transaction as we can get
                if (await messageReceiver.RenewLockAsync(lockToken) != null)
                {
                    await messageReceiver.CompleteAsync(lockToken);

                    await queueCollector.AddAsync(feedStateItem.EncodeToMessage(delaySeconds));
                }
            }

            log.LogInformation($"Purge Trigger Complete: {feedStateItem.name}");
        }
Exemple #12
0
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
            [SignalR(HubName = "chat")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            var serializedObject = new JsonSerializer()
                                   .Deserialize(new JsonTextReader(new StreamReader(req.Body)));

            var message =
                JsonConvert
                .DeserializeObject <ChatMessage>(serializedObject.ToString());

            if (message.TypeInfo.Name == nameof(UserConnectedMessage))
            {
                message = JsonConvert
                          .DeserializeObject <UserConnectedMessage>(serializedObject.ToString());
                await signalRMessages.AddAsync(
                    new SignalRMessage
                {
                    GroupName = message.GroupName,
                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                });
            }
            else if (message.TypeInfo.Name == nameof(SimpleTextMessage))
            {
                message = JsonConvert
                          .DeserializeObject <SimpleTextMessage>(serializedObject.ToString());
                var signalRMessage = new SignalRMessage
                {
                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                };
                if (message.GroupName != null)
                {
                    signalRMessage.GroupName = message.GroupName;
                }
                else if (message.Recipient != null)
                {
                    signalRMessage.UserId = message.Recipient;
                }

                await signalRMessages.AddAsync(signalRMessage);
            }
            else if (message.TypeInfo.Name == nameof(PhotoMessage))
            {
                var photoMessage =
                    JsonConvert
                    .DeserializeObject <PhotoMessage>(serializedObject.ToString());
                var bytes =
                    Convert.FromBase64String(photoMessage.Base64Photo);

                var url = await StorageHelper.Upload(bytes, photoMessage.FileEnding);

                message = new PhotoUrlMessage(photoMessage.Sender)
                {
                    Id        = photoMessage.Id,
                    Timestamp = photoMessage.Timestamp,
                    Url       = url,
                    IsFile    = photoMessage.IsFile
                };

                await signalRMessages.AddAsync(
                    new SignalRMessage
                {
                    UserId = message.Recipient,

                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                });
            }
            else if (message.TypeInfo.Name == nameof(VideoMessage))
            {
                var photoMessage =
                    JsonConvert
                    .DeserializeObject <VideoMessage>(serializedObject.ToString());
                var bytes =
                    Convert.FromBase64String(photoMessage.Base64Photo);

                var url = await StorageHelper.Upload(bytes, photoMessage.FileEnding);

                message = new VideoMessage(photoMessage.Sender)
                {
                    Id         = photoMessage.Id,
                    Timestamp  = photoMessage.Timestamp,
                    IsVideo    = photoMessage.IsVideo,
                    VideoImage = photoMessage.VideoImage,
                    VideoUrl   = photoMessage.VideoUrl
                };

                await signalRMessages.AddAsync(
                    new SignalRMessage
                {
                    UserId = message.Recipient,

                    Target    = "ReceiveMessage",
                    Arguments = new[] { message }
                });
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request,
            [CosmosDB(databaseName: Constants.DATABASE_NAME, collectionName: Constants.PLANETS_COLLECTION_NAME, ConnectionStringSetting = Constants.CONNECTION_STRING_SETTING, CreateIfNotExists = true)] IAsyncCollector <Planet> planetsCollector,
            [CosmosDB(databaseName: Constants.DATABASE_NAME, collectionName: Constants.CHARACTERS_COLLECTION_NAME, ConnectionStringSetting = Constants.CONNECTION_STRING_SETTING, CreateIfNotExists = true)] IAsyncCollector <Character> charactersCollector)
        {
            await planetsCollector.AddAsync(new Planet { WorldId = 1, Name = "Tatooine" });

            await planetsCollector.AddAsync(new Planet { WorldId = 2, Name = "Alderaan" });

            await planetsCollector.AddAsync(new Planet { WorldId = 8, Name = "Naboo" });

            await planetsCollector.AddAsync(new Planet { WorldId = 10, Name = "Kamino" });

            await planetsCollector.AddAsync(new Planet { WorldId = 14, Name = "Kashyyyk" });

            await planetsCollector.AddAsync(new Planet { WorldId = 20, Name = "Stewjon" });

            await planetsCollector.AddAsync(new Planet { WorldId = 21, Name = "Eriadu" });

            await planetsCollector.AddAsync(new Planet { WorldId = 22, Name = "Corellia" });

            await planetsCollector.AddAsync(new Planet { WorldId = 23, Name = "Rodia" });

            await planetsCollector.AddAsync(new Planet { WorldId = 24, Name = "Nal Hutta" });

            await planetsCollector.AddAsync(new Planet { WorldId = 26, Name = "Bestine IV" });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Luke Skywalker", BirthYear = "19BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "C-3PO", BirthYear = "112BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "R2-D2", BirthYear = "33BBY", HomeworldId = 8 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Darth Vader", BirthYear = "41.9BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Leia Organa", BirthYear = "19BBY", HomeworldId = 2 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Owen Lars", BirthYear = "52BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Beru Whitesun Lars", BirthYear = "47BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "R5-D4", BirthYear = "Unknown", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Biggs Darklighter", BirthYear = "24BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Obi-Wan Kenobi", BirthYear = "57BBY", HomeworldId = 20 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Anakin Skywalker", BirthYear = "41.9BBY", HomeworldId = 1 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Wilhuff Tarkin", BirthYear = "64BBY", HomeworldId = 21 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Chewbacca", BirthYear = "200BBY", HomeworldId = 14 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Han Solo", BirthYear = "29BBY", HomeworldId = 22 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Greedo", BirthYear = "44BBY", HomeworldId = 23 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Jabba Desilijic Tiure", BirthYear = "600BBY", HomeworldId = 24 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Wedge Antilles", BirthYear = "21BBY", HomeworldId = 22 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Jek Tono Porkins", BirthYear = "Unknown", HomeworldId = 26 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Palpatine", BirthYear = "82BBY", HomeworldId = 8 });

            await charactersCollector.AddAsync(new Character { CharacterId = Guid.NewGuid().ToString("N"), Name = "Boba Fett", BirthYear = "31.5BBY", HomeworldId = 10 });

            return(new OkResult());
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [CosmosDB("vnaaats-net", "flights",
                      ConnectionStringSetting = "DbConnectionString")] IAsyncCollector <object> flights,
            ILogger log)
        {
            try {
                // Deserialise the request
                string callsign      = req.Query["callsign"];
                string ac_type       = req.Query["type"];
                int    assignedLevel = Convert.ToInt32(req.Query["level"]);
                int    assignedMach  = Convert.ToInt32(req.Query["mach"]);
                string track         = req.Query["track"];
                string route         = req.Query["route"];
                string routeEtas     = req.Query["routeEtas"];
                string departure     = req.Query["departure"];
                string arrival       = req.Query["arrival"];
                bool   direction     = req.Query["direction"] == "1" ? true : false;
                string etd           = req.Query["etd"];
                string selcal        = req.Query["selcal"];
                bool   datalink      = req.Query["connected_datalink"] == "1" ? true : false;
                if (string.IsNullOrWhiteSpace(req.Query["connectedDatalink"]))
                {
                    datalink = false;
                }
                else
                {
                    datalink = req.Query["datalink"] == "1" ? true : false;
                }
                bool   isEquipped = req.Query["isEquipped"] == "1" ? true : false;
                string state      = req.Query["state"];

                bool       relevant   = req.Query["relevant"] == "1" ? true : false;
                TargetMode targetMode = (TargetMode)Convert.ToInt32(req.Query["targetMode"]);
                string     trackedBy  = req.Query["trackedBy"];
                string     trackedId  = req.Query["trackedById"];

                // Create data object
                FlightData fdata = new FlightData
                {
                    callsign          = callsign,
                    type              = ac_type,
                    etd               = etd,
                    assignedLevel     = assignedLevel,
                    assignedMach      = assignedMach,
                    track             = track,
                    route             = route,
                    routeEtas         = routeEtas,
                    departure         = departure,
                    arrival           = arrival,
                    direction         = direction,
                    selcal            = selcal,
                    datalinkConnected = datalink,
                    isEquipped        = isEquipped,
                    state             = state,
                    relevant          = relevant,
                    targetMode        = targetMode,
                    trackedBy         = trackedBy,
                    trackedById       = trackedId,
                    lastUpdated       = DateTime.UtcNow
                };

                // Add data object
                await flights.AddAsync(fdata);

                // Log and return success code
                log.LogInformation($"Item {fdata.callsign} inserted successfully.");
                return(new StatusCodeResult(StatusCodes.Status200OK));
            }
            catch (Exception ex)
            {
                // Catch any errors
                log.LogError($"Could not insert flight data. Exception thrown: {ex.Message}.");
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task Run([QueueTrigger("messagetomom", Connection = "AzureWebJobsStorage")] MessageToMom myQueueItem,
                              [Queue("outputletter")] IAsyncCollector <FormLetter> letterCollector,
                              ILogger log)
        {
            log.LogInformation($"{myQueueItem.Greeting} {myQueueItem.HowMuch} {myQueueItem.HowSoon}");
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
            //TODO parse flattery list into comma separated string

            //here I grabbed the information from myQueueItem and created a new string from it.
            string parsed = $"{myQueueItem.Flattery[0]}" + ", " + $"{myQueueItem.Flattery[1]}" + ", " + $"{myQueueItem.Flattery[2]}";

            log.LogInformation($"{parsed}");

            //TODO populate Header with salutation comma separated string and "Mother"

            //Not sure if the point was to use the myQueue.greeting so i did both possibilities
            string     salutations2 = $"{myQueueItem.Greeting}, Mother";
            FormLetter p            = new FormLetter();

            p.Heading = ($"salutation" + ", " + $"Mother");

            //TODO calculate likelihood of receiving loan based on this decision tree
            // 100 percent likelihood (initial value) minus the probability expressed from the quotient of howmuch and the total maximum amount ($10000)
            //Not sure if I understood the goal of this one but it was some easy math.
            //grab the variable from myQueueItem.howMuch

            var division = (10000 / myQueueItem.HowMuch);
            var percent  = (100 - division);

            log.LogInformation($"{percent}");

            //TODO calculate approximate actual date of loan receipt based on this decision tree

            // funds will be made available 10 business days after day of submission
            // business days are weekdays, there are no holidays that are applicable

            //For this I grabbed the current DateTime, found out what day of the week that was.
            //Then ran that through some if else statements to figure out when the loan would be due.
            var dt  = DateTime.Now;
            var day = dt.DayOfWeek;

            log.LogInformation($"{dt.DayOfWeek}");
            if (day == DayOfWeek.Monday || day == DayOfWeek.Tuesday || day == DayOfWeek.Wednesday || day == DayOfWeek.Thursday || day == DayOfWeek.Friday)
            {
                var dueDay = dt.AddDays(14);
                log.LogInformation($"The actual date of loan receipt is, " + $"{dueDay}");
            }
            else if (day == DayOfWeek.Saturday)
            {
                var dueDay = dt.AddDays(13);
                log.LogInformation($"The actual date of loan receipt is, " + $"{dueDay}");
            }
            else if (day == DayOfWeek.Sunday)
            {
                var dueDay = dt.AddDays(12);
                log.LogInformation($"The actual date of loan receipt is, " + $"{dueDay}");
            }



            //TODO use new values to populate letter values per the following:

            //Body:"Really need help: I need $5523.23 by December 12,2020"
            //ExpectedDate = calculated date
            //RequestedDate = howsoon
            //Heading=Greeting
            //Likelihood = calculated likelihood

            //for this I created a new FormLetter and defined some variables that I would need inside.

            FormLetter help = new FormLetter();

            dt  = DateTime.Now;
            day = dt.DayOfWeek;

            {
                var expected = dt;

                if (day == DayOfWeek.Monday || day == DayOfWeek.Tuesday || day == DayOfWeek.Wednesday || day == DayOfWeek.Thursday || day == DayOfWeek.Friday)
                {
                    var dueDay = dt.AddDays(14);
                    /*  log.LogInformation($"The actual date of loan receipt is, " + $"{dueDay}");*/

                    expected = dueDay;
                }
                else if (day == DayOfWeek.Saturday)
                {
                    var dueDay = dt.AddDays(13);

                    expected = dueDay;
                }
                else if (day == DayOfWeek.Sunday)
                {
                    var dueDay = dt.AddDays(12);

                    expected = dueDay;
                }
                log.LogInformation($"This is in calculaeDates, {expected}");
                string   reallyNeedHelp = "Really need help: I need $5523.23 by December 12,2020";
                DateTime requestDate    = new DateTime(2020, 12, 12);
                //Then I applied all these variables into the FormLetter format.
                {
                    help.Heading       = $"{myQueueItem.Greeting}";
                    help.Likelihood    = (100 - (10000 / 5523.23));
                    help.ExpectedDate  = expected;
                    help.RequestedDate = requestDate;
                    help.Body          = reallyNeedHelp;
                };
                log.LogInformation($"This is the expected date, { expected}");
            }
            await letterCollector.AddAsync(help);

            log.LogInformation($"{help.Heading}" + $"The likelihood of being about to make a loan in that amount is, " + $"{help.Likelihood}");
        }
Exemple #16
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [Queue("messagetomom")] IAsyncCollector <newMessage> letterCollector,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            log.LogInformation($"This is req , {req}");



            /*     string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
             *   log.LogInformation("This is the request body", requestBody);
             *   var data = JsonConvert.DeserializeObject(requestBody);
             *   //TODO model HttpRequest from fields of MessageToMom*/

            string     requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            newMessage data        = JsonConvert.DeserializeObject <newMessage>(requestBody);

            /*     newMessage data = JsonConvert.DeserializeObject(requestBody);*/
            data.Greeting = data.Greeting ?? data?.Greeting;
            /*  Greeting = name ?? data?.Greeting; */

            log.LogInformation($"This is Data, {data}");

            newMessage obj = JsonConvert.DeserializeObject <newMessage>(requestBody);



            var newNote = new newMessage
            {
                Flattery = data.Flattery,
                Greeting = data.Greeting,
                HowMuch  = data.HowMuch,
                HowSoon  = data.HowSoon,
                From     = data.From
            };

            await letterCollector.AddAsync(newNote);



            /*   string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
             *
             * log.LogInformation($"This is the request body {requestBody}");
             *     Message data = JsonConvert.DeserializeObject(requestBody);
             *
             *
             *
             *
             *
             * //This is how I thought I would solve this problem.  I had a lot of trouble figuring out how to get the req.body out.
             * //I am still learning C# and it was quite different than what I have used before as far as api calls go.
             *
             * /*     var formEntryToBeParsed = [];
             *   req.Form.TryGetValue("out string", out formEntryToBeParsed);
             *   {
             *       log.LogInformation($"{formEntryToBeParsed}");
             *//* List<string> fieldToBeAssigned1 = ToString(); //Parse the string value or values
             *       string fieldToBeAssigned2; //Parse the string value or values
             *       double fieldToBeAssigned3; //Parse the string value or values
             *       DateTime fieldToBeAssigned4; //Parse the string value or value*//*
             *   }*/
            /*
             *          var message = new MessageToMom
             *          {
             *              Flattery = fieldToBeAssigned1,
             *              Greeting = fieldToBeAssigned2,
             *              HowMuch = fieldToBeAssigned3,
             *              HowSoon = fieldToBeAssigned4,
             *              From = "*****@*****.**"
             *
             *          };*/



            //Map new model values (from HttpRequest) to MessageToMom below

            /*  var message = new MessageToMom
             * {
             *    Flattery = new List<string> { "amazing", "fabulous", "profitable" },
             *    Greeting = "So Good To Hear From You",
             *    HowMuch = 1222.22M,
             *    HowSoon = DateTime.UtcNow.AddDays(1),
             *    From = "*****@*****.**"
             *
             * };
             *
             * await letterCollector.AddAsync(message);*/


            /*return new OkObjectResult(message);*/
            return((ActionResult) new OkObjectResult($"Hello, Johnny"));
        }
        public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent,
                                     [ServiceBus("%QueueName%", Connection = "ServiceBusConnectionString", EntityType = EntityType.Queue)] IAsyncCollector <Message> asyncCollector,
                                     ExecutionContext context,
                                     ILogger log)
        {
            try
            {
                if (eventGridEvent == null && string.IsNullOrWhiteSpace(eventGridEvent.EventType))
                {
                    throw new ArgumentNullException("Null or Invalid Event Grid Event");
                }

                log.LogInformation($@"New Event Grid Event:
    - Id=[{eventGridEvent.Id}]
    - EventType=[{eventGridEvent.EventType}]
    - EventTime=[{eventGridEvent.EventTime}]
    - Subject=[{eventGridEvent.Subject}]
    - Topic=[{eventGridEvent.Topic}]");

                if (eventGridEvent.Data is JObject jObject)
                {
                    // Create message
                    var message = new Message(Encoding.UTF8.GetBytes(jObject.ToString()))
                    {
                        MessageId = eventGridEvent.Id
                    };

                    switch (eventGridEvent.EventType)
                    {
                    case BlobCreatedEvent:
                    {
                        var blobCreatedEvent   = jObject.ToObject <StorageBlobCreatedEventData>();
                        var storageDiagnostics = JObject.Parse(blobCreatedEvent.StorageDiagnostics.ToString()).ToString(Newtonsoft.Json.Formatting.None);

                        log.LogInformation($@"Received {BlobCreatedEvent} Event: 
    - Api=[{blobCreatedEvent.Api}]
    - BlobType=[{blobCreatedEvent.BlobType}]
    - ClientRequestId=[{blobCreatedEvent.ClientRequestId}]
    - ContentLength=[{blobCreatedEvent.ContentLength}]
    - ContentType=[{blobCreatedEvent.ContentType}]
    - ETag=[{blobCreatedEvent.ETag}]
    - RequestId=[{blobCreatedEvent.RequestId}]
    - Sequencer=[{blobCreatedEvent.Sequencer}]
    - StorageDiagnostics=[{storageDiagnostics}]
    - Url=[{blobCreatedEvent.Url}]
");

                        // Set message label
                        message.Label = "BlobCreatedEvent";

                        // Add custom properties
                        message.UserProperties.Add("id", eventGridEvent.Id);
                        message.UserProperties.Add("topic", eventGridEvent.Topic);
                        message.UserProperties.Add("eventType", eventGridEvent.EventType);
                        message.UserProperties.Add("eventTime", eventGridEvent.EventTime);
                        message.UserProperties.Add("subject", eventGridEvent.Subject);
                        message.UserProperties.Add("api", blobCreatedEvent.Api);
                        message.UserProperties.Add("blobType", blobCreatedEvent.BlobType);
                        message.UserProperties.Add("clientRequestId", blobCreatedEvent.ClientRequestId);
                        message.UserProperties.Add("contentLength", blobCreatedEvent.ContentLength);
                        message.UserProperties.Add("contentType", blobCreatedEvent.ContentType);
                        message.UserProperties.Add("eTag", blobCreatedEvent.ETag);
                        message.UserProperties.Add("requestId", blobCreatedEvent.RequestId);
                        message.UserProperties.Add("sequencer", blobCreatedEvent.Sequencer);
                        message.UserProperties.Add("storageDiagnostics", storageDiagnostics);
                        message.UserProperties.Add("url", blobCreatedEvent.Url);

                        // Add message to AsyncCollector
                        await asyncCollector.AddAsync(message);

                        // Telemetry
                        telemetry.Context.Operation.Id   = context.InvocationId.ToString();
                        telemetry.Context.Operation.Name = "BlobCreatedEvent";
                        telemetry.TrackEvent($"[{blobCreatedEvent.Url}] blob created");
                        var properties = new Dictionary <string, string>
                        {
                            { "BlobType", blobCreatedEvent.BlobType },
                            { "ContentType ", blobCreatedEvent.ContentType }
                        };
                        telemetry.TrackMetric("ProcessBlobEvents Created", 1, properties);
                    }
                    break;

                    case BlobDeletedEvent:
                    {
                        var blobDeletedEvent   = jObject.ToObject <StorageBlobDeletedEventData>();
                        var storageDiagnostics = JObject.Parse(blobDeletedEvent.StorageDiagnostics.ToString()).ToString(Newtonsoft.Json.Formatting.None);

                        log.LogInformation($@"Received {BlobDeletedEvent} Event: 
    - Api=[{blobDeletedEvent.Api}]
    - BlobType=[{blobDeletedEvent.BlobType}]
    - ClientRequestId=[{blobDeletedEvent.ClientRequestId}]
    - ContentType=[{blobDeletedEvent.ContentType}]
    - RequestId=[{blobDeletedEvent.RequestId}]
    - Sequencer=[{blobDeletedEvent.Sequencer}]
    - StorageDiagnostics=[{storageDiagnostics}]
    - Url=[{blobDeletedEvent.Url}]
");

                        // Set message label
                        message.Label = "BlobDeletedEvent";

                        // Add custom properties
                        message.UserProperties.Add("id", eventGridEvent.Id);
                        message.UserProperties.Add("topic", eventGridEvent.Topic);
                        message.UserProperties.Add("eventType", eventGridEvent.EventType);
                        message.UserProperties.Add("eventTime", eventGridEvent.EventTime);
                        message.UserProperties.Add("subject", eventGridEvent.Subject);
                        message.UserProperties.Add("api", blobDeletedEvent.Api);
                        message.UserProperties.Add("blobType", blobDeletedEvent.BlobType);
                        message.UserProperties.Add("clientRequestId", blobDeletedEvent.ClientRequestId);
                        message.UserProperties.Add("contentType", blobDeletedEvent.ContentType);
                        message.UserProperties.Add("requestId", blobDeletedEvent.RequestId);
                        message.UserProperties.Add("sequencer", blobDeletedEvent.Sequencer);
                        message.UserProperties.Add("storageDiagnostics", storageDiagnostics);
                        message.UserProperties.Add("url", blobDeletedEvent.Url);

                        // Add message to AsyncCollector
                        await asyncCollector.AddAsync(message);

                        // Telemetry
                        telemetry.Context.Operation.Id   = context.InvocationId.ToString();
                        telemetry.Context.Operation.Name = "BlobDeletedEvent";
                        telemetry.TrackEvent($"[{blobDeletedEvent.Url}] blob deleted");
                        var properties = new Dictionary <string, string>
                        {
                            { "BlobType", blobDeletedEvent.BlobType },
                            { "ContentType ", blobDeletedEvent.ContentType }
                        };
                        telemetry.TrackMetric("ProcessBlobEvents Deleted", 1, properties);
                    }
                    break;
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, ex.Message);
                throw;
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "ministries",
                 collectionName: "diaconate",
                 ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <DiaconateDB> diaconateDocuments,

            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var diaconate   = JsonSerializer.Deserialize <DiaconateDB>(requestBody, options);

            try
            {
                if (diaconate.id == null)
                {
                    diaconate.id = Guid.NewGuid().ToString();
                }
                else
                {
                    if (diaconate.meetingDate != diaconate.newMeetingDate)
                    {
                        var           meetingUrl = System.Environment.GetEnvironmentVariable("MeetingUrl");
                        DeaconMeeting meeting    = new DeaconMeeting();
                        meeting.ZoomLink    = diaconate.meetingUrl;
                        meeting.DiaconateId = diaconate.id;
                        meeting.Year        = diaconate.year;
                        if (DateTimeFormatInfo.CurrentInfo != null)
                        {
                            meeting.Month = DateTimeFormatInfo.CurrentInfo.GetMonthName(diaconate.month);
                        }
                        if (diaconate.newMeetingDate.HasValue)
                        {
                            var meetingTime = diaconate.newMeetingDate.Value.AddHours(-5);
                            meeting.DeaconDate = meetingTime.ToLongDateString() + " " + meetingTime.ToShortTimeString();
                        }
                        if (diaconate.meetingDate.HasValue)
                        {
                            meeting.OldMeetingDate = diaconate.meetingDate.Value.AddHours(-5).ToLongDateString();
                        }

                        var registrantDb = JsonSerializer.Serialize <DeaconMeeting>(meeting);
                        var client       = new HttpClient();
                        _ = client.PostAsync(meetingUrl, new StringContent(registrantDb, Encoding.UTF8, "application/json"));
                        diaconate.meetingDate = diaconate.newMeetingDate;
                    }
                }
                diaconate.startDate      = new DateTime(diaconate.year, diaconate.month, 1);
                diaconate.newMeetingDate = null;
                await diaconateDocuments.AddAsync(diaconate);
            }
            catch (Exception e)
            {
                log.LogInformation(e.ToString());
            }

            return(new OkObjectResult(diaconate));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "import")] HttpRequest req,
            [EventHub("%EventHubName%", Connection = "EventHubConnection")] IAsyncCollector <EventData> outputEvents,
            ILogger log)
        {
            log.LogInformation("FHIR Proxy - Import Function Invoked");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            /* Get/update/check current bearer token to authenticate the proxy to the FHIR Server
             * The following parameters must be defined in environment variables:
             * FS_URL = the fully qualified URL to the FHIR Server
             * FS_TENANT_NAME = the GUID or UPN of the AAD tenant that is hosting FHIR Server Authentication
             * FS_CLIENT_ID = the client or app id of the private client authorized to access the FHIR Server
             * FS_SECRET = the client secret to pass to FHIR Server Authentication
             * FS_RESOURCE = the audience or resource for the FHIR Server for Azure API for FHIR should be https://azurehealthcareapis.com
             */
            if (!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("FS_CLIENT_ID")) && (_bearerToken == null || FHIRClient.isTokenExpired(_bearerToken)))
            {
                lock (_lock)
                {
                    log.LogInformation($"Obtaining new OAUTH2 Bearer Token for access to FHIR Server");
                    _bearerToken = FHIRClient.GetOAUTH2BearerToken(System.Environment.GetEnvironmentVariable("FS_TENANT_NAME"), System.Environment.GetEnvironmentVariable("FS_RESOURCE"),
                                                                   System.Environment.GetEnvironmentVariable("FS_CLIENT_ID"), System.Environment.GetEnvironmentVariable("FS_SECRET"));
                }
            }

            /*
             * Create User Custom Headers these headers are passed to the FHIR Server to communicate credentials of the authorized user for each proxy call
             * this is ensures accruate audit trails for FHIR server access. Note: This headers are honored by the Azure API for FHIR Server
             */
            List <HeaderParm> auditheaders = new List <HeaderParm>();

            auditheaders.Add(new HeaderParm("X-MS-AZUREFHIR-AUDIT-PROXY", "FHIREventProcessor-Import"));
            /* Preserve FHIR Specific change control headers and include in the proxy call */
            List <HeaderParm> customandrestheaders = new List <HeaderParm>();

            foreach (string key in req.Headers.Keys)
            {
                string s = key.ToLower();
                if (s.Equals("etag"))
                {
                    customandrestheaders.Add(new HeaderParm(key, req.Headers[key].First()));
                }
                else if (s.StartsWith("if-"))
                {
                    customandrestheaders.Add(new HeaderParm(key, req.Headers[key].First()));
                }
            }
            /* Add User Audit Headers */
            customandrestheaders.AddRange(auditheaders);
            /* Get a FHIR Client instance to talk to the FHIR Server */
            log.LogInformation($"Instanciating FHIR Client Proxy");
            FHIRClient fhirClient = new FHIRClient(System.Environment.GetEnvironmentVariable("FS_URL"), _bearerToken);
            //Check for transaction bundle
            JObject       result            = JObject.Parse(requestBody);
            List <string> effectedresources = new List <string>();
            int           updated           = 0;

            if (result != null && ((string)result["resourceType"]).Equals("Bundle") && ((string)result["type"]).Equals("transaction"))
            {
                if (result["entry"] != null)
                {
                    JArray entries = (JArray)result["entry"];
                    foreach (JToken tok in entries)
                    {
                        JObject res  = (JObject)tok["resource"];
                        var     rslt = fhirClient.SaveResource(res, "PUT", customandrestheaders.ToArray());
                        if (rslt.StatusCode == HttpStatusCode.OK || rslt.StatusCode == HttpStatusCode.Created)
                        {
                            updated++;
                            string    msg = "{\"effectedresource\":\"" + (string)res["resourceType"] + "\",\"id\":\"" + (string)res["id"] + "\"}";
                            EventData dt  = new EventData(Encoding.UTF8.GetBytes(msg));
                            await outputEvents.AddAsync(dt);
                        }
                    }
                }
            }
            else
            {
                if (result != null)
                {
                    var rslt = fhirClient.SaveResource(result, "POST", customandrestheaders.ToArray());
                    if (rslt.StatusCode == HttpStatusCode.OK || rslt.StatusCode == HttpStatusCode.Created)
                    {
                        updated++;
                        string    msg = "{\"effectedresource\":\"" + (string)result["resourceType"] + "\",\"id\":\"" + (string)result["id"] + "\"}";
                        EventData dt  = new EventData(Encoding.UTF8.GetBytes(msg));
                        await outputEvents.AddAsync(dt);
                    }
                }
            }
            string retval = "{\"updated\":\"" + updated + "\"}";

            return(new JsonResult(JObject.Parse(retval)));
        }
Exemple #20
0
        public static async Task Run([IoTHubTrigger("iothubtrigger", Connection = "IoTHubEndpoint", ConsumerGroup = "FunctionGroup")] EventData[] eventMessages,
                                     [CosmosDB(
                                          databaseName: "FreeCosmosDB",
                                          collectionName: "TelemetryData",
                                          ConnectionStringSetting = "CosmosDBConnection"
                                          )]
                                     IAsyncCollector <dynamic> output,
                                     [SendGrid(ApiKey = "SendGridAPIKey")] IAsyncCollector <SendGridMessage> messageCollector,
                                     ExecutionContext context,
                                     ILogger log)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var SendEmailTo = config["SendEmailsTo"];

            SendEmailFrom = config["SendEmailFrom"];
            EmailsTo      = new List <EmailAddress>();
            List <string> emailList = SendEmailTo.Split(",").ToList();

            foreach (var item in emailList)
            {
                EmailsTo.Add(new EmailAddress(item));
            }
            log.LogInformation($"C# IoT Hub trigger function processed a message: {eventMessages.Length}");
            string jsonStr;

            foreach (var eventData in eventMessages)
            {
                try
                {
                    if (eventData.SystemProperties.EnqueuedTimeUtc >= DateTime.UtcNow.AddMinutes(-1))
                    {
                        jsonStr = Encoding.UTF8.GetString(eventData.Body.Array);
                    }
                    else
                    {
                        return;
                    }

                    if (JToken.Parse(jsonStr) is JObject)
                    {
                        JObject json = JsonConvert.DeserializeObject <JObject>(jsonStr);
                        log.LogInformation($"JObject: {json}");

                        if (json.Value <bool>("isHomeSecured"))
                        {
                            SendEmail(json, messageCollector);
                        }
                        //if (json.Value<string>("SourceInfo") == "Someone is at home: True" || json.Value<string>("SourceInfo") == "Someone is at home: False")
                        //    SendEmail(json, messageCollector);
                        await output.AddAsync(json);
                    }
                    else //array, from the Stream Analytics it comes as an Array
                    {
                        JArray json = JsonConvert.DeserializeObject <JArray>(jsonStr);
                        foreach (JObject doc in json)
                        {
                            if (doc.Value <bool>("isHomeSecured"))
                            {
                                SendEmail(doc, messageCollector);
                            }

                            log.LogInformation($"JArray: {doc}");
                            await output.AddAsync(doc);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.LogInformation($"Caught exception: {ex.Message}");
                }
            }
        }
        public static async Task RunAsync(
            [EventHubTrigger("%EventHubName%", Connection = "EventHubConnectionString", ConsumerGroup = "%ConsumerGroup%")]
            EventData[] messages,
            [DocumentDB("%CosmosDBDataBase%", "%CosmosDBCollection%", ConnectionStringSetting = "CosmosDBConnectionString", CreateIfNotExists = false)]
            IAsyncCollector <dynamic> documents,
            ExecutionContext context,
            TraceWriter log)
        {
            CustomTelemetry.TrackMetric(context, "IoTHubMessagesReceived", messages.Length);

            var ticksUTCNow = DateTimeOffset.UtcNow;
            var cutoffTime  = DateTimeOffset.UtcNow.AddMinutes(-5);

            // Track whether messages are arriving at the function late.
            DateTime?firstMsgEnqueuedTicksUtc = messages[0]?.EnqueuedTimeUtc;

            if (firstMsgEnqueuedTicksUtc.HasValue)
            {
                CustomTelemetry.TrackMetric(
                    context,
                    "IoTHubMessagesReceivedFreshnessMsec",
                    (ticksUTCNow - firstMsgEnqueuedTicksUtc.Value).TotalMilliseconds);
            }

            int count           = 0;
            int droppedMessages = 0;

            foreach (var message in messages)
            {
                // Drop stale messages,
                if (message.EnqueuedTimeUtc < cutoffTime)
                {
                    log.Info($"Dropping late message batch. Enqueued time = {message.EnqueuedTimeUtc}, Cutoff = {cutoffTime}");
                    droppedMessages++;
                    continue;
                }

                var text = Encoding.UTF8.GetString(message.GetBytes());
                log.Info($"Process message: {text}");

                try
                {
                    dynamic telemetry = JObject.Parse(text);
                    if (telemetry.sensorType == DroneSensorEventType)
                    {
                        string position = telemetry.position;
                        var(latitude, longitude) = DroneTelemetryConverter.ConvertPosition(position);

                        await documents.AddAsync(new
                        {
                            id        = telemetry.deviceId,
                            deviceId  = telemetry.deviceId,
                            Location  = new Point(longitude, latitude),
                            Timestamp = message.EnqueuedTimeUtc
                        });

                        count++;
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Error processing message", ex);
                }
            }

            CustomTelemetry.TrackMetric(
                context,
                "IoTHubMessagesDropped",
                droppedMessages);
            CustomTelemetry.TrackMetric(
                context,
                "CosmosDbDocumentsCreated",
                count);
        }
        public static async Task Run(
            [TimerTrigger("0 0 9 * * MON")] TimerInfo timer, // Every Monday @ 9:00 AM
            [SendGrid] IAsyncCollector <SendGridMessage> messageCollector,
            ILogger log)
        {
            var browsingContext = BrowsingContext.New(Configuration.Default.WithDefaultLoader());

            string profileUrl      = "https://www.spoj.com/users/davidgalehouse";
            var    profileDocument = await browsingContext.OpenAsync(profileUrl);

            var solvedProblems = profileDocument
                                 .QuerySelector("#user-profile-tables table")
                                 .QuerySelectorAll("tr td a")
                                 .Select(e => e.TextContent?.Trim())
                                 .Where(p => !string.IsNullOrWhiteSpace(p))
                                 .ToHashSet();

            log.LogInformation($"Profile URL opened, {solvedProblems.Count} solved problems found.");

            string problems151to200Url      = "https://www.spoj.com/problems/classical/sort=6,start=150";
            var    problems151to200Document = await browsingContext.OpenAsync(problems151to200Url);

            var problems151to200 = problems151to200Document
                                   .QuerySelectorAll("table.problems tbody tr")
                                   .Select(e => e.QuerySelector("a"))
                                   .OfType <IHtmlAnchorElement>()
                                   .Select(a => a.Href.Split('/', StringSplitOptions.RemoveEmptyEntries).Last()?.Trim())
                                   .Where(p => !string.IsNullOrWhiteSpace(p))
                                   .ToArray();

            log.LogInformation($"Problems 151 to 200 URL opened, {problems151to200.Length} problems found " +
                               $"(first problem: {problems151to200.FirstOrDefault()}, last problem: {problems151to200.LastOrDefault()}).");

            if (solvedProblems.Count < 200 ||
                solvedProblems.Distinct().Count() != solvedProblems.Count ||
                solvedProblems.Any(p => !IsValidProblem(p)) ||
                problems151to200.Length != 50 ||
                problems151to200.Distinct().Count() != 50 ||
                problems151to200.Any(p => !IsValidProblem(p)))
            {
                throw new Exception("There's something wrong with the way SPOJ is being scraped.");
            }

            var unsolvedProblems = problems151to200
                                   .Select((p, i) => (problem: p, index: 151 + i))
                                   .Where(p => !solvedProblems.Contains(p.problem))
                                   .ToArray();

            if (unsolvedProblems.Any())
            {
                log.LogInformation($"Unsolved problems found: {string.Join(", ", unsolvedProblems)}.");

                var message = new SendGridMessage();
                message.AddTo(Environment.GetEnvironmentVariable("SendGridMessageTo"));
                message.SetSubject(unsolvedProblems.Length == 1 ? "A problem from SPOJ's top 200 needs to be solved!"
                    : $"{unsolvedProblems.Length} problems from SPOJ's top 200 need to be solved!");
                message.AddContent("text/plain", string.Join(Environment.NewLine, unsolvedProblems
                                                             .Select(p => $"#{p.index}: https://www.spoj.com/problems/{p.problem}")));
                await messageCollector.AddAsync(message);
            }
        }
        private static async Task <IActionResult> KillMethod(
            IAsyncCollector <string> console,
            IDurableClient client,
            string name,
            string target,
            string with,
            User userCheck)
        {
            if (string.IsNullOrEmpty(target))
            {
                await console.AddAsync($"User {name} tried to kill nothing.");

                return(new BadRequestObjectResult("Target is required."));
            }
            if (string.IsNullOrEmpty(with))
            {
                await console.AddAsync($"User {name} tried to kill {target} with no weapon.");

                return(new BadRequestObjectResult("With is required."));
            }
            if (!userCheck.InventoryList.Contains(with))
            {
                await console.AddAsync($"User {name} tried to use a non-existing {with}.");

                return(new BadRequestObjectResult($"User doesn't have {with}"));
            }
            var monster = await name.GetEntityForUserOrThrow <Monster>(client);

            if (!monster.IsAlive)
            {
                await console.AddAsync($"User {name} tried to kill an already dead {target}.");

                return(new BadRequestObjectResult($"{target} is already dead."));
            }

            var monsterInventory = monster.InventoryList[0];
            var inventoryNames   = await name.GetEntityForUserOrThrow <InventoryList>(client);

            var room = await name.GetEntityForUserOrThrow <Room>(client);

            // monster dies
            await client.SignalEntityAsync <IMonsterOperations>(
                name.AsEntityIdFor <Monster>(),
                operation => operation.Kill());

            // monster drops inventory, inventory => room
            await client.SignalEntityAsync <IInventoryOperations>(
                name.AsEntityIdFor <Inventory>(monsterInventory),
                operation => operation.SetRoom(room.Name));

            // add inventory to room
            await client.SignalEntityAsync <IRoomOperations>(
                name.AsEntityIdFor <Room>(),
                operation => operation.AddInventory(monsterInventory));

            await console.AddAsync($"User {name} valiantly killed {target} with {with}.");

            await console.AddAsync($"User {name} notices {target} dropped a {monsterInventory}.");

            var gameMonitor = await Global.FindJob(
                client,
                DateTime.UtcNow,
                nameof(MonitorFunctions.GameMonitorWorkflow),
                name,
                true,
                false);

            if (gameMonitor != null)
            {
                await client.RaiseEventAsync(gameMonitor.InstanceId,
                                             MonitorFunctions.KILLMONSTER);
            }
            return(new OkResult());
        }
Exemple #24
0
    public override async Task <ICommandResult> HandleAsync(ComponentDeleteCommand command, IAsyncCollector <ICommand> commandQueue, IDurableOrchestrationContext orchestrationContext, ILogger log)
    {
        if (command is null)
        {
            throw new ArgumentNullException(nameof(command));
        }

        if (commandQueue is null)
        {
            throw new ArgumentNullException(nameof(commandQueue));
        }

        var commandResult = command.CreateResult();

        try
        {
            commandResult.Result = await componentRepository
                                   .RemoveAsync(command.Payload, true)
                                   .ConfigureAwait(false);

            var existingComponentTasks = componentTaskRepository
                                         .ListAsync(commandResult.Result.Id)
                                         .Where(ct => ct.Type == ComponentTaskType.Custom && ct.TaskState.IsActive());

            await foreach (var existingComponentTask in existingComponentTasks)
            {
                var cancelCommand = new ComponentTaskCancelCommand(command.User, existingComponentTask);

                await commandQueue
                .AddAsync(cancelCommand)
                .ConfigureAwait(false);
            }

            var componentTask = new ComponentTask
            {
                Organization     = commandResult.Result.Organization,
                OrganizationName = commandResult.Result.OrganizationName,
                ComponentId      = commandResult.Result.Id,
                ComponentName    = commandResult.Result.Slug,
                ProjectId        = commandResult.Result.ProjectId,
                ProjectName      = commandResult.Result.ProjectName,
                Type             = ComponentTaskType.Delete,
                RequestedBy      = command.User.Id,
                InputJson        = commandResult.Result.InputJson
            };

            componentTask = await componentTaskRepository
                            .AddAsync(componentTask)
                            .ConfigureAwait(false);

            await commandQueue
            .AddAsync(new ComponentTaskRunCommand(command.User, componentTask))
            .ConfigureAwait(false);

            commandResult.RuntimeStatus = CommandRuntimeStatus.Completed;
        }
        catch (Exception exc)
        {
            commandResult.Errors.Add(exc);
        }

        return(commandResult);
    }
Exemple #25
0
            public async Task Func([Test6("{k}")] IAsyncCollector <AlphaType> collector)
            {
                await collector.AddAsync(AlphaType.New("v1"));

                await collector.AddAsync(AlphaType.New("v2"));
            }
        public static async Task RunOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context,
            [ServiceBus("machines", Connection = "ServiceBusConnection")] ICollector <string> machineOutput,
            [ServiceBus("logs", Connection = "ServiceBusConnection")] ICollector <string> logOutput,
            [EventHub("mainlogs", Connection = "EventHubConnectionAppSetting")] IAsyncCollector <string> outputEvents,
            ILogger log)
        {
            var settingsList = new List <Settings>
            {
                Settings.AverageProductionTime,
                Settings.ProductionTimeVariability,
                Settings.AverageFailureRate,
                Settings.FailureRateVariability,
                Settings.MachineFailureRate
            };

            try
            {
                using (IDbConnection conn = new SqlConnection(Environment.GetEnvironmentVariable("SqlConnection")))
                {
                    var settingsRepo = new SettingRepository(conn);
                    var machineRepo  = new MachineRepository(conn);

                    var settings = settingsRepo.GetSettings(settingsList).Result;
                    var machines = machineRepo.GetActiveMachines().Result;

                    var results = new List <MachineRun>();

                    foreach (var machine in machines)
                    {
                        var run = new MachineRun(machine, settings.ToList());

                        var result = RunMachine(run);

                        results.Add(result);

                        /* if (result.MachineBroken)
                         * {
                         *   await context.CallActivityAsync("BreakMachine", result.Machine);
                         *   machineOutput.Add(JsonConvert.SerializeObject(result.Machine,
                         *       new JsonSerializerSettings
                         *       {
                         *           ContractResolver = new CamelCasePropertyNamesContractResolver()
                         *       }));
                         *   logOutput.Add($"{TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time")).ToLongTimeString()} Machine {result.Machine.Id} broken.");
                         * }*/
                    }

                    var runLog = await context.CallActivityAsync <MachineRunResults>("ProcessResults", results);

                    if (runLog != null)
                    {
                        runLog.MachineRuns = results;
                        var logResults = machineRepo.CreateRunResults(runLog).Result;
                        outputEvents.AddAsync(JsonConvert.SerializeObject(runLog,
                                                                          new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        })).RunSynchronously();
                    }
                }
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
            }
        }
Exemple #27
0
        public static async Task SayHello([ActivityTrigger] UserInfo userInfo, [Queue("informuserqueue", Connection = "StorageConnectionString")] IAsyncCollector <UserInfo> userInfos)
        {
            await userInfos.AddAsync(userInfo);

            await userInfos.FlushAsync();
        }
        public static async Task Run([EventHubTrigger("datashare", Connection = "source_EVENTHUB")] EventData[] events,
                                     [EventHub("datasource", Connection = "destination_EVENTHUB")] IAsyncCollector <string> outputEvents,
                                     ILogger log, ExecutionContext context)
        {
            var exceptions = new List <Exception>();

            if (serviceClient == null)
            {
                var config   = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory).AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
                var iothubCS = config.GetConnectionString("iothub_connection_string");
                serviceClient = ServiceClient.CreateFromConnectionString(iothubCS);
                await serviceClient.OpenAsync();
            }

            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
                    // Send to SignalR service event hub
                    dynamic envDataJson = Newtonsoft.Json.JsonConvert.DeserializeObject(messageBody);
                    if (envDataJson.GetType().Name == "JArray")
                    {
                        dynamic envData    = envDataJson[0];
                        string  envDataMsg = Newtonsoft.Json.JsonConvert.SerializeObject(envData);
                        await outputEvents.AddAsync(envDataMsg);

                        // Send command to device when discomfort index become to high or become to low by threshold.
                        // Notice: following logic can work only when number of devices is not so large. you should think that you move this logic to Stream Analytics.
                        if (envData.temperature != null && envData.humidity != null && envData.deviceid != null)
                        {
                            string deviceId        = envData.deviceid;
                            double temperature     = envData.temperature;
                            double humidity        = envData.humidity;
                            double discomfortIndex = 0.81 * temperature + 0.01 * humidity * (0.99 * temperature - 14.3) + 46.3;
                            string alertCommand    = null;
                            lock (alertingDevices) {
                                bool isAlerting = false;
                                if (alertingDevices.Contains(deviceId))
                                {
                                    isAlerting = true;
                                }

                                if (discomfortIndex > 80.0)
                                {
                                    if (!isAlerting)
                                    {
                                        alertingDevices.Add(deviceId);
                                        alertCommand = "on";
                                    }
                                }
                                else
                                {
                                    if (isAlerting)
                                    {
                                        alertingDevices.Remove(deviceId);
                                        alertCommand = "off";
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(alertCommand))
                            {
                                var command = new {
                                    command = new {
                                        alert = alertCommand
                                    }
                                };
                                var commandMsg = new Message(System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(command)));
                                await serviceClient.SendAsync(deviceId, commandMsg);
                            }
                        }
                    }

                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
            {
                throw new AggregateException(exceptions);
            }

            if (exceptions.Count == 1)
            {
                throw exceptions.Single();
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(
                 AuthorizationLevel.Function, "post", Route = null)] HttpRequest request,
            [ServiceBus(
                 "processtext",
                 Connection = "ProcessTextQueueServicebusConnectionString")] IAsyncCollector <dynamic> processTextQueue,
            [CosmosDB(
                 databaseName: "TextContent",
                 collectionName: "Web",
                 ConnectionStringSetting = "tkawchak-textanalysis_DOCUMENTDB")] IAsyncCollector <dynamic> outputDocument,
            ILogger log)
        {
            ObjectResult httpResponse;

            log.LogInformation("C# ProcessTextHttp function received request.");

            // format the data for the response message
            string bodyContent  = string.Empty;
            string errorMessage = string.Empty;

            using (var reader = new StreamReader(request.Body))
            {
                bodyContent = await reader.ReadToEndAsync();
            }

            ProcessTextRequest requestContent;

            if (string.IsNullOrWhiteSpace(bodyContent))
            {
                errorMessage = "Error processing request - Request Body is empty. Cannot process an empty body.";
            }

            requestContent = JsonConvert.DeserializeObject <ProcessTextRequest>(bodyContent);
            if (string.IsNullOrWhiteSpace(requestContent.Title))
            {
                errorMessage = "Error processing request - Title not specified";
            }

            if (string.IsNullOrWhiteSpace(requestContent.Domain))
            {
                errorMessage = "Error processing request - Domain not specified";
            }

            if (!string.IsNullOrWhiteSpace(errorMessage))
            {
                log.LogError(errorMessage);
                httpResponse = new BadRequestObjectResult(errorMessage);
                return(httpResponse);
            }

            log.LogInformation($"Received request to store data for webpage at {requestContent.Url}");
            var outputDoc = Utils.Converters.ConvertProcessTextRequestToProcessedTextDocument(requestContent);

            log.LogInformation($"Document Title: {outputDoc.Title}");
            log.LogInformation($"Document Domain: {outputDoc.Domain}");

            await processTextQueue.AddAsync(outputDoc);

            log.LogInformation($"Sent webpage data to process text queue");

            await outputDocument.AddAsync(outputDoc);

            log.LogInformation($"Stored webpage data to storage");

            string message = $"Successfully Processed request to store data for webpage at {requestContent.Domain}.";

            log.LogInformation(message);
            httpResponse = new OkObjectResult(message);

            return(httpResponse);
        }
 public static Task SaveState_BindToStoreName(
     string storeName,
     [DaprState("{storeName}", Key = "key1")] IAsyncCollector <int> state)
 {
     return(state.AddAsync(42));
 }