Esempio n. 1
0
        public async Task Run([TimerTrigger("0 0 * * * *")] MyInfo myTimer, FunctionContext context)
        {
            var log = context.GetLogger("UserNotifier");

            log.LogInformation($"UserNotifier trigger function executed at: {DateTime.Now}");
            await userNotificationManager.RunAllNotificatons().ConfigureAwait(false);
        }
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req, FunctionContext functionContext)
        {
            var logger = functionContext.GetLogger(nameof(GetGitHubClientId));

            logger.LogInformation("Retrieving Organizations Url");

            if (string.IsNullOrWhiteSpace(_enableOrganizationsUrl))
            {
                var notFoundResponse = req.CreateResponse(System.Net.HttpStatusCode.NotFound);
                await notFoundResponse.WriteStringAsync("Enable Organizations Url Not Found").ConfigureAwait(false);

                return(notFoundResponse);
            }

            if (string.IsNullOrWhiteSpace(GetGitHubClientId.ClientId))
            {
                var notFoundResponse = req.CreateResponse(System.Net.HttpStatusCode.NotFound);
                await notFoundResponse.WriteStringAsync("Client Id Not Found").ConfigureAwait(false);

                return(notFoundResponse);
            }

            var okResponse = req.CreateResponse(System.Net.HttpStatusCode.OK);

            var getGitTrendsEnableOrganizationsUri = JsonConvert.SerializeObject(new GitTrendsEnableOrganizationsUriDTO(new Uri(_enableOrganizationsUrl + GetGitHubClientId.ClientId)));

            await okResponse.WriteStringAsync(getGitTrendsEnableOrganizationsUri).ConfigureAwait(false);

            return(okResponse);
        }
Esempio n. 3
0
        public static async Task <object> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("Messages");

            logger.LogInformation("C# HTTP trigger function processed a request.");
            var message = await req.ReadFromJsonAsync <FireMessage>();

            var game = CosmosDbHandler.FindGame(message?.GameId, logger);

            if (game == null)
            {
                return(null);
            }
            game = GameController.Fire(game, message.PlayerId, message.Row, message.Column);
            game = await CosmosDbHandler.SaveGameAsync(game, logger);

            return(new
            {
                Target = "gameUpdated",
                Arguments = new Game[]
                {
                    game
                }
            });
        }
        public async Task Run(
            [ServiceBusTrigger(
                 "%QueueListenerNameForDequeue%",
                 Connection = "ServiceBusConnectionString")]
            byte[] message,
            FunctionContext context)
        {
            var logger = context.GetLogger("ReplyToRequestFromPostOffice");

            logger.LogInformation("C# ServiceBus ReplyToDequeueFromPostOffice triggered");

            try
            {
                var dequeueNotification          = _dequeueNotificationParser.Parse(message);
                var dataAvailableNotificationIds = await _storageHandler
                                                   .GetDataAvailableNotificationIdsAsync(dequeueNotification)
                                                   .ConfigureAwait(false);

                logger.LogInformation($"Dequeue received for {dequeueNotification.MarketOperator.Value} with notification ids: {string.Join(",", dataAvailableNotificationIds)}");
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not process message.", e);
            }
        }
Esempio n. 5
0
        public static void Run([TimerTrigger("0 */5 * * * *")] MyInfo timerInfo,
                               FunctionContext context)
        {
            var logger = context.GetLogger("TimerFunction");

            logger.LogInformation($"Function Ran. Next timer schedule = {timerInfo.ScheduleStatus.Next}");
        }
        public async Task Run(
            [KafkaTrigger("KAFKA_BROKERS", "input-to-process-profile-page", ConsumerGroup = "input-processor-group")]
            KafkaMessage ev,
            FunctionContext context)
        {
            var logger = context.GetLogger("ProfilePageGeneratorFunc");

            logger.LogInformation($"Start ProfilePageGeneratorFunc");

            var msg = JsonSerializer.Deserialize <InputToProcessEvent>(ev.Value);

            if (msg is null)
            {
                logger.LogError($"value of event is empty | timestamp: {ev.Timestamp}");
                return;
            }

            var storageClient = new MinioClient(MinioEndpoint, MinioAccessKey, MinioSecretKey);
            // 1, Download input file from S3 bucket (minio)
            var input = await DownloadInputData(logger, storageClient, msg.bucketName, msg.objectName);

            logger.LogInformation($"processing {input.template} input");
            // 2. Download html template from s3 repo (should sync by other periodic function)
            var template = await GetTemplate(input.template);

            // 3. Combine these two sources into one html file
            var output = GenerateOutput(input.data, template);

            // 4. Put generated file to the S3
            await UploadGeneratedOutput(storageClient, output, input.template);

            logger.LogInformation($"end ProfilePageGeneratorFunc");
        }
Esempio n. 7
0
        public async Task CampaignCreatedHandler(
            [QueueTrigger("%ENVIRONMENT%-" + QueueNames.CampaignCreated, Connection = "StorageConnection")] string message,
            FunctionContext executionContext
            )
        {
            var logger = executionContext.GetLogger(FunctionNames.CampaignCreated);

            logger.LogInformation("Function '{FunctionName}' was triggered.", FunctionNames.CampaignCreated);
            var campaign = JsonSerializer.Deserialize <CampaignQueueItem>(message, JsonSerializerOptionDefaults.GetDefaultSettings());

            if (!campaign.Published)
            {
                return;
            }
            if (campaign.DeliveryChannel.HasFlag(CampaignQueueItem.CampaignDeliveryChannel.PushNotification))
            {
                await ProcessPushNotifications(campaign);

                return;
            }
            if (campaign.DeliveryChannel.HasFlag(CampaignQueueItem.CampaignDeliveryChannel.Email))
            {
                // TODO: Create next hop to send campaign via email.
                return;
            }
            if (campaign.DeliveryChannel.HasFlag(CampaignQueueItem.CampaignDeliveryChannel.SMS))
            {
                // TODO: Create next hop to send campaign via SMS gateway.
                return;
            }
        }
Esempio n. 8
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            var logger = context.GetLogger <AuthenticationMiddleware>();
            var data   = context.BindingContext.BindingData;

            if (data.ContainsKey("Headers"))
            {
                data.TryGetValue("Headers", out var headersObject);

                var headers = JsonSerializer.Deserialize <JsonDocument>(headersObject as string);

                var authzHeaderExists = headers.RootElement.TryGetProperty("Authorization", out JsonElement authorizationHeader);

                if (authzHeaderExists)
                {
                    var token = authorizationHeader.ToString().Substring("Bearer ".Length);

                    var principal = await _authenticationProvider.AuthenticateAsync(context, token);

                    if (principal != null)
                    {
                        await next(context);

                        return;
                    }
                }
            }

            // return 401
        }
Esempio n. 9
0
        public static MultiResponse Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
                                        FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("HttpExample");

            logger.LogInformation("C# HTTP trigger function processed a request.");

            var message = "Welcome to Azure Functions!";

            var response = req.CreateResponse(HttpStatusCode.OK);

            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            response.WriteString(message);

            // Return a response to both HTTP trigger and Azure Cosmos DB output binding.
            return(new MultiResponse()
            {
                Document = new MyDocument
                {
                    id = System.Guid.NewGuid().ToString(),
                    message = message
                },
                HttpResponse = response
            });
        }
Esempio n. 10
0
        public static void Run([BlobTrigger("reproerrorazbt/{name}", Connection = "nicocsetrips_STORAGE")] Stream myBlob, string name,
                               FunctionContext context)
        {
            var logger = context.GetLogger("BlobTriggerCSharpError");

            logger.LogInformation($"C# Blob trigger function Processed blob\n Name: {name} \n Data: {myBlob}");
        }
        public async Task Run(
            [EventHubTrigger(
                "client-events",
                Connection = "clientEventsListenerEventHubConnectionString",
                ConsumerGroup = "client-events-processing-consumer-group")] TrainEvent[] input,
            FunctionContext context)
        {
            await _trainEventsRepository.StoreAsync(input);

            // calculate regular behavior

            foreach (var trainEvent in input)
            {
                var all = _trainEventsRepository.GetEventsByVehicleAndOrderAsync(
                    trainEvent.VehicleId,
                    trainEvent.OrderNumberCurrent);

                var list = new List<int>();
                await foreach (var e in all)
                {
                    list.Add(e.
                }
            }

            // 


            var logger = context.GetLogger("IngressEventHub");
            logger.LogInformation($"First Event Hubs triggered message: {input[0]}");
        }
        public async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
                                                 FunctionContext executionContext)
        {
            var log = executionContext.GetLogger <Function1>();

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

            var    query = HttpUtility.ParseQueryString(req.Url.Query);
            string name  = query["name"];

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

            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            var response = req.CreateResponse(HttpStatusCode.OK);

            response.Headers.Add("Content", "Content-Type: text/html; charset=utf-8");
            response.WriteString(responseMessage);

            return(response);
        }
 public TestData QueueTriggerAndOutputPoco(
     [QueueTrigger("test-input-dotnet-isolated-poco")] TestData message,
     FunctionContext context)
 {
     context.GetLogger <QueueTestFunctions>().LogInformation(".NET Queue trigger POCO function processed a message: " + message.Id);
     return(message);
 }
Esempio n. 14
0
        public async Task <IReadOnlyList <AdvocateModel> > GetAzureAdvocatesTimerTrigger([TimerTrigger(_runOncePerMonth)] TimerInfo myTimer, FunctionContext context)
        {
            var log = context.GetLogger <GetAdvocatesFunction>();

            log.LogInformation($"{nameof(GetAzureAdvocatesTimerTrigger)} Started");

            var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            var optOutList = await _optOutDatabase.GetAllOptOutModels().ConfigureAwait(false);

            var currentAdvocateList = await _advocateService.GetCurrentAdvocates(cancellationTokenSource.Token).ConfigureAwait(false);

            var advocateModels = new List <AdvocateModel>();

            foreach (var advocate in currentAdvocateList)
            {
                if (!HasUserOptedOut(advocate, optOutList))
                {
                    advocateModels.Add(advocate);
                }
            }

            log.LogInformation($"{nameof(GetAzureAdvocatesTimerTrigger)} Completed");

            return(advocateModels);
        }
        public async Task <HttpResponseData> GetCourseDirectoryQualificationJson(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequestData request,
            FunctionContext functionContext)
        {
            var logger = functionContext.GetLogger("HttpFunction");

            try
            {
                logger.LogInformation("Course directory GetCourseDirectoryQualificationJson function was called.");

                var json = await _courseDirectoryDataService.GetTLevelQualificationJsonFromCourseDirectoryApi();

                var response = request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "application/json");
                await response.WriteStringAsync(json);

                return(response);
            }
            catch (Exception e)
            {
                var errorMessage = $"Error reading json data from course directory. Internal Error Message {e}";
                logger.LogError(errorMessage);

                return(request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
        public static async Task Run([ServiceBusTrigger(
                                          "<your_queue_name>",
                                          Connection = "QueueConnectionString")]
                                     byte[] item,
                                     Int32 deliveryCount,
                                     DateTime enqueuedTimeUtc,
                                     string messageId,
                                     IDictionary <string, object> UserProperties,
                                     FunctionContext context)
        {
            var logger = context.GetLogger("ServiceBusFunction");

            logger.LogInformation($"MessageID: {messageId}");
            FunctionInputData functionInputData = new FunctionInputData(item, messageId, UserProperties);

            var settings =
                new StorageSettingData(
                    "<your_blob_storage_container_name>",
                    "<your_blob_storage_connection_string>",
                    VeryLargeMessageStrategy.Storage);
            FunctionMessageReader reader = new FunctionMessageReader(settings);

            await reader.SubScribe(functionInputData,
                                   (arg) =>
            {
                //PUT HERE YOUR MESSAGE HANDLING LOGIC
                logger.LogInformation($"function processed object: {arg.ReceivedEventMessage?.ObjectName??arg.ReceivedEventMessage.Body.Substring(0,10)}");
            });

            return;
        }
        public async Task <HttpResponseData> ManualImport(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequestData request,
            FunctionContext functionContext)
        {
            var logger = functionContext.GetLogger("HttpFunction");

            try
            {
                logger.LogInformation("Course directory manual import function was called.");

                var(savedProviders, deletedProviders, savedQualifications, deletedQualifications) = await Import(logger);

                logger.LogInformation("Course directory manual import finished.");

                var response = request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "application/text");

                await response.WriteStringAsync(
                    $"Inserted or updated {savedProviders} and deleted {deletedProviders} providers.\r\n" +
                    $"Inserted or updated {savedQualifications} and deleted {deletedQualifications} qualifications.");

                return(response);
            }
            catch (Exception e)
            {
                var errorMessage = $"Error importing data from course directory. Internal Error Message {e}";
                logger.LogError(errorMessage);

                return(request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 18
0
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req, FunctionContext context)
        {
            var log = context.GetLogger(nameof(GetAppCenterApiKeys));

            log.LogInformation("Retrieving Client Id");

            if (string.IsNullOrWhiteSpace(_iOS))
            {
                var notFoundResponse = req.CreateResponse(HttpStatusCode.NotFound);
                await notFoundResponse.WriteStringAsync($"{nameof(_iOS)} Not Found").ConfigureAwait(false);

                return(notFoundResponse);
            }
            else if (string.IsNullOrWhiteSpace(_android))
            {
                var notFoundResponse = req.CreateResponse(HttpStatusCode.NotFound);
                await notFoundResponse.WriteStringAsync($"{nameof(_android)} Not Found").ConfigureAwait(false);

                return(notFoundResponse);
            }
            else
            {
                var response = req.CreateResponse(HttpStatusCode.OK);

                var appCenterApiKeyDtoJson = JsonConvert.SerializeObject(new AppCenterApiKeyDTO(_iOS, _android));

                await response.WriteStringAsync(appCenterApiKeyDtoJson).ConfigureAwait(false);

                return(response);
            }
        }
Esempio n. 19
0
        public async Task <HttpResponseData> Blob(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestData req,
            [BlobInput("samples/Sample.mp4", Connection = "AzureWebJobsStorage")] Stream sample,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("HttpFunction");

            logger.LogInformation("message logged");

            var blobContainerClient = blobServiceClient.GetBlobContainerClient("test");

            await blobContainerClient.CreateIfNotExistsAsync();

            var blobClient = blobContainerClient.GetBlobClient("sample.mp4");

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            await blobClient.UploadAsync(sample);

            stopwatch.Stop();

            var response = req.CreateResponse(HttpStatusCode.OK);
            var buffer   = Encoding.UTF8.GetBytes(stopwatch.ElapsedMilliseconds.ToString());
            await response.Body.WriteAsync(buffer, 0, buffer.Length);

            return(response);
        }
Esempio n. 20
0
        /// <inheritdoc/>
        public async Task <HttpResponseData> RenderOpenApiDocument(HttpRequestData req, string version, string extension, FunctionContext ctx)
        {
            var log = ctx.GetLogger(nameof(OpenApiTriggerFunction));

            log.LogInformation($"{version}.{extension} was requested.");

            var fi       = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
            var request  = new HttpRequestObject(req);
            var result   = default(string);
            var response = default(HttpResponseData);

            try
            {
                var auth = await this._context
                           .SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin : false)
                           .AuthorizeAsync(request)
                           .ConfigureAwait(false);

                if (!auth.IsNullOrDefault())
                {
                    response = req.CreateResponse(auth.StatusCode);
                    response.Headers.Add("Content-Type", auth.ContentType);
                    await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

                    return(response);
                }

                result = await this._context
                         .Document
                         .InitialiseDocument()
                         .AddMetadata(this._context.OpenApiConfigurationOptions.Info)
                         .AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
                         .AddNamingStrategy(this._context.NamingStrategy)
                         .AddVisitors(this._context.GetVisitorCollection())
                         .Build(this._context.ApplicationAssembly, this._context.GetOpenApiVersionType(version))
                         .ApplyDocumentFilters(this._context.GetDocumentFilterCollection())
                         .RenderAsync(this._context.GetOpenApiSpecVersion(version), this._context.GetOpenApiFormat(extension))
                         .ConfigureAwait(false);

                response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", this._context.GetOpenApiFormat(extension).GetContentType());
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

                result = ex.Message;
                if (this._context.IsDevelopment)
                {
                    result += "\r\n\r\n";
                    result += ex.StackTrace;
                }
                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.Headers.Add("Content-Type", ContentTypeText);
                await response.WriteStringAsync(result).ConfigureAwait(false);
            }

            return(response);
        }
Esempio n. 21
0
        public async Task SendPushNotificationHandler(
            [QueueTrigger("%ENVIRONMENT%-" + QueueNames.SendPushNotification, Connection = "StorageConnection")] string message,
            FunctionContext executionContext
            )
        {
            var logger = executionContext.GetLogger(FunctionNames.SendPushNotification);

            logger.LogInformation("Function '{FunctionName}' was triggered.", FunctionNames.SendPushNotification);
            var pushNotification = JsonSerializer.Deserialize <PushNotificationQueueItem>(message, JsonSerializerOptionDefaults.GetDefaultSettings());
            var data             = pushNotification.Campaign?.Data ?? new ExpandoObject();
            var dataDictionary   = data as IDictionary <string, object>;

            if (!dataDictionary.ContainsKey("id"))
            {
                data.TryAdd("id", pushNotification.Campaign.Id);
            }
            if (pushNotification.Broadcast)
            {
                await PushNotificationService.BroadcastAsync(pushNotification.Campaign.Title, pushNotification.Campaign.Content, data, pushNotification.Campaign?.Type?.Name);
            }
            else
            {
                await PushNotificationService.SendAsync(pushNotification.Campaign.Title, pushNotification.Campaign.Content, data, pushNotification.UserCode, classification : pushNotification.Campaign?.Type?.Name);
            }
        }
Esempio n. 22
0
        public async Task RunAsync(
            [ServiceBusTrigger("%QueueListenerName%", Connection = "ServiceBusConnectionString", IsSessionsEnabled = true)]
            byte[] message,
            FunctionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var logger = context.GetLogger("ReplyToRequestFromPostOffice");

            logger.LogInformation($"C# ServiceBus queue trigger function processesing message: {message}");

            try
            {
                var bundleRequestDto             = _requestBundleParser.Parse(message);
                var requestDataBundleResponseDto = await CreateResponseAsync(bundleRequestDto).ConfigureAwait(false);

                await _responseSender.SendAsync(requestDataBundleResponseDto).ConfigureAwait(false);
            }
            catch (MessageHubStorageException e)
            {
                logger.LogError("Error Processing message: {0}", e);
                throw;
            }
        }
        public async Task <SubmissionResponse> Submit([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "markers")] HttpRequestData req,
                                                      FunctionContext context)
        {
            var logger = context.GetLogger("submit-markers");

            using var streamReader = new StreamReader(req.Body);
            var submission = streamReader.ReadToEnd().Deserialize <MarkerSubmissionDto>();

            if (string.IsNullOrEmpty(submission.Name) || string.IsNullOrEmpty(submission.Description))
            {
                return(new SubmissionResponse
                {
                    Response = req.CreateResponse(HttpStatusCode.BadRequest)
                });
            }

            string fileHandle = null;

            if (!string.IsNullOrEmpty(submission.Base64Image))
            {
                var fileBytes = Convert.FromBase64String(submission.Base64Image);
                fileHandle = await imageStorageService.UploadFileAndGetHandle(fileBytes);
            }

            var pending = await markersService.AddMarkerSubmission(submission, fileHandle);

            logger.LogInformation($"DeepLinkBaseUrl: {pending.DeepLinkBaseUrl}");
            return(new SubmissionResponse
            {
                QueueMessage = pending,
                Response = req.CreateResponse(HttpStatusCode.OK)
            });
        }
Esempio n. 24
0
        public async Task InsertIntoLeaderboard(
            [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger <LeaderboardFunction>();

            logger.LogInformation("Insert Into Leaderboard");

            try
            {
                var e = await req.Deserialize <BoardEntry>();

                var board = new Board {
                    UserId = e.UserId, NumOfWorkouts = e.NumOfWorkouts
                };
                var boardUser = new BoardUser
                {
                    UserId      = e.UserId,
                    Email       = e.Email,
                    LastWorkout = e.LastWorkout,
                    Name        = e.Name
                };

                board.User = boardUser;

                _d.Store.Boards.Add(board);
                await _d.Store.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, nameof(InsertIntoLeaderboard));
                throw;
            }
        }
        public async Task Run(
            [KafkaTrigger("KAFKA_BROKERS", "minio-events-inputs", ConsumerGroup = "input-processor-group")]
            KafkaMessage ev,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("InputProcessorFunc");

            logger.LogInformation("InputProcessorFunc start");

            var minioEvent = JsonSerializer.Deserialize <S3ObjectEvent>(ev.Value);

            switch (minioEvent.EventName)
            {
            case "s3:ObjectRemoved:Delete":
                logger.LogInformation($"deleted {minioEvent.Key}");
                break;

            case "s3:ObjectCreated:Put":
            {
                await InputObjectCreated(logger, minioEvent);

                break;
            }

            default:
                logger.LogInformation($"no executor for {minioEvent.EventName}");
                break;
            }
        }
Esempio n. 26
0
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
                                                        FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("Post");

            logger.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            Tarefa obj         = JsonConvert.DeserializeObject <Tarefa>(requestBody);
            var    repositorio = new TarefaRepositorio();
            var    okRetorno   = req.CreateResponse();

            if (obj == null)
            {
                await okRetorno.WriteAsJsonAsync(new BadRequestObjectResult(new { message = "Dados para criação de uma tarefa é obrigatoria" }));
            }
            else
            {
                obj.Id       = Guid.NewGuid();
                obj.DtCreate = DateTime.UtcNow;
                await repositorio.Save(obj);

                await okRetorno.WriteAsJsonAsync(new CreatedResult("", obj));
            }

            return(okRetorno);
        }
Esempio n. 27
0
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req,
                                                        FunctionContext executionContext)
        {
            var    repositorio = new TarefaRepositorio();
            var    okRetorno   = req.CreateResponse();
            var    logger      = executionContext.GetLogger("GetById");
            Tarefa tarefa      = new();

            logger.LogInformation("C# HTTP trigger function processed a request.");
            var query = System.Web.HttpUtility.ParseQueryString(req.Url.Query);
            var value = query["id"];

            if (value != null)
            {
                tarefa = repositorio.GetById(new Guid(value));
                if (tarefa == null)
                {
                    okRetorno = req.CreateResponse(System.Net.HttpStatusCode.NotFound);
                }
                else
                {
                    await okRetorno.WriteAsJsonAsync(new OkObjectResult(tarefa));
                }
            }
            else
            {
                okRetorno = req.CreateResponse(System.Net.HttpStatusCode.BadRequest);
            }


            return(okRetorno);
        }
Esempio n. 28
0
        public async Task <HttpResponseData> RunHttpTrigger([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("HttpTrigger");

            var principal = await _authentication.AuthenticateAsync(executionContext, req);

            if (principal == null)
            {
                return(_authentication.ReplyUnauthorized(req));
            }

            var microsoftGraph = new GraphServiceClient(new DelegateAuthenticationProvider(async(request) =>
            {
                var token = await _authentication.GetAccessTokenForUserAsync(req, new string[] { "https://graph.microsoft.com/.default" });
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            }));

            var name = principal.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").First().Value;

            logger.LogInformation($"User is {name}!");

            var inbox = await microsoftGraph.Me.MailFolders.Inbox.Request().GetAsync();

            logger.LogInformation($"{name} has {inbox.UnreadItemCount} unread e-mails!");

            var response = req.CreateResponse(HttpStatusCode.OK);

            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString($"Welcome to Azure Functions Out-Of-Process, {name}!\n\nYou have {inbox.UnreadItemCount} unread e-mails!");

            return(response);
        }
Esempio n. 29
0
        public async Task <PlaceOrderOutputType> OrderProductV2Async([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
                                                                     FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("ProductFunctions");

            logger.LogInformation("Order Product is called");

            var output = new PlaceOrderOutputType();

            var order = await req.ReadFromJsonAsync <ProductOrder>();

            var p = ProductStore.Products.FirstOrDefault(x => x.Name == order.Name);

            if (p != null)
            {
                logger.LogInformation("Product found, sending message");
                output.HttpResponse = req.CreateResponse(HttpStatusCode.OK);
                output.Order        = new PlaceOrder
                {
                    OrderId = Guid.NewGuid().ToString(),
                    Product = p,
                    Buyer   = order.Buyer
                };
            }
            else
            {
                logger.LogWarning("Product not found");
                output.HttpResponse = req.CreateResponse(HttpStatusCode.NotFound);
            }
            return(output);
        }
Esempio n. 30
0
        public async Task Run([TimerTrigger("0 0 0 */1 * *")] MyInfo myTimer, FunctionContext context)
        {
            var log = context.GetLogger("HttpExample");

            log.LogInformation($"Getting Stats trigger function executed at: {DateTime.Now}");
            var connectionString = Environment.GetEnvironmentVariable("TMDBServerConnectionString");
            var sendGridApiKey   = Environment.GetEnvironmentVariable("SendGridApiKey");
            var instanceName     = Environment.GetEnvironmentVariable("InstanceName");

            var siteStats = new SiteStats();

            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();

                siteStats.UserCount = await CountUsers(log, conn).ConfigureAwait(false);

                siteStats.EventCount = await CountEvents(log, conn).ConfigureAwait(false);

                siteStats.AttendeeCount = await CountEventAttendees(log, conn).ConfigureAwait(false);

                siteStats.FutureEventsCount = await CountFutureEvents(log, conn).ConfigureAwait(false);

                siteStats.FutureEventAttendeesCount = await CountFutureEventAttendees(log, conn).ConfigureAwait(false);

                siteStats.ContactRequestsCount = await CountContactRequests(log, conn).ConfigureAwait(false);
            }

            await SendSummaryReport(siteStats, instanceName, sendGridApiKey).ConfigureAwait(false);
        }