/* * This section is only used by the tools */ internal static RuntimeOptions Create (string http_message_handler, string tls_provider) { var options = new RuntimeOptions (); options.http_message_handler = ParseHttpMessageHandler (http_message_handler); options.tls_provider = ParseTlsProvider (tls_provider); return options; }
public ConfigurableLrTable(ILrDfa dfa, RuntimeOptions flags) { this.grammar = dfa.GrammarAnalysis; this.data = new MutableTable<int>(dfa.States.Length, grammar.Symbols.Count); Configure(dfa, flags, out underlyingTable); }
public void Initialize(RuntimeOptions options) { HRESULT res = NuiInitialize((uint)options); if (res != HRESULT.S_OK) throw new InvalidOperationException("Failed to initialize the kinect runtime, return value:" + res.ToString()); kinectWatcherThread = new Thread(new ParameterizedThreadStart(this.KinectWatcherThreadProc)); kinectWatcherThread.IsBackground = true; kinectWatcherThread.Start(); }
public DefaultHost(RuntimeOptions options, IAssemblyLoadContextAccessor loadContextAccessor) { _projectDirectory = Path.GetFullPath(options.ApplicationBaseDirectory); _targetFramework = options.TargetFramework; _loadContextAccessor = loadContextAccessor; _runtimeEnvironment = PlatformServices.Default.Runtime; _serviceProvider = new ServiceProvider(); Initialize(options, loadContextAccessor); }
public DesignTimeHostProjectCompiler(IApplicationShutdown shutdown, RuntimeOptions runtimeOptions) { // Using this ctor because it works on mono, this is hard coded to ipv4 // right now. Mono will eventually have the dualmode overload var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Loopback, runtimeOptions.CompilationServerPort.Value)); var networkStream = new NetworkStream(socket); _compiler = new DesignTimeHostCompiler(shutdown, networkStream); }
/// <summary> /// Initializes a new instance of the <see cref="KinectSensor"/> class and initializes the attached Kinect device. /// </summary> /// <param name="index">The index of the sensor to attach to.</param> /// <param name="options">The options to apply to the sensor to start with.</param> protected KinectSensor(int index, RuntimeOptions options) { Contract.Requires(index >= 0 && index < Runtime.Kinects.Count); myIndex = index; myOptions = options; this.Device.Initialize(options); _DepthFrames = Observable.FromEventPattern<ImageFrameReadyEventArgs>(this.Device, "DepthFrameReady").Select(ep => ep.EventArgs); _SkeletonFrames = Observable.FromEventPattern<SkeletonFrameReadyEventArgs>(this.Device, "SkeletonFrameReady").Select(ep => ep.EventArgs); _VideoFrames = Observable.FromEventPattern<ImageFrameReadyEventArgs>(this.Device, "VideoFrameReady").Select(ep => ep.EventArgs); }
private bool Configure(ILrDfa dfa, RuntimeOptions flags, out ILrParserTable outputTable) { bool result; ComplyWithConfiguration = true; switch (flags & RuntimeOptions.ParserAlgorithmMask) { case RuntimeOptions.ForceDeterministic: outputTable = BuildCanonicalLRTable(dfa); RequiresGlr = false; result = outputTable != null && !outputTable.RequiresGlr; if (!result) { data.Clear(); ComplyWithConfiguration = false; RequiresGlr = true; outputTable = BuildReductionModifiedLRTable(dfa); } break; case RuntimeOptions.ForceNonDeterministic: RequiresGlr = true; outputTable = BuildReductionModifiedLRTable(dfa); result = outputTable != null; break; case RuntimeOptions.AllowNonDeterministic: outputTable = BuildCanonicalLRTable(dfa); result = outputTable != null && !outputTable.RequiresGlr; if (!result) { data.Clear(); goto case RuntimeOptions.ForceNonDeterministic; } RequiresGlr = false; break; default: #if DEBUG throw new InvalidOperationException( "Internal error: unsupported language flags: " + (int)flags); #else result = false; outputTable = null; break; #endif } return result; }
public static string GetAuthorizationcode(RuntimeOptions runtimeOptions) { string url = string.Format("https://login.microsoftonline.com/{0}/oauth2/authorize?client_id={1}&response_type=code&prompt=login&redirect_uri={2}&resource={3}", runtimeOptions.tenantName, runtimeOptions.clientId, System.Web.HttpUtility.UrlEncode(runtimeOptions.redirectUrl), System.Web.HttpUtility.UrlEncode(runtimeOptions.resource)); using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }) { Timeout = new TimeSpan(0, 2, 0) }) { var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get }; HttpResponseMessage response = client.SendAsync(request).Result; var statusCode = (int)response.StatusCode; // We want to handle redirects ourselves so that we can determine the final redirect Location (via header) if (statusCode >= 300 && statusCode <= 399) { var redirectUri = response.Headers.Location; if (!redirectUri.IsAbsoluteUri) { redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri); } } else if (!response.IsSuccessStatusCode) { throw new Exception(); } return(""); } }
protected void ConnectOpenfin() { LogMessage("Configuration..."); var options = new RuntimeOptions { Version = RuntimeVersion, UUID = Uuid, }; LogMessage("Connection..."); Runtime = Runtime.GetRuntimeInstance(options); Runtime.OnIncommingMessage += (sender, e) => LogMessage(e.MessageContent); Runtime.OnOutgoingMessage += (sender, e) => LogMessage(e.MessageContent); Runtime.OnOutgoingMessage += (sender, e) => LogMessage(e.MessageContent); Runtime.Error += (sender, e) => LogMessage(e.ExceptionObject.ToString()); Runtime.Connect(() => { InterAppBus = Runtime.InterApplicationBus; LogMessage("Subscribers..."); InterAppBus.addSubscribeListener(SubscriptionListener); LogMessage("Unsubscribers..."); InterAppBus.addUnsubscribeListener(UnsubscriptionListener); var topics = ConfigurationManager.AppSettings .AllKeys .Where(key => key.StartsWith("openfin.topic")) .Select(key => ConfigurationManager.AppSettings[key]); foreach (var topic in topics) { LogMessage("Message Bus Subscribe..."); Subscriptions.Add(InterApplicationBus.Subscription <string>(Runtime, topic)); Subscriptions.Last().MessageReceived += (s, e) => LogMessage(e.Message); } }); }
private void LoadRuntimeOptions() { try { if (FileManager.FileExists(FileWindow.ApplicationFolderForThisProgram + @"RuntimeOptions.xml")) { mRuntimeOptions = RuntimeOptions.FromFile(FileWindow.ApplicationFolderForThisProgram + @"RuntimeOptions.xml"); // It's possible the runtime options may have a 0 width or height. If so, let's fix that here if (mRuntimeOptions.WindowHeight <= 1) { mRuntimeOptions.WindowHeight = 480; } if (mRuntimeOptions.WindowWidth <= 1) { mRuntimeOptions.WindowWidth = 640; } this.Size = new System.Drawing.Size( mRuntimeOptions.WindowWidth, mRuntimeOptions.WindowHeight); if (mRuntimeOptions.FullScreen) { this.WindowState = FormWindowState.Maximized; } OnResize(true); } } catch (Exception e) { // Who cares, not a big deal, just carry on } }
public Form1() { InitializeComponent(); this.lblConnectionStatus.Text = "Connecting..."; //Runtime options is how we set up the OpenFin Runtime environment, var runtimeOptions = new RuntimeOptions { Version = "stable", EnableRemoteDevTools = true, RemoteDevToolsPort = 9090 }; //Create our two embedded view controlls. chartEmbeddedView = new EmbeddedView(); //Add the embedded view controlls to each tabPage panel1.Controls.Add(chartEmbeddedView); //Initialize the chart view by passing the runtime Options and the ApplicationOptions chartEmbeddedView.Initialize(runtimeOptions, new ApplicationOptions("of-chart-tab", "of-chart-tab-uuid", "http://cdn.openfin.co/embed-web/chart.html")); //We can get the instance of the singleton runtime object by usig the GetRuntimeInstance function and passing var openFinRuntime = Runtime.GetRuntimeInstance(runtimeOptions); chartEmbeddedView.Ready += (sender, e) => { //Update the conection status: Utils.InvokeOnUiThreadIfRequired(this, () => { this.lblConnectionStatus.Text = "Connected"; }); //subscribe to chart-click messages from the chartEmbeddedView openFinRuntime.InterApplicationBus.subscribe(chartEmbeddedView.OpenfinApplication.getUuid(), "chart-click", (senderUuid, topic, data) => { var dataAsJObject = JObject.FromObject(data); Utils.InvokeOnUiThreadIfRequired(this, () => { label5.Text = string.Format("Key:{0}, {1} at {2}", dataAsJObject.GetValue("key"), dataAsJObject.GetValue("y"), dataAsJObject.GetValue("x")); }); }); }; }
public void TestApi() { var config = new Config { AppKey = Environment.GetEnvironmentVariable("IOT_APP_KEY"), AppSecret = Environment.GetEnvironmentVariable("IOT_APP_SECRET"), Domain = "api.link.aliyun.com" }; var client = new Client(config); var param = new Dictionary <string, object> { { "input", "test" } }; var req = new CommonParams { ApiVer = "1.0.0" }; var body = new IoTApiRequest { Params = param, Request = req }; var runtime = new RuntimeOptions(); var resp = client.DoRequest("/kit/debug/ping", "HTTPS", "POST", null, body, runtime); var obj = AlibabaCloud.TeaUtil.Common.ReadAsJSON(resp.Body); var map = AlibabaCloud.TeaUtil.Common.AssertAsMap(obj); Assert.Contains("test", map.Get("data").ToSafeString()); }
static void Main(string[] args) { RuntimeOptions runtimeOptions = new RuntimeOptions(); if (!ParseArguments(args.Length, args, ref runtimeOptions)) { PrintHelp(); return; } if ((runtimeOptions.mode & ImportForm) == ImportForm) { OutlookFormsProxy.ImportFormToPersonalFormsLibrary(runtimeOptions.formPath, runtimeOptions.formName); } if ((runtimeOptions.mode & RemoveForm) == RemoveForm) { OutlookFormsProxy.RemoveFormFromPersonalFormsLibrary(runtimeOptions.formName); } if ((runtimeOptions.mode & ClearFormCache) == ClearFormCache) { OutlookFormsProxy.ClearLocalFormCache(); } if ((runtimeOptions.mode & SetDefaultCalendarForm) == SetDefaultCalendarForm) { OutlookFormsProxy.SetDefaultCalendarForm(runtimeOptions.formName, runtimeOptions.formClass); } if ((runtimeOptions.mode & SetDefaultInboxForm) == SetDefaultInboxForm) { OutlookFormsProxy.SetDefaultInboxForm(runtimeOptions.formName, runtimeOptions.formClass); } if ((runtimeOptions.mode & ResetDefaultForms) == ResetDefaultForms) { Console.WriteLine("Reset logic not yet implemented!"); } //OutlookFormsProxy.ResetDefaultForms(); OutlookFormsProxy.Exit(); }
private void InitRuntime() { //Some Runtimes' status will be NotPowered, or some other error state. Only want to Initialize the runtime, if it is connected. if (_Kinect.Status == KinectStatus.Connected) { bool skeletalViewerAvailable = IsSkeletalViewerAvailable; // NOTE: Skeletal tracking only works on one Kinect per process right now. RuntimeOptions = skeletalViewerAvailable ? RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor : RuntimeOptions.UseDepth | RuntimeOptions.UseColor; _Kinect.Initialize(RuntimeOptions); skeletonPanel.Visibility = skeletalViewerAvailable ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed; if (RuntimeOptions.HasFlag(RuntimeOptions.UseSkeletalTracking)) { _Kinect.SkeletonEngine.TransformSmooth = true; } } string[] array = { "HipCenterX", "HipCenterY", "HipCenterZ", "SpineX", "SpineY", "SpineZ", "ShoulderCenterX", "ShoulderCenterY", "ShoulderCenterZ", "HeadX", "HeadY", "HeadZ", "ShoulderLeftX", "ShoulderLeftY", "ShoulderLeftZ", "ElbowLeftX", "ElbowLeftY", "ElbowLeftZ", "WristLeftX", "WristLeftY", "WristLeftZ", "HandLeftX", "HandLeftY", "HandLeftZ", "ShoulderRightX", "ShoulderRightY", "ShoulderRightZ", "ElbowRightX", "ElbowRightY", "ElbowRightZ", "WristRightX", "WristRightY", "WristRightZ", "HandRightX", "HandRightY", "HandRightZ", "HipLeftX", "HipLeftY", "HipLeftZ", "KneeLeftX", "KneeLeftY", "KneeLeftZ", "AnkleLeftX", "AnkleLeftY", "AnkleLeftZ", "FootLeftX", "FootLeftY", "FootLeftZ", "HipRightX", "HipRightY", "HipRightZ", "KneeRightX", "KneeRightY", "KneeRightZ", "AnkleRightX", "AnkleRightY", "AnkleRightZ", "FootRightX", "FootRightY", "FootRightZ", "Angle", "x", "y", "z", "w" }; for (int i = 0; i < 65; i++) { DataColumn column1 = new DataColumn(array[i], System.Type.GetType("System.Double")); dt1.Columns.Add(column1); } }
public void InitializeCommon() { SelectRegistrar(); SelectMonoNative(); RuntimeOptions = RuntimeOptions.Create(this, HttpMessageHandler, TlsProvider); if (RequiresXcodeHeaders && SdkVersion < SdkVersions.GetVersion(this)) { switch (Platform) { case ApplePlatform.iOS: case ApplePlatform.TVOS: case ApplePlatform.WatchOS: throw ErrorHelper.CreateError(180, Errors.MX0180, ProductName, PlatformName, SdkVersions.GetVersion(this), SdkVersions.Xcode); case ApplePlatform.MacOSX: throw ErrorHelper.CreateError(179, Errors.MX0179, ProductName, PlatformName, SdkVersions.GetVersion(this), SdkVersions.Xcode); default: // Default to the iOS error message, it's better than showing MX0071 (unknown platform), which would be completely unrelated goto case ApplePlatform.iOS; } } if (DeploymentTarget != null) { if (DeploymentTarget < Xamarin.SdkVersions.GetMinVersion(this)) { throw new ProductException(73, true, Errors.MT0073, Constants.Version, DeploymentTarget, Xamarin.SdkVersions.GetMinVersion(this), PlatformName, ProductName); } if (DeploymentTarget > Xamarin.SdkVersions.GetVersion(this)) { throw new ProductException(74, true, Errors.MX0074, Constants.Version, DeploymentTarget, Xamarin.SdkVersions.GetVersion(this), PlatformName, ProductName); } } if (Platform == ApplePlatform.WatchOS && EnableCoopGC.HasValue && !EnableCoopGC.Value) { throw ErrorHelper.CreateError(88, Errors.MT0088); } if (!EnableCoopGC.HasValue) { EnableCoopGC = Platform == ApplePlatform.WatchOS; } SetObjectiveCExceptionMode(); SetManagedExceptionMode(); if (SymbolMode == SymbolMode.Default) { #if MONOTOUCH SymbolMode = EnableBitCode ? SymbolMode.Code : SymbolMode.Linker; #else SymbolMode = SymbolMode.Linker; #endif } #if MONOTOUCH if (EnableBitCode && SymbolMode != SymbolMode.Code) { // This is a warning because: // * The user will get a linker error anyway if they do this. // * I see it as quite unlikely that anybody will in fact try this (it must be manually set in the additional mtouch arguments). // * I find it more probable that Apple will remove the -u restriction, in which case someone might actually want to try this, and if it's a warning, we won't prevent it. ErrorHelper.Warning(115, Errors.MT0115); } #endif if (!DebugTrack.HasValue) { DebugTrack = false; } else if (DebugTrack.Value && !EnableDebug) { ErrorHelper.Warning(32, Errors.MT0032); } if (!package_managed_debug_symbols.HasValue) { package_managed_debug_symbols = EnableDebug; } else if (package_managed_debug_symbols.Value && IsLLVM) { ErrorHelper.Warning(3007, Errors.MX3007); } Optimizations.Initialize(this, out var messages); ErrorHelper.Show(messages); if (Driver.Verbosity > 3) { Driver.Log(4, $"Enabled optimizations: {Optimizations}"); } }
public BaseFunction(RuntimeOptions options) { Options = options; }
public NetworkController(IOptions <RuntimeOptions> runtime, ILogger <NetworkController> logger, NetworkEndpointProvider provider) { log = logger; this.provider = provider; this.runtime = runtime.Value; }
/// <inheritdoc /> public IEngine UseOptions(RuntimeOptions options) { Options = options; Initialize(); return(this); }
/// <summary> /// Boots the runtime within a timer. /// </summary> protected virtual IFactory Boot(IRegister register, DisposableTimer timer) { Composition composition = null; try { // Setup event listener UnattendedInstalled += CoreRuntime_UnattendedInstalled; // throws if not full-trust new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted).Demand(); // run handlers RuntimeOptions.DoRuntimeBoot(ProfilingLogger); // application caches var appCaches = GetAppCaches(); // database factory var databaseFactory = GetDatabaseFactory(); // configs var configs = GetConfigs(); // type loader var typeLoader = new TypeLoader(appCaches.RuntimeCache, configs.Global().LocalTempPath, ProfilingLogger); // runtime state // beware! must use '() => _factory.GetInstance<T>()' and NOT '_factory.GetInstance<T>' // as the second one captures the current value (null) and therefore fails _state = new RuntimeState(Logger, configs.Settings(), configs.Global(), new Lazy <IMainDom>(() => _factory.GetInstance <IMainDom>()), new Lazy <IServerRegistrar>(() => _factory.GetInstance <IServerRegistrar>())) { Level = RuntimeLevel.Boot }; // TODO: remove this in netcore, this is purely backwards compat hacks with the empty ctor if (MainDom == null) { MainDom = new MainDom(Logger, new MainDomSemaphoreLock(Logger)); } // create the composition composition = new Composition(register, typeLoader, ProfilingLogger, _state, configs); composition.RegisterEssentials(Logger, Profiler, ProfilingLogger, MainDom, appCaches, databaseFactory, typeLoader, _state); // run handlers RuntimeOptions.DoRuntimeEssentials(composition, appCaches, typeLoader, databaseFactory); // register runtime-level services // there should be none, really - this is here "just in case" Compose(composition); // acquire the main domain - if this fails then anything that should be registered with MainDom will not operate AcquireMainDom(MainDom); // determine our runtime level DetermineRuntimeLevel(databaseFactory, ProfilingLogger); // get composers, and compose var composerTypes = ResolveComposerTypes(typeLoader); IEnumerable <Attribute> enableDisableAttributes; using (ProfilingLogger.DebugDuration <CoreRuntime>("Scanning enable/disable composer attributes")) { enableDisableAttributes = typeLoader.GetAssemblyAttributes(typeof(EnableComposerAttribute), typeof(DisableComposerAttribute)); } var composers = new Composers(composition, composerTypes, enableDisableAttributes, ProfilingLogger); composers.Compose(); // create the factory _factory = Current.Factory = composition.CreateFactory(); // determines if unattended install is enabled and performs it if required DoUnattendedInstall(databaseFactory); // determine our runtime level (AFTER UNATTENDED INSTALL) // TODO: Feels kinda weird to call this again DetermineRuntimeLevel(databaseFactory, ProfilingLogger); // if level is Run and reason is UpgradeMigrations, that means we need to perform an unattended upgrade if (_state.Reason == RuntimeLevelReason.UpgradeMigrations && _state.Level == RuntimeLevel.Run) { // do the upgrade DoUnattendedUpgrade(_factory.GetInstance <DatabaseBuilder>()); // upgrade is done, set reason to Run _state.Reason = RuntimeLevelReason.Run; } // create & initialize the components _components = _factory.GetInstance <ComponentCollection>(); _components.Initialize(); } catch (Exception e) { var bfe = e as BootFailedException ?? new BootFailedException("Boot failed.", e); if (_state != null) { _state.Level = RuntimeLevel.BootFailed; _state.BootFailedException = bfe; } timer?.Fail(exception: bfe); // be sure to log the exception - even if we repeat ourselves // if something goes wrong above, we may end up with no factory // meaning nothing can get the runtime state, etc - so let's try // to make sure we have a factory if (_factory == null) { try { _factory = Current.Factory = composition?.CreateFactory(); } catch { // In this case we are basically dead, we do not have a factory but we need // to report on the state so we need to manually set that, this is the only time // we ever do this. Current.RuntimeState = _state; } } Debugger.Break(); // throwing here can cause w3wp to hard-crash and we want to avoid it. // instead, we're logging the exception and setting level to BootFailed. // various parts of Umbraco such as UmbracoModule and UmbracoDefaultOwinStartup // understand this and will nullify themselves, while UmbracoModule will // throw a BootFailedException for every requests. } return(_factory); }
internal static RuntimeOptions Read () { var top_level = NSBundle.MainBundle.BundlePath; var plist_path = GetFileName (top_level); if (!File.Exists (plist_path)) return null; using (var plist = NSDictionary.FromFile (plist_path)) { var options = new RuntimeOptions (); options.http_message_handler = (NSString) plist ["HttpMessageHandler"]; options.tls_provider = (NSString) plist ["TlsProvider"]; return options; } }
public DesignTimeHostProjectCompiler(IApplicationShutdown shutdown, IFileWatcher watcher, RuntimeOptions runtimeOptions) { // Using this ctor because it works on mono, this is hard coded to ipv4 // right now. Mono will eventually have the dualmode overload var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Loopback, runtimeOptions.CompilationServerPort.Value)); var networkStream = new NetworkStream(socket); _compiler = new DesignTimeHostCompiler(shutdown, watcher, networkStream); }
/// <summary> /// Initializes a <see cref="PluginAttribute"/> with the given <see cref="IPA.RuntimeOptions"/> /// to indicate the runtime capabilities of the plugin. /// </summary> /// <param name="runtimeOptions">the options to use for this plugin</param> public PluginAttribute(RuntimeOptions runtimeOptions) { RuntimeOptions = runtimeOptions; }
public ResultFunction(RuntimeOptions options) : base(options) { }
public static IServiceCollection AddHq(this IServiceCollection services, IWebHostEnvironment env, IConfiguration config, ISafeLogger logger) { var subject = Assembly.GetCallingAssembly(); if (!(config is IConfigurationRoot configRoot)) { throw new ArgumentException("HQ requires access to the root configuration.", nameof(config)); } services.TryAddSingleton(configRoot); services.TryAddSingleton(services); var hq = configRoot.GetSection("HQ"); // // Core Services: services.AddTypeResolver(); services.AddLocalTimestamps(); services.AddSafeLogging(); services.AddValidOptions(); services.AddTraceContext(); // // Platform Services: services.AddSecurityPolicies(hq.GetSection("Security"), hq.GetSection("SuperUser"), logger); services.AddVersioning(hq.GetSection("Versioning")); services.AddMultiTenancy <IdentityTenant, IdentityApplication>(hq.GetSection("MultiTenancy")) .AddIdentityTenantContextStore <IdentityTenant>() .AddIdentityApplicationContextStore <IdentityApplication>(); // // Platform APIs: services .AddOperationsApi(hq.GetSection("Ops")) .AddPlatformApi(hq.GetSection("Api")) .AddBackgroundTasksApi(hq.GetSection("BackgroundTasks")) .AddConfigurationApi(configRoot, hq.GetSection("Configuration")) .AddIdentityApi(hq.GetSection("IdentityApi")) .AddSchemaApi(hq.GetSection("Schema")) .AddMetaApi(hq.GetSection("Meta")); var tasksBuilder = services.AddBackgroundTasks(hq.GetSection("BackgroundTasks")); var identityBuilder = services.AddIdentityExtended(hq.GetSection("Identity")); var runtimeBuilder = services.AddRuntimeApi(hq.GetSection("Runtime")); var schemaBuilder = services.AddSchemaDiscovery(hq.GetSection("Schema")); // // Cloud: var cloud = configRoot.GetSection("Cloud"); switch (cloud["Provider"]) { case nameof(Azure): { var options = new AzureOptions(); cloud.FastBind(options); services.AddCloudServices(logger, options); break; } } // // Backend Services: var backend = configRoot.GetSection("Backend"); var dbConfig = backend.GetSection("DbOptions"); if (dbConfig?.Value == null) { dbConfig = null; } var backendType = backend["Type"]; if (string.IsNullOrWhiteSpace(backendType)) { logger.Warn(() => "No backend type found!"); } else { logger.Info(() => "Installing {BackendType} back-end services.", backendType); } switch (backendType) { case nameof(DocumentDb): tasksBuilder.AddDocumentDbBackgroundTaskStore(backend.GetConnectionString("Tasks")); identityBuilder.AddDocumentDbIdentityStore <IdentityUserExtended, IdentityRoleExtended, IdentityTenant, IdentityApplication>(backend.GetConnectionString("Identity")); runtimeBuilder.AddDocumentDbRuntimeStores(backend.GetConnectionString("Runtime"), ConnectionScope.ByRequest, dbConfig); schemaBuilder.AddDocumentDbSchemaStores(backend.GetConnectionString("Schema")); break; case nameof(SqlServer): tasksBuilder.AddSqlServerBackgroundTasksStore(backend.GetConnectionString("Tasks"), r => r.GetRequiredService <IServerTimestampService>().GetCurrentTime()); identityBuilder.AddSqlServerIdentityStore <IdentityUserExtended, IdentityRoleExtended, IdentityTenant, IdentityApplication>(backend.GetConnectionString("Identity"), ConnectionScope.ByRequest, dbConfig); runtimeBuilder.AddSqlServerRuntime(backend.GetConnectionString("Runtime"), ConnectionScope.ByRequest, dbConfig); schemaBuilder.AddSqlServerSchemaStores(); break; case nameof(Sqlite): tasksBuilder.AddSqliteBackgroundTasksStore(backend.GetConnectionString("Tasks")); identityBuilder.AddSqliteIdentityStore <IdentityUserExtended, IdentityRoleExtended, IdentityTenant, IdentityApplication>(backend.GetConnectionString("Identity"), ConnectionScope.ByRequest, dbConfig); runtimeBuilder.AddSqliteRuntime(backend.GetConnectionString("Runtime"), ConnectionScope.ByRequest, dbConfig); schemaBuilder.AddSqliteSchemaStores(); break; default: throw new ArgumentOutOfRangeException(backendType, typeof(string), null); } // // Runtime Services: { var runtimeOptions = new RuntimeOptions(); hq.GetSection("Runtime").FastBind(runtimeOptions); if (runtimeOptions.EnableRest) { services.AddRestRuntime(); logger.Info(() => "REST is enabled."); } if (runtimeOptions.EnableGraphQl) { services.AddGraphQlRuntime(); logger.Info(() => "GraphQL is enabled."); } } // // Notification Services: services.AddEmailNotifications(hq.GetSection("Email")); // // Media Services: // // Custom Objects: services.ScanForGeneratedObjects(backendType, hq.GetSection("Security"), logger, "/api", subject); return(services); }
public void InitializeCommon() { SelectRegistrar(); SelectMonoNative(); RuntimeOptions = RuntimeOptions.Create(this, HttpMessageHandler, TlsProvider); if (RequiresXcodeHeaders && SdkVersion < SdkVersions.GetVersion(Platform)) { throw ErrorHelper.CreateError(91, Errors.MX0091, ProductName, PlatformName, SdkVersions.GetVersion(Platform), SdkVersions.Xcode, Error91LinkerSuggestion); } if (DeploymentTarget != null) { if (DeploymentTarget < Xamarin.SdkVersions.GetMinVersion(Platform)) { throw new ProductException(73, true, Errors.MT0073, Constants.Version, DeploymentTarget, Xamarin.SdkVersions.GetMinVersion(Platform), PlatformName, ProductName); } if (DeploymentTarget > Xamarin.SdkVersions.GetVersion(Platform)) { throw new ProductException(74, true, Errors.MX0074, Constants.Version, DeploymentTarget, Xamarin.SdkVersions.GetVersion(Platform), PlatformName, ProductName); } } if (Platform == ApplePlatform.WatchOS && EnableCoopGC.HasValue && !EnableCoopGC.Value) { throw ErrorHelper.CreateError(88, Errors.MT0088); } if (!EnableCoopGC.HasValue) { EnableCoopGC = Platform == ApplePlatform.WatchOS; } if (EnableCoopGC.Value) { switch (MarshalObjectiveCExceptions) { case MarshalObjectiveCExceptionMode.UnwindManagedCode: case MarshalObjectiveCExceptionMode.Disable: throw ErrorHelper.CreateError(89, Errors.MT0089, "--marshal-objectivec-exceptions", MarshalObjectiveCExceptions.ToString().ToLowerInvariant()); } switch (MarshalManagedExceptions) { case MarshalManagedExceptionMode.UnwindNativeCode: case MarshalManagedExceptionMode.Disable: throw ErrorHelper.CreateError(89, Errors.MT0089, "--marshal-managed-exceptions", MarshalManagedExceptions.ToString().ToLowerInvariant()); } } bool isSimulatorOrDesktopDebug = EnableDebug; #if MTOUCH isSimulatorOrDesktopDebug &= IsSimulatorBuild; #endif if (MarshalObjectiveCExceptions == MarshalObjectiveCExceptionMode.Default) { if (EnableCoopGC.Value || (Platform == ApplePlatform.MacOSX && EnableDebug)) { MarshalObjectiveCExceptions = MarshalObjectiveCExceptionMode.ThrowManagedException; } else { MarshalObjectiveCExceptions = isSimulatorOrDesktopDebug ? MarshalObjectiveCExceptionMode.UnwindManagedCode : MarshalObjectiveCExceptionMode.Disable; } } if (MarshalManagedExceptions == MarshalManagedExceptionMode.Default) { if (EnableCoopGC.Value) { MarshalManagedExceptions = MarshalManagedExceptionMode.ThrowObjectiveCException; } else { MarshalManagedExceptions = isSimulatorOrDesktopDebug ? MarshalManagedExceptionMode.UnwindNativeCode : MarshalManagedExceptionMode.Disable; } IsDefaultMarshalManagedExceptionMode = true; } if (SymbolMode == SymbolMode.Default) { #if MONOTOUCH SymbolMode = EnableBitCode ? SymbolMode.Code : SymbolMode.Linker; #else SymbolMode = SymbolMode.Linker; #endif } #if MONOTOUCH if (EnableBitCode && SymbolMode != SymbolMode.Code) { // This is a warning because: // * The user will get a linker error anyway if they do this. // * I see it as quite unlikely that anybody will in fact try this (it must be manually set in the additional mtouch arguments). // * I find it more probable that Apple will remove the -u restriction, in which case someone might actually want to try this, and if it's a warning, we won't prevent it. ErrorHelper.Warning(115, Errors.MT0115); } #endif if (!DebugTrack.HasValue) { DebugTrack = false; } else if (DebugTrack.Value && !EnableDebug) { ErrorHelper.Warning(32, Errors.MT0032); } if (!package_managed_debug_symbols.HasValue) { package_managed_debug_symbols = EnableDebug; } else if (package_managed_debug_symbols.Value && IsLLVM) { ErrorHelper.Warning(3007, Errors.MX3007); } Optimizations.Initialize(this); }
/// <summary> /// Initializes the Notification Service. /// </summary> /// <param name="manifestUri">The Uri pointing to the notification service manifest.</param> public static void Initialize(Uri manifestUri) { if (OnInitComplete == null) { throw new InvalidOperationException("InitializationComplete handler must be registered before calling Initialize()"); } var runtimeOptions = RuntimeOptions.LoadManifest(manifestUri); runtimeOptions.Arguments += " --inspect"; var entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); if (entryAssembly != null) { var productAttributes = entryAssembly.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true); if (productAttributes.Length > 0) { runtimeOptions.UUID = ((System.Reflection.AssemblyProductAttribute)productAttributes[0]).Product; } else { runtimeOptions.UUID = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; } } else { runtimeOptions.UUID = Guid.NewGuid().ToString(); } _runtime = Runtime.GetRuntimeInstance(runtimeOptions); _runtime.Connect(() => { var notificationsService = _runtime.CreateApplication(runtimeOptions.StartupApplicationOptions); notificationsService.isRunning( async ack => { if (!(bool)(ack.getData() as JValue).Value) { notificationsService.run(); } _channelClient = _runtime.InterApplicationBus.Channel.CreateClient(ServiceConstants.NotificationServiceChannelName); _channelClient.RegisterTopic <NotificationEvent>(ChannelTopics.Events, (@event) => { switch (@event.EventType) { case NotificationEventTypes.NotificationAction: NotificationActionOccurred?.Invoke(@event); break; case NotificationEventTypes.NotificationClosed: NotificationClosed?.Invoke(@event); break; case NotificationEventTypes.NotificationCreated: NotificationCreated?.Invoke(@event); break; default: throw new ArgumentException($"Invalid event type : {@event.EventType}"); } }); await _channelClient.ConnectAsync(); await _channelClient.DispatchAsync(ApiTopics.AddEventListener, NotificationEventTypes.NotificationAction); OnInitComplete.Invoke(); }); }); }
static void Main(string[] args) { var logger = default(ILogger); var options = new Options(); var settings = Settings.Default; try { if (!Parser.Default.ParseArguments(args, options)) { Environment.Exit(1); } Console.WriteLine($"{ApplicationName} {Version}"); Console.WriteLine($"Copyright © {CompanyName} 2016"); Console.WriteLine(); var logLevelSwitch = new LoggingLevelSwitch { MinimumLevel = options.LogEventLevel }; var logConfiguration = new LoggerConfiguration() .MinimumLevel.ControlledBy(logLevelSwitch) .WriteTo.ColoredConsole(); var runtimeOptions = new RuntimeOptions(options, settings); if (!string.IsNullOrWhiteSpace(runtimeOptions.LoggingServerUrl)) { logConfiguration = logConfiguration .WriteTo.Seq(runtimeOptions.LoggingServerUrl); } Log.Logger = logConfiguration.CreateLogger(); logger = Log.Logger.ForContext <Program>(); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterInstance(options); containerBuilder.RegisterInstance(settings); containerBuilder.RegisterInstance(runtimeOptions); containerBuilder.RegisterModule <AppModule>(); using (containerBuilder.Build()) { var awaiter = new AutoResetEvent(false); Console.CancelKeyPress += (s, e) => { e.Cancel = true; awaiter.Set(); }; logger.Information("Service is now started, press Ctrl+C for exit"); awaiter.WaitOne(); } } catch (Exception exception) { if (logger != null) { logger.Fatal(exception, "A fatal unhandled exception occured during execution"); Environment.Exit(1); } else { throw; } } }
// Called from CoreTlsProviderStep internal static TypeDefinition GetTlsProvider (RuntimeOptions options, ModuleDefinition module) { var provider = options != null ? options.tls_provider : DefaultTlsProviderValue; TypeDefinition type; switch (provider) { case DefaultTlsProviderValue: case AppleTlsProviderValue: type = module.GetType (Namespaces.Security + ".Tls.AppleTlsProvider"); break; case LegacyTlsProviderValue: type = module.GetType (Namespaces.Security + ".Tls.OldTlsProvider"); break; default: throw new InvalidOperationException (string.Format ("Unknown TlsProvider `{0}`.", provider)); } if (type == null) throw new InvalidOperationException (string.Format ("Cannot load TlsProvider `{0}`.", provider)); return type; }
// Called from CoreHttpMessageHandler internal static TypeDefinition GetHttpMessageHandler (RuntimeOptions options, ModuleDefinition httpModule, ModuleDefinition platformModule = null) { var handler = options != null ? options.http_message_handler : HttpClientHandlerValue; TypeDefinition type; switch (handler) { #if MONOMAC case HttpClientHandlerValue: type = httpModule.GetType ("System.Net.Http", "HttpClientHandler"); break; case CFNetworkHandlerValue: type = platformModule.GetType ("System.Net.Http", "CFNetworkHandler"); break; case NSUrlSessionHandlerValue: type = platformModule.GetType ("Foundation", "NSUrlSessionHandler"); break; #else case HttpClientHandlerValue: type = httpModule.GetType ("System.Net.Http", "HttpClientHandler"); break; case CFNetworkHandlerValue: type = httpModule.GetType ("System.Net.Http", "CFNetworkHandler"); break; case NSUrlSessionHandlerValue: type = httpModule.GetType ("System.Net.Http", "NSUrlSessionHandler"); break; #endif default: throw new InvalidOperationException (string.Format ("Unknown HttpMessageHandler `{0}`.", handler)); } if (type == null) throw new InvalidOperationException (string.Format ("Cannot load HttpMessageHandler `{0}`.", handler)); return type; }
static bool ParseArguments(int argc, string[] argv, ref RuntimeOptions runtimeOptions) { runtimeOptions.authUrl = "https://login.windows.net"; for (int i = 0; i < argc; i++) { switch (argv[i][0]) { case '-': case '/': case '\\': if (0 == argv[i][1]) { return(false); } switch (Char.ToLower(argv[i][1])) { case 'm': if (i + 1 < argc) { if (Convert.ToInt32(argv[i + 1]) == 1) { runtimeOptions.runningMode = RunningMode.Native; } else if (Convert.ToInt32(argv[i + 1]) == 2) { runtimeOptions.runningMode = RunningMode.Web; } else { return(false); } } else { return(false); } break; case 't': if (i + 1 < argc) { runtimeOptions.tenantName = argv[i + 1]; i++; } else { return(false); } break; case 'a': if (i + 1 < argc) { runtimeOptions.authUrl = argv[i + 1]; i++; } else { return(false); } break; case 'c': if (i + 1 < argc) { runtimeOptions.clientId = argv[i + 1]; i++; } else { return(false); } break; case 'k': if (i + 1 < argc) { runtimeOptions.key = argv[i + 1]; i++; } else { return(false); } break; case 'r': if (i + 1 < argc) { runtimeOptions.resource = argv[i + 1]; i++; } else { return(false); } break; case 'u': if (i + 1 < argc) { runtimeOptions.redirectUrl = argv[i + 1]; i++; } else { return(false); } break; case 'f': { runtimeOptions.adminConsent = true; } break; case '?': default: return(false); } break; } } return(true); }
private void Initialize(RuntimeOptions options, IAssemblyLoadContextAccessor loadContextAccessor) { var applicationHostContext = new ApplicationHostContext { ProjectDirectory = _projectDirectory, RuntimeIdentifiers = _runtimeEnvironment.GetAllRuntimeIdentifiers(), TargetFramework = _targetFramework }; var libraries = ApplicationHostContext.GetRuntimeLibraries(applicationHostContext, throwOnInvalidLockFile: true); Logger.TraceInformation("[{0}]: Project path: {1}", GetType().Name, applicationHostContext.ProjectDirectory); Logger.TraceInformation("[{0}]: Project root: {1}", GetType().Name, applicationHostContext.RootDirectory); Logger.TraceInformation("[{0}]: Project configuration: {1}", GetType().Name, options.Configuration); Logger.TraceInformation("[{0}]: Packages path: {1}", GetType().Name, applicationHostContext.PackagesDirectory); _applicationHostContext = applicationHostContext; _project = applicationHostContext.Project; #if FEATURE_DNX_MIN_VERSION_CHECK ValidateMinRuntimeVersion(libraries); #endif // Create a new Application Environment for running the app. It needs a reference to the Host's application environment // (if any), which we can get from the service provider we were given. // If this is null (i.e. there is no Host Application Environment), that's OK, the Application Environment we are creating // will just have it's own independent set of global data. var hostEnvironment = PlatformServices.Default.Application; var applicationEnvironment = new ApplicationEnvironment(Project, _targetFramework, options.Configuration, hostEnvironment); var compilationContext = new CompilationEngineContext( applicationEnvironment, _runtimeEnvironment, loadContextAccessor.Default, new CompilationCache()); // Compilation services available only for runtime compilation compilationContext.AddCompilationService(typeof(RuntimeOptions), options); compilationContext.AddCompilationService(typeof(IApplicationShutdown), _shutdown); var compilationEngine = new CompilationEngine(compilationContext); var runtimeLibraryExporter = new RuntimeLibraryExporter(() => compilationEngine.CreateProjectExporter(Project, _targetFramework, options.Configuration)); var runtimeLibraryManager = new RuntimeLibraryManager(applicationHostContext); // Default services _serviceProvider.Add(typeof(ILibraryExporter), runtimeLibraryExporter); _serviceProvider.Add(typeof(IApplicationShutdown), _shutdown); _serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment); _serviceProvider.Add(typeof(IRuntimeEnvironment), PlatformServices.Default.Runtime); _serviceProvider.Add(typeof(ILibraryManager), runtimeLibraryManager); _serviceProvider.Add(typeof(IAssemblyLoadContextAccessor), PlatformServices.Default.AssemblyLoadContextAccessor); _serviceProvider.Add(typeof(IAssemblyLoaderContainer), PlatformServices.Default.AssemblyLoaderContainer); PlatformServices.SetDefault( PlatformServices.Create( PlatformServices.Default, application: applicationEnvironment, libraryManager: runtimeLibraryManager )); if (options.CompilationServerPort.HasValue) { // Change the project reference provider Project.DefaultCompiler = Project.DefaultDesignTimeCompiler; } CallContextServiceLocator.Locator.ServiceProvider = _serviceProvider; // TODO: Dedupe this logic in the RuntimeLoadContext var projects = libraries.Where(p => p.Type == LibraryTypes.Project) .ToDictionary(p => p.Identity.Name, p => (ProjectDescription)p); var assemblies = PackageDependencyProvider.ResolvePackageAssemblyPaths(libraries); // Configure Assembly loaders _loaders.Add(new ProjectAssemblyLoader(loadContextAccessor, compilationEngine, projects.Values)); _loaders.Add(new PackageAssemblyLoader(loadContextAccessor, assemblies, libraries)); var compilerOptionsProvider = new CompilerOptionsProvider(projects); _serviceProvider.Add(typeof(ICompilerOptionsProvider), compilerOptionsProvider); CompilationServices.SetDefault( CompilationServices.Create( libraryExporter: runtimeLibraryExporter, compilerOptionsProvider: compilerOptionsProvider ) ); #if DNX451 PackageDependencyProvider.EnableLoadingNativeLibraries(libraries); #endif AddBreadcrumbs(libraries); }
private void Initialize(RuntimeOptions options, IServiceProvider hostServices, IAssemblyLoadContextAccessor loadContextAccessor, IFileWatcher fileWatcher) { var applicationHostContext = new ApplicationHostContext { ProjectDirectory = _projectDirectory, TargetFramework = _targetFramework }; ApplicationHostContext.Initialize(applicationHostContext); Logger.TraceInformation("[{0}]: Project path: {1}", GetType().Name, applicationHostContext.ProjectDirectory); Logger.TraceInformation("[{0}]: Project root: {1}", GetType().Name, applicationHostContext.RootDirectory); Logger.TraceInformation("[{0}]: Project configuration: {1}", GetType().Name, options.Configuration); Logger.TraceInformation("[{0}]: Packages path: {1}", GetType().Name, applicationHostContext.PackagesDirectory); _libraryManager = applicationHostContext.LibraryManager; _project = applicationHostContext.Project; if (options.WatchFiles) { fileWatcher.OnChanged += _ => { _shutdown.RequestShutdownWaitForDebugger(); }; } // Create a new Application Environment for running the app. It needs a reference to the Host's application environment // (if any), which we can get from the service provider we were given. // If this is null (i.e. there is no Host Application Environment), that's OK, the Application Environment we are creating // will just have it's own independent set of global data. var hostEnvironment = (IApplicationEnvironment)hostServices.GetService(typeof(IApplicationEnvironment)); var applicationEnvironment = new ApplicationEnvironment(Project, _targetFramework, options.Configuration, hostEnvironment); var compilationContext = new CompilationEngineContext(applicationEnvironment, loadContextAccessor.Default, new CompilationCache(), fileWatcher, new ProjectGraphProvider()); // Compilation services available only for runtime compilation compilationContext.AddCompilationService(typeof(RuntimeOptions), options); compilationContext.AddCompilationService(typeof(IApplicationShutdown), _shutdown); var compilationEngine = new CompilationEngine(compilationContext); // Default services _serviceProvider.Add(typeof(IApplicationEnvironment), applicationEnvironment); _serviceProvider.Add(typeof(ILibraryManager), _libraryManager); // TODO: Make this lazy _serviceProvider.Add(typeof(ILibraryExporter), compilationEngine.CreateProjectExporter(Project, _targetFramework, options.Configuration)); _serviceProvider.Add(typeof(IApplicationShutdown), _shutdown); _serviceProvider.Add(typeof(ICompilerOptionsProvider), new CompilerOptionsProvider(_libraryManager)); if (options.CompilationServerPort.HasValue) { // Change the project reference provider Project.DefaultCompiler = Project.DefaultDesignTimeCompiler; } CallContextServiceLocator.Locator.ServiceProvider = ServiceProvider; // Configure Assembly loaders _loaders.Add(new ProjectAssemblyLoader( loadContextAccessor, compilationEngine, _libraryManager)); _loaders.Add(new PackageAssemblyLoader(loadContextAccessor, _libraryManager)); }
public StopFunction(RuntimeOptions options) : base(options) { }
//private static void ImplementationRender(Type type, TypeBuilder typeBuilder) //{ // var targetMethod = DynamicHelpers.GetMethod(typeof(ITemplate), "Render", new Type[] { typeof(TextWriter) }); // MethodBuilder method = typeBuilder.DefineMethod(targetMethod.Name, targetMethod.Attributes & (~MethodAttributes.Abstract), targetMethod.ReturnType, new Type[] { typeof(TextWriter) }); // ILGenerator il = method.GetILGenerator(); // il.Emit(OpCodes.Ldarg_0); // il.Emit(OpCodes.Ldarg_1); // il.Emit(OpCodes.Ldarg_0); // il.Emit(OpCodes.Call, DynamicHelpers.GetPropertyInfo(typeof(ITemplate), "Context").SetMethod); // il.Emit(OpCodes.Call, DynamicHelpers.GetMethod(typeof(ICompileTemplate), "Render", new Type[] { typeof(TextWriter), typeof(TemplateContext) })); // il.Emit(OpCodes.Ret); //} /// <summary> /// Generate Context /// </summary> /// <param name="name">template name</param> /// <param name="options">The </param> /// <returns></returns> private static CompileContext GenerateContext(string name, RuntimeOptions options) { return(GenerateContext(name, options, new VariableScope(options.Data, TypeDetect.Absolute))); }
public StatusFunction(RuntimeOptions options) : base(options) { }
/// <summary> /// Boots the runtime within a timer. /// </summary> protected virtual IFactory Boot(IRegister register, DisposableTimer timer) { Composition composition = null; try { // throws if not full-trust new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted).Demand(); // run handlers RuntimeOptions.DoRuntimeBoot(ProfilingLogger); // application caches var appCaches = GetAppCaches(); // database factory var databaseFactory = GetDatabaseFactory(); // configs var configs = GetConfigs(); // type loader var typeLoader = new TypeLoader(appCaches.RuntimeCache, configs.Global().LocalTempPath, ProfilingLogger); // runtime state // beware! must use '() => _factory.GetInstance<T>()' and NOT '_factory.GetInstance<T>' // as the second one captures the current value (null) and therefore fails _state = new RuntimeState(Logger, configs.Settings(), configs.Global(), new Lazy <IMainDom>(() => _factory.GetInstance <IMainDom>()), new Lazy <IServerRegistrar>(() => _factory.GetInstance <IServerRegistrar>())) { Level = RuntimeLevel.Boot }; // main dom var mainDom = new MainDom(Logger); // create the composition composition = new Composition(register, typeLoader, ProfilingLogger, _state, configs); composition.RegisterEssentials(Logger, Profiler, ProfilingLogger, mainDom, appCaches, databaseFactory, typeLoader, _state); // run handlers RuntimeOptions.DoRuntimeEssentials(composition, appCaches, typeLoader, databaseFactory); // register runtime-level services // there should be none, really - this is here "just in case" Compose(composition); // acquire the main domain - if this fails then anything that should be registered with MainDom will not operate AcquireMainDom(mainDom); // determine our runtime level DetermineRuntimeLevel(databaseFactory, ProfilingLogger); // get composers, and compose var composerTypes = ResolveComposerTypes(typeLoader); composition.WithCollectionBuilder <ComponentCollectionBuilder>(); var composers = new Composers(composition, composerTypes, ProfilingLogger); composers.Compose(); // create the factory _factory = Current.Factory = composition.CreateFactory(); // create & initialize the components _components = _factory.GetInstance <ComponentCollection>(); _components.Initialize(); } catch (Exception e) { var bfe = e as BootFailedException ?? new BootFailedException("Boot failed.", e); if (_state != null) { _state.Level = RuntimeLevel.BootFailed; _state.BootFailedException = bfe; } timer?.Fail(exception: bfe); // be sure to log the exception - even if we repeat ourselves // if something goes wrong above, we may end up with no factory // meaning nothing can get the runtime state, etc - so let's try // to make sure we have a factory if (_factory == null) { try { _factory = Current.Factory = composition?.CreateFactory(); } catch { /* yea */ } } Debugger.Break(); // throwing here can cause w3wp to hard-crash and we want to avoid it. // instead, we're logging the exception and setting level to BootFailed. // various parts of Umbraco such as UmbracoModule and UmbracoDefaultOwinStartup // understand this and will nullify themselves, while UmbracoModule will // throw a BootFailedException for every requests. } return(_factory); }
/// <summary> /// Starts the Kinect with the specified options. /// </summary> /// <param name="options">The options to run the Kinect with as a set of flags.</param> /// <param name="kinectIndex">Index of the Kinect device you want to start, unless you have multiple Kinects attached you want to use the default value of 0.</param> /// <returns>A sensor instance which will allow you to operate on the Kinect that was just started.</returns> public static KinectSensor Start(RuntimeOptions options, int kinectIndex = 0) { Contract.Requires(0 < Runtime.Kinects.Count); Contract.Requires(kinectIndex >= 0 && kinectIndex < Runtime.Kinects.Count); Contract.Ensures(Contract.Result<KinectSensor>() != null && ReferenceEquals(Contract.Result<KinectSensor>().Device, Runtime.Kinects[kinectIndex])); lock (ourKinectSensors) { if (ourKinectSensors[kinectIndex] != null) AddRuntimeOptions(ourKinectSensors[kinectIndex], options); else ourKinectSensors[kinectIndex] = new KinectSensor(kinectIndex, options); return ourKinectSensors[kinectIndex]; } }
// Called from CoreHttpMessageHandler internal static TypeDefinition GetHttpMessageHandler(Application app, RuntimeOptions options, ModuleDefinition httpModule, ModuleDefinition platformModule = null) { string handler; if (options != null) { handler = options.http_message_handler; } else if (app.Platform == Utils.ApplePlatform.WatchOS) { handler = NSUrlSessionHandlerValue; } else { handler = HttpClientHandlerValue; } TypeDefinition type; switch (handler) { #if MONOMAC case HttpClientHandlerValue: type = httpModule.GetType("System.Net.Http", "HttpClientHandler"); break; case CFNetworkHandlerValue: type = platformModule.GetType("System.Net.Http", "CFNetworkHandler"); break; case NSUrlSessionHandlerValue: type = platformModule.GetType("Foundation", "NSUrlSessionHandler"); break; #else case HttpClientHandlerValue: if (app.Platform == Utils.ApplePlatform.WatchOS) { ErrorHelper.Warning(2015, Errors.MT2015, handler); type = platformModule.GetType("System.Net.Http", "NSUrlSessionHandler"); } else { type = httpModule.GetType("System.Net.Http", "HttpClientHandler"); } break; case CFNetworkHandlerValue: if (app.Platform == Utils.ApplePlatform.WatchOS) { ErrorHelper.Warning(2015, Errors.MT2015, handler); type = platformModule.GetType("System.Net.Http", "NSUrlSessionHandler"); } else { type = platformModule.GetType("System.Net.Http", "CFNetworkHandler"); } break; case NSUrlSessionHandlerValue: type = platformModule.GetType("System.Net.Http", "NSUrlSessionHandler"); break; #endif default: throw new InvalidOperationException(string.Format("Unknown HttpMessageHandler `{0}`.", handler)); } if (type == null) { throw new InvalidOperationException(string.Format("Cannot load HttpMessageHandler `{0}`.", handler)); } return(type); }
private static void AddRuntimeOptions(KinectSensor sensor, RuntimeOptions options) { Contract.Requires(sensor != null); sensor.myOptions |= options; sensor.Device.Uninitialize(); sensor.Device.Initialize(sensor.myOptions); }
private void InitialiseOpenFin() { this.runtimeOptions = new RuntimeOptions { Version = "18.87.55.19" }; this.runtime = Runtime.GetRuntimeInstance(runtimeOptions); runtime.Connect(async() => { // Enable our buttons now that we're connected to the runtime this.Dispatcher.Invoke(() => { this.submitButton.IsEnabled = true; this.gridButton.IsEnabled = true; this.tabbedButton.IsEnabled = true; this.columnsButton.IsEnabled = true; this.rowsButton.IsEnabled = true; }); runtime.System.getAllWindows((result) => { this.Dispatcher.Invoke(() => { if (!this.windowsSelector.IsEnabled && result.isSuccessful()) { var windows = result.getData(); foreach (var window in windows.Children()) { if (window["uuid"].ToString() == "openfin-local-demo-platform") { foreach (var odpWindow in window["childWindows"]) { if (odpWindow.Value <bool>("isShowing")) { var windowName = odpWindow.Value <string>("name"); this.windowsSelector.Items.Add(windowName); this.windowsSelector.IsEnabled = true; } } } } } }); }); try { var channel = runtime.InterApplicationBus.Channel.CreateProvider("MyAppActions"); channel.RegisterTopic <string>("SayHello", (payload) => { return($"Hello {payload}!"); }); this.client = this.runtime.InterApplicationBus.Channel.CreateClient("pack-actions"); await this.client.ConnectAsync(); this.client.Opened += Client_Opened; this.client.Closed += Client_Closed; //var result = await client.DispatchAsync<string>("SayHello", "Your name goes here"); //Console.WriteLine($"Responded with \"{result}\"."); Console.WriteLine("Client channel connected"); } catch (Exception e) { Console.WriteLine(e); } }); }
/// <summary> /// Execute internal of OData v2 call /// </summary> /// <typeparam name="REQ"></typeparam> /// <typeparam name="RES"></typeparam> /// <param name="endpoint"></param> /// <param name="req"></param> /// <param name="parm"></param> /// <param name="runtimeOption"></param> /// <returns></returns> private OD2Body <RES> ExecuteODataV2Internal <REQ, RES>(string endpoint, REQ req, Parameters parm, RuntimeOptions runtimeOption, MeisterOptions options) { CancellationTokenSource cancel = null; try { RestRequest request = new RestRequest(Method.GET); DoResourceAllocation(request, ExecuteMeister); request.AddQueryParameter(EndPoint, InQuotes(endpoint)); request.AddQueryParameter(Parms, InQuotes(PerformExtensions <Parameters>(parm))); if (options.HasFlag(MeisterOptions.CompressionsOutbound)) { request.AddQueryParameter(Content, InQuotes(Zip(PerformExtensions <REQ>(req)))); } else { request.AddQueryParameter(Content, InQuotes(PerformExtensions <REQ>(req))); } cancel = new CancellationTokenSource(); IRestResponse <OD2Body <RES> > response = null; if (runtimeOption.HasFlag(RuntimeOptions.ExecuteAsync)) { var task = Task.Run(async() => { response = await Client.ExecuteAsync <OD2Body <RES> >(request, cancel.Token).ConfigureAwait(true); BuildStatusData <RES, OD2Body <RES> >(response); return(response.Data); }); task.Wait(cancel.Token); return(task.Result); } else { return(ExecuteSync <OD2Body <RES> >(request).Result); } } finally { if (cancel != null) { cancel.Dispose(); } } }
//Kinect enabled apps should customize which Kinect services it initializes here. private void InitializeKinectServices(Runtime runtime) { runtimeOptions = RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor; //KinectSDK TODO: should be able to understand a Kinect used by another app without having to try/catch. try { Kinect.Initialize(runtimeOptions); } catch (COMException comException) { //TODO: make CONST if (comException.ErrorCode == -2147220947) //Runtime is being used by another app. { Kinect = null; ShowStatus(ErrorCondition.KinectAppConflict); return; } else { throw comException; } } ////////////kinectViewer.RuntimeOptions = runtimeOptions; ////////////kinectViewer.Kinect = Kinect; Kinect.SkeletonEngine.TransformSmooth = true; Kinect.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SkeletonsReady); //////////speechRecognizer = SpeechRecognizer.Create(); //returns null if problem with speech prereqs or instantiation. //////////if (speechRecognizer != null) //////////{ ////////// speechRecognizer.Start(new KinectAudioSource()); //KinectSDK TODO: expose Runtime.AudioSource to return correct audiosource. ////////// speechRecognizer.SaidSomething += new EventHandler<SpeechRecognizer.SaidSomethingEventArgs>(recognizer_SaidSomething); //////////} //////////else //////////{ ////////// ShowStatus(ErrorCondition.NoSpeech); ////////// speechRecognizer = null; //////////} }
private bool ParseArgs(string[] args, out RuntimeOptions defaultHostOptions, out string[] outArgs, out int exitCode) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = "Microsoft.Dnx.ApplicationHost"; app.FullName = app.Name; var optionWatch = app.Option("--watch", "Watch file changes", CommandOptionType.NoValue); var optionConfiguration = app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue); var optionCompilationServer = app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue); var runCmdExecuted = false; app.HelpOption("-?|-h|--help"); var env = (IRuntimeEnvironment)_serviceProvider.GetService(typeof(IRuntimeEnvironment)); app.VersionOption("--version", () => env.GetShortVersion(), () => env.GetFullVersion()); var runCmd = app.Command("run", c => { // We don't actually execute "run" command here // We are adding this command for the purpose of displaying correct help information c.Description = "Run application"; c.OnExecute(() => { runCmdExecuted = true; return(0); }); }, throwOnUnexpectedArg: false); app.Execute(args); defaultHostOptions = null; outArgs = null; exitCode = 0; if (app.IsShowingInformation) { // If help option or version option was specified, exit immediately with 0 exit code return(true); } else if (!(app.RemainingArguments.Any() || runCmdExecuted)) { // If no subcommand was specified, show error message // and exit immediately with non-zero exit code Console.WriteLine("Please specify the command to run"); exitCode = 2; return(true); } defaultHostOptions = new RuntimeOptions(); defaultHostOptions.WatchFiles = optionWatch.HasValue(); defaultHostOptions.TargetFramework = _environment.RuntimeFramework; defaultHostOptions.Configuration = optionConfiguration.Value() ?? _environment.Configuration ?? "Debug"; defaultHostOptions.ApplicationBaseDirectory = _environment.ApplicationBasePath; var portValue = optionCompilationServer.Value() ?? Environment.GetEnvironmentVariable(EnvironmentNames.CompilationServerPort); int port; if (!string.IsNullOrEmpty(portValue) && int.TryParse(portValue, out port)) { defaultHostOptions.CompilationServerPort = port; } var remainingArgs = new List <string>(); if (runCmdExecuted) { // Later logic will execute "run" command // So we put this argment back after it was consumed by parser remainingArgs.Add("run"); remainingArgs.AddRange(runCmd.RemainingArguments); } else { remainingArgs.AddRange(app.RemainingArguments); } if (remainingArgs.Any()) { defaultHostOptions.ApplicationName = remainingArgs[0]; outArgs = remainingArgs.Skip(1).ToArray(); } else { outArgs = remainingArgs.ToArray(); } return(false); }