public void NewInvocationContextIsConfiguredCorrectly() { var configuration = new DomainConfiguration(); configuration.EnsureCommitted(); var domainContext = new DomainContext(configuration); var context = new InvocationContext(domainContext); Assert.Same(domainContext, context.DomainContext); }
public void NewInvocationContextIsConfiguredCorrectly() { var container = new RestierContainerBuilder(typeof(TestApi)); var provider = container.BuildContainer(); var api = provider.GetService<ApiBase>(); var apiContext = api.Context; var context = new InvocationContext(apiContext); Assert.Same(apiContext, context.ApiContext); }
public void InvocationContextGetsApiServicesCorrectly() { var container = new RestierContainerBuilder(typeof(TestApi)); var provider = container.BuildContainer(); var api = provider.GetService<ApiBase>(); var apiContext = api.Context; var context = new InvocationContext(apiContext); Assert.Same(TestApi.ApiService, context.GetApiService<IServiceA>()); }
public void InvocationContextGetsHookPointsCorrectly() { var hook = new HookA(); var configuration = new ApiConfiguration().AddHookHandler<IHookA>(hook); configuration.EnsureCommitted(); var apiContext = new ApiContext(configuration); var context = new InvocationContext(apiContext); Assert.Same(hook, context.GetHookHandler<IHookA>()); }
public Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { var model = new EdmModel(); var dummyType = new EdmEntityType("NS", "Dummy"); model.AddElement(dummyType); var container = new EdmEntityContainer("NS", "DefaultContainer"); container.AddEntitySet("Test", dummyType); model.AddElement(container); return Task.FromResult((IEdmModel)model); }
public bool IsVisible( DomainConfiguration configuration, InvocationContext context, IEdmModel model, IEdmSchemaElement element) { if (element.Name == "TestName") { return false; } return true; }
public bool IsVisible( DomainConfiguration configuration, InvocationContext context, IEdmModel model, IEdmEntityContainerElement element) { if (element.Name == "TestEntitySet") { return false; } return true; }
public Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { var model = new EdmModel(); var entityType = new EdmEntityType( "TestNamespace", "TestName"); var entityContainer = new EdmEntityContainer( "TestNamespace", "Entities"); entityContainer.AddEntitySet("TestEntitySet", entityType); model.AddElement(entityType); model.AddElement(entityContainer); return Task.FromResult<IEdmModel>(model); }
/// <summary> /// Returns an EventAttribute for the given call context. /// </summary> /// <param name="context">The context of the call.</param> /// <param name="nextEventId">The next event ID to use if not specified by some other mechanism.</param> /// <param name="parameterMapping">The parameter mapping for the method, or null if not a method call.</param> /// <returns>The EventAttribute for the call context.</returns> public virtual EventAttribute GetEventAttribute(InvocationContext context, int nextEventId, IReadOnlyCollection<ParameterMapping> parameterMapping) { if (context == null) throw new ArgumentNullException("context"); EventAttribute eventAttribute = context.MethodInfo.GetCustomAttribute<EventAttribute>(); if (eventAttribute != null) return eventAttribute; return new EventAttribute(nextEventId) { Level = GetEventLevelForContext(context, null), Message = GetEventMessage(context, parameterMapping) }; }
/// <summary> /// Returns an EventAttribute for the Completed or Faulted events for a call context. /// </summary> /// <param name="baseAttribute">The EventAttribute for the method call that should be copied.</param> /// <param name="context">The context of the call.</param> /// <param name="nextEventId">The next event ID to use if not specified by some other mechanism.</param> /// <returns>The EventAttribute for the call context.</returns> public virtual EventAttribute CopyEventAttribute(EventAttribute baseAttribute, InvocationContext context, int nextEventId) { if (baseAttribute == null) throw new ArgumentNullException("baseAttribute"); if (context == null) throw new ArgumentNullException("context"); return new EventAttribute(nextEventId) { Keywords = baseAttribute.Keywords, Level = GetEventLevelForContext(context, baseAttribute), Message = GetEventMessage(context, null), Opcode = baseAttribute.Opcode, Task = baseAttribute.Task, Version = baseAttribute.Version }; }
public void InvocationContextGetsHookPointsCorrectly() { var configuration = new DomainConfiguration(); var singletonHookPoint = new object(); configuration.SetHookPoint(typeof(object), singletonHookPoint); var multiCastHookPoint = new object(); configuration.AddHookPoint(typeof(object), multiCastHookPoint); configuration.EnsureCommitted(); var domainContext = new DomainContext(configuration); var context = new InvocationContext(domainContext); Assert.Same(singletonHookPoint, context.GetHookPoint<object>()); Assert.True(context.GetHookPoints<object>() .SequenceEqual(new object[] { multiCastHookPoint })); }
public async Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { EdmModel model = null; if (this.InnerHandler != null) { model = await this.InnerHandler.GetModelAsync(context, cancellationToken) as EdmModel; } if (model == null) { // We don't plan to extend an empty model with operations. return null; } this.ScanForOperations(); this.BuildFunctions(model); this.BuildActions(model); return model; }
public async Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { IEdmModel innerModel = null; if (this.InnerHandler != null) { innerModel = await this.InnerHandler.GetModelAsync(context, cancellationToken); } var entityType = new EdmEntityType( "TestNamespace", "TestName" + _index); var model = innerModel as EdmModel; Assert.NotNull(model); model.AddElement(entityType); (model.EntityContainer as EdmEntityContainer) .AddEntitySet("TestEntitySet" + _index, entityType); return model; }
/// <summary> /// Determines whether the given invocation context requires context to be provided. /// </summary> /// <param name="context">The context of the invocation.</param> /// <returns>True if EventSourceProxy should ask for context, false to skip context generation.</returns> public virtual bool ShouldProvideContext(InvocationContext context) { if (context == null) throw new ArgumentNullException("context"); // NOTE: this method is called at proxy generation time and is not called at runtime // so we don't need to cache anything here // if this returns false, then ProvideContext will never be called for the given context // check the method first var attribute = context.MethodInfo.GetCustomAttribute<TraceContextAttribute>(); if (attribute != null) return attribute.EnabledFor.HasFlag(context.ContextType); // now check the class attribute = context.MethodInfo.DeclaringType.GetCustomAttribute<TraceContextAttribute>(); if (attribute != null) return attribute.EnabledFor.HasFlag(context.ContextType); // it's enabled by default return true; }
public async Task JoinUserToGroup([SignalRTrigger] InvocationContext invocationContext, string userName, string groupName) { await UserGroups.AddToGroupAsync(userName, groupName); }
public async Task LeaveUserFromGroup([SignalRTrigger] InvocationContext invocationContext, string userName, string groupName) { await UserGroups.RemoveFromGroupAsync(userName, groupName); }
/// <summary> /// Emits a proxy to a method that just calls the base method. /// </summary> /// <param name="invocationContext">The current invocation context.</param> /// <param name="methodBuilder">The method to implement.</param> /// <param name="baseMethod">The base method.</param> /// <param name="parameterMapping">The mapping of the parameters.</param> private void EmitDirectProxy(InvocationContext invocationContext, MethodBuilder methodBuilder, MethodInfo baseMethod, List<ParameterMapping> parameterMapping) { /* * This method assumes that a default return value has been pushed on the stack. * * base(params); * return (top of stack); */ ILGenerator mIL = methodBuilder.GetILGenerator(); // copy the parameters to the stack // arg.0 = this // so we go to length+1 mIL.Emit(OpCodes.Ldarg_0); for (int i = 0; i < parameterMapping.Count; i++) { var parameter = parameterMapping[i]; if (parameter.HasSource) { ProxyHelper.EmitSerializeValue( _typeBuilder, methodBuilder, invocationContext, _invocationContexts, _invocationContextsField, parameter, _serializationProvider, _serializationProviderField); } else { // if this method supports context, then add a context parameter // note that we pass null in here and then build the context from within EmitCallWriteEvent mIL.Emit(OpCodes.Ldnull); } } // now that all of the parameters have been loaded, call the base method mIL.Emit(OpCodes.Call, baseMethod); mIL.Emit(OpCodes.Ret); }
private async Task<IEdmModel> GetModelReturnedByInnerHandlerAsync( InvocationContext context, CancellationToken cancellationToken) { var innerHandler = InnerModelBuilder; if (innerHandler != null) { return await innerHandler.GetModelAsync(context, cancellationToken); } return null; }
public async Task JoinGroup([SignalRTrigger] InvocationContext invocationContext, string connectionId, string groupName) { await Groups.AddToGroupAsync(connectionId, groupName); }
public static int Run(InvocationContext context) { var additionalArgs = context.ParseResult.ValueForOption <string[]>("additional"); var configSwitches = context.ParseResult.ValueForOption <string[]>("config"); var defineMacros = context.ParseResult.ValueForOption <string[]>("define-macro"); var excludedNames = context.ParseResult.ValueForOption <string[]>("exclude"); var files = context.ParseResult.ValueForOption <string[]>("file"); var fileDirectory = context.ParseResult.ValueForOption <string>("file-directory"); var headerFile = context.ParseResult.ValueForOption <string>("headerFile"); var includeDirectories = context.ParseResult.ValueForOption <string[]>("include-directory"); var language = context.ParseResult.ValueForOption <string>("language"); var libraryPath = context.ParseResult.ValueForOption <string>("libraryPath"); var methodClassName = context.ParseResult.ValueForOption <string>("methodClassName"); var methodPrefixToStrip = context.ParseResult.ValueForOption <string>("prefixStrip"); var namespaceName = context.ParseResult.ValueForOption <string>("namespace"); var outputLocation = context.ParseResult.ValueForOption <string>("output"); var remappedNameValuePairs = context.ParseResult.ValueForOption <string[]>("remap"); var std = context.ParseResult.ValueForOption <string>("std"); var testOutputLocation = context.ParseResult.ValueForOption <string>("test-output"); var traversalNames = context.ParseResult.ValueForOption <string[]>("traverse"); var withAttributeNameValuePairs = context.ParseResult.ValueForOption <string[]>("with-attribute"); var withCallConvNameValuePairs = context.ParseResult.ValueForOption <string[]>("with-callconv"); var withLibraryPathNameValuePairs = context.ParseResult.ValueForOption <string[]>("with-librarypath"); var withSetLastErrors = context.ParseResult.ValueForOption <string[]>("with-setlasterror"); var withTypeNameValuePairs = context.ParseResult.ValueForOption <string[]>("with-type"); var withUsingNameValuePairs = context.ParseResult.ValueForOption <string[]>("with-using"); var suppressGcMethods = context.ParseResult.ValueForOption <string[]>("suppress-gc"); var errorList = new List <string>(); if (!files.Any()) { errorList.Add("Error: No input C/C++ files provided. Use --file or -f"); } if (string.IsNullOrWhiteSpace(namespaceName)) { errorList.Add("Error: No namespace provided. Use --namespace or -n"); } if (string.IsNullOrWhiteSpace(outputLocation)) { errorList.Add("Error: No output file location provided. Use --output or -o"); } ParseKeyValuePairs(remappedNameValuePairs, errorList, out Dictionary <string, string> remappedNames); ParseKeyValuePairs(withAttributeNameValuePairs, errorList, out Dictionary <string, IReadOnlyList <string> > withAttributes); ParseKeyValuePairs(withCallConvNameValuePairs, errorList, out Dictionary <string, string> withCallConvs); ParseKeyValuePairs(withLibraryPathNameValuePairs, errorList, out Dictionary <string, string> withLibraryPath); ParseKeyValuePairs(withTypeNameValuePairs, errorList, out Dictionary <string, string> withTypes); ParseKeyValuePairs(withUsingNameValuePairs, errorList, out Dictionary <string, IReadOnlyList <string> > withUsings); var configOptions = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PInvokeGeneratorConfigurationOptions.None : PInvokeGeneratorConfigurationOptions.GenerateUnixTypes; foreach (var configSwitch in configSwitches) { switch (configSwitch) { case "compatible-codegen": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode; configOptions &= ~PInvokeGeneratorConfigurationOptions.GeneratePreviewCode; break; } case "default-remappings": { configOptions &= ~PInvokeGeneratorConfigurationOptions.NoDefaultRemappings; break; } case "exclude-com-proxies": { configOptions |= PInvokeGeneratorConfigurationOptions.ExcludeComProxies; break; } case "exclude-empty-records": { configOptions |= PInvokeGeneratorConfigurationOptions.ExcludeEmptyRecords; break; } case "exclude-enum-operators": { configOptions |= PInvokeGeneratorConfigurationOptions.ExcludeEnumOperators; break; } case "explicit-vtbls": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateExplicitVtbls; break; } case "generate-aggressive-inlining": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateAggressiveInlining; break; } case "generate-macro-bindings": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateMacroBindings; break; } case "generate-tests-nunit": { if (string.IsNullOrWhiteSpace(testOutputLocation)) { errorList.Add("Error: No test output file location provided. Use --test-output or -to"); } if (configOptions.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateTestsXUnit)) { errorList.Add("Cannot generate both NUnit and XUnit tests."); } configOptions |= PInvokeGeneratorConfigurationOptions.GenerateTestsNUnit; break; } case "generate-tests-xunit": { if (string.IsNullOrWhiteSpace(testOutputLocation)) { errorList.Add("Error: No test output file location provided. Use --test-output or -to"); } if (configOptions.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateTestsNUnit)) { errorList.Add("Cannot generate both NUnit and XUnit tests."); } configOptions |= PInvokeGeneratorConfigurationOptions.GenerateTestsXUnit; break; } case "implicit-vtbls": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateExplicitVtbls; break; } case "latest-codegen": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode; configOptions &= ~PInvokeGeneratorConfigurationOptions.GeneratePreviewCode; break; } case "log-exclusions": { configOptions |= PInvokeGeneratorConfigurationOptions.LogExclusions; break; } case "log-visited-files": { configOptions |= PInvokeGeneratorConfigurationOptions.LogVisitedFiles; break; } case "multi-file": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateMultipleFiles; break; } case "no-default-remappings": { configOptions |= PInvokeGeneratorConfigurationOptions.NoDefaultRemappings; break; } case "preview-codegen": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode; configOptions |= PInvokeGeneratorConfigurationOptions.GeneratePreviewCode; break; } case "preview-codegen-nint": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode; configOptions |= PInvokeGeneratorConfigurationOptions.GeneratePreviewCodeNint; break; } case "preview-codegen-fnptr": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode; configOptions |= PInvokeGeneratorConfigurationOptions.GeneratePreviewCodeFnptr; break; } case "single-file": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateMultipleFiles; break; } case "unix-types": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateUnixTypes; break; } case "windows-types": { configOptions &= ~PInvokeGeneratorConfigurationOptions.GenerateUnixTypes; break; } default: { errorList.Add($"Error: Unrecognized config switch: {configSwitch}."); break; } } } if (!string.IsNullOrWhiteSpace(testOutputLocation) && !configOptions.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateTestsNUnit) && !configOptions.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateTestsXUnit)) { errorList.Add("Error: No test format provided. Use --config generate-tests-nunit or --config generate-tests-xunit"); } if (errorList.Any()) { foreach (var error in errorList) { context.Console.Error.Write(error); context.Console.Error.Write(Environment.NewLine); } context.Console.Error.Write(Environment.NewLine); new HelpBuilder(context.Console).Write(s_rootCommand); return(-1); } var clangCommandLineArgs = new string[] { $"--language={language}", // Treat subsequent input files as having type <language> $"--std={std}", // Language standard to compile for "-Wno-pragma-once-outside-header" // We are processing files which may be header files }; clangCommandLineArgs = clangCommandLineArgs.Concat(includeDirectories.Select(x => "--include-directory=" + x)).ToArray(); clangCommandLineArgs = clangCommandLineArgs.Concat(defineMacros.Select(x => "--define-macro=" + x)).ToArray(); clangCommandLineArgs = clangCommandLineArgs.Concat(additionalArgs).ToArray(); foreach (var arg in clangCommandLineArgs) { Console.WriteLine(arg); } var translationFlags = CXTranslationUnit_Flags.CXTranslationUnit_None; translationFlags |= CXTranslationUnit_Flags.CXTranslationUnit_IncludeAttributedTypes; // Include attributed types in CXType translationFlags |= CXTranslationUnit_Flags.CXTranslationUnit_VisitImplicitAttributes; // Implicit attributes should be visited var config = new PInvokeGeneratorConfiguration(libraryPath, namespaceName, outputLocation, testOutputLocation, configOptions, excludedNames, headerFile, methodClassName, methodPrefixToStrip, remappedNames, traversalNames, withAttributes, withCallConvs, withLibraryPath, withSetLastErrors, withTypes, withUsings, suppressGcMethods); if (config.GenerateMacroBindings) { translationFlags |= CXTranslationUnit_Flags.CXTranslationUnit_DetailedPreprocessingRecord; } var exitCode = 0; using (var pinvokeGenerator = new PInvokeGenerator(config)) { foreach (var file in files) { var filePath = Path.Combine(fileDirectory, file); var translationUnitError = CXTranslationUnit.TryParse(pinvokeGenerator.IndexHandle, filePath, clangCommandLineArgs, Array.Empty <CXUnsavedFile>(), translationFlags, out var handle); var skipProcessing = false; if (translationUnitError != CXErrorCode.CXError_Success) { Console.WriteLine($"Error: Parsing failed for '{filePath}' due to '{translationUnitError}'."); skipProcessing = true; } else if (handle.NumDiagnostics != 0) { Console.WriteLine($"Diagnostics for '{filePath}':"); for (uint i = 0; i < handle.NumDiagnostics; ++i) { using var diagnostic = handle.GetDiagnostic(i); Console.Write(" "); Console.WriteLine(diagnostic.Format(CXDiagnostic.DefaultDisplayOptions).ToString()); skipProcessing |= (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Error); skipProcessing |= (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Fatal); } } if (skipProcessing) { Console.WriteLine($"Skipping '{filePath}' due to one or more errors listed above."); Console.WriteLine(); exitCode = -1; continue; } try { using var translationUnit = TranslationUnit.GetOrCreate(handle); Console.WriteLine($"Processing '{filePath}'"); pinvokeGenerator.GenerateBindings(translationUnit, filePath, clangCommandLineArgs, translationFlags); } catch (Exception e) { Console.WriteLine(e); } } if (pinvokeGenerator.Diagnostics.Count != 0) { Console.WriteLine("Diagnostics for binding generation:"); foreach (var diagnostic in pinvokeGenerator.Diagnostics) { Console.Write(" "); Console.WriteLine(diagnostic); if (diagnostic.Level == DiagnosticLevel.Warning) { if (exitCode >= 0) { exitCode++; } } else if (diagnostic.Level == DiagnosticLevel.Error) { if (exitCode >= 0) { exitCode = -1; } else { exitCode--; } } } } } return(exitCode); }
public async Task InvokeAsync(InvocationContext context) { await _next(context); }
public ParametersFileWriter(InvocationContext invocationContext) { this.invocationContext = invocationContext; }
public void Run(InvocationContext context, string project) { Styles.Load(); #if GTK var app = new Application(Platforms.Gtk); #elif WPF var app = new Application(Platforms.Wpf); #else var app = new Application(Platforms.Mac64); #endif app.Style = "PipelineTool"; PipelineSettings.Default.Load(); if (!string.IsNullOrEmpty(PipelineSettings.Default.ErrorMessage)) { var logwin = new LogWindow(); logwin.LogText = PipelineSettings.Default.ErrorMessage; app.Run(logwin); return; } #if !DEBUG try #endif { var win = new MainWindow(); var controller = PipelineController.Create(win); #if GTK Global.Application.AddWindow(win.ToNative() as Gtk.Window); #endif #if GTK && !DEBUG GLib.ExceptionManager.UnhandledException += (e) => { var logwin = new LogWindow(); logwin.LogText = e.ExceptionObject.ToString(); logwin.Show(); win.Close(); }; #endif if (!string.IsNullOrEmpty(project)) { controller.OpenProject(project); } app.Run(win); } #if !DEBUG catch (Exception ex) { PipelineSettings.Default.ErrorMessage = ex.ToString(); PipelineSettings.Default.Save(); app.Restart(); } #endif }
private void ShowVersion(InvocationContext context) { var version = Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion; context.Console.Out.WriteLine(version); }
static void RootCommmandHandler(InvocationContext context, CommandLineOptions options) { _invocationContext = context; _serialPort = GetSerialPort(options); // open serial port Console.WriteLine("Connecting to: {0}", SerialPortToString()); try { _serialPort.Open(); if (options.resetEsp32) { ResetEsp32(100); } } catch (Exception) { Console.WriteLine($"Failed to open {_serialPort.PortName}"); } // wait while receiving data and handle disconnection and control keys bool reconnecting = false; bool paused = false; _continue = true; while (_continue) { // handle serial disconnection and reconnection if (!paused && !_serialPort.IsOpen) { try { _serialPort.Open(); reconnecting = false; Console.WriteLine("Reconnected."); } catch (System.IO.FileNotFoundException) { if (!reconnecting) { Console.WriteLine("Disconnected."); } if (options.disconnectExit) { return; } reconnecting = true; } catch (System.IO.IOException) { } } // control keys if (Console.KeyAvailable) { paused = ProcessKeys(paused); } Thread.Sleep(100); } }
/// <summary> /// Emits a call to the base method by pushing all of the arguments. /// </summary> /// <param name="m">The method to append to.</param> /// <param name="invocationContext">The invocation context for this call.</param> /// <param name="field">The field containing the interface to call.</param> /// <param name="originalMethod">The the original method signature.</param> /// <param name="baseMethod">The method to call.</param> private void EmitBaseMethodCall(MethodBuilder m, InvocationContext invocationContext, FieldInfo field, MethodInfo originalMethod, MethodInfo baseMethod) { // if this is a generic method, we have to instantiate our type of method if (baseMethod.IsGenericMethodDefinition) baseMethod = baseMethod.MakeGenericMethod(baseMethod.GetGenericArguments()); var sourceParameters = originalMethod.GetParameters(); var targetParameters = baseMethod.GetParameters(); // load the pointer from the field, push the parameters and call the method // this is an instance method, so arg.0 is the this pointer ILGenerator mIL = m.GetILGenerator(); mIL.Emit(OpCodes.Ldarg_0); mIL.Emit(OpCodes.Ldfld, field); // go through and serialize the parameters for (int i = 0; i < targetParameters.Length; i++) { ProxyHelper.EmitSerializeValue( _typeBuilder, m, invocationContext, _invocationContexts, _invocationContextsField, i, sourceParameters[i].ParameterType, targetParameters[i].ParameterType, null, _serializationProvider, _serializerField); } // call the method mIL.Emit(OpCodes.Callvirt, baseMethod); }
public async Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { if (CalledCount++ == 0) { await Task.Delay(100); throw new Exception("Deliberate failure"); } return new EdmModel(); }
protected override string GetStringLiteralAtIndex(InvocationContext context, int index) => context.Node is InvocationExpressionSyntax invocation
/// <summary> /// Emits the code needed to properly push an object on the stack, /// serializing the value if necessary. /// </summary> /// <param name="typeBuilder">The TypeBuilder for the method being built.</param> /// <param name="methodBuilder">The method currently being built.</param> /// <param name="invocationContext">The invocation context for this call.</param> /// <param name="invocationContexts">A list of invocation contexts that will be appended to.</param> /// <param name="invocationContextsField">The static field containing the array of invocation contexts at runtime.</param> /// <param name="parameterMapping">The mapping of source parameters to destination parameters.</param> /// <param name="serializationProvider">The serialization provider for the current interface.</param> /// <param name="serializationProviderField"> /// The field on the current object that contains the serialization provider at runtime. /// This method assume the current object is stored in arg.0. /// </param> internal static void EmitSerializeValue( TypeBuilder typeBuilder, MethodBuilder methodBuilder, InvocationContext invocationContext, List<InvocationContext> invocationContexts, FieldBuilder invocationContextsField, ParameterMapping parameterMapping, TraceSerializationProvider serializationProvider, FieldBuilder serializationProviderField) { var sourceCount = parameterMapping.Sources.Count(); if (sourceCount == 0) return; if (sourceCount == 1) { var parameter = parameterMapping.Sources.First(); EmitSerializeValue( typeBuilder, methodBuilder, invocationContext, invocationContexts, invocationContextsField, parameter.Position, parameter.SourceType, parameterMapping.CleanTargetType, parameter.Converter, serializationProvider, serializationProviderField); return; } var il = methodBuilder.GetILGenerator(); // use the serializer to serialize the objects var context = new TraceSerializationContext(invocationContext.SpecifyType(InvocationContextTypes.BundleParameters), -1); context.EventLevel = serializationProvider.GetEventLevelForContext(context); if (context.EventLevel != null) { // get the object serializer from the this pointer il.Emit(OpCodes.Ldsfld, serializationProviderField); // create a new dictionary strings and values il.Emit(OpCodes.Newobj, typeof(Dictionary<string, string>).GetConstructor(Type.EmptyTypes)); foreach (var parameter in parameterMapping.Sources) { il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldstr, parameter.Alias); EmitSerializeValue( typeBuilder, methodBuilder, invocationContext, invocationContexts, invocationContextsField, parameter.Position, parameter.SourceType, parameterMapping.CleanTargetType, parameter.Converter, serializationProvider, serializationProviderField); var method = typeof(Dictionary<string, string>).GetMethod("Add"); il.Emit(OpCodes.Call, method); } // get the invocation context from the array on the provider il.Emit(OpCodes.Ldsfld, invocationContextsField); il.Emit(OpCodes.Ldc_I4, invocationContexts.Count); il.Emit(OpCodes.Ldelem, typeof(TraceSerializationContext)); invocationContexts.Add(context); il.Emit(OpCodes.Callvirt, typeof(TraceSerializationProvider).GetMethod("ProvideSerialization", BindingFlags.Instance | BindingFlags.Public)); } else il.Emit(OpCodes.Ldnull); }
protected abstract TExpressionSyntax GetArgumentAtIndex(InvocationContext context, int index);
private void BuildEntitySetsAndSingletons(InvocationContext context, EdmModel model) { var configuration = context.ApiContext.Configuration; foreach (var property in this.publicProperties) { if (configuration.IsPropertyIgnored(property.Name)) { continue; } var isEntitySet = IsEntitySetProperty(property); if (!isEntitySet) { if (!IsSingletonProperty(property)) { continue; } } var propertyType = property.PropertyType; if (isEntitySet) { propertyType = propertyType.GetGenericArguments()[0]; } var entityType = model.FindDeclaredType(propertyType.FullName) as IEdmEntityType; if (entityType == null) { // Skip property whose entity type has not been declared yet. continue; } var container = model.EnsureEntityContainer(this.targetType); if (isEntitySet) { if (container.FindEntitySet(property.Name) == null) { this.entitySetProperties.Add(property); var addedEntitySet = container.AddEntitySet(property.Name, entityType); this.addedNavigationSources.Add(addedEntitySet); } } else { if (container.FindSingleton(property.Name) == null) { this.singletonProperties.Add(property); var addedSingleton = container.AddSingleton(property.Name, entityType); this.addedNavigationSources.Add(addedSingleton); } } } }
public virtual object Apply(InvocationContext <TContext> ctx) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the TraceSerializationContext class. /// </summary> /// <param name="invocationContext">The InvocationContext this is based on.</param> /// <param name="parameterIndex">The index of the parameter being serialized.</param> internal TraceSerializationContext(InvocationContext invocationContext, int parameterIndex) : base(invocationContext.MethodInfo, invocationContext.ContextType) { ParameterIndex = parameterIndex; }
public static int Run(InvocationContext context) { string sourceDirectory = context.ParseResult.ValueForOption <string>("sourceDir"); string arch = context.ParseResult.ValueForOption <string>("arch"); string interopFileName = context.ParseResult.ValueForOption <string>("interopFileName"); string outputFileName = context.ParseResult.ValueForOption <string>("outputFileName"); string version = context.ParseResult.ValueForOption <string>("version"); var remappedNameValuePairs = context.ParseResult.ValueForOption <string[]>("remap"); var enumAdditionsNameValuePairs = context.ParseResult.ValueForOption <string[]>("enum-Addition"); var enumMakeFlags = context.ParseResult.ValueForOption <string[]>("enum-Make-Flags"); var reducePointerLevelPairs = context.ParseResult.ValueForOption <string[]>("reducePointerLevel"); var typeImportValuePairs = context.ParseResult.ValueForOption <string[]>("typeImport"); var requiredNamespaceValuePairs = context.ParseResult.ValueForOption <string[]>("requiredNamespaceForName"); var autoTypes = context.ParseResult.ValueForOption <string[]>("autoTypes"); var remaps = ConvertValuePairsToDictionary(remappedNameValuePairs); var enumAdditions = ConvertValuePairsToEnumAdditions(enumAdditionsNameValuePairs); var reducePointerLevels = new HashSet <string>(reducePointerLevelPairs); var typeImports = ConvertValuePairsToDictionary(typeImportValuePairs); var requiredNamespaces = ConvertValuePairsToDictionary(requiredNamespaceValuePairs); string rawVersion = version.Split('-')[0]; Version assemblyVersion = Version.Parse(rawVersion); string archForAutoTypes = arch == "crossarch" ? "x64" : arch; NativeTypedefStructsCreator.CreateNativeTypedefsSourceFile(autoTypes, Path.Combine(sourceDirectory, $"generated\\{archForAutoTypes}\\autotypes.cs")); Console.Write($"Compiling source files..."); System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew(); ClangSharpSourceCompilation clangSharpCompliation = ClangSharpSourceCompilation.Create( sourceDirectory, arch, interopFileName, remaps, enumAdditions, enumMakeFlags, typeImports, requiredNamespaces, reducePointerLevels); Console.Write("looking for errors..."); var diags = clangSharpCompliation.GetDiagnostics(); watch.Stop(); int errors = 0; const int MaxErrorsToShow = 10000; foreach (var diag in diags) { if (errors == 0) { Console.WriteLine("errors were found."); } errors++; Console.WriteLine(diag.ToString()); if (errors >= MaxErrorsToShow) { Console.WriteLine($"Only showing the first {MaxErrorsToShow} errors."); break; } } if (errors > 0) { return(-1); } string timeTaken = watch.Elapsed.ToString("c"); Console.WriteLine($"took {timeTaken}"); Console.WriteLine($"Emitting {outputFileName}..."); var generator = ClangSharpSourceWinmdGenerator.GenerateWindmdForCompilation( clangSharpCompliation, typeImports, reducePointerLevels, assemblyVersion, outputFileName); foreach (var diag in generator.GetDiagnostics()) { Console.WriteLine($"{diag.Severity}: {diag.Message}"); } return(generator.WroteWinmd ? 0 : -1); }
// For every cycle, a new set of keys are required for the validators. This key generation process // is done on-chain. That means, every communication between participating nodes happen via transactions // in the block. For example, if node A wants to send a msg to node B, then node A encrypts the // msg with node B's public key and broadcast this as a transaction to the governance contract. // After this transaction is added to the chain, node B can decrypt the msg and read it. // During block execution, after every system transaction is executed, the following method // is invoked. It evaluates the transaction and if it's keygen related, it produces // appropriate response in form of a transaction and adds it to the pool for the addition // in the block. private void BlockManagerOnSystemContractInvoked(object _, InvocationContext context) { if (context.Receipt is null) { return; } var highestBlock = _blockSynchronizer.GetHighestBlock(); var willParticipate = !highestBlock.HasValue || GovernanceContract.IsKeygenBlock(context.Receipt.Block) && GovernanceContract.SameCycle(highestBlock.Value, context.Receipt.Block); if (!willParticipate) { Logger.LogInformation( highestBlock != null ? $"Will not participate in keygen: highest block is {highestBlock.Value}, call block is {context.Receipt.Block}" : $"Will not participate in keygen: highest block is null, call block is {context.Receipt.Block}" ); } var tx = context.Receipt.Transaction; if ( !tx.To.Equals(ContractRegisterer.GovernanceContract) && !tx.To.Equals(ContractRegisterer.StakingContract) ) { return; } if (context.Receipt.Block < _blockManager.GetHeight() && !GovernanceContract.SameCycle(context.Receipt.Block, _blockManager.GetHeight())) { Logger.LogWarning( $"System contract invoked from outdated tx: {context.Receipt.Hash}, tx block {context.Receipt.Block}, our height is {_blockManager.GetHeight()}"); return; } if (tx.Invocation.Length < 4) { return; } var signature = ContractEncoder.MethodSignatureAsInt(tx.Invocation); var decoder = new ContractDecoder(tx.Invocation.ToArray()); var contractAddress = tx.To; if (contractAddress.Equals(ContractRegisterer.GovernanceContract) && signature == ContractEncoder.MethodSignatureAsInt(GovernanceInterface.MethodFinishCycle)) { Logger.LogDebug("Aborting ongoing keygen because cycle was finished"); _keyGenRepository.SaveKeyGenState(Array.Empty <byte>()); } else if (signature == ContractEncoder.MethodSignatureAsInt(StakingInterface.MethodFinishVrfLottery)) { Logger.LogDebug($"Detected call of StakingInterface.{StakingInterface.MethodFinishVrfLottery}"); var cycle = GovernanceContract.GetCycleByBlockNumber(context.Receipt.Block); var data = new GovernanceContract(context).GetNextValidators(); var publicKeys = (data ?? throw new ArgumentException("Cannot parse method args")) .Select(x => x.ToPublicKey()) .ToArray(); Logger.LogDebug( $"Keygen is started in cycle={cycle}, block={context.Receipt.Block} for validator set: {string.Join(",", publicKeys.Select(x => x.ToHex()))}" ); if (!publicKeys.Contains(_privateWallet.EcdsaKeyPair.PublicKey)) { Logger.LogWarning("Skipping validator change event since we are not new validator"); return; } var keygen = GetCurrentKeyGen(); if (keygen != null && keygen.Cycle == cycle) { throw new ArgumentException("Cannot start keygen, since one is already running"); } if (keygen != null) { Logger.LogWarning($"Aborted keygen for cycle {keygen.Cycle} to start keygen for cycle {cycle}"); } _keyGenRepository.SaveKeyGenState(Array.Empty <byte>()); var faulty = (publicKeys.Length - 1) / 3; keygen = new TrustlessKeygen(_privateWallet.EcdsaKeyPair, publicKeys, faulty, cycle); var commitTx = MakeCommitTransaction(keygen.StartKeygen(), cycle); Logger.LogTrace($"Produced commit tx with hash: {commitTx.Hash.ToHex()}"); if (willParticipate) { Logger.LogInformation($"Try to send KeyGen Commit transaction"); if (_transactionPool.Add(commitTx) is var error && error != OperatingError.Ok) { Logger.LogError($"Error creating commit transaction ({commitTx.Hash.ToHex()}): {error}"); } else { Logger.LogInformation($"KeyGen Commit transaction sent"); } } Logger.LogDebug($"Saving keygen {keygen.ToBytes().ToHex()}"); _keyGenRepository.SaveKeyGenState(keygen.ToBytes()); }
protected override Task <int> Handle(CArgument argument, IConsole console, InvocationContext context, PipelineContext operation, CancellationToken cancellationToken) => Task.FromResult(0);
public void OnDisconnected([SignalRTrigger] InvocationContext invocationContext) { }
public Task InvokeAsync(InvocationContext context) { return(context.ProceedAsync()); }
public DomainModel(InvocationContext context, IEdmModel model) { this.Configuration = context.DomainContext.Configuration; this.Context = context; this.InnerModel = model; }
protected override ExpressionSyntax GetArgumentAtIndex(InvocationContext context, int index) => context.Node is InvocationExpressionSyntax invocation
/// <summary> /// Emits the implementation of a given interface method. /// </summary> /// <param name="executeMethod">The execute method to implement.</param> private void EmitMethodImpl(MethodInfo executeMethod) { /* * public TReturn Method (params) * { * var scope = new EventActivityScope(true); * try * { * _log.Method(params); * object value = _execute.Method(params); * _log.Method_Completed(value); * } * catch (Exception e) * { * _log.Method_Faulted(e); * throw; * } * finally * { * scope.Dispose(); * } * } */ var invocationContext = new InvocationContext(executeMethod, InvocationContextTypes.MethodCall); // start building the interface MethodBuilder m = _typeBuilder.DefineMethod(executeMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual); ProxyHelper.CopyMethodSignature(executeMethod, m); var parameterTypes = executeMethod.GetParameters().Select(p => p.ParameterType).ToArray(); ILGenerator mIL = m.GetILGenerator(); // set up a place to hold the return value LocalBuilder returnValue = null; if (m.ReturnType != typeof(void)) returnValue = mIL.DeclareLocal(m.ReturnType); // set up the activity scope LocalBuilder scope = null; if (_callWithActivityScope) { scope = mIL.DeclareLocal(typeof(EventActivityScope)); mIL.Emit(OpCodes.Ldc_I4_1); mIL.Emit(OpCodes.Newobj, typeof(EventActivityScope).GetConstructor(new Type[] { typeof(bool) })); mIL.Emit(OpCodes.Stloc, scope); } // start the try block mIL.BeginExceptionBlock(); // call the method on the log that matches the execute method var targetParameterTypes = parameterTypes.Select(p => p.IsGenericParameter ? TypeImplementer.GetTypeSupportedByEventSource(p) : p).ToArray(); var logMethod = DiscoverMethod(_logField.FieldType, executeMethod.Name, String.Empty, targetParameterTypes); if (logMethod != null) { // call the log method and throw away the result if there is one EmitBaseMethodCall(m, invocationContext, _logField, executeMethod, logMethod); if (logMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Pop); } // call execute EmitBaseMethodCall(m, invocationContext, _executeField, executeMethod, executeMethod); if (executeMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Stloc, returnValue); // if there is a completed method, then call that var completedParameterTypes = (executeMethod.ReturnType == typeof(void)) ? Type.EmptyTypes : new Type[] { executeMethod.ReturnType }; var completedMethod = DiscoverMethod(_logField.FieldType, executeMethod.Name, TypeImplementer.CompletedSuffix, completedParameterTypes); if (completedMethod != null) { // load this._log mIL.Emit(OpCodes.Ldarg_0); mIL.Emit(OpCodes.Ldfld, _logField); // load the value from the local variable if (executeMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Ldloc, returnValue); mIL.Emit(OpCodes.Call, completedMethod); if (completedMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Pop); } // handle exceptions by logging them and rethrowing mIL.BeginCatchBlock(typeof(Exception)); var faultedMethod = DiscoverMethod(_logField.FieldType, executeMethod.Name, TypeImplementer.FaultedSuffix, new Type[] { typeof(Exception) }); if (faultedMethod != null) { // save the exception var exception = mIL.DeclareLocal(typeof(Exception)); mIL.Emit(OpCodes.Stloc, exception); // load this._log mIL.Emit(OpCodes.Ldarg_0); mIL.Emit(OpCodes.Ldfld, _logField); // load the exception mIL.Emit(OpCodes.Ldloc, exception); // call the fault handler mIL.Emit(OpCodes.Call, faultedMethod); if (faultedMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Pop); } mIL.Emit(OpCodes.Rethrow); // clean up the activity scope if (_callWithActivityScope) { mIL.BeginFinallyBlock(); mIL.Emit(OpCodes.Ldloc, scope); mIL.Emit(OpCodes.Callvirt, typeof(EventActivityScope).GetMethod("Dispose")); } mIL.EndExceptionBlock(); // return the result if (executeMethod.ReturnType != typeof(void)) mIL.Emit(OpCodes.Ldloc, returnValue); mIL.Emit(OpCodes.Ret); }
protected override async Task <int> Handle(CArgument argument, IConsole console, InvocationContext context, PipelineContext pipeline, CancellationToken cancellationToken) { IWorkspace workspace = pipeline.Services.GetWorkspace(); if (argument.Delete) { await workspace.Clear(); } else { await workspace.Initialize(); await workspace.Templates.SetValue("c", Resources.Programming.FileTemplates.C); await workspace.Templates.SetValue("python", Resources.Programming.FileTemplates.Python); await workspace.Templates.SetValue("cpp", Resources.Programming.FileTemplates.Cpp); await workspace.Templates.SetValue("csharp", Resources.Programming.FileTemplates.CSharp); await workspace.Templates.SetValue("python", Resources.Programming.FileTemplates.Python); await workspace.Templates.SetValue("fsharp", Resources.Programming.FileTemplates.FSharp); await workspace.Templates.SetValue("go", Resources.Programming.FileTemplates.Go); await workspace.Templates.SetValue("java", Resources.Programming.FileTemplates.Java); await workspace.Templates.SetValue("dir", new Package <BaseTemplate>(FileBasedCommandLineOperation.GetDirectoryTemplate())); await workspace.Operations.SetValue("c", Resources.Programming.FileOperations.C); await workspace.Operations.SetValue("python", Resources.Programming.FileOperations.Python); await workspace.Operations.SetValue("cpp", Resources.Programming.FileOperations.Cpp); await workspace.Operations.SetValue("python", Resources.Programming.FileOperations.Python); await workspace.Operations.SetValue("go", Resources.Programming.FileOperations.Go); await workspace.Operations.SetValue("ruby", Resources.Programming.FileOperations.Ruby); await workspace.Operations.SetValue("javascript", Resources.Programming.FileOperations.JavaScript); await workspace.Operations.SetValue("dir", new Package <BaseOperation>(new FileBasedCommandLineOperation())); } return(0); }
public async Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { await Task.Delay(30); Interlocked.Increment(ref CalledCount); return new EdmModel(); }
public async Task LeaveGroup([SignalRTrigger] InvocationContext invocationContext, string connectionId, string groupName) { await Groups.RemoveFromGroupAsync(connectionId, groupName); }
static MethodDelegateAdapter() { pType = InvocationContext.GetInvocationType <T1>(); }
/// <summary> /// Emits the code needed to properly push an object on the stack, /// serializing the value if necessary. /// </summary> /// <param name="typeBuilder">The TypeBuilder for the method being built.</param> /// <param name="methodBuilder">The method currently being built.</param> /// <param name="invocationContext">The invocation context for this call.</param> /// <param name="invocationContexts">A list of invocation contexts that will be appended to.</param> /// <param name="invocationContextsField">The static field containing the array of invocation contexts at runtime.</param> /// <param name="i">The index of the current parameter being pushed.</param> /// <param name="sourceType">The type that the parameter is being converted from.</param> /// <param name="targetType">The type that the parameter is being converted to.</param> /// <param name="converter">An optional converter to apply to the source type.</param> /// <param name="serializationProvider">The serialization provider for the current interface.</param> /// <param name="serializationProviderField"> /// The field on the current object that contains the serialization provider at runtime. /// This method assume the current object is stored in arg.0. /// </param> internal static void EmitSerializeValue( TypeBuilder typeBuilder, MethodBuilder methodBuilder, InvocationContext invocationContext, List<InvocationContext> invocationContexts, FieldBuilder invocationContextsField, int i, Type sourceType, Type targetType, LambdaExpression converter, TraceSerializationProvider serializationProvider, FieldBuilder serializationProviderField) { ILGenerator mIL = methodBuilder.GetILGenerator(); // if the source is a parameter, then load the parameter onto the stack if (i >= 0) mIL.Emit(OpCodes.Ldarg, i + 1); // if a converter is passed in, then define a static method and use it to convert if (converter != null) { MethodBuilder mb = typeBuilder.DefineMethod(Guid.NewGuid().ToString(), MethodAttributes.Static | MethodAttributes.Public, converter.ReturnType, converter.Parameters.Select(p => p.Type).ToArray()); converter.CompileToMethod(mb); mIL.Emit(OpCodes.Call, mb); // the object on the stack is now the return type. we may need to convert it further sourceType = converter.ReturnType; } // if the source type is a reference to the target type, we have to dereference it if (sourceType.IsByRef && sourceType.GetElementType() == targetType) { sourceType = sourceType.GetElementType(); mIL.Emit(OpCodes.Ldobj, sourceType); return; } // if the types match, just put the argument on the stack if (sourceType == targetType) return; // this is not a match, so convert using the serializer. // verify that the target type is a string if (targetType != typeof(string)) throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Cannot convert type {0} to a type compatible with EventSource", targetType.FullName)); // for fundamental types, just convert them with ToString and be done with it var underlyingType = Nullable.GetUnderlyingType(sourceType) ?? sourceType; if (!sourceType.IsGenericParameter && (underlyingType.IsEnum || (underlyingType.IsValueType && underlyingType.Assembly == typeof(string).Assembly))) { // convert the argument to a string with ToString LocalBuilder lb = mIL.DeclareLocal(sourceType); mIL.Emit(OpCodes.Stloc, lb.LocalIndex); mIL.Emit(OpCodes.Ldloca, lb.LocalIndex); mIL.Emit(OpCodes.Call, sourceType.GetMethod("ToString", Type.EmptyTypes)); return; } // non-fundamental types use the object serializer var context = new TraceSerializationContext(invocationContext, i); context.EventLevel = serializationProvider.GetEventLevelForContext(context); if (context.EventLevel != null) { LocalBuilder lb = mIL.DeclareLocal(sourceType); mIL.Emit(OpCodes.Stloc, lb.LocalIndex); // get the object serializer from the this pointer mIL.Emit(OpCodes.Ldsfld, serializationProviderField); mIL.Emit(OpCodes.Ldloc, lb.LocalIndex); // if the source type is a reference to the target type, we have to dereference it if (sourceType.IsByRef) { sourceType = sourceType.GetElementType(); mIL.Emit(OpCodes.Ldobj, sourceType); } // if it's a value type, we have to box it to log it if (sourceType.IsGenericParameter || sourceType.IsValueType) mIL.Emit(OpCodes.Box, sourceType); // get the invocation context from the array on the provider mIL.Emit(OpCodes.Ldsfld, invocationContextsField); mIL.Emit(OpCodes.Ldc_I4, invocationContexts.Count); mIL.Emit(OpCodes.Ldelem, typeof(TraceSerializationContext)); invocationContexts.Add(context); mIL.Emit(OpCodes.Callvirt, typeof(TraceSerializationProvider).GetMethod("ProvideSerialization", BindingFlags.Instance | BindingFlags.Public)); } else { mIL.Emit(OpCodes.Pop); mIL.Emit(OpCodes.Ldnull); } }
public int Invoke(InvocationContext context) => InvokeAsync(context).GetAwaiter().GetResult();
protected abstract Task <int> Handle(T argument, IConsole console, InvocationContext context, PipelineContext operation, CancellationToken cancellationToken);
public int Invoke(InvocationContext context) => 42;
/// <summary> /// Determines whether the given invocation supports a context provider. /// </summary> /// <param name="invocationContext">The current InvocationContext.</param> /// <returns>True if the context provider should be invoked for the context.</returns> private bool SupportsContext(InvocationContext invocationContext) { return _contextProvider != null && _contextProvider.ShouldProvideContext(invocationContext); }
public virtual Task <int> InvokeAsync(InvocationContext context) => Task.FromResult(42);
/// <inheritdoc/> public async Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { Ensure.NotNull(context, "context"); IEdmModel modelReturned = await GetModelReturnedByInnerHandlerAsync(context, cancellationToken); if (modelReturned == null) { // There is no model returned so return an empty model. var emptyModel = new EdmModel(); emptyModel.EnsureEntityContainer(ModelCache.targetType); return emptyModel; } EdmModel edmModel = modelReturned as EdmModel; if (edmModel == null) { // The model returned is not an EDM model. return modelReturned; } ModelCache.ScanForDeclaredPublicProperties(); ModelCache.BuildEntitySetsAndSingletons(context, edmModel); ModelCache.AddNavigationPropertyBindings(edmModel); return edmModel; }
public override Task <int> InvokeAsync(InvocationContext context) => Task.FromResult(41);
public Task<IEdmModel> GetModelAsync(InvocationContext context, CancellationToken cancellationToken) { throw new NotImplementedException(); }
protected override int Invoke(InvocationContext context) => this.exitCode;
public override string ProvideContext(InvocationContext context) { Method = context.MethodInfo.Name; WasCalled = true; return "context"; }
/// <summary> /// Provides context information, such as security context, for a trace session. /// </summary> /// <param name="context">The context of the current invocation.</param> /// <returns>A string representing the current context.</returns> public abstract string ProvideContext(InvocationContext context);
public Task <int> InvokeAsync(InvocationContext context) => DoJobAsync();
/// <summary> /// Handles shared memory operations. /// </summary> /// <param name="context">The current invocation context.</param> /// <param name="attribute">The intrinsic attribute.</param> /// <returns>The resulting value.</returns> private static ValueReference HandleViewOperation( ref InvocationContext context, ViewIntrinsicAttribute attribute) { var builder = context.Builder; var location = context.Location; // These methods are instance calls -> load instance value var paramOffset = 0; var instanceValue = builder.CreateLoad( location, context[paramOffset++]); return(attribute.IntrinsicKind switch { ViewIntrinsicKind.GetViewLength => builder.CreateGetViewLength( location, instanceValue), ViewIntrinsicKind.GetViewLongLength => builder.CreateGetViewLongLength( location, instanceValue), ViewIntrinsicKind.GetViewLengthInBytes => builder.CreateArithmetic( location, builder.CreateGetViewLongLength(location, instanceValue), builder.CreateLongSizeOf( location, (instanceValue.Type as AddressSpaceType).ElementType), BinaryArithmeticKind.Mul), ViewIntrinsicKind.GetSubView => builder.CreateSubViewValue( location, instanceValue, context[paramOffset++], context[paramOffset++]), ViewIntrinsicKind.GetSubViewImplicitLength => builder.CreateSubViewValue( location, instanceValue, context[paramOffset], builder.CreateArithmetic( location, builder.CreateGetViewLongLength(location, instanceValue), context[paramOffset], BinaryArithmeticKind.Sub)), ViewIntrinsicKind.GetViewElementAddress => builder.CreateLoadElementAddress( location, instanceValue, context[paramOffset++]), ViewIntrinsicKind.CastView => builder.CreateViewCast( location, instanceValue, builder.CreateType(context.GetMethodGenericArguments()[0])), ViewIntrinsicKind.IsValidView => builder.CreateCompare( location, builder.CreateGetViewLongLength(location, instanceValue), builder.CreatePrimitiveValue(location, 0L), CompareKind.GreaterThan), ViewIntrinsicKind.GetViewExtent => builder.CreateIndex( location, builder.CreateGetViewLength(location, instanceValue)), ViewIntrinsicKind.GetViewLongExtent => builder.CreateIndex( location, builder.CreateGetViewLongLength(location, instanceValue)), ViewIntrinsicKind.GetViewElementAddressByIndex => builder.CreateLoadElementAddress( location, instanceValue, builder.CreateGetField( location, context[paramOffset++], new FieldAccess(0))), ViewIntrinsicKind.GetViewLinearElementAddress => RemapToLinearElementAddress(ref context), ViewIntrinsicKind.AsLinearView => instanceValue, _ => throw context.Location.GetNotSupportedException( ErrorMessages.NotSupportedViewIntrinsic, attribute.IntrinsicKind.ToString()), });