public void Initialize() { this.settings = new FunctionGenerator.PhysicalAssemblySettings("TryCatch", "dll", AppDomain.CurrentDomain.BaseDirectory); this.functionGenerator = new FunctionGenerator(this.settings); this.provider = new TryCatchBlockProvider(this.functionGenerator); }
public void Initialize() { this.settings = new FunctionGenerator.PhysicalAssemblySettings("Log", "dll", AppDomain.CurrentDomain.BaseDirectory); this.functionGenerator = new FunctionGenerator(this.settings); this.provider = new LogProvider(this.functionGenerator, Visibility.Debug | Visibility.Warning); }
public void Initialize() { this.settings = new FunctionGenerator.PhysicalAssemblySettings("Translate", "dll", AppDomain.CurrentDomain.BaseDirectory); this.functionGenerator = new FunctionGenerator(this.settings); this.provider = new TranslationProvider(this.functionGenerator, shouldThrowExceptions: true); }
/// <summary> /// Creates an instance of <see cref="IBoilerplateContext"/> /// </summary> /// <param name="identity">The current identity being used (rights and roles contract requirements/restrictions will apply to this identity)</param> /// <param name="accessProvider">An access provider for specific types (available through IBoilerplateContext.Open<T>())</param> /// <param name="permissionsProvider">The provider that will be used for all permissions verification attempts</param> /// <param name="visibility">The visibility level that this context has. This will affect operations that rely on visibility (e.g. logging).</param> /// <returns>An instance of <see cref="IBoilerplateContext"/></returns> public static IBoilerplateContext New(IIdentity identity = null, ITypeAccessProvider accessProvider = null, IPermissionsProvider permissionsProvider = null, Visibility visibility = Visibility.None) { var actualIdentity = identity ?? Identity.Default; var actualTypeAccessProvider = accessProvider ?? TypeAccessProvider.Empty; var actualPermissionsProvider = permissionsProvider ?? PermissionsProvider.Default; var functionGenerator = new FunctionGenerator(); //Core providers var translationProvider = new TranslationProvider(functionGenerator); var validationProvider = new ValidationProvider(functionGenerator); var logProvider = new LogProvider(functionGenerator, visibility); //Set up error handling var tryCatchProvider = new TryCatchBlockProvider(functionGenerator); var exceptionHandlerProvider = new ExceptionHandlerProvider(logProvider); var errorContext = new ImmutableErrorContext(logProvider, tryCatchProvider, exceptionHandlerProvider); var bundle = new ContextBundle(permissionsProvider: actualPermissionsProvider, errorContext: errorContext, translationProvider: translationProvider, accessProvider: actualTypeAccessProvider, validationProvider: validationProvider, logProvider: logProvider, visibility: visibility); return new InitialBoilerplateContext<ContractContext>(bundle, actualIdentity); }
public void Generate_WithMultipleOutParameters() { string functionName = "FunctionWithOuts"; Collection <ParameterDescriptor> parameters = new Collection <ParameterDescriptor>(); parameters.Add(new ParameterDescriptor("param1", typeof(string))); parameters.Add(new ParameterDescriptor("param2", typeof(string).MakeByRefType()) { Attributes = ParameterAttributes.Out }); parameters.Add(new ParameterDescriptor("param3", typeof(string).MakeByRefType()) { Attributes = ParameterAttributes.Out }); FunctionMetadata metadata = new FunctionMetadata(); TestInvoker invoker = new TestInvoker(); FunctionDescriptor function = new FunctionDescriptor(functionName, invoker, metadata, parameters); Collection <FunctionDescriptor> functions = new Collection <FunctionDescriptor>(); functions.Add(function); // generate the Type Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", functions); // verify the generated function MethodInfo method = functionType.GetMethod(functionName); ParameterInfo[] functionParams = method.GetParameters(); // Verify that we have the correct number of parameters Assert.Equal(parameters.Count, functionParams.Length); // Verify that out parameters were correctly generated Assert.True(functionParams[1].IsOut); Assert.True(functionParams[2].IsOut); // Verify that the method is invocable method.Invoke(null, new object[] { "test", null, null }); // verify our custom invoker was called Assert.Equal(1, invoker.InvokeCount); }
public void ThrownArgumentNullExceptionWithArgumentExceptionBlockWillNotHandled() { var message = "Error message"; var handledExceptionTypes = ImmutableQueue <Type> .Empty .Enqueue(typeof(ArgumentNullException)); var handler = new Mock <IExceptionHandler <ArgumentNullException> >(MockBehavior.Strict); var handlerProvider = new Mock <IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); tryCatch.Try(() => { throw new ArgumentException(message); }); }
public void TryBlockBodyCanReturnResult() { var handledExceptionTypes = ImmutableQueue <Type> .Empty .Enqueue(typeof(Exception)); var handler = new Mock <IResultExceptionHandler <Exception, int> >(MockBehavior.Strict); var handlerProvider = new Mock <IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); var result = tryCatch.Try <int>(() => 5); result.Should().Be(5, "because that's what the handler returned"); }
public static bool CheckOrCreateDefaultFunction(string rootPath, string file, int points, int numOfDims) { if (File.Exists(file)) { return(true); } if (File.Exists(Path.Combine(rootPath, file))) { return(true); } var delta = 2 * Math.PI / points; List <double[]> rows = FunctionGenerator.CreateFunction(points, numOfDims, delta); Write2CSVFile(rows.ToArray(), Path.Combine(rootPath, file), false); return(false); }
public void Generate_WithValueTypes_Succeeds() { string functionName = "FunctionWithValueTypes"; Collection <ParameterDescriptor> parameters = new Collection <ParameterDescriptor>(); parameters.Add(new ParameterDescriptor("param1", typeof(string))); parameters.Add(new ParameterDescriptor("param2", typeof(DateTimeOffset))); parameters.Add(new ParameterDescriptor("param3", typeof(int))); FunctionMetadata metadata = new FunctionMetadata(); object[] invocationArguments = null; TestInvoker invoker = new TestInvoker(args => { invocationArguments = args; }); FunctionDescriptor function = new FunctionDescriptor(functionName, invoker, metadata, parameters); Collection <FunctionDescriptor> functions = new Collection <FunctionDescriptor>(); functions.Add(function); // generate the Type Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", null, functions); // verify the generated function MethodInfo method = functionType.GetMethod(functionName); ParameterInfo[] functionParams = method.GetParameters(); // Verify that we have the correct number of parameters Assert.Equal(parameters.Count, functionParams.Length); // Verify that the method is invocable DateTimeOffset input = DateTimeOffset.Now; method.Invoke(null, new object[] { "test", input, 44 }); // verify our custom invoker was called Assert.Equal(1, invoker.InvokeCount); Assert.NotNull(invocationArguments); Assert.Equal(input, (DateTimeOffset)invocationArguments[1]); Assert.Equal(44, (int)invocationArguments[2]); }
/// <summary> /// Generate function wrappers from descriptors. /// </summary> private void GenerateFunctions(IEnumerable <Type> directTypes) { // generate Type level attributes var typeAttributes = CreateTypeAttributes(ScriptOptions); string generatingMsg = string.Format(CultureInfo.InvariantCulture, "Generating {0} job function(s)", Functions.Count); _logger?.LogInformation(generatingMsg); // generate the Type wrapper string typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", GeneratedTypeNamespace, GeneratedTypeName); Type functionWrapperType = FunctionGenerator.Generate(HostAssemblyName, typeName, typeAttributes, Functions); // configure the Type locator var types = new List <Type>(); types.Add(functionWrapperType); types.AddRange(directTypes); _typeLocator.SetTypes(types); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { if (Method.Arguments.Length != Arguments.Length) { throw new ArgumentException("Incorrect number of arguments!"); } LLVMValueRef[] args = new LLVMValueRef[Method.Arguments.Length]; for (int i = 0; i < Method.Arguments.Length; i++) { args[i] = Arguments[i].GetRef(codeGenerator, Method.Arguments[i]); } LLVMValueRef?val = Method.GenerateCall(codeGenerator, args.ToArray()); if (val.HasValue) { SetRef(val.Value); } }
public void ThrownExceptionWillBeHandled() { var message = "Error message"; var handledExceptionTypes = ImmutableQueue<Type>.Empty.Enqueue(typeof(Exception)); var retryCount = 0; var handler = new Mock<IVoidReturnExceptionHandler<Exception>>(MockBehavior.Strict); handler.Setup(x => x.Handle(It.Is<Exception>(p => p.Message == message))); handler.Setup(x => x.RetryCount).Returns(retryCount); var handlerProvider = new Mock<IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.TryGetHandler<Exception>()).Returns(handler.Object); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); tryCatch.Try(() => { throw new Exception(message); }); }
private void EmitCanonFunctionMethod(TypeBuilder dcType, string methName, MethodInfo parentMethod, Action<ILGenerator> dcFieldLoader, SchemaObject funcInfo) { if (parentMethod != null) { FunctionGenerator generator = new FunctionGenerator(this, dcType, funcInfo, methName, MethodAttributes.Public); if (generator.Method != null) { ILGenerator iLGenerator = generator.Method.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); dcFieldLoader(iLGenerator); int position = 0; foreach (Parameter parameter in funcInfo.Parameters) { position++; generator.Method.DefineParameter(position, ParameterAttributes.None, parameter.ClrName); iLGenerator.Emit(OpCodes.Ldarg, position); } iLGenerator.Emit(OpCodes.Call, parentMethod); iLGenerator.Emit(OpCodes.Ret); } } }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { LLVMValueRef function; if (Method.IsVirtual) { LLVMValueRef typeInfoPtr = LLVM.BuildLoad(codeGenerator.Builder, Instance.ResultType.GetTypeInfoField(codeGenerator, Instance.GetRef()), ""); function = Method.Parent.TypeInfo.GetMethod(codeGenerator, Method, typeInfoPtr); } else { function = Method.GetPointer(codeGenerator); } if (Method.Arguments.Length != Arguments.Length + 1) { throw new ArgumentException("Incorrect number of arguments!"); } LLVMValueRef[] args = new LLVMValueRef[Method.Arguments.Length]; args[0] = Instance.GetRef(codeGenerator, Method.Arguments[0]); for (int i = 0; i < Method.Arguments.Length - 1; i++) { args[1 + i] = Arguments[i].GetRef(codeGenerator, Method.Arguments[1 + i]); } if (Method.ReturnType != PrimitiveType.Void) { SetRef(LLVM.BuildCall(codeGenerator.Builder, function, args.ToArray(), "")); } else { LLVM.BuildCall(codeGenerator.Builder, function, args.ToArray(), ""); } }
protected virtual void Initialize() { List <FunctionDescriptorProvider> descriptionProviders = new List <FunctionDescriptorProvider>() { new ScriptFunctionDescriptorProvider(this, ScriptConfig), new NodeFunctionDescriptorProvider(this, ScriptConfig) }; if (ScriptConfig.HostConfig.IsDevelopment) { ScriptConfig.HostConfig.UseDevelopmentSettings(); } // read host.json and apply to JobHostConfiguration string hostConfigFilePath = Path.Combine(ScriptConfig.RootScriptPath, "host.json"); _traceWriter.Verbose(string.Format("Reading host configuration file '{0}'", hostConfigFilePath)); string json = File.ReadAllText(hostConfigFilePath); JObject hostConfig = JObject.Parse(json); ApplyConfiguration(hostConfig, ScriptConfig); // read all script functions and apply to JobHostConfiguration Collection <FunctionDescriptor> functions = ReadFunctions(ScriptConfig, descriptionProviders); string defaultNamespace = "Host"; string typeName = string.Format("{0}.{1}", defaultNamespace, "Functions"); _traceWriter.Verbose(string.Format("Generating {0} job function(s)", functions.Count)); Type type = FunctionGenerator.Generate(HostAssemblyName, typeName, functions); List <Type> types = new List <Type>(); types.Add(type); ScriptConfig.HostConfig.TypeLocator = new TypeLocator(types); ScriptConfig.HostConfig.NameResolver = new NameResolver(); Functions = functions; }
private static MethodInfo GenerateMethod(BindingMetadata trigger) { string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Node"); FunctionMetadata metadata = new FunctionMetadata(); metadata.Name = "Test"; metadata.ScriptFile = Path.Combine(rootPath, @"Common\test.js"); metadata.Bindings.Add(trigger); List <FunctionMetadata> functions = new List <FunctionMetadata>(); functions.Add(metadata); var environment = new Mock <IScriptHostEnvironment>(); ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration() { RootScriptPath = rootPath }; Collection <FunctionDescriptor> functionDescriptors = null; using (ScriptHost host = ScriptHost.Create(environment.Object, scriptConfig, SettingsManager)) { FunctionDescriptorProvider[] descriptorProviders = new FunctionDescriptorProvider[] { new NodeFunctionDescriptorProvider(host, scriptConfig) }; functionDescriptors = host.GetFunctionDescriptors(functions, descriptorProviders); } Type t = FunctionGenerator.Generate("TestScriptHost", "Host.Functions", null, functionDescriptors); MethodInfo method = t.GetMethods(BindingFlags.Public | BindingFlags.Static).First(); return(method); }
public void ThrownExceptionWillBeHandled() { var message = "Error message"; var handledExceptionTypes = ImmutableQueue <Type> .Empty.Enqueue(typeof(Exception)); var retryCount = 0; var handler = new Mock <IVoidReturnExceptionHandler <Exception> >(MockBehavior.Strict); handler.Setup(x => x.Handle(It.Is <Exception>(p => p.Message == message))); handler.Setup(x => x.RetryCount).Returns(retryCount); var handlerProvider = new Mock <IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.TryGetHandler <Exception>()).Returns(handler.Object); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); tryCatch.Try(() => { throw new Exception(message); }); }
public void ExceptionHandlerCanProvokeRetry() { var handledExceptionTypes = ImmutableQueue <Type> .Empty .Enqueue(typeof(Exception)); var retryCount = 5; var handler = new Mock <IResultExceptionHandler <Exception, int> >(MockBehavior.Strict); handler.Setup(x => x.RetryCount).Returns(retryCount); handler.Setup(x => x.RetryIntervalInMilliseconds).Returns(0); var handlerProvider = new Mock <IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.TryGetHandler <Exception, int>()).Returns(handler.Object); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); var numberOfTries = 0; var result = tryCatch.Try <int>(() => { numberOfTries++; if (numberOfTries < retryCount) { throw new Exception(); } return(5); }); result.Should().Be(5, "because that's what the handler returned"); numberOfTries.Should().Be(retryCount, "because that's the number of retries requested"); }
private static MethodInfo GenerateMethod(BindingMetadata trigger, ScriptHostInfo scriptHostInfo) { FunctionMetadata metadata = new FunctionMetadata(); metadata.Name = FunctionName; metadata.ScriptFile = Path.Combine(scriptHostInfo.RootPath, @"Common\test.ps1"); metadata.Bindings.Add(trigger); metadata.ScriptType = ScriptType.PowerShell; List <FunctionMetadata> functions = new List <FunctionMetadata>(); functions.Add(metadata); FunctionDescriptorProvider[] descriptorProviders = new FunctionDescriptorProvider[] { new PowerShellFunctionDescriptorProvider(scriptHostInfo.Host, scriptHostInfo.Configuration) }; var functionDescriptors = scriptHostInfo.Host.GetFunctionDescriptors(functions, descriptorProviders); Type t = FunctionGenerator.Generate("TestScriptHost", "Host.Functions", null, functionDescriptors); MethodInfo method = t.GetMethods(BindingFlags.Public | BindingFlags.Static).First(); return(method); }
public void ExceptionHandlerCanProvokeRetry() { var handledExceptionTypes = ImmutableQueue<Type>.Empty .Enqueue(typeof(Exception)); var retryCount = 5; var handler = new Mock<IResultExceptionHandler<Exception, int>>(MockBehavior.Strict); handler.Setup(x => x.RetryCount).Returns(retryCount); handler.Setup(x => x.RetryIntervalInMilliseconds).Returns(0); var handlerProvider = new Mock<IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.TryGetHandler<Exception, int>()).Returns(handler.Object); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); var numberOfTries = 0; var result = tryCatch.Try<int>(() => { numberOfTries++; if (numberOfTries < retryCount) throw new Exception(); return 5; }); result.Should().Be(5, "because that's what the handler returned"); numberOfTries.Should().Be(retryCount, "because that's the number of retries requested"); }
public void ExceptionHandlerCanReturnResult() { var message = "Error message"; var handledExceptionTypes = ImmutableQueue<Type>.Empty .Enqueue(typeof(Exception)); var retryCount = 0; var handler = new Mock<IResultExceptionHandler<Exception, int>>(MockBehavior.Strict); handler.Setup(x => x.RetryCount).Returns(retryCount); handler.Setup(x => x.Handle(It.Is<Exception>(p => p.Message == message))).Returns(5); var handlerProvider = new Mock<IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.TryGetHandler<Exception, int>()).Returns(handler.Object); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); var result = tryCatch.Try<int>(() => { throw new Exception(message); }); result.Should().Be(5, "because that's what the handler returned"); }
public void TryBlockBodyCanReturnResult() { var handledExceptionTypes = ImmutableQueue<Type>.Empty .Enqueue(typeof(Exception)); var handler = new Mock<IResultExceptionHandler<Exception, int>>(MockBehavior.Strict); var handlerProvider = new Mock<IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); var result = tryCatch.Try<int>(() => 5); result.Should().Be(5, "because that's what the handler returned"); }
protected virtual void Initialize() { string hostLogPath = Path.Combine(ScriptConfig.RootLogPath, "Host"); FileUtility.EnsureDirectoryExists(hostLogPath); string debugSentinelFileName = Path.Combine(hostLogPath, ScriptConstants.DebugSentinelFileName); this.LastDebugNotify = File.GetLastWriteTime(debugSentinelFileName); IMetricsLogger metricsLogger = ScriptConfig.HostConfig.GetService <IMetricsLogger>(); if (metricsLogger == null) { metricsLogger = new MetricsLogger(); ScriptConfig.HostConfig.AddService <IMetricsLogger>(metricsLogger); } using (metricsLogger.LatencyEvent(MetricEventNames.HostStartupLatency)) { // read host.json and apply to JobHostConfiguration string hostConfigFilePath = Path.Combine(ScriptConfig.RootScriptPath, ScriptConstants.HostMetadataFileName); // If it doesn't exist, create an empty JSON file if (!File.Exists(hostConfigFilePath)) { File.WriteAllText(hostConfigFilePath, "{}"); } if (ScriptConfig.HostConfig.IsDevelopment || InDebugMode) { // If we're in debug/development mode, use optimal debug settings ScriptConfig.HostConfig.UseDevelopmentSettings(); } string json = File.ReadAllText(hostConfigFilePath); JObject hostConfig; try { hostConfig = JObject.Parse(json); } catch (JsonException ex) { throw new FormatException(string.Format("Unable to parse {0} file.", ScriptConstants.HostMetadataFileName), ex); } ApplyConfiguration(hostConfig, ScriptConfig); // Set up a host level TraceMonitor that will receive notification // of ALL errors that occur. This allows us to inspect/log errors. var traceMonitor = new TraceMonitor() .Filter(p => { return(true); }) .Subscribe(HandleHostError); ScriptConfig.HostConfig.Tracing.Tracers.Add(traceMonitor); TraceLevel hostTraceLevel = ScriptConfig.HostConfig.Tracing.ConsoleLevel; if (ScriptConfig.FileLoggingMode != FileLoggingMode.Never) { // Host file logging is only done conditionally string hostLogFilePath = Path.Combine(ScriptConfig.RootLogPath, "Host"); TraceWriter fileTraceWriter = new FileTraceWriter(hostLogFilePath, hostTraceLevel).Conditional(p => FileLoggingEnabled); if (TraceWriter != null) { // create a composite writer so our host logs are written to both TraceWriter = new CompositeTraceWriter(new[] { TraceWriter, fileTraceWriter }); } else { TraceWriter = fileTraceWriter; } } if (TraceWriter != null) { ScriptConfig.HostConfig.Tracing.Tracers.Add(TraceWriter); } else { // if no TraceWriter has been configured, default it to Console TraceWriter = new ConsoleTraceWriter(hostTraceLevel); } _debugModeFileWatcher = new AutoRecoveringFileSystemWatcher(hostLogPath, ScriptConstants.DebugSentinelFileName, includeSubdirectories: false, changeTypes: WatcherChangeTypes.Created | WatcherChangeTypes.Changed); _debugModeFileWatcher.Changed += OnDebugModeFileChanged; var storageString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage); Task <BlobLeaseManager> blobManagerCreation = null; if (storageString == null) { // Disable core storage ScriptConfig.HostConfig.StorageConnectionString = null; blobManagerCreation = Task.FromResult <BlobLeaseManager>(null); } else { blobManagerCreation = BlobLeaseManager.CreateAsync(storageString, TimeSpan.FromSeconds(15), ScriptConfig.HostConfig.HostId, InstanceId, TraceWriter); } var bindingProviders = LoadBindingProviders(ScriptConfig, hostConfig, TraceWriter); ScriptConfig.BindingProviders = bindingProviders; TraceWriter.Info(string.Format(CultureInfo.InvariantCulture, "Reading host configuration file '{0}'", hostConfigFilePath)); if (ScriptConfig.FileWatchingEnabled) { _scriptFileWatcher = new AutoRecoveringFileSystemWatcher(ScriptConfig.RootScriptPath); _scriptFileWatcher.Changed += OnFileChanged; } // If a file change should result in a restart, we debounce the event to // ensure that only a single restart is triggered within a specific time window. // This allows us to deal with a large set of file change events that might // result from a bulk copy/unzip operation. In such cases, we only want to // restart after ALL the operations are complete and there is a quiet period. _restart = (e) => { TraceWriter.Info(string.Format(CultureInfo.InvariantCulture, "File change of type '{0}' detected for '{1}'", e.ChangeType, e.FullPath)); TraceWriter.Info("Host configuration has changed. Signaling restart."); RestartHost(); }; _restart = _restart.Debounce(500); // take a snapshot so we can detect function additions/removals _directoryCountSnapshot = Directory.EnumerateDirectories(ScriptConfig.RootScriptPath).Count(); List <FunctionDescriptorProvider> descriptionProviders = new List <FunctionDescriptorProvider>() { new ScriptFunctionDescriptorProvider(this, ScriptConfig), new NodeFunctionDescriptorProvider(this, ScriptConfig), new DotNetFunctionDescriptorProvider(this, ScriptConfig), new PowerShellFunctionDescriptorProvider(this, ScriptConfig) }; // Allow BindingProviders to initialize foreach (var bindingProvider in ScriptConfig.BindingProviders) { try { bindingProvider.Initialize(); } catch (Exception ex) { // If we're unable to initialize a binding provider for any reason, log the error // and continue TraceWriter.Error(string.Format("Error initializing binding provider '{0}'", bindingProvider.GetType().FullName), ex); } } // Create the lease manager that will keep handle the primary host blob lease acquisition and renewal // and subscribe for change notifications. _blobLeaseManager = blobManagerCreation.GetAwaiter().GetResult(); if (_blobLeaseManager != null) { _blobLeaseManager.HasLeaseChanged += BlobLeaseManagerHasLeaseChanged; } // read all script functions and apply to JobHostConfiguration Collection <FunctionDescriptor> functions = ReadFunctions(descriptionProviders); Collection <CustomAttributeBuilder> typeAttributes = CreateTypeAttributes(ScriptConfig); string defaultNamespace = "Host"; string typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", defaultNamespace, "Functions"); TraceWriter.Info(string.Format(CultureInfo.InvariantCulture, "Generating {0} job function(s)", functions.Count)); Type type = FunctionGenerator.Generate(HostAssemblyName, typeName, typeAttributes, functions); List <Type> types = new List <Type>(); types.Add(type); ScriptConfig.HostConfig.TypeLocator = new TypeLocator(types); Functions = functions; if (ScriptConfig.FileLoggingMode != FileLoggingMode.Never) { PurgeOldLogDirectories(); } } }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { SetRef(fgen.LoadDirect(Field.GetFieldAddress(codeGenerator))); }
public void Initialize() { var settings = new FunctionGenerator.PhysicalAssemblySettings("Test", "dll", AppDomain.CurrentDomain.BaseDirectory); var functionGenerator = new FunctionGenerator(settings); this.provider = new ValidationProvider(functionGenerator, shouldThrowExceptions: true); }
protected virtual void Initialize() { // read host.json and apply to JobHostConfiguration string hostConfigFilePath = Path.Combine(ScriptConfig.RootScriptPath, HostConfigFileName); // If it doesn't exist, create an empty JSON file if (!File.Exists(hostConfigFilePath)) { File.WriteAllText(hostConfigFilePath, "{}"); } if (ScriptConfig.HostConfig.IsDevelopment) { ScriptConfig.HostConfig.UseDevelopmentSettings(); } else { // TEMP: Until https://github.com/Azure/azure-webjobs-sdk-script/issues/100 is addressed // we're using some presets that are a good middle ground ScriptConfig.HostConfig.Queues.MaxPollingInterval = TimeSpan.FromSeconds(10); ScriptConfig.HostConfig.Singleton.ListenerLockPeriod = TimeSpan.FromSeconds(15); } string json = File.ReadAllText(hostConfigFilePath); JObject hostConfig = JObject.Parse(json); ApplyConfiguration(hostConfig, ScriptConfig); // Set up a host level TraceMonitor that will receive notificaition // of ALL errors that occur. This allows us to inspect/log errors. var traceMonitor = new TraceMonitor() .Filter(p => { return(true); }) .Subscribe(HandleHostError); ScriptConfig.HostConfig.Tracing.Tracers.Add(traceMonitor); if (ScriptConfig.FileLoggingEnabled) { string hostLogFilePath = Path.Combine(ScriptConfig.RootLogPath, "Host"); TraceWriter = new FileTraceWriter(hostLogFilePath, TraceLevel.Verbose); ScriptConfig.HostConfig.Tracing.Tracers.Add(TraceWriter); } else { TraceWriter = NullTraceWriter.Instance; } TraceWriter.Verbose(string.Format(CultureInfo.InvariantCulture, "Reading host configuration file '{0}'", hostConfigFilePath)); if (ScriptConfig.TraceWriter != null) { ScriptConfig.HostConfig.Tracing.Tracers.Add(ScriptConfig.TraceWriter); } else { ScriptConfig.TraceWriter = NullTraceWriter.Instance; } if (ScriptConfig.FileWatchingEnabled) { _fileWatcher = new FileSystemWatcher(ScriptConfig.RootScriptPath) { IncludeSubdirectories = true, EnableRaisingEvents = true }; _fileWatcher.Changed += OnFileChanged; _fileWatcher.Created += OnFileChanged; _fileWatcher.Deleted += OnFileChanged; _fileWatcher.Renamed += OnFileChanged; } // If a file change should result in a restart, we debounce the event to // ensure that only a single restart is triggered within a specific time window. // This allows us to deal with a large set of file change events that might // result from a bulk copy/unzip operation. In such cases, we only want to // restart after ALL the operations are complete and there is a quiet period. _restart = (e) => { TraceWriter.Verbose(string.Format(CultureInfo.InvariantCulture, "File change of type '{0}' detected for '{1}'", e.ChangeType, e.FullPath)); TraceWriter.Verbose("Host configuration has changed. Signaling restart."); // signal host restart _restartEvent.Set(); }; _restart = _restart.Debounce(500); // take a snapshot so we can detect function additions/removals _directoryCountSnapshot = Directory.EnumerateDirectories(ScriptConfig.RootScriptPath).Count(); var dashboardString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Dashboard); var config = ScriptConfig.HostConfig; if (dashboardString != null) { var fastLogger = new FastLogger(dashboardString); config.AddService <IAsyncCollector <FunctionInstanceLogEntry> >(fastLogger); } config.DashboardConnectionString = null; // disable slow logging IMetricsLogger metricsLogger = ScriptConfig.HostConfig.GetService <IMetricsLogger>(); if (metricsLogger == null) { ScriptConfig.HostConfig.AddService <IMetricsLogger>(new MetricsLogger()); } // Bindings may use name resolution, so provide this before reading the bindings. var nameResolver = new NameResolver(); var storageString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage); if (storageString == null) { // Disable core storage ScriptConfig.HostConfig.StorageConnectionString = null; } ScriptConfig.HostConfig.NameResolver = nameResolver; List <FunctionDescriptorProvider> descriptionProviders = new List <FunctionDescriptorProvider>() { new ScriptFunctionDescriptorProvider(this, ScriptConfig), new NodeFunctionDescriptorProvider(this, ScriptConfig), new CSharpFunctionDescriptionProvider(this, ScriptConfig) }; // read all script functions and apply to JobHostConfiguration Collection <FunctionDescriptor> functions = ReadFunctions(ScriptConfig, descriptionProviders); string defaultNamespace = "Host"; string typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", defaultNamespace, "Functions"); TraceWriter.Verbose(string.Format(CultureInfo.InvariantCulture, "Generating {0} job function(s)", functions.Count)); Type type = FunctionGenerator.Generate(HostAssemblyName, typeName, functions); List <Type> types = new List <Type>(); types.Add(type); ScriptConfig.HostConfig.TypeLocator = new TypeLocator(types); ApplyBindingConfiguration(functions, ScriptConfig.HostConfig); Functions = functions; }
static void Main(string[] args) { //List<Dictionary<string, object>> data = new List<Dictionary<string, object>>() //{ // new Dictionary<string, object>() // { // {"C", "data"}, // {"A.Data","data1"}, // {"A.Data1",2}, // {"B.Data","data3"}, // {"B.Data1",4}, // {"D.Data","data5"}, // {"D.Data1",6} // }, // new Dictionary<string, object>() // { // {"C", "data"}, // {"A.Data","data1"}, // {"A.Data1",2}, // {"B.Data","data3"}, // {"B.Data1",4}, // {"D.Data","data7"}, // {"D.Data1",8} // }, // new Dictionary<string, object>() // { // {"C", "data"}, // {"A.Data","data1"}, // {"A.Data1",2}, // {"B.Data","data9"}, // {"B.Data1",10}, // {"D.Data","data5"}, // {"D.Data1",6} // }, // new Dictionary<string, object>() // { // {"C", "data"}, // {"A.Data","data1"}, // {"A.Data1",2}, // {"B.Data","data9"}, // {"B.Data1",10}, // {"D.Data","data7"}, // {"D.Data1",8} // } //}; List <Dictionary <string, object> > data = new List <Dictionary <string, object> >() { new Dictionary <string, object>() { { "C", "data" }, { "A.Data", "data1" }, { "A.Data1", 2 }, { "B.Data", "data3" }, { "B.Data1", 4 }, { "D.Data", "data5" }, { "D.Data1", 6 } }, new Dictionary <string, object>() { { "C", "data" }, //{"A.Data","data1"}, { "A.Data1", 2 }, { "B.Data", "data3" }, { "B.Data1", 4 }, { "D.Data", "data7" }, { "D.Data1", 8 } }, new Dictionary <string, object>() { { "C", "data" }, //{"A.Data","data1"}, { "A.Data1", 2 }, { "B.Data", "data9" }, { "B.Data1", 10 }, { "D.Data", "data5" }, { "D.Data1", null } }, new Dictionary <string, object>() { { "C", "data" }, //{"A.Data","data1"}, { "A.Data1", 2 }, { "B.Data", "data9" }, { "B.Data1", 10 }, { "D.Data", "data7" }, { "D.Data1", 8 } } }; //var meh = Automapper.GenerateMapper<TestType1>().CreateDelegate()(data); var blah = FunctionGenerator.GenerateKeyGenerator(typeof(TestType5)).Instructions(); var result = Nested.Automapper.Map <TestType1>(data); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { SetRef(fgen.LoadLocal(Index)); }
public async Task Generate_EndToEnd() { // construct our TimerTrigger attribute ([TimerTrigger("00:00:02", RunOnStartup = true)]) Collection <ParameterDescriptor> parameters = new Collection <ParameterDescriptor>(); ParameterDescriptor parameter = new ParameterDescriptor("timerInfo", typeof(TimerInfo)); ConstructorInfo ctorInfo = typeof(TimerTriggerAttribute).GetConstructor(new Type[] { typeof(string) }); PropertyInfo runOnStartupProperty = typeof(TimerTriggerAttribute).GetProperty("RunOnStartup"); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder( ctorInfo, new object[] { "00:00:02" }, new PropertyInfo[] { runOnStartupProperty }, new object[] { true }); parameter.CustomAttributes.Add(attributeBuilder); parameters.Add(parameter); // create the FunctionDefinition FunctionMetadata metadata = new FunctionMetadata(); TestInvoker invoker = new TestInvoker(); FunctionDescriptor function = new FunctionDescriptor("TimerFunction", invoker, metadata, parameters); Collection <FunctionDescriptor> functions = new Collection <FunctionDescriptor>(); functions.Add(function); // Get the Type Attributes (in this case, a TimeoutAttribute) ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration(); scriptConfig.FunctionTimeout = TimeSpan.FromMinutes(5); Collection <CustomAttributeBuilder> typeAttributes = ScriptHost.CreateTypeAttributes(scriptConfig); // generate the Type Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", typeAttributes, functions); // verify the generated function MethodInfo method = functionType.GetMethod("TimerFunction"); TimeoutAttribute timeoutAttribute = (TimeoutAttribute)functionType.GetCustomAttributes().Single(); Assert.Equal(TimeSpan.FromMinutes(5), timeoutAttribute.Timeout); Assert.True(timeoutAttribute.ThrowOnTimeout); Assert.True(timeoutAttribute.TimeoutWhileDebugging); ParameterInfo triggerParameter = method.GetParameters()[0]; TimerTriggerAttribute triggerAttribute = triggerParameter.GetCustomAttribute <TimerTriggerAttribute>(); Assert.NotNull(triggerAttribute); // start the JobHost which will start running the timer function JobHostConfiguration config = new JobHostConfiguration() { TypeLocator = new TypeLocator(functionType) }; config.UseTimers(); JobHost host = new JobHost(config); await host.StartAsync(); await Task.Delay(3000); await host.StopAsync(); // verify our custom invoker was called Assert.True(invoker.InvokeCount >= 2); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { SetRef(fgen.GetArgument(Index)); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { IType lhs = Lhs.ResultType; if (lhs is EnumType) { lhs = ((EnumType)lhs).UnderlyingType; } LLVMValueRef lhsValue = Lhs.GetRef(codeGenerator, lhs); IType target = lhs; if (Operation == OperationType.Not) { SetRef(codeGenerator, target, LLVM.BuildNot(codeGenerator.Builder, lhsValue, "")); return; } else if (Operation == OperationType.Negate) { SetRef(codeGenerator, target, LLVM.BuildNeg(codeGenerator.Builder, lhsValue, "")); return; } IType rhs = Rhs.ResultType; if (rhs is EnumType) { rhs = ((EnumType)rhs).UnderlyingType; } LLVMValueRef rhsValue = Rhs.GetRef(codeGenerator, target); if (!lhs.IsStackCompatible(rhs)) { throw new NotImplementedException("Numeric ops on different types not implemented yet"); } switch (Operation) { case OperationType.Add: SetRef(codeGenerator, target, LLVM.BuildAdd(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.Subtract: SetRef(codeGenerator, target, LLVM.BuildSub(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.Multiply: SetRef(codeGenerator, target, LLVM.BuildMul(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.Divide: SetRef(codeGenerator, target, LLVM.BuildSDiv(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.DivideUnsigned: SetRef(codeGenerator, target, LLVM.BuildUDiv(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.Remainder: SetRef(codeGenerator, target, LLVM.BuildSRem(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.RemainderUnsigned: SetRef(codeGenerator, target, LLVM.BuildURem(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.ShiftLeft: SetRef(codeGenerator, target, LLVM.BuildShl(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.ShiftRight: SetRef(codeGenerator, target, LLVM.BuildAShr(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.ShiftRightUnsigned: SetRef(codeGenerator, target, LLVM.BuildLShr(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.And: SetRef(codeGenerator, target, LLVM.BuildAnd(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.Or: SetRef(codeGenerator, target, LLVM.BuildOr(codeGenerator.Builder, lhsValue, rhsValue, "")); break; case OperationType.XOr: SetRef(codeGenerator, target, LLVM.BuildXor(codeGenerator.Builder, lhsValue, rhsValue, "")); break; default: throw new NotImplementedException("Unknown operationType " + Operation); } }
private void startButton_Click(object sender, System.EventArgs e) { // Change the mouse to an hourglass for the duration of this function. Cursor.Current = Cursors.WaitCursor; // Read UI selections DigitalEdgeStartTriggerEdge triggerEdge; if (this.triggerEdgeComboBox.Text == "Rising") { triggerEdge = DigitalEdgeStartTriggerEdge.Rising; } else { triggerEdge = DigitalEdgeStartTriggerEdge.Falling; } try { // Create the master and slave tasks inputTask = new Task("inputTask"); outputTask = new Task("outputTask"); // Configure both tasks with the values selected on the UI. inputTask.AIChannels.CreateVoltageChannel(inputChannelComboBox.Text, "", AITerminalConfiguration.Differential, Convert.ToDouble(inputMinValNumeric.Value), Convert.ToDouble(inputMaxValNumeric.Value), AIVoltageUnits.Volts); outputTask.AOChannels.CreateVoltageChannel(outputChannelComboBox.Text, "", Convert.ToDouble(outputMinValNumeric.Value), Convert.ToDouble(outputMaxValNumeric.Value), AOVoltageUnits.Volts); // Set up the timing inputTask.Timing.ConfigureSampleClock("", Convert.ToDouble(rateNumeric.Value), SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(samplesNumeric.Value)); outputTask.Timing.ConfigureSampleClock("", Convert.ToDouble(rateNumeric.Value), SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(samplesNumeric.Value)); // Set up the start trigger string deviceName = inputChannelComboBox.Text.Split('/')[0]; string terminalNameBase = "/" + GetDeviceName(deviceName) + "/"; outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge); // Verify the tasks inputTask.Control(TaskAction.Verify); outputTask.Control(TaskAction.Verify); // Write data to each output channel FunctionGenerator fGen = new FunctionGenerator(Convert.ToString(frequencyNumeric.Value), Convert.ToString(samplesNumeric.Value), Convert.ToString(frequencyNumeric.Value / (rateNumeric.Value / samplesNumeric.Value)), waveformTypeComboBox.Text, amplitudeNumeric.Value.ToString()); output = fGen.Data; writer = new AnalogSingleChannelWriter(outputTask.Stream); writer.WriteMultiSample(false, output); // Officially start the task StartTask(); outputTask.Start(); inputTask.Start(); // Start reading as well inputCallback = new AsyncCallback(InputRead); reader = new AnalogSingleChannelReader(inputTask.Stream); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. reader.SynchronizeCallbacks = true; reader.BeginReadMultiSample(Convert.ToInt32(samplesNumeric.Value), inputCallback, inputTask); } catch (Exception ex) { StopTask(); MessageBox.Show(ex.Message); } }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { fgen.StoreLocal(FieldIndex, Value.GetRef(codeGenerator, FieldType)); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { SetRef(Field.Parent.GetFieldAddress(codeGenerator, Object.GetRef(), Field)); }
public async Task Generate_EndToEnd() { // construct our TimerTrigger attribute ([TimerTrigger("00:00:02", RunOnStartup = true)]) Collection <ParameterDescriptor> parameters = new Collection <ParameterDescriptor>(); ParameterDescriptor parameter = new ParameterDescriptor("timerInfo", typeof(TimerInfo)); ConstructorInfo ctorInfo = typeof(TimerTriggerAttribute).GetConstructor(new Type[] { typeof(string) }); PropertyInfo runOnStartupProperty = typeof(TimerTriggerAttribute).GetProperty("RunOnStartup"); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder( ctorInfo, new object[] { "00:00:02" }, new PropertyInfo[] { runOnStartupProperty }, new object[] { true }); parameter.CustomAttributes.Add(attributeBuilder); parameters.Add(parameter); // create the FunctionDefinition FunctionMetadata metadata = new FunctionMetadata(); TestInvoker invoker = new TestInvoker(); FunctionDescriptor function = new FunctionDescriptor("TimerFunction", invoker, metadata, parameters, null, null, null); Collection <FunctionDescriptor> functions = new Collection <FunctionDescriptor>(); functions.Add(function); // Get the Type Attributes (in this case, a TimeoutAttribute) ScriptJobHostOptions scriptConfig = new ScriptJobHostOptions(); scriptConfig.FunctionTimeout = TimeSpan.FromMinutes(5); Collection <CustomAttributeBuilder> typeAttributes = new Collection <CustomAttributeBuilder>(); // generate the Type Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", typeAttributes, functions); // verify the generated function MethodInfo method = functionType.GetMethod("TimerFunction"); ParameterInfo triggerParameter = method.GetParameters()[0]; TimerTriggerAttribute triggerAttribute = triggerParameter.GetCustomAttribute <TimerTriggerAttribute>(); Assert.NotNull(triggerAttribute); // start the JobHost which will start running the timer function var builder = new HostBuilder() .ConfigureWebJobs(b => { b.AddTimers() .AddAzureStorageCoreServices(); }) .ConfigureServices(s => { s.AddSingleton <ITypeLocator>(new TestTypeLocator(functionType)); s.AddSingleton <ILoggerFactory>(new LoggerFactory()); }); using (var host = builder.Build()) { await host.StartAsync(); await Task.Delay(3000); await host.StopAsync(); } // verify our custom invoker was called Assert.True(invoker.InvokeCount >= 2); }
public void ThrownArgumentNullExceptionWithArgumentExceptionBlockWillNotHandled() { var message = "Error message"; var handledExceptionTypes = ImmutableQueue<Type>.Empty .Enqueue(typeof(ArgumentNullException)); var handler = new Mock<IExceptionHandler<ArgumentNullException>>(MockBehavior.Strict); var handlerProvider = new Mock<IExceptionHandlerProvider>(MockBehavior.Strict); handlerProvider.Setup(x => x.HandledTypesInCatchOrder).Returns(handledExceptionTypes); handlerProvider.Setup(x => x.HandledExceptionTypes).Returns(handledExceptionTypes.ToImmutableHashSet()); var generator = new FunctionGenerator(); var provider = new TryCatchBlockProvider(generator); var tryCatch = provider.GetTryCatchFor(handlerProvider.Object); tryCatch.Try(() => { throw new ArgumentException(message); }); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { fgen.StoreDirect(Value.GetRef(codeGenerator, Type), Address.GetRef(codeGenerator, PrimitiveType.UIntPtr)); }
public void Initialize() { var functionGenerator = new FunctionGenerator(); this.provider = new TranslationProvider(functionGenerator, shouldThrowExceptions: true); }
public abstract void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen);
protected override DbCommandDefinition CreateDbCommandDefinition( DbProviderManifest providerManifest, DbCommandTree commandTree) { if (commandTree == null) { throw new ArgumentNullException("commandTree"); } SqlGenerator generator = null; if (commandTree is DbQueryCommandTree) { generator = new SelectGenerator(); } else if (commandTree is DbInsertCommandTree) { generator = new InsertGenerator(); } else if (commandTree is DbUpdateCommandTree) { generator = new UpdateGenerator(); } else if (commandTree is DbDeleteCommandTree) { generator = new DeleteGenerator(); } else if (commandTree is DbFunctionCommandTree) { generator = new FunctionGenerator(); } string sql = generator.GenerateSQL(commandTree); EFMySqlCommand cmd = new EFMySqlCommand(); cmd.CommandText = sql; if (generator is FunctionGenerator) { cmd.CommandType = (generator as FunctionGenerator).CommandType; } SetExpectedTypes(commandTree, cmd); EdmFunction function = null; if (commandTree is DbFunctionCommandTree) { function = (commandTree as DbFunctionCommandTree).EdmFunction; } // Now make sure we populate the command's parameters from the CQT's parameters: foreach (KeyValuePair <string, TypeUsage> queryParameter in commandTree.Parameters) { DbParameter parameter = cmd.CreateParameter(); parameter.ParameterName = queryParameter.Key; parameter.Direction = ParameterDirection.Input; parameter.DbType = Metadata.GetDbType(queryParameter.Value); FunctionParameter funcParam; if (function != null && function.Parameters.TryGetValue(queryParameter.Key, false, out funcParam)) { parameter.ParameterName = funcParam.Name; parameter.Direction = Metadata.ModeToDirection(funcParam.Mode); parameter.DbType = Metadata.GetDbType(funcParam.TypeUsage); } cmd.Parameters.Add(parameter); } // Now add parameters added as part of SQL gen foreach (DbParameter p in generator.Parameters) { cmd.Parameters.Add(p); } return(CreateCommandDefinition(cmd)); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { TargetType.LoadDefault(codeGenerator, Target.GetRef()); }
public override void Generate(CodeGenerator codeGenerator, FunctionGenerator fgen) { SetRef(Value.GetRef(codeGenerator, ResultType)); }
private MethodInfo EmitFunctionMethod(TypeBuilder dcType, string methName, SchemaObject funcInfo, string objectPrefix, MethodAttributes accessibility) { FunctionGenerator generator = new FunctionGenerator(this, dcType, funcInfo, methName, accessibility); if (generator.Method == null) { return null; } generator.AddAttributes(objectPrefix); ILGenerator iLGenerator = generator.Method.GetILGenerator(); LocalBuilder local = iLGenerator.DeclareLocal(typeof(object[])); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetCurrentMethod", BindingFlags.Public | BindingFlags.Static, null, Type.EmptyTypes, null)); iLGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo)); iLGenerator.Emit(OpCodes.Ldc_I4, funcInfo.Parameters.Count); iLGenerator.Emit(OpCodes.Newarr, typeof(object)); iLGenerator.Emit(OpCodes.Stloc, local); int arg = 0; foreach (Parameter parameter in funcInfo.Parameters) { iLGenerator.Emit(OpCodes.Ldloc, local); iLGenerator.Emit(OpCodes.Ldc_I4, arg); iLGenerator.Emit(OpCodes.Ldarg, (int) (arg + 1)); if (parameter.ClrType.IsValueType) { iLGenerator.Emit(OpCodes.Box, parameter.ClrType); } iLGenerator.Emit(OpCodes.Stelem_Ref); arg++; } iLGenerator.Emit(OpCodes.Ldloc, local); MethodInfo meth = typeof(DataContext).GetMethod((funcInfo is TableFunction) ? "CreateMethodCallQuery" : "ExecuteMethodCall", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(object), typeof(MethodInfo), typeof(object[]) }, null); if (funcInfo is TableFunction) { meth = meth.MakeGenericMethod(new Type[] { generator.ResultType }); } iLGenerator.Emit(OpCodes.Call, meth); if (funcInfo is ScalarFunction) { iLGenerator.Emit(OpCodes.Callvirt, typeof(IExecuteResult).GetProperty("ReturnValue").GetGetMethod()); iLGenerator.Emit(generator.ResultType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, generator.ResultType); } iLGenerator.Emit(OpCodes.Ret); return generator.Method; }