Exemple #1
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var config = new JobHostConfiguration();

            config.UseTimers();
            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            Console.WriteLine("Starting WebJob");
            _engine = new InitializationEngine((IEnumerable <IInitializableModule>)null, HostType.WebApplication, new AssemblyList(true).AllowedAssemblies);
            Console.WriteLine("Episerver Initialization");
            _engine.Initialize();

            var cancellationToken = new WebJobsShutdownWatcher().Token;

            cancellationToken.Register(() =>
            {
                Console.WriteLine("Episerver Uninitialization");
                _engine.Uninitialize();
            });

            var host = new JobHost(config);

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
Exemple #2
0
        // https://github.com/Azure/azure-webjobs-sdk/issues/1940
        // https://github.com/Azure/azure-webjobs-sdk/issues/2088

        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        private static async Task Main()
        {
            var builder = new HostBuilder();

            builder.ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddAzureStorage();
                //b.AddTimers();
            });
            var host = builder.Build();

            var cancellationToken = new WebJobsShutdownWatcher().Token;

            cancellationToken.Register(() =>
            {
                host.Services.GetService <IJobHost>().StopAsync();
                // bye bye
            });

            using (host)
            {
                await host.StartAsync(cancellationToken);

                var jobHost = host.Services.GetService <IJobHost>();

                await jobHost.CallAsync(nameof(Functions.LongRunningContinuousProcess),
                                        cancellationToken : cancellationToken);
            }
        }
Exemple #3
0
        public static void ProcessQueueMessage([QueueTrigger("myfakequeue")] string message, ILogger logger)
        {
            var shutdownWatcher = new WebJobsShutdownWatcher();

            shutdownWatcher.Token.Register(() => ShutdownRequested(logger));
            Thread.Sleep(30000);
            logger.LogInformation(message);
        }
        public void InvalidPath()
        {
            using (new WebJobsShutdownContext(@"C:\This\path\should\not\exist"))
            using (var watcher = new WebJobsShutdownWatcher())
            {
                var token = watcher.Token;

                // When no env set, then token can never be cancelled. 
                Assert.True(!token.CanBeCanceled);
                Assert.True(!token.IsCancellationRequested);
            }
        }
Exemple #5
0
        public void InvalidPath()
        {
            using (new WebJobsShutdownContext(@"C:\This\path\should\not\exist"))
                using (var watcher = new WebJobsShutdownWatcher())
                {
                    var token = watcher.Token;

                    // When no env set, then token can never be cancelled.
                    Assert.True(!token.CanBeCanceled);
                    Assert.True(!token.IsCancellationRequested);
                }
        }
Exemple #6
0
        public void None()
        {
            // Env var not set
            using (new WebJobsShutdownContext(null))
                using (var watcher = new WebJobsShutdownWatcher())
                {
                    var token = watcher.Token;

                    // When no env set, then token can never be cancelled.
                    Assert.True(!token.CanBeCanceled);
                    Assert.True(!token.IsCancellationRequested);
                }
        }
        public void None()
        {
            // Env var not set
            using (new WebJobsShutdownContext(null))
            using (var watcher = new WebJobsShutdownWatcher())
            {
                var token = watcher.Token;

                // When no env set, then token can never be cancelled. 
                Assert.True(!token.CanBeCanceled);
                Assert.True(!token.IsCancellationRequested);
            }
        }
    static async Task Main(string[] args)
    {
        var host = new HostBuilder()
                   .ConfigureHost()
                   .Build();

        var cancellationToken = new WebJobsShutdownWatcher().Token;

        using (host)
        {
            await host.RunAsync(cancellationToken)
            .ConfigureAwait(false);
        }
    }
        public void Signaled()
        {
            using (WebJobsShutdownContext shutdownContext = new WebJobsShutdownContext())
            using (var watcher = new WebJobsShutdownWatcher())
            {
                var token = watcher.Token;
                Assert.True(!token.IsCancellationRequested);

                // Write the file
                shutdownContext.NotifyShutdown();

                // Token should be signaled very soon 
                Assert.True(token.WaitHandle.WaitOne(500));
            }
        }
Exemple #10
0
        public void Signaled()
        {
            using (WebJobsShutdownContext shutdownContext = new WebJobsShutdownContext())
                using (var watcher = new WebJobsShutdownWatcher())
                {
                    var token = watcher.Token;
                    Assert.True(!token.IsCancellationRequested);

                    // Write the file
                    shutdownContext.NotifyShutdown();

                    // Token should be signaled very soon
                    Assert.True(token.WaitHandle.WaitOne(500));
                }
        }
Exemple #11
0
        public static async Task Main()
        {
            var hostBuilder = new HostBuilder()
                              .ConfigureWebJobs(webJobsBuilder => {
                webJobsBuilder.AddAzureStorageCoreServices();
                webJobsBuilder.AddAzureStorage();
            })
                              .ConfigureLogging((context, loggingBuilder) => {
                // add your logging here - we'll use a simple console logger for this demo
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            })
                              .ConfigureServices((context, services) => {
                services
                .AddSingleton(context.Configuration);
            })
                              .UseConsoleLifetime();

            using (var host = hostBuilder.Build()) {
                var logger = host.Services.GetService <ILogger <Program> >();

                try {
#if DEBUG
                    Environment.SetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE", "c:\\temp\\WebJobsShutdown");
#endif

                    var watcher           = new WebJobsShutdownWatcher();
                    var cancellationToken = watcher.Token;

                    logger.LogInformation("Starting the host");
                    await host.StartAsync(cancellationToken);

                    var jobHost = host.Services.GetService <IJobHost>();

                    logger.LogInformation("Starting the Hangfire server");
                    await jobHost
                    .CallAsync(nameof(HangfireServer.RunServer),
                               cancellationToken : cancellationToken)
                    .ContinueWith(result => {
                        logger.LogInformation(
                            $"The job host stopped with state: {result.Status}");
                    }, cancellationToken);
                }
                catch (Exception ex) {
                    logger.LogError(ex.Message);
                }
            }
        }
Exemple #12
0
        public void NotSignaledAfterDisposed()
        {
            using (WebJobsShutdownContext shutdownContext = new WebJobsShutdownContext())
            {
                CancellationToken token;
                using (var watcher = new WebJobsShutdownWatcher())
                {
                    token = watcher.Token;
                    Assert.True(!token.IsCancellationRequested);
                }
                // Write the file
                shutdownContext.NotifyShutdown();

                Assert.True(!token.IsCancellationRequested);
            }
        }
Exemple #13
0
        static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            using (var host = new JobHost(config))
            {
                var token      = new WebJobsShutdownWatcher().Token;
                var methodInfo = typeof(Program).GetMethod(nameof(RunAsync));
                host.CallAsync(methodInfo, token).GetAwaiter().GetResult();
            }
        }
Exemple #14
0
        static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
                Console.WriteLine("Using Dev Settings");
            }
            var host            = new JobHost(config);
            var shutdownWatcher = new WebJobsShutdownWatcher();

            shutdownWatcher.Token.Register(() => ShutdownRequested());
            host.CallAsync(typeof(Functions).GetMethod("ProcessAQueueAsync"), new { message = "hello" });
            host.RunAndBlock();
        }
        public void NotSignaledAfterDisposed()
        {
            using (WebJobsShutdownContext shutdownContext = new WebJobsShutdownContext())
            {

                CancellationToken token;
                using (var watcher = new WebJobsShutdownWatcher())
                {
                    token = watcher.Token;
                    Assert.True(!token.IsCancellationRequested);
                }
                // Write the file
                shutdownContext.NotifyShutdown();

                Assert.True(!token.IsCancellationRequested);
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new ConsoleTraceListener());

            foreach (var assembly in typeof(PackageProcessor).Assembly.GetReferencedAssemblies())
            {
                Trace.WriteLine(assembly.FullName);
            }

            var cancelSource = new CancellationTokenSource();

            System.Console.CancelKeyPress += (o, e) =>
            {
                cancelSource.Cancel();
                e.Cancel = true;
            };

            var shutdownWatcher = new WebJobsShutdownWatcher();
            var shutdownSource  = CancellationTokenSource.CreateLinkedTokenSource(new[]
            {
                shutdownWatcher.Token,
                cancelSource.Token
            });

            var configuration = new DefaultConfigurationService();
            var builder       = new ContainerBuilder();

            DefaultContainerBuilder.Register(builder, configuration);
            SupportContainerBuilder.Register(builder, SupportEnvironment.WebJob);
            EmailContainerBuilder.Register(builder);
            PackageProcessorContainerBuilder.Register(builder);

            var container = builder.Build();

            var support = container.Resolve <ISupportConfiguration>();

            if (!string.IsNullOrWhiteSpace(support.InsightsInstrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = support.InsightsInstrumentationKey;
            }

            var scheduler = container.Resolve <ISchedulerService>();

            scheduler.ListenAndProcess(shutdownSource.Token);
        }
Exemple #17
0
        static void Main(string[] args)
        {
            try
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsetting.json", optional: true, reloadOnChange: true)
                              .AddEnvironmentVariables();

                IConfigurationRoot configuration = builder.Build();

                var appConfig = configuration.GetSection("Configurations").Get <Configurations>();

                if (appConfig == null)
                {
                    Console.WriteLine("No application configuration found!...");
                    Environment.Exit(0);
                }

                Console.WriteLine($"Simulator is running on ({appConfig.Environment}) environment.");


                var watcher = new WebJobsShutdownWatcher();

                if (DeviceManager.InitializeDevice(appConfig))
                {
                    TaskManager.InitializeTasksAndRun(appConfig);
                }

                var host = new JobHost(configuration, );
                host.CallAsync(typeof(Functions).GetMethod("ProcessMethod"));
                host.RunAndBlock();
            }
            catch (OperationCanceledException)
            { }
            catch (Exception ex)
            {
                Console.WriteLine($"Error occured while running simulator (Error: { ex.Message }");
            }
        }
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            var config = new JobHostConfiguration();

            if (config.IsDevelopment)
            {
                config.UseDevelopmentSettings();
            }

            var host = new JobHost(config);

            var cancellationToken = new WebJobsShutdownWatcher().Token;

            cancellationToken.Register(async() =>
            {
                try
                {
                    Console.WriteLine("-----" + "Shutdown started");
                    for (int i = 0; i < 30; i++)
                    {
                        Console.WriteLine(i);
                        await Task.Delay(1000);
                    }
                    Console.WriteLine("------" + "Shutdown complete");
                    host.Stop();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            });

            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
Exemple #19
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine($"{nameof(WebJob)} started");
            var cancellationToken = new WebJobsShutdownWatcher().Token;

            cancellationToken.Register(() =>
            {
                Console.WriteLine("Cancellation received");
                host.Stop();
            });
            // Assuming you want to get your shitty code up in the cloud ASAP
            // so I've created this minimalistic config
            var jobHostConfig = new JobHostConfiguration
            {
                HostId = Guid.NewGuid().ToString("N"),
                StorageConnectionString   = string.Empty,
                DashboardConnectionString = string.Empty
            };

            host = new JobHost(jobHostConfig);
            await host.CallAsync(nameof(OneTimeTask));

            Console.WriteLine($"{nameof(WebJob)} terminated");
        }
Exemple #20
0
        /// <summary>
        /// Execute a job with some arguments
        /// </summary>
        /// <param name="verbose"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        static int ExecuteJob(bool verbose, string[] args)
        {
            // Check if a parameter is defined

            switch (args.Length)
            {
            case 0:
                Info("Running Web jobs ...");

                // WebJob is running if and only if the application has a connection string to a storage account into azure environment

                string connectionString = ConfigurationManager.ConnectionStrings[ConfigurationManager.CONNEXION_STRING_AZURE]?.ConnectionString;
                if (String.IsNullOrWhiteSpace(connectionString))
                {
                    break;
                }

                // Run a function on terminating the application by the webjob process

                System.Threading.CancellationToken cancellationToken = new WebJobsShutdownWatcher().Token;
                cancellationToken.Register(() => {
                    // The process is correctly done ...
                    // This notification is raised on closing the web jobs
                    OnClose();
                });

                // Run WebJob in continuous mode

                JobHostConfiguration config = new JobHostConfiguration();
                if (config.IsDevelopment)
                {
                    config.UseDevelopmentSettings();
                }

                config.UseTimers();

                var host = new JobHost(config);
                host.RunAndBlock();
                return(0);

            case 1:
                Info("Running test ...");

                // run a module without any function

                switch (args[0])
                {
                case "Test":
                    return((new Syncytium.WebJob.Module.Test.Job()).Run(verbose, args.RemoveAt(0, 1)));
                }
                break;

            default:
                // run a module within a function

                switch (args[0])
                {
                case Syncytium.Module.Administration.DatabaseContext.AREA_NAME:
                    break;

                case Syncytium.Module.Customer.DatabaseContext.AREA_NAME:
                    break;
                }
                break;
            }

            Usage(args);
            return(-1);
        }