Exemplo n.º 1
0
        static void Main(string[] args)
        {
            var config = new JobHostConfiguration();

            config.DashboardConnectionString = null;

            // apply config before creating the host.
            var cloudToDeviceExtension = new IoTHubExtension.Config.IoTCloudToDeviceExtension();

            config.AddExtension(cloudToDeviceExtension);

            var directMethodExtension = new IoTHubExtension.Config.IoTDirectMethodExtension();

            config.AddExtension(directMethodExtension);

            var setDeviceTwinExtension = new IoTHubExtension.Config.IoTSetDeviceTwinExtension();

            config.AddExtension(setDeviceTwinExtension);

            var getDeviceTwinExtension = new IoTHubExtension.Config.IoTGetDeviceTwinExtension();

            config.AddExtension(getDeviceTwinExtension);

            // Debug diagnostics!
            config.CreateMetadataProvider().DebugDumpGraph(Console.Out);

            var host = new JobHost(config);

            //var method = typeof(Functions).GetMethod("Dummy");

            //Test some invocations.
            //var method = typeof(Functions).GetMethod("WriteMessageFromC2D");
            //host.Call(method);

            var method = typeof(Functions).GetMethod("WriteMessageFromC2DArg");

            host.Call(method, new { deviceId = "receiverBob" });

            //Test some invocations.
            method = typeof(Functions).GetMethod("DirectInvokeMethod");
            host.Call(method, new { deviceId = "receiverAlice" });

            //// Test some invocations.
            method = typeof(Functions).GetMethod("SetDeviceTwin");
            host.Call(method, new { deviceId = "receiverBob" });


            //// Test some invocations.
            method = typeof(Functions).GetMethod("GetDeviceTwinTwinObject");
            host.Call(method, new { deviceId = "receiverBob", messageId = "123" });

            // host.RunAndBlock();
        }
        public static JobHost NewHost <T>(EventGridExtensionConfig ext = null)
        {
            JobHostConfiguration config = new JobHostConfiguration();

            config.HostId = Guid.NewGuid().ToString("n");
            config.StorageConnectionString   = null;
            config.DashboardConnectionString = null;
            config.TypeLocator = new FakeTypeLocator <T>();
            config.AddExtension(ext ?? new EventGridExtensionConfig());
            config.AddExtension(new TestExtensionConfig());
            var host = new JobHost(config);

            return(host);
        }
        public void Test()
        {
            MyProg prog      = new MyProg();
            var    activator = new FakeActivator();

            activator.Add(prog);

            JobHostConfiguration config = TestHelpers.NewConfig <MyProg>(activator);

            var ext = new TestExtension();

            config.AddExtension(ext);

            var host = new TestJobHost <MyProg>(config);
            IJobHostMetadataProvider metadataProvider = host.CreateMetadataProvider();

            Assert.Equal(1, ext._counter);

            // Callable
            host.Call("Test");
            Assert.Equal(1, ext._counter);

            // Fact that we registered a Widget converter is enough to add the assembly
            Assembly asm;
            bool     resolved;

            resolved = metadataProvider.TryResolveAssembly(typeof(Widget).Assembly.GetName().Name, out asm);
            Assert.True(resolved);
            Assert.Same(asm, typeof(Widget).Assembly);

            // check with full name
            resolved = metadataProvider.TryResolveAssembly(typeof(Widget).Assembly.GetName().FullName, out asm);
            Assert.True(resolved);
            Assert.Same(asm, typeof(Widget).Assembly);

            // This requires the target attribute to be unique within the assembly.
            var attrType = metadataProvider.GetAttributeTypeFromName("Test9");

            Assert.Equal(typeof(Test9Attribute), attrType);

            // JObject --> Attribute
            var attr = GetAttr <Test9Attribute>(metadataProvider, new { Flag = "xyz" });

            Assert.Equal("xyz", attr.Flag);

            // Getting default type.
            var defaultType = metadataProvider.GetDefaultType(attr, FileAccess.Read, null);

            Assert.Equal(typeof(JObject), defaultType);

            // If we have no match for output, we'll try IAsyncCollector<string>
            Assert.Equal(typeof(IAsyncCollector <string>), metadataProvider.GetDefaultType(attr, FileAccess.Write, typeof(object)));
        }
        // Load a single extension
        private void LoadExtension(IExtensionConfigProvider instance, string locationHint = null)
        {
            JobHostConfiguration config = _config.HostConfig;

            var    type = instance.GetType();
            string name = type.Name;

            string msg = $"Loaded custom extension: {name} from '{locationHint}'";

            _logger.LogInformation(msg);
            config.AddExtension(instance);
        }
Exemplo n.º 5
0
        public void Test()
        {
            MyProg prog      = new MyProg();
            var    activator = new FakeActivator();

            activator.Add(prog);

            JobHostConfiguration config = TestHelpers.NewConfig <MyProg>(activator);

            var ext = new TestExtension();

            config.AddExtension(ext);

            IJobHostMetadataProvider tooling = config.CreateMetadataProvider();

            Assert.Equal(1, ext._counter);

            // Callable
            var host = new TestJobHost <MyProg>(config);

            host.Call("Test");
            Assert.Equal(1, ext._counter);

            // Fact that we registered a Widget converter is enough to add the assembly
            Assembly asm;
            bool     resolved;

            resolved = tooling.TryResolveAssembly(typeof(Widget).Assembly.GetName().Name, out asm);
            Assert.True(resolved);
            Assert.Same(asm, typeof(Widget).Assembly);

            // check with full name
            resolved = tooling.TryResolveAssembly(typeof(Widget).Assembly.GetName().FullName, out asm);
            Assert.True(resolved);
            Assert.Same(asm, typeof(Widget).Assembly);

            var attrType = tooling.GetAttributeTypeFromName("Test");

            Assert.Equal(typeof(TestAttribute), attrType);

            // JObject --> Attribute
            var attr = GetAttr <TestAttribute>(tooling, new { Flag = "xyz" });

            Assert.Equal("xyz", attr.Flag);

            // Getting default type.
            var defaultType = tooling.GetDefaultType(attr, FileAccess.Read, null);

            Assert.Equal(typeof(JObject), defaultType);

            Assert.Throws <InvalidOperationException>(() => tooling.GetDefaultType(attr, FileAccess.Write, typeof(object)));
        }
        public static JobHost NewHost <T>(IExtensionConfigProvider ext)
        {
            JobHostConfiguration config = new JobHostConfiguration();

            config.HostId = Guid.NewGuid().ToString("n");
            config.StorageConnectionString   = null;
            config.DashboardConnectionString = null;
            config.TypeLocator = new FakeTypeLocator <T>();
            config.AddExtension(ext);
            var host = new JobHost(config);

            return(host);
        }
Exemplo n.º 7
0
        public SendGridScriptBindingProviderTests()
        {
            JobHostConfiguration config = new JobHostConfiguration();

            config.AddExtension(new SendGridConfiguration());
            TestTraceWriter traceWriter  = new TestTraceWriter(TraceLevel.Verbose);
            JObject         hostMetadata = new JObject();

            var provider = new GeneralScriptBindingProvider(config, hostMetadata, traceWriter);

            provider.CompleteInitialization();
            _provider = provider;
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var config = new JobHostConfiguration();

            config.DashboardConnectionString = null;
            config.HostId = "sample";

            // Register the dropbox extension
            if (args.Length != 2)
            {
                Console.WriteLine(@"Set arg[0] to the folder name, arg[1] to Dropbox OAuth string");
                return;
            }
            var folderName = args[0];
            var oauthToken = args[1];
            var ext        = new DropboxExtension
            {
                Connection = oauthToken
            };

            config.AddExtension(ext);


            // Invoke some calls that bind to the extension.
            var param = new Dictionary <string, object>
            {
                { "folder", folderName },
                { "name", "test" }
            };
            var host = new JobHost(config);

            host.CallAsync(nameof(SimpleClient)).Wait();


            host.CallAsync(nameof(SimpleWrite), param).Wait();

            host.CallAsync(nameof(SimpleWriteAsReturn), param).Wait();

            host.CallAsync(nameof(SimpleRead), param).Wait();

            host.CallAsync(nameof(CopyExample), param).Wait();
        }
Exemplo n.º 9
0
        private void LoadExtensions(JobHostConfiguration hostConfig, Assembly assembly, string locationHint)
        {
            // Traverseing the exported types will cause type loads and possible type-load failures.
            foreach (var type in assembly.ExportedTypes)
            {
                if (type.IsAbstract || !typeof(IExtensionConfigProvider).IsAssignableFrom(type))
                {
                    continue;
                }

                try
                {
                    IExtensionConfigProvider instance = (IExtensionConfigProvider)Activator.CreateInstance(type);
                    hostConfig.AddExtension(instance);
                }
                catch (Exception e)
                {
                    // this.TraceWriter.Error($"Failed to load custom extension {type} from '{locationHint}'", e);
                }
            }
        }
        public void TestServices()
        {
            // Test configuration similar to how ScriptRuntime works.
            // - config is created and immediatey passed to a JobHost ctor
            // - config is then initialized, including adding extensions
            // - extensions may register their own services.
            JobHostConfiguration config = new JobHostConfiguration();
            var host = new JobHost(config);

            var lockManager = config.GetService <IDistributedLockManager>();

            Assert.Null(lockManager); // Not initialized yet.

            var nameResolver = new FakeNameResolver();

            config.AddExtension(new TestExtension()); // this extension will add services.
            config.AddService <INameResolver>(nameResolver);

            //  Now succeeds when called on JobHost instead of Config object.
            lockManager = host.Services.GetService <IDistributedLockManager>();
            Assert.NotNull(lockManager);
            Assert.IsType <TestLockManager>(lockManager); // verify it's our custom type
        }
        // Static initialization. Returns a service provider with some new services initialized.
        // The new services:
        // - can retrieve static config like binders and converters; but the listeners haven't yet started.
        // - can be flowed into the runtime initialization to get a JobHost spun up and running.
        // This is just static initialization and should not need to make any network calls,
        // and so this method should not need to be async.
        // This can be called multiple times on a config, which is why it returns a new ServiceProviderWrapper
        // instead of modifying the config.
        public static ServiceProviderWrapper CreateStaticServices(this JobHostConfiguration config)
        {
            var services = new ServiceProviderWrapper(config);

            var consoleProvider = services.GetService <IConsoleProvider>();
            var nameResolver    = services.GetService <INameResolver>();
            IWebJobsExceptionHandler exceptionHandler   = services.GetService <IWebJobsExceptionHandler>();
            IQueueConfiguration      queueConfiguration = services.GetService <IQueueConfiguration>();
            var blobsConfiguration = config.Blobs;

            IStorageAccountProvider storageAccountProvider = services.GetService <IStorageAccountProvider>();
            IBindingProvider        bindingProvider        = services.GetService <IBindingProvider>();
            SingletonManager        singletonManager       = services.GetService <SingletonManager>();

            IHostIdProvider hostIdProvider = services.GetService <IHostIdProvider>();
            var             hostId         = config.HostId;

            if (hostId != null)
            {
                hostIdProvider = new FixedHostIdProvider(hostId);
            }

            // Need a deferred getter since the IFunctionIndexProvider service isn't created until later.
            Func <IFunctionIndexProvider> deferredGetter = () => services.GetService <IFunctionIndexProvider>();

            if (hostIdProvider == null)
            {
                hostIdProvider = new DynamicHostIdProvider(storageAccountProvider, deferredGetter);
            }
            services.AddService <IHostIdProvider>(hostIdProvider);

            AzureStorageDeploymentValidator.Validate();

            IExtensionTypeLocator extensionTypeLocator = services.GetService <IExtensionTypeLocator>();

            if (extensionTypeLocator == null)
            {
                extensionTypeLocator = new ExtensionTypeLocator(services.GetService <ITypeLocator>());
                services.AddService <IExtensionTypeLocator>(extensionTypeLocator);
            }

            ContextAccessor <IMessageEnqueuedWatcher> messageEnqueuedWatcherAccessor = new ContextAccessor <IMessageEnqueuedWatcher>();

            services.AddService(messageEnqueuedWatcherAccessor);
            ContextAccessor <IBlobWrittenWatcher> blobWrittenWatcherAccessor = new ContextAccessor <IBlobWrittenWatcher>();
            ISharedContextProvider sharedContextProvider = new SharedContextProvider();

            // Create a wrapper TraceWriter that delegates to both the user
            // TraceWriters specified via config (if present), as well as to Console
            TraceWriter trace = new ConsoleTraceWriter(config.Tracing, consoleProvider.Out);

            services.AddService <TraceWriter>(trace);

            // Add built-in extensions
            var metadataProvider = new JobHostMetadataProvider(deferredGetter);

            metadataProvider.AddAttributesFromAssembly(typeof(TableAttribute).Assembly);

            var  exts          = config.GetExtensions();
            bool builtinsAdded = exts.GetExtensions <IExtensionConfigProvider>().OfType <TableExtension>().Any();

            if (!builtinsAdded)
            {
                config.AddExtension(new TableExtension());
                config.AddExtension(new QueueExtension());
            }

            ExtensionConfigContext context = new ExtensionConfigContext
            {
                Config          = config,
                Trace           = trace,
                PerHostServices = services
            };

            InvokeExtensionConfigProviders(context);

            // After this point, all user configuration has been set.

            if (singletonManager == null)
            {
                var logger = config.LoggerFactory?.CreateLogger(LogCategories.Singleton);

                IDistributedLockManager lockManager = services.GetService <IDistributedLockManager>();
                if (lockManager == null)
                {
                    lockManager = new BlobLeaseDistributedLockManager(
                        storageAccountProvider,
                        trace,
                        logger);
                    services.AddService <IDistributedLockManager>(lockManager);
                }

                singletonManager = new SingletonManager(
                    lockManager,
                    config.Singleton,
                    trace,
                    exceptionHandler,
                    config.LoggerFactory,
                    hostIdProvider,
                    services.GetService <INameResolver>());
                services.AddService <SingletonManager>(singletonManager);
            }

            IExtensionRegistry      extensions             = services.GetExtensions();
            ITriggerBindingProvider triggerBindingProvider = DefaultTriggerBindingProvider.Create(nameResolver,
                                                                                                  storageAccountProvider, extensionTypeLocator, hostIdProvider, queueConfiguration, blobsConfiguration, exceptionHandler,
                                                                                                  messageEnqueuedWatcherAccessor, blobWrittenWatcherAccessor, sharedContextProvider, extensions, singletonManager, trace, config.LoggerFactory);

            services.AddService <ITriggerBindingProvider>(triggerBindingProvider);

            if (bindingProvider == null)
            {
                bindingProvider = DefaultBindingProvider.Create(nameResolver, config.LoggerFactory, storageAccountProvider, extensionTypeLocator, blobWrittenWatcherAccessor, extensions);
                services.AddService <IBindingProvider>(bindingProvider);
            }

            var converterManager = (ConverterManager)config.ConverterManager;

            metadataProvider.Initialize(bindingProvider, converterManager, exts);
            services.AddService <IJobHostMetadataProvider>(metadataProvider);

            return(services);
        }
Exemplo n.º 12
0
        static int Main(string[] args)
        {
            Console.WriteLine("WebJobs BYOB Extension Analyzer v0.1");

            var config = new JobHostConfiguration();

            config.DashboardConnectionString = null;

            if (args.Length == 0)
            {
                Console.WriteLine("Error: arg0 should be path to a WebJobs extension (either .dll or .csproj)");
                return(1);
            }
            var path = args[0];

            var      webjobsAsssembly = typeof(JobHostConfiguration).Assembly;
            Assembly asm = (path == "builtin") ? webjobsAsssembly : Load(path);

            var types = asm.GetTypes();

            Console.WriteLine("=============================");

            foreach (var type in asm.GetTypes())
            {
                if (typeof(IExtensionConfigProvider).IsAssignableFrom(type) && !type.IsInterface)
                {
                    Console.WriteLine("Found extension: {0}", type.FullName);

                    try
                    {
                        var obj       = Activator.CreateInstance(type);
                        var extension = (IExtensionConfigProvider)obj;

                        config.AddExtension(extension);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: Failed to instantiate extension: " + e.Message);
                    }
                }
            }
            Console.WriteLine();

            // This will run the extension's Initialize() method and build up the binding graph.
            var host     = new JobHost(config);
            var metadata = (JobHostMetadataProvider)host.Services.GetService(typeof(IJobHostMetadataProvider));

            var rules = metadata.GetRules();

            // Limit to just this extension
            if (asm != webjobsAsssembly)
            {
                rules = rules.Where(rule => rule.SourceAttribute.Assembly == asm).ToArray();
            }


            HashSet <Type> attrs = new HashSet <Type>();

            foreach (var rule in rules)
            {
                attrs.Add(rule.SourceAttribute);
            }
            DumpAttributes(attrs);

            Console.WriteLine("--------");
            Console.WriteLine("Binding Rules:");
            Console.WriteLine();
            DumpRule(rules, Console.Out);

            return(0);
        }
Exemplo n.º 13
0
 public DispatchQueueEndToEndTests(ITestOutputHelper output)
 {
     _output            = output;
     _hostConfiguration = new JobHostConfiguration();
     _hostConfiguration.AddExtension(new DispatchQueueTestConfig());
 }