Ejemplo n.º 1
0
        /// <summary>
        /// thanks to https://github.com/kobake/AspNetCore.RouteAnalyzer/issues/28
        /// for the idea
        /// </summary>
        public static void CreateCronJobs(
            this IEndpointRouteBuilder endpoints,
            ISetCronJobClient cronJobClient,
            string baseUrl)
        {
            var cronJobEndPoints = endpoints
                                   .DataSources
                                   .SelectMany(dataSource => dataSource
                                               .Endpoints.OfType <RouteEndpoint>()
                                               .Select(ep => new
            {
                Endpoint = ep,
                CronJobs = ep.Metadata.OfType <SetCronJobAttribute>()
            }).Where(jobs => jobs.CronJobs.Any()));

            foreach (var ep in cronJobEndPoints)
            {
                // just spitballing here
                cronJobClient.CreateJobAsync(new CronJob()
                {
                    Url  = baseUrl + ep.Endpoint.RoutePattern.RawText,
                    Name = ep.Endpoint.DisplayName
                }).Wait();
            }
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISetCronJobClient cronJobClient)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapDefaultControllerRoute();
                endpoints.CreateCronJobs(cronJobClient, env.WebRootPath);
            });
        }
        private static async Task UpdateCronJobAsync(
            Account account, Notification notification, ISetCronJobClient cronJobClient,
            string baseUrl, string callbackFunctionCode, ILogger logger)
        {
            var cronJob = new CronJob()
            {
                Id         = notification.CronJobId ?? 0,
                Expression = notification.Schedule,
                Name       = $"{account.Name}.{notification.Name}",
                Status     = (notification.IsActive) ? JobStatus.Active : JobStatus.Disabled,
                TimeZone   = account.TimeZone,
                Method     = "GET",
                Url        = baseUrl + $"api/CronJobExecute?code={callbackFunctionCode}&accountId={account.Id}&name={notification.Name}"
            };

            string errorContext = null;

            try
            {
                if (notification.IsCronJobEnabled && !notification.CronJobId.HasValue)
                {
                    // create new
                    errorContext = "creating";
                    var result = await cronJobClient.CreateJobAsync(cronJob);

                    notification.CronJobId = result.Id;
                }
                else if (notification.CronJobId.HasValue)
                {
                    // update or disable
                    errorContext = "updating";
                    await cronJobClient.UpdateJobAsync(cronJob);
                }
            }
            catch (Exception exc)
            {
                string message = exc.Message + $" while {errorContext}";
                notification.CronJobMessage = message;
                logger?.LogError(exc, message);
            }
        }
        /// <summary>
        /// used to create (post) or update (put) a Notification object
        /// </summary>
        public static async Task <int> SaveNotificationAsync(
            SqlConnection connection, string accountName, string accountKey,
            Notification notification, ISetCronJobClient cronJobClient,
            string baseUrl, string callbackFunctionCode,
            ILogger logger)
        {
            var account = await AuthenticateAsync(connection, accountName, accountKey, logger);

            // notification must be in your account
            notification.AccountId = account.Id;

            // update cron job in backend service
            await UpdateCronJobAsync(account, notification, cronJobClient, baseUrl, callbackFunctionCode, logger);

            var user = new SystemUser(account.Name);

            // set the Id to 0 and merge so that you can't overwrite someone else's record
            notification.Id = 0;
            var notificationId = await connection.MergeAsync(notification, user : user);

            return(notificationId);
        }