public async System.Threading.Tasks.Task TestCheckGithubAsyncAsync()
        {
            var logger    = new MockLogger();
            var timerInfo = new TimerInfo(new MockSchedule(), null);
            var context   = new Microsoft.Azure.WebJobs.ExecutionContext()
            {
                InvocationId         = Guid.NewGuid(),
                FunctionAppDirectory = $@"C:\code\COVID19\COVID19_Azure_DataSync\COVI19_Timer_Function\bin\Debug\netcoreapp2.1"
            };


            IConfigurationRoot config = new ConfigurationBuilder()
                                        .SetBasePath(context.FunctionAppDirectory)
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            var AzureWebJobsStorage = config.GetValue <string>("Values:AzureWebJobsStorage");

            var covidTable = Helper.GetCloudTable("Covid19", AzureWebJobsStorage, logger, context);
            var syncTable  = Helper.GetCloudTable("SyncStatus", AzureWebJobsStorage, logger, context);
            var errorTable = Helper.GetCloudTable("ErrorLogs", AzureWebJobsStorage, logger, context);

            ICollector <string> queue = new MockCollector <string>();


            var function = new COIVD19_Api(new COVIDService(new System.Net.Http.HttpClient()));
            await function.CheckGithubAsync(timerInfo, syncTable, queue, logger);
        }
Beispiel #2
0
        public static async Task <HttpResponseMessage> Run(
            Microsoft.Azure.WebJobs.ExecutionContext context,
            HttpRequest request,
            ILogger log)

        {
            try
            {
                var configuration = HostConfiguration <THost> .GetConfiguration(context.FunctionAppDirectory);

                var serverRecords = TenantApps <TStartup> .GetServerRecords(context.FunctionAppDirectory, configuration, log);

                var path = new PathString(request.Path.Value.ToLower());
                log.LogInformation($"C# HTTP trigger:{request.Method} {path}.");

                var query = from item in serverRecords
                            where path.StartsWithSegments(item.PathStringBaseUrl)
                            select item;
                var serverRecord             = query.FirstOrDefault();
                HttpResponseMessage response = null;
                if (serverRecord == null)
                {
                    response = new HttpResponseMessage(HttpStatusCode.NotFound);
                    return(response);
                }


                var httpRequestMessageFeature = new TenantHttpRequestMessageFeature(request);
                var httpRequestMessage        = httpRequestMessageFeature.HttpRequestMessage;

                HttpClient client = serverRecord.TestServer.CreateClient();
                client.BaseAddress = new Uri($"{request.Scheme}://{request.Host}");

                // trim off the front router hints
                path = path.Value.Substring(serverRecord.PathStringBaseUrl.Value.Length);
                var uriBuilder = new UriBuilder(request.Scheme, request.Host.Host)
                {
                    Path  = path,
                    Query = request.QueryString.Value
                };
                if (request.Host.Port != null)
                {
                    uriBuilder.Port = (int)request.Host.Port;
                }

                httpRequestMessage.RequestUri = uriBuilder.Uri;
                httpRequestMessage.Headers.Remove("Host");
                var responseMessage = await client.SendAsync(httpRequestMessage);

                return(responseMessage);
            }
            catch (Exception e)
            {
                log.LogError(e, $"MainEntry Exception:{e.Message}");
                return(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
        public async Task <IActionResult> ExecuteManuallyAsync(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = "")] HttpRequestMessage req,
            CancellationToken cancellationToken,
            ExecutionContext executionContext)
        {
            var q    = req.RequestUri.ParseQueryString();
            var body = await req.Content.ReadAsStringAsync();

            var overrides = JsonConvert.DeserializeObject <Overrides>(body) ?? Overrides.None;

            // keep legacy parameter around until next breaking change is introduced
            var value = q.GetValues("NewCertificate")?.FirstOrDefault();

            if (!string.IsNullOrEmpty(value))
            {
                _logger.LogWarning("Detected legacy querystring parameter \"newCertificate\" which will be removed in a future version! " +
                                   "Please provide the \"forceNewCertificates\" parameter in the body instead. " +
                                   "See the changelog for details: https://github.com/MarcStan/lets-encrypt-azure/blob/master/Changelog.md");
                overrides.ForceNewCertificates = "true".Equals(value, StringComparison.OrdinalIgnoreCase);
            }
            try
            {
                await RenewAsync(overrides, executionContext, cancellationToken);

                return(new AcceptedResult());
            }
            catch (Exception)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Certificate renewal failed, check appinsights for details"
                }));
            }
        }
        public static async Task <ResponseObject> DeviceSleepCheck(
            [OrchestrationTrigger] DurableOrchestrationContext context, Microsoft.Azure.WebJobs.ExecutionContext executionContext, ILogger log)
        {
            var devAddr           = context.GetInput <string>();
            var jsonTempaltesPath = Path.Combine(executionContext.FunctionDirectory, @"..\json_templates");
            var json = File.ReadAllText(jsonTempaltesPath + @"\enumerate.json");

            json = json.Replace("#DEV_ADDR#", $"{devAddr}");

            while (true)
            {
                var resEnum = await context.CallSubOrchestratorAsync <string>("GWSendCommandWithResponse", json);


                var errorMessage = Utils.CheckResponse(resEnum, out dynamic resEnumJObject);
                if (errorMessage != "" && resEnumJObject.data.statusStr != "info missing")
                {
                    log.LogInformation("Enumerate error: " + errorMessage);
                    return(new ResponseObject(ResultMessages.ErrorResult, ResultMessages.DiscoveryError, errorMessage));
                }

                if (resEnumJObject.data.statusStr != "info missing")
                {
                    return(new ResponseObject(ResultMessages.Success, ResultMessages.EnumerateSuccess, resEnum));
                }
                else
                {
                    // Orchestration sleeps until this time.
                    var nextCheck = context.CurrentUtcDateTime.AddSeconds(10);
                    await context.CreateTimer(nextCheck, CancellationToken.None);
                }
            }
        }
Beispiel #5
0
        public async Task <IActionResult> ExportIssuersZip(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "issuers/export/zip")] ExportIssuersQuery queryArg,
            HttpRequest req,
            Microsoft.Azure.WebJobs.ExecutionContext context,
            ILogger log)
        {
            return(await ExecuteAsync <ExportIssuersQuery, ExportIssuersResponse>(context,
                                                                                  req,
                                                                                  queryArg,
                                                                                  async (r) => {
                var outputStream = new MemoryStream();
                using (var zipArchive = new ZipArchive(outputStream, ZipArchiveMode.Create, true))
                {
                    var zipEntry = zipArchive.CreateEntry(r.FileName);
                    using (var zipStream = zipEntry.Open())
                    {
                        using (var ms = new MemoryStream(r.Content))
                        {
                            await ms.CopyToAsync(zipStream);
                        }
                    }
                }

                outputStream.Position = 0;
                var result = new FileStreamResult(outputStream, "application/octet-stream")
                {
                    FileDownloadName = "export.zip"
                };
                return result;
            }));
        }
Beispiel #6
0
        public static void Run(
            [EventHubTrigger("%EventHubName%", Connection = "EventHubConnection", ConsumerGroup = "%ConsumerGroupName%")] EventData[] eventHubMessages,
            Microsoft.Azure.WebJobs.ExecutionContext exCtx,
            PartitionContext PartitionContext,
            TraceWriter log)
        {
            try
            {
                log.Info($"Function1 | Run - functionId: {exCtx.InvocationId}");

                Schema writerObjectSchema = Schema.Parse(SchemaClass.SCHEMA_OBJECT_ENTITY);
                Avro.Specific.SpecificDatumReader <ObjectEntity> r = new Avro.Specific.SpecificDatumReader <ObjectEntity>(writerObjectSchema, writerObjectSchema);

                for (int i = 0; i < eventHubMessages.Length; i++)
                {
                    ObjectEntity objectEntityWithSchema = null;

                    using (MemoryStream memStream = new MemoryStream(eventHubMessages[i].GetBytes()))
                    {
                        memStream.Seek(0, SeekOrigin.Begin);
                        objectEntityWithSchema = r.Read(null, new Avro.IO.BinaryDecoder(memStream));
                    }

                    /// Here use the deserialized object for your logic
                    /// Put your code here
                    ///
                }
                log.Info($"Function1 | Run - functionId: {exCtx.InvocationId}");
            }
            catch (Exception ex)
            {
                log.Error($"Function1 | Run - functionId: {exCtx.InvocationId}. Error StackTrace: {ex.StackTrace}");
                throw;
            }
        }
        public static int AddTask(Microsoft.Azure.WebJobs.ExecutionContext execContext, CloudMediaContext context, IJob job, IAsset sourceAsset, string value, string processor, string presetfilename, string stringtoreplace, ref int taskindex, int priority = 10, string specifiedStorageAccountName = null)
        {
            if (value != null)
            {
                // Get a media processor reference, and pass to it the name of the
                // processor to use for the specific task.
                IMediaProcessor mediaProcessor = MediaServicesHelper.GetLatestMediaProcessorByName(context, processor);

                string presetPath = Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", presetfilename);

                string Configuration = File.ReadAllText(presetPath).Replace(stringtoreplace, value);

                // Create a task with the encoding details, using a string preset.
                var task = job.Tasks.AddNew(processor + " task",
                                            mediaProcessor,
                                            Configuration,
                                            TaskOptions.None);

                task.Priority = priority;

                // Specify the input asset to be indexed.
                task.InputAssets.Add(sourceAsset);

                // Add an output asset to contain the results of the job.
                // Use a non default storage account in case this was provided in 'AddTask'

                task.OutputAssets.AddNew(sourceAsset.Name + " " + processor + " Output", specifiedStorageAccountName, AssetCreationOptions.None);

                return(taskindex++);
            }
            else
            {
                return(-1);
            }
        }
Beispiel #8
0
        public static async Task <IActionResult> GetTextSentimentAzure(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "text/sentiment/azure")]
            HttpRequest request,
            TraceWriter traceWriter,
            ExecutionContext executionContext
            )
        {
            var appsettings = new AppSettings(executionContext);
            var azureCognitiveServicesConfig = appsettings.AzureCognitiveServicesConfig;

            _textAnalyticsClient = _textAnalyticsClient ?? GetTextAnalyticsClient(azureCognitiveServicesConfig);

            var documentBatch = JsonConvert.DeserializeObject <DocumentBatch>(await GetBodyAsString(request));

            var documents = documentBatch.Documents.Select((Models.Document doc) => new MultiLanguageInput
            {
                Id       = doc.Id,
                Language = doc.LanguageCode,
                Text     = doc.Text
            }).ToList();

            try
            {
                var sentimentBatchResult = await _textAnalyticsClient.SentimentAsync(new MultiLanguageBatchInput(documents));

                var result = DocumentBatchSentimentUtil.FromSentimentBatchResult(sentimentBatchResult);
                return(new OkObjectResult(result));
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + ex.InnerException?.ToString();
                traceWriter.Error(error, ex);
                return(new BadRequestObjectResult(error));
            }
        }
Beispiel #9
0
        public static async Task <IActionResult> GetTextSentimentGoogle(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "text/sentiment/google")]
            HttpRequest request,
            TraceWriter traceWriter,
            ExecutionContext executionContext
            )
        {
            var appsettings = new AppSettings(executionContext);

            string bodyString = await GetBodyAsString(request);

            var documentBatch = JsonConvert.DeserializeObject <DocumentBatch>(bodyString.Trim());

            //var creds = GoogleCredential.FromJson(File.ReadAllText("CommentQulity-19b70adeab44.json"));
            var creds        = GoogleCredential.FromJson(JsonConvert.SerializeObject(appsettings.GoogleCredentialsData));
            var channelCreds = creds.ToChannelCredentials();
            var channel      = new Channel(LanguageServiceClient.DefaultEndpoint.ToString(), channelCreds);

            var langServiceClient = LanguageServiceClient.Create(channel);

            var analyzeSentimentRequest  = GetSentimentAnalysisRequest(documentBatch);
            var analyzeSentimentResponse = langServiceClient.AnalyzeSentiment(analyzeSentimentRequest);

            var result = DocumentBatchSentimentUtil.FromAnnotatedAnalyzeSentimentResponse(analyzeSentimentResponse);

            return(new ObjectResult(result));
        }
        public async Task Run(
            Microsoft.Azure.WebJobs.ExecutionContext context,
            [ServiceBusTrigger("sbq-queueflow", Connection = "ServiceBusConnection")] string myQueueItem,
            ILogger logger)
        {
            await dotnetcore.azFunction.AppShim.Global.InitializeShimAsync(context, _functionsAppShim, logger);

            var job  = _serializer.Deserialize <Job>(myQueueItem);
            var json = _serializer.Serialize(job);

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


            var httpRequestMessage = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost/api/MyServiceBusTriggerFunction")
            {
                Content = new StringContent(
                    json,
                    Encoding.UTF8, "application/json")
            };


            var response = await _functionsAppShim.SendAsync(context, httpRequestMessage);
        }
Beispiel #11
0
        public async Task <IActionResult> HttpTrigger(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
            HttpRequest request,
            ExecutionContext executionContext,
            CancellationToken cancellationToken
            )
        {
            var queryParameter = request.GetQueryParameterDictionary();

            var awaitSave = true;
            var dateTime  = DateTime.UtcNow;

            if (!queryParameter.TryGetValue("await", out var awaitSaveString) && !bool.TryParse(awaitSaveString, out awaitSave))
            {
                awaitSave = true;
            }

            if (queryParameter.TryGetValue("dtOffsetDays", out var dateTimeOffsetDaysString) && int.TryParse(dateTimeOffsetDaysString, out var offset))
            {
                dateTime = DateTime.UtcNow.AddDays(offset);
            }

            return(new ObjectResult(await this.HandleRequest(executionContext, awaitSave, dateTime, cancellationToken))
            {
                StatusCode = (int)HttpStatusCode.Accepted
            });
        }
        public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                               ILogger log,
                               ExecutionContext executionContext,
                               [ServiceBus("testqueue", Connection = "serviceBusConnectionString")] ICollector <Message> collector,
                               CancellationToken cancellationToken
                               //[Queue("markerqueue", Connection = "storageConnectionString")]ICollector<SomeResult> collector
                               )
        {
            /*
             * //string name = req.Query["name"];
             * string requestBody = new StreamReader(req.Body).ReadToEnd();
             * //dynamic data = JsonConvert.DeserializeObject(requestBody);
             * //name = name ?? data?.name;
             * using (StreamWriter writer = new StreamWriter(outputBlob))
             * {
             *  await writer.WriteAsync(requestBody);
             * }*/

            //return $"{Guid.NewGuid()}.json";

            CancellationTokenSource tokenSource = CancellationTokenSource.CreateLinkedTokenSource(req.HttpContext.RequestAborted, cancellationToken);

            string json = JsonConvert.SerializeObject(new SomeResult
            {
                Message = "Hello world"
            });
            Message message = new Message(Encoding.UTF8.GetBytes(json));

            collector.Add(message);
            //return new OkObjectResult();
        }
Beispiel #13
0
        public static async Task Run([OrchestrationTrigger] IDurableOrchestrationContext context,
                                     Microsoft.Azure.WebJobs.ExecutionContext executionContext, ILogger log)
        {
            log.LogInformation("Enter orchestration workflow");
            using (var timeoutCts = new CancellationTokenSource())
            {
                DateTime dueTime        = context.CurrentUtcDateTime.AddSeconds(15);
                Task     durableTimeout = context.CreateTimer(dueTime, timeoutCts.Token);

                log.LogInformation("Start timer");

                Task <bool> startEvent = context.WaitForExternalEvent <bool>("StartEvent");

                if (startEvent == await Task.WhenAny(startEvent, durableTimeout))
                {
                    timeoutCts.Cancel();
                    log.LogInformation("Stop timer");
                    return;
                }
                else
                {
                    await Stop(GetAzureContext(executionContext), log);

                    log.LogInformation("Stop instance");
                    return;
                }
            }
        }
Beispiel #14
0
        public static async Task Raise([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                                       [DurableClient] IDurableOrchestrationClient client,
                                       Microsoft.Azure.WebJobs.ExecutionContext executionContext,
                                       ILogger log)
        {
            string instanceId       = InstanceId;
            var    eventData        = req.Query["event"];
            var    existingInstance = await client.GetStatusAsync(instanceId);

            if (eventData == "stop")
            {
                log.LogInformation("Start orchestration");

                await client.StartNewAsync("OrchestrationWorkflow", instanceId);
            }
            else if (eventData == "start")
            {
                await Start(GetAzureContext(executionContext), log);

                if (existingInstance == null ||
                    existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Completed ||
                    existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Failed ||
                    existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Terminated)
                {
                    log.LogInformation("There is no timers to interrupt");
                }
                else
                {
                    log.LogInformation("Raise start instance event");

                    bool isStartEvent = true;
                    await client.RaiseEventAsync(instanceId, "StartEvent", isStartEvent);
                }
            }
        }
Beispiel #15
0
        private async Task OnExecutingAsync(HttpRequest request, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            // Extract token from header, return 'Unauthorized' error if the token is null.
            string token = string.Empty;

            if (request.Headers.ContainsKey("Authorization") && request.Headers["Authorization"][0].StartsWith("Bearer "))
            {
                token = request.Headers["Authorization"][0].Substring("Bearer ".Length);
            }
            else
            {
                request.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                throw new HttpRequestException("Unauthorized");
            }

            // Get Azure AD env settings
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            _instance = config["AzureAd:Instance"];
            _tenantId = config["AzureAd:TenantId"];
            _clientId = config["AzureAd:ClientId"];

            // Validate token (authorization)
            string audience = $"api://{_clientId}";

            _userClaim = await TokenValidation.VerifyUserHasAnyAcceptedScope(token, _instance, _tenantId, _clientId, audience, _allowedScopes, new CancellationToken());
        }
        public async Task <IActionResult> ExecuteManuallyAsync(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = "")] HttpRequestMessage req,
            CancellationToken cancellationToken,
            ExecutionContext executionContext)
        {
            var q         = req.RequestUri.ParseQueryString();
            var overrides = new Overrides
            {
                NewCertificate = "true".Equals(q.GetValues(nameof(Overrides.NewCertificate))?.FirstOrDefault(), StringComparison.OrdinalIgnoreCase)
            };

            try
            {
                await RenewAsync(overrides, executionContext, cancellationToken);

                return(new AcceptedResult());
            }
            catch (Exception)
            {
                return(new BadRequestObjectResult(new
                {
                    message = "Certificate renewal failed, check appinsights for details"
                }));
            }
        }
Beispiel #17
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "graphql")]
            HttpRequestMessage reqMessage,
            HttpRequest req,
            ExecutionContext context,
            ILogger log)
        {
            var httpContextAccessor = FunctionStartup.EstablishHttpContextAccessor(context, reqMessage, req);

            FunctionStartup.EstablishContextAccessor(context);
            await FunctionStartup.EstablishIdentityAsync(context, httpContextAccessor);

            var factory         = FunctionStartup.GetFactory(context);
            var functionHandler = factory.Create <IGraphQLFunction>();
            await functionHandler.InvokeAsync();

            return(httpContextAccessor.HttpResponseMessage);

            /*
             *
             * var tokenValidator = factory.ServiceProvider.GetService(typeof(ITokenValidator)) as ITokenValidator;
             * httpContextAccessor.HttpContext.User = await tokenValidator.ValidateTokenAsync(reqMessage.Headers.Authorization); ;
             *
             * if (httpContextAccessor.HttpContext.User == null)
             * {
             *  return reqMessage.CreateResponse(HttpStatusCode.Unauthorized);
             * }
             * // Authentication boilerplate code end
             *
             * return reqMessage.CreateResponse(HttpStatusCode.OK, "Hello " + httpContextAccessor.HttpContext.User.Identity.Name);
             */
        }
        public static async Task <HttpResponseMessage> HttpStart(
            [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestMessage req,
            [OrchestrationClient] DurableOrchestrationClient starter,
            TraceWriter log,
            Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            // Function input comes from the request content.
            VidUploadProcessRequest requestData = await req.Content.ReadAsAsync <VidUploadProcessRequest>();

            //Get the config settings and add them to the requestData object
            requestData.config = GetSettings(context);

            // Starting a new orchestrator with request data
            string instanceId = await starter.StartNewAsync("UploadVideo_Orchestrator", requestData);

            log.Info($"Started orchestration with ID = '{instanceId}'.");

            var response = starter.CreateCheckStatusResponse(req, instanceId);

            // I specify a response interval so the Logic App doesn't check the status
            // until after 10 seconds has passed. If work will be longer you can change this
            // value as needed.
            response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(10));
            return(response);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "getadwstatus")] HttpRequest req,
            ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            string  currentStatus;
            dynamic dbInfoObject;

            log.LogInformation("autoscaleup of adw initiated");

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            var kvURL    = config["KeyVaultURL"];

            try
            {
                var dwLocation = config["SqlDwLocation"];
                //var tableName = config["DwScaleLogsTable"];
                var dwuConfigFile    = config["DwuConfigFile"];
                var resourceIdSecret = config["ResourceId"];
                var resourceId       = (await kvClient.GetSecretAsync(kvURL, resourceIdSecret)).Value;
                //string startupPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName;
                //string dwuConfigFilePath = startupPath + "\\" + dwuConfigFile;
                //var dwuConfigManager = new DwuConfigManager(dwuConfigFilePath);

                //var taskResult = await Task.Factory.StartNew<int>(() =>
                //{
                //    Thread.Sleep(300000);
                //    return 0;
                //});

                // Create a DataWarehouseManagementClient
                var dwClient = await DwClientFactory.Create(resourceId.ToString(), context);

                do
                {
                    // Get database information
                    var dbInfo = dwClient.GetDatabase();

                    dbInfoObject  = JsonConvert.DeserializeObject(dbInfo);
                    currentStatus = dbInfoObject.properties.status.ToString();
                    //logEntity.DwuBefore = currentDwu;
                    log.LogInformation($"Current DWU is {currentStatus}");
                } while (currentStatus != "Online");



                return(new OkObjectResult(dbInfoObject));
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult($"Bad Operation {ex}"));
            }
        }
        public static async Task <HttpResponseMessage> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "analyze")] HttpRequestMessage request,
            TraceWriter log,
            ExecutionContext context,
            CancellationToken cancellationToken)
        {
            using (IUnityContainer childContainer = Container.CreateChildContainer().WithTracer(log, true))
            {
                // Create a tracer for this run (that will also log to the specified TraceWriter)
                IExtendedTracer tracer = childContainer.Resolve <IExtendedTracer>();
                tracer.TraceInformation($"Analyze function request received with invocation Id {context.InvocationId}");
                tracer.AddCustomProperty("FunctionName", context.FunctionName);
                tracer.AddCustomProperty("InvocationId", context.InvocationId.ToString("N", CultureInfo.InvariantCulture));

                try
                {
                    // Trace app counters (before analysis)
                    tracer.TraceAppCounters();

                    // Read the request
                    SmartDetectorExecutionRequest smartDetectorExecutionRequest = await request.Content.ReadAsAsync <SmartDetectorExecutionRequest>(cancellationToken);

                    tracer.AddCustomProperty("SmartDetectorId", smartDetectorExecutionRequest.SmartDetectorId);
                    tracer.TraceInformation($"Analyze request received: {JsonConvert.SerializeObject(smartDetectorExecutionRequest)}");

                    // Process the request
                    ISmartDetectorRunner runner = childContainer.Resolve <ISmartDetectorRunner>();
                    bool shouldDetectorTrace    = bool.Parse(ConfigurationReader.ReadConfig("ShouldDetectorTrace", required: true));
                    List <ContractsAlert> alertPresentations = await runner.RunAsync(smartDetectorExecutionRequest, shouldDetectorTrace, cancellationToken);

                    tracer.TraceInformation($"Analyze completed, returning {alertPresentations.Count} Alerts");

                    // Create the response with StringContent to prevent Json from serializing to a string
                    var response = request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(JsonConvert.SerializeObject(alertPresentations), Encoding.UTF8, "application/json");
                    return(response);
                }
                catch (AnalysisFailedException afe)
                {
                    // Handle the exception
                    TopLevelExceptionHandler.TraceUnhandledException(afe, tracer, log);

                    // Return error status
                    return(request.CreateResponse(afe.StatusCode, afe.ReasonPhrase));
                }
                catch (Exception e)
                {
                    // Handle the exception
                    TopLevelExceptionHandler.TraceUnhandledException(e, tracer, log);

                    // Return error status
                    return(request.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
                }
                finally
                {
                    // Trace app counters (after analysis)
                    tracer.TraceAppCounters();
                }
            }
        }
Beispiel #21
0
        public static async Task <IActionResult> LongTimeFunction(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [OrchestrationClient] DurableOrchestrationClient client,
            Microsoft.Azure.WebJobs.ExecutionContext context,
            ILogger log)
        {
            var cekResponse = new CEKResponse();
            var clovaClient = new ClovaClient();
            var cekRequest  = await clovaClient.GetRequest(req.Headers["SignatureCEK"], req.Body);

            switch (cekRequest.Request.Type)
            {
            case RequestType.LaunchRequest:
            {
                // UserId をインスタンス ID として新しい関数を実行
                await client.StartNewAsync(nameof(LongTimeOrchestrationFunction), cekRequest.Session.User.UserId, context.FunctionAppDirectory);

                cekResponse.AddText("時間のかかる処理を実行しました。結果はLINEでお知らせします。");
                break;
            }

            case RequestType.IntentRequest:
            default:
            {
                // インテントリクエスト他は特に用意しない
                cekResponse.AddText("すみません。よくわかりませんでした。");
                break;
            }
            }

            return(new OkObjectResult(cekResponse));
        }
        public string SayHello([ActivityTrigger] string name, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            logger.LogInformation("SayHello beginning " + " " + context.InvocationId);

            log.LogInformation($"Saying hello to {name}.");
            return($"Hello {name}!");
        }
Beispiel #23
0
        private static IAzure GetAzureContext(Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            //var azureAuthFile = Path.Combine(context.FunctionAppDirectory, AzureAuthFile);
            //var credentials = SdkContext.AzureCredentialsFactory
            //    .FromFile(Environment.GetEnvironmentVariable(azureAuthFile));

            var servicePrinciple = new ServicePrincipalLoginInformation()
            {
                ClientId     = ClientId,
                ClientSecret = Secret,
            };

            var azureCredentials = new AzureCredentials(servicePrinciple, TenantId, AzureEnvironment.AzureGlobalCloud);

            try
            {
                return(Microsoft.Azure.Management.Fluent.Azure
                       .Configure()
                       .Authenticate(azureCredentials).WithSubscription(SubscriptionName));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            Microsoft.Azure.WebJobs.ExecutionContext functionContext,
            ILogger log)
        {
            var init = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            log.LogInformation("C# HTTP trigger function START.");

            var    id         = functionContext.InvocationId;
            string instanceId = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");

            DoWork();
            // DoSleep();

            log.LogInformation("C# HTTP trigger function END.");
            var end = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            var res = new
            {
                Init         = init,
                End          = end,
                InvocationID = id,
                InstanceID   = instanceId
            };
            // string responseMessage = $"{init}, {end}, {id}";
            string responseMessage = JsonConvert.SerializeObject(res);

            return(new OkObjectResult(responseMessage));
        }
Beispiel #25
0
        private static void hae(ExecutionContext context, TraceWriter log, string videoId)
        {
            // ToDo: kinda slow for 10k comments. Consider using Durable Functions to split up the work

            var             appSettings    = new AppSettings(context);
            IYouTubeDataApi youtubeDataApi = new YouTubeDataApi(appSettings.YouTubeApiSettings);

            var commentThreadIterator = new CommentThreadIterator(youtubeDataApi);
            var commentIterator       = new CommentIterator(youtubeDataApi);

            var batchedCommentsProvider = new DocumentBatchProvider(
                new BatchedCommentsProviderConfig(10, 10000, document => !string.IsNullOrWhiteSpace(document.Text)),
                new CommentProvider(commentThreadIterator, commentIterator));

            batchedCommentsProvider.Init(videoId);

            DocumentBatch docBatch;

            while ((docBatch = batchedCommentsProvider.GetNextDocumentBatch()).Documents.Any())
            {
                foreach (var docBatchDocument in docBatch.Documents)
                {
                    log.Info($"{docBatchDocument.Id} - {docBatchDocument.Text}");
                }
            }
        }
Beispiel #26
0
        private async Task RenewAsync(
            Overrides overrides,
            ExecutionContext executionContext,
            CancellationToken cancellationToken)
        {
            var configurations = await _configurationLoader.LoadConfigFilesAsync(executionContext, cancellationToken);

            var stopwatch = new Stopwatch();
            // with lots of certificate renewals this could run into function timeout (10mins)
            // with 30 days to expiry (default setting) this isn't a big problem as next day all unfinished renewals are continued
            // user will only get email <= 14 days before expiry so acceptable for now
            var errors = new List <Exception>();

            foreach ((var name, var config) in configurations)
            {
                using (_logger.BeginScope($"Working on certificates from {name}"))
                {
                    foreach (var cert in config.Certificates)
                    {
                        stopwatch.Restart();
                        var hostNames = string.Join(";", cert.HostNames);
                        cert.Overrides = overrides ?? Overrides.None;
                        try
                        {
                            _logger.LogInformation($"await _renewalService.RenewCertificateAsync(config.Acme, cert, cancellationToken) {cert.TargetResource.Name}");
                            var result = await _renewalService.RenewCertificateAsync(config.Acme, cert, cancellationToken);

                            switch (result)
                            {
                            case RenewalResult.NoChange:
                                _logger.LogInformation($"Certificate renewal skipped for: {hostNames} (no change required yet)");
                                break;

                            case RenewalResult.Success:
                                _logger.LogInformation($"Certificate renewal succeeded for: {hostNames}");
                                break;

                            default:
                                throw new ArgumentOutOfRangeException(result.ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.LogError(e, $"Certificate renewal failed for: {hostNames}!");
                            errors.Add(e);
                        }
                        _logger.LogInformation($"Renewing certificates for {hostNames} took: {stopwatch.Elapsed}");
                    }
                }
            }
            if (!configurations.Any())
            {
                _logger.LogWarning("No configurations where processed, refere to the sample on how to set up configs!");
            }
            if (errors.Any())
            {
                throw new AggregateException("Failed to process all certificates", errors);
            }
        }
Beispiel #27
0
 public static async Task Run3(
     [QueueTrigger("Test3", Connection = "AzureWebJobsStorage")] string myQueueItem
     , ExecutionContext context
     , [Table("Test3", Connection = "AzureWebJobsStorage")] CloudTable table
     , TraceWriter log)
 {
     await Run(myQueueItem, context, table, log);
 }
 public static async Task <HttpResponseMessage> RunAllPaths(
     CancellationToken ct,
     [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", "patch", "options", Route = "{*x:regex(^(?!admin|debug|runtime).*$)}")] HttpRequestMessage req,
     ILogger log,
     ExecutionContext ctx)
 {
     return(await ServerHttpClient.SendAsync(req, ct));
 }
 public static async Task <HttpResponseMessage> RunRoot(
     CancellationToken ct,
     [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", "patch", "options", Route = "/")] HttpRequestMessage req,
     ILogger log,
     ExecutionContext ctx)
 {
     return(await ServerHttpClient.SendAsync(req, ct));
 }
Beispiel #30
0
        public static async Task Run([BlobTrigger("rawdocuments/{name}", Connection = "Documents")] CloudBlockBlob fileBlob,
                                     [Blob("parseddocuments", Connection = "Documents")] CloudBlobContainer parsedDirectory,
                                     ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context,
                                     CancellationToken cancellationToken)
        {
            try
            {
                if (fileBlob.Metadata.ContainsKey("DocumentType"))
                {
                    //skip already processed documents
                    return;
                }

                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                string predictionKey                 = config["PredictionKey"];
                string predictionProjectId           = config["PredictionProjectId"];
                string cognativeKey                  = config["CognativeKey"];
                double minimumPrecision              = double.Parse(config["MinimalPrecision"]);
                string computerVisionServiceHostName = config["ComputerVisionServiceHostName"];
                string customVisionServiceHostName   = config["CustomVisionServiceHostName"];

                string documentURLWithSAS = GetBlobSasUri(fileBlob);
                string tagName            = await AnalyseImageAsync(documentURLWithSAS, predictionKey, predictionProjectId, minimumPrecision, customVisionServiceHostName, cancellationToken);

                if (!tagName.IsEmpty())
                {
                    MortgageApplicationDocument mortgageApplicationDocument = new MortgageApplicationDocument();
                    mortgageApplicationDocument.PopuplateFromBlobProperties(fileBlob);
                    mortgageApplicationDocument.DateParsed = DateTimeOffset.UtcNow;

                    var parsedResults = await ParseDocumentTextAsync(documentURLWithSAS, cognativeKey, computerVisionServiceHostName, mortgageApplicationDocument.FileName, cancellationToken);

                    string parsedFileName = $"{tagName}/{fileBlob.Name.Trim('/')}";

                    CloudBlockBlob blob = parsedDirectory.GetBlockBlobReference(parsedFileName);
                    mortgageApplicationDocument.SetBlobProperties(blob);
                    blob.Properties.ContentType = "application/json";

                    await blob.UploadTextAsync(JsonConvert.SerializeObject(parsedResults));
                }
                else
                {
                    tagName = "N/A";
                }

                fileBlob.Metadata.Add("DocumentType", tagName);
                await fileBlob.SetMetadataAsync();
            }
            catch (Exception ex)
            {
                log.LogError($"Identity Document failed: {ex.ToString()}");
            }
        }