public void CompatibilityCheck_Properties(string scenario, bool hasMultipleProperties, PropertyTestData[] properties) { if (scenario != Scenario.ConfigMultiple && scenario != Scenario.Mixed && scenario != Scenario.NonContextMixedAppHost && scenario != Scenario.NonContextMixedDotnet) { throw new Exception($"Unexpected scenario: {scenario}"); } string propertyCompatConfig = Path.Combine(sharedState.BaseDirectory, "propertyCompat.runtimeconfig.json"); var config = RuntimeConfig.FromFile(propertyCompatConfig) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, SharedTestState.NetCoreAppVersion)); foreach (var kv in properties) { config.WithProperty(kv.Name, kv.NewValue); } config.Save(); string appOrConfigPath = scenario == Scenario.ConfigMultiple ? hasMultipleProperties ? sharedState.RuntimeConfigPath_MultiProperty : sharedState.RuntimeConfigPath : hasMultipleProperties ? sharedState.AppPath_MultiProperty : sharedState.AppPath; string[] args = { HostContextArg, scenario, CheckProperties.None, sharedState.HostFxrPath, appOrConfigPath, propertyCompatConfig }; CommandResult result; try { result = sharedState.CreateNativeHostCommand(args, sharedState.DotNetRoot) .EnvironmentVariable(Constants.HostTracing.VerbosityEnvironmentVariable, "3") .EnvironmentVariable("TEST_BLOCK_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.block") .EnvironmentVariable("TEST_SIGNAL_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.signal") .Execute(); } finally { File.Delete(propertyCompatConfig); } result.Should().Pass() .And.CreateDelegateMock_InMemoryAssembly(); switch (scenario) { case Scenario.ConfigMultiple: result.Should() .InitializeContextForConfig(appOrConfigPath) .And.CreateDelegateMock_COM(); break; case Scenario.Mixed: result.Should() .InitializeContextForApp(appOrConfigPath) .And.ExecuteAssemblyMock(appOrConfigPath, new string[0]); break; case Scenario.NonContextMixedAppHost: case Scenario.NonContextMixedDotnet: result.Should() .ExecuteAssemblyMock(appOrConfigPath, new string[0]); break; } bool shouldHaveDifferentProperties = false; foreach (var prop in properties) { if (prop.ExistingValue == null) { shouldHaveDifferentProperties = true; result.Should() .HaveStdErrContaining($"The property [{prop.Name}] is not present in the previously loaded runtime"); } else if (!prop.ExistingValue.Equals(prop.NewValue)) { shouldHaveDifferentProperties = true; result.Should() .InitializeSecondaryContext(propertyCompatConfig, Success_DifferentRuntimeProperties) .And.HaveStdErrContaining($"The property [{prop.Name}] has a different value [{prop.NewValue}] from that in the previously loaded runtime [{prop.ExistingValue}]"); } } if (shouldHaveDifferentProperties) { result.Should() .InitializeSecondaryContext(propertyCompatConfig, Success_DifferentRuntimeProperties); } else { result.Should() .InitializeSecondaryContext(propertyCompatConfig, Success_HostAlreadyInitialized); if (properties.Length > 0) { result.Should() .HaveStdErrContaining("All specified properties match those in the previously loaded runtime"); } } }
private static void Initialize() { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } lock (s_lock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } try { if (HostingEnvironment.IsHosted) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level"); } RoleManagerSection roleManager = RuntimeConfig.GetAppConfig().RoleManager; if (!s_EnabledSet) { s_Enabled = roleManager.Enabled; } s_CookieName = roleManager.CookieName; s_CacheRolesInCookie = roleManager.CacheRolesInCookie; s_CookieTimeout = (int)roleManager.CookieTimeout.TotalMinutes; s_CookiePath = roleManager.CookiePath; s_CookieRequireSSL = roleManager.CookieRequireSSL; s_CookieSlidingExpiration = roleManager.CookieSlidingExpiration; s_CookieProtection = roleManager.CookieProtection; s_Domain = roleManager.Domain; s_CreatePersistentCookie = roleManager.CreatePersistentCookie; s_MaxCachedResults = roleManager.MaxCachedResults; if (s_Enabled) { if (s_MaxCachedResults < 0) { throw new ProviderException(System.Web.SR.GetString("Value_must_be_non_negative_integer", new object[] { "maxCachedResults" })); } InitializeSettings(roleManager); InitializeDefaultProvider(roleManager); } } catch (Exception exception) { s_InitializeException = exception; } s_Initialized = true; } if (s_InitializeException != null) { throw s_InitializeException; } }
private static void Asset(RuntimeConfig runtimeConfig) { runtimeConfig.Framework.Version.Should().Be("2.1.0"); runtimeConfig.Framework.Name.Should().Be("Microsoft.NETCore.App"); runtimeConfig.IsPortable.Should().BeTrue(); }
static void Main(string[] args) { if (args.Length == 0) { var cfgList = new List <RuntimeConfig>(); var obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17777; //auto obj.AppName = "Login.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "LoginService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17778; //auto obj.AppName = "Match.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MatchService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17779; //auto obj.AppName = "Master.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MasterService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17780; //auto obj.AppName = "Zone.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "ZoneService" }; cfgList.Add(obj); using (var sw = new StreamWriter("app.json", false, Encoding.UTF8)) { var content = JsonConvert.SerializeObject(cfgList, Formatting.Indented); sw.Write(content); } Environment.SetEnvironmentVariable("AppName", "Login.App"); //Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly}, cfgList, OnInit, isMultiProcess:true); //单进程模式 Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit, isMultiProcess: false); //单进程模式 } else { var builder = new ConfigurationBuilder().AddCommandLine(args); var cmdLine = builder.Build(); //将命令行参数,设置到进程的环境变量 Environment.SetEnvironmentVariable("AppName", cmdLine["AppName"]); using (var sr = new StreamReader(cmdLine["Config"])) { var cfgList = JsonConvert.DeserializeObject <List <RuntimeConfig> >(sr.ReadToEnd()); Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit, isMultiProcess: true); //分布式 } } }
protected internal override void Render(HtmlTextWriter output) { CacheDependency dependency = null; if (this._outputString != null) { output.Write(this._outputString); this.RegisterValidationEvents(); } else if (this._cachingDisabled || !RuntimeConfig.GetAppConfig().OutputCache.EnableFragmentCache) { this._cachedCtrl.RenderControl(output); } else { string str; DateTime noAbsoluteExpiration; TimeSpan noSlidingExpiration; if (this._sqlDependency != null) { dependency = SqlCacheDependency.CreateOutputCacheDependency(this._sqlDependency); } this._cacheEntry.CssStyleString = this.GetCssStyleRenderString(output.GetType()); StringWriter tw = new StringWriter(); HtmlTextWriter writer = Page.CreateHtmlTextWriterFromType(tw, output.GetType()); TextWriter writer3 = this.Context.Response.SwitchWriter(tw); try { this.Page.PushCachingControl(this); this._cachedCtrl.RenderControl(writer); this.Page.PopCachingControl(); } finally { this.Context.Response.SwitchWriter(writer3); } this._cacheEntry.OutputString = tw.ToString(); output.Write(this._cacheEntry.OutputString); CacheDependency dependencies = this._cacheDependency; if (dependency != null) { if (dependencies == null) { dependencies = dependency; } else { AggregateCacheDependency dependency3 = new AggregateCacheDependency(); dependency3.Add(new CacheDependency[] { dependencies }); dependency3.Add(new CacheDependency[] { dependency }); dependencies = dependency3; } } ControlCachedVary cachedVary = null; if (((this._varyByParamsCollection == null) && (this._varyByControlsCollection == null)) && (this._varyByCustom == null)) { str = this._cacheKey; } else { string[] varyByParams = null; if (this._varyByParamsCollection != null) { varyByParams = this._varyByParamsCollection.GetParams(); } cachedVary = new ControlCachedVary(varyByParams, this._varyByControlsCollection, this._varyByCustom); HashCodeCombiner combinedHashCode = new HashCodeCombiner(this._nonVaryHashCode); str = this.ComputeVaryCacheKey(combinedHashCode, cachedVary); } if (this._useSlidingExpiration) { noAbsoluteExpiration = Cache.NoAbsoluteExpiration; noSlidingExpiration = (TimeSpan)(this._utcExpirationTime - DateTime.UtcNow); } else { noAbsoluteExpiration = this._utcExpirationTime; noSlidingExpiration = Cache.NoSlidingExpiration; } try { OutputCache.InsertFragment(this._cacheKey, cachedVary, str, this._cacheEntry, dependencies, noAbsoluteExpiration, noSlidingExpiration, this._provider); } catch { if (dependencies != null) { dependencies.Dispose(); } throw; } } }
private ApplicationLogic() : base("SouthParkDL") { m_episodes = new ArrayList(); runtimeConfig = new RuntimeConfig(); }
public override int Read(byte[] buffer, int offset, int count) { if ((this._Context.WorkerRequest == null) || (count == 0)) { return(0); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if ((offset < 0) || ((offset + count) > buffer.Length)) { throw new ArgumentException(null, "offset"); } if (count < 0) { throw new ArgumentException(null, "count"); } int numBytesRead = 0; if (!this._MaxLengthRead) { this._MaxRequestLength = RuntimeConfig.GetConfig(this._Context).HttpRuntime.MaxRequestLengthBytes; if (this.Length > this._MaxRequestLength) { if (!(this._Context.WorkerRequest is IIS7WorkerRequest)) { this._Context.Response.CloseConnectionAfterError(); } throw new HttpException(System.Web.SR.GetString("Max_request_length_exceeded"), null, 0xbbc); } this._MaxLengthRead = true; } if (!this._PreloadedConsumed) { byte[] preloadedEntityBody = this._Context.WorkerRequest.GetPreloadedEntityBody(); if (preloadedEntityBody != null) { int num2 = preloadedEntityBody.Length - ((int)this._CurrentPosition); int num3 = Math.Min(count, num2); Buffer.BlockCopy(preloadedEntityBody, (int)this._CurrentPosition, buffer, offset, num3); this.UpdateCounters(num3, ref offset, ref count, ref numBytesRead); this._PreloadedConsumed = numBytesRead == num2; } else { this._PreloadedConsumed = true; } } if ((count != 0) && !this._Context.WorkerRequest.IsEntireEntityBodyIsPreloaded()) { while (count > 0) { long num4 = this._MaxRequestLength - this._CurrentPosition; int size = (int)Math.Min(0x7fffffffL, Math.Min((long)count, num4 + 1L)); int bytesRead = this._Context.WorkerRequest.ReadEntityBody(buffer, offset, size); if (bytesRead <= 0) { if (!this._Context.WorkerRequest.IsClientConnected()) { throw new HttpException(System.Web.SR.GetString("ViewState_ClientDisconnected")); } return(numBytesRead); } this.UpdateCounters(bytesRead, ref offset, ref count, ref numBytesRead); } return(numBytesRead); } return(numBytesRead); }
private static void Initialize() { if (s_Initialized && s_InitializedDefaultProvider) { return; } if (s_InitializeException != null) { throw s_InitializeException; } if (HostingEnvironment.IsHosted) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level); } lock (s_lock) { if (s_Initialized && s_InitializedDefaultProvider) { return; } if (s_InitializeException != null) { throw s_InitializeException; } bool initializeGeneralSettings = !s_Initialized; // the default provider can be initialized once the pre start init has happened (i.e. when compilation has begun) // or if this is not even a hosted scenario bool initializeDefaultProvider = !s_InitializedDefaultProvider && (!HostingEnvironment.IsHosted || BuildManager.PreStartInitStage == PreStartInitStage.AfterPreStartInit); if (!initializeDefaultProvider && !initializeGeneralSettings) { return; } bool generalSettingsInitialized; bool defaultProviderInitialized = false; try { RuntimeConfig appConfig = RuntimeConfig.GetAppConfig(); MembershipSection settings = appConfig.Membership; generalSettingsInitialized = InitializeSettings(initializeGeneralSettings, appConfig, settings); defaultProviderInitialized = InitializeDefaultProvider(initializeDefaultProvider, settings); } catch (Exception e) { s_InitializeException = e; throw; } // update this state only after the whole method completes to preserve the behavior where // the system is uninitialized if any exceptions were thrown. if (generalSettingsInitialized) { s_Initialized = true; } if (defaultProviderInitialized) { s_InitializedDefaultProvider = true; } } }
private static void ValidateTargetFrameworkMoniker(string targetFrameworkMoniker) { CompilationSection compilation = RuntimeConfig.GetAppConfig().Compilation; int lineNumber = compilation.ElementInformation.LineNumber; string source = compilation.ElementInformation.Source; try { string str2 = targetFrameworkMoniker; if (GetVersion(targetFrameworkMoniker) != null) { str2 = ".NETFramework,Version=v" + str2; } s_targetFrameworkName = CreateFrameworkName(str2); } catch (ArgumentException exception) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_target_framework_version", new object[] { s_configTargetFrameworkAttributeName, targetFrameworkMoniker, exception.Message }), source, lineNumber); } Version frameworkNameVersion = GetFrameworkNameVersion(s_targetFrameworkName); if (frameworkNameVersion < Version40) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_lower_target_version", new object[] { s_configTargetFrameworkAttributeName }), source, lineNumber); } Version version3 = GetFrameworkNameVersion(LatestFrameworkName); if ((version3 == null) || (version3 < frameworkNameVersion)) { Version installedTargetVersion = GetInstalledTargetVersion(frameworkNameVersion.Major); if ((installedTargetVersion == null) || (installedTargetVersion < frameworkNameVersion)) { try { FrameworkName name = new FrameworkName(s_targetFrameworkName.Identifier, s_targetFrameworkName.Version); Version version = Environment.Version; string str3 = string.Concat(new object[] { version.Major, ".", version.Minor, ".", version.Build }); string str4 = @"SOFTWARE\Microsoft\.NETFramework\v" + str3 + @"\SKUs"; foreach (string str5 in Registry.LocalMachine.OpenSubKey(str4).GetSubKeyNames()) { try { FrameworkName name2 = CreateFrameworkName(str5); FrameworkName name3 = new FrameworkName(name2.Identifier, name2.Version); if (string.Equals(name.FullName, name3.FullName, StringComparison.OrdinalIgnoreCase)) { return; } } catch { } } } catch { } throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_higher_target_version", new object[] { s_configTargetFrameworkAttributeName }), source, lineNumber); } } }
//////////////////////////////////////////////////////////// // Public Methods ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// public override void Initialize(string name, NameValueCollection config) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level); if (String.IsNullOrEmpty(name)) { name = "AuthorizationStoreRoleProvider"; } if (config == null) { throw new ArgumentNullException("config"); } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", SR.GetString(SR.RoleAuthStoreProvider_description)); } base.Initialize(name, config); _CacheRefreshInterval = SecUtility.GetIntValue(config, "cacheRefreshInterval", 60, false, 0); _ScopeName = config["scopeName"]; if (_ScopeName != null && _ScopeName.Length == 0) { _ScopeName = null; } _ConnectionString = config["connectionStringName"]; if (_ConnectionString == null || _ConnectionString.Length < 1) { throw new ProviderException(SR.GetString(SR.Connection_name_not_specified)); } ConnectionStringsSection sec1 = null; sec1 = RuntimeConfig.GetAppConfig().ConnectionStrings; ConnectionStringSettings connObj = sec1.ConnectionStrings[_ConnectionString]; if (connObj == null) { throw new ProviderException(SR.GetString(SR.Connection_string_not_found, _ConnectionString)); } if (string.IsNullOrEmpty(connObj.ConnectionString)) { throw new ProviderException(SR.GetString(SR.Connection_string_not_found, _ConnectionString)); } _ConnectionString = connObj.ConnectionString; _AppName = config["applicationName"]; if (string.IsNullOrEmpty(_AppName)) { _AppName = SecUtility.GetDefaultAppName(); } if (_AppName.Length > 256) { throw new ProviderException(SR.GetString(SR.Provider_application_name_too_long)); } config.Remove("connectionStringName"); config.Remove("cacheRefreshInterval"); config.Remove("applicationName"); config.Remove("scopeName"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) { throw new ProviderException(SR.GetString(SR.Provider_unrecognized_attribute, attribUnrecognized)); } } }
public override async Task <bool> InstallAsync(CancellationToken cancellationToken) { Log.Output($"Installing {DisplayName}"); var dest = GetToolRoot(); var url = _assetInfo.DownloadUrl; if (!await DownloadAndExtractAsync(url, dest, ZipExtractor.Extract, cancellationToken)) { return(false); } var manifestFile = Path.Combine(dest, "dnvm.json"); if (!File.Exists(manifestFile)) { Log.Error("This tool is missing the 'dnvm.json' manifest file"); Uninstall(); return(false); } try { var manifest = ToolManifest.LoadFromFile(manifestFile); var secondaryInstalls = new List <Task>(); foreach (var command in manifest.Commands) { if (!LinkExecutable(command.Key, command.Value)) { Uninstall(); return(false); } if (command.Value.Portable == true) { var runtimeConfigPath = Path.Combine(dest, command.Value.RuntimeConfig); var runtimeConfig = RuntimeConfig.LoadFromFile(runtimeConfigPath); var name = runtimeConfig?.RuntimeOptions?.Framework?.Name; if (!"Microsoft.NETCore.App".Equals(name, StringComparison.OrdinalIgnoreCase)) { Log.Error($"This tool requires an unsupported shared framework: {name}"); Uninstall(); return(false); } var version = runtimeConfig.RuntimeOptions.Framework.Version; var sharedFx = new RuntimeAsset(Log, _env, version, Architecture.X64); secondaryInstalls.Add(sharedFx.InstallAsync(cancellationToken)); } } await Task.WhenAll(secondaryInstalls); } catch (FormatException ex) { Log.Verbose(ex.Message); Log.Error("This tool has an unrecognized 'dnvm.json' manifest format"); Uninstall(); return(false); } Log.Output($"Installed {DisplayName}"); return(true); }
private static bool InternalAuthenticate(String name, String password) { ////////////////////////////////////////////////////////////////////// // Step 1: Make sure we are initialized if (name == null || password == null) { return(false); } Initialize(); ////////////////////////////////////////////////////////////////////// // Step 2: Get the user database AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication; settings.ValidateAuthenticationMode(); FormsAuthenticationUserCollection Users = settings.Forms.Credentials.Users; // Hashtable hTable = settings.Credentials; if (Users == null) { return(false); } ////////////////////////////////////////////////////////////////////// // Step 3: Get the (hashed) password for this user FormsAuthenticationUser u = Users[name.ToLower(CultureInfo.InvariantCulture)]; if (u == null) { return(false); } String pass = (String)u.Password; if (pass == null) { return(false); } ////////////////////////////////////////////////////////////////////// // Step 4: Hash the given password String encPassword; #pragma warning disable 618 // HashPasswordForStorignInConfigFile is now obsolete switch (settings.Forms.Credentials.PasswordFormat) { case FormsAuthPasswordFormat.SHA256: encPassword = HashPasswordForStoringInConfigFile(password, "sha256"); break; case FormsAuthPasswordFormat.SHA384: encPassword = HashPasswordForStoringInConfigFile(password, "sha384"); break; case FormsAuthPasswordFormat.SHA512: encPassword = HashPasswordForStoringInConfigFile(password, "sha512"); break; case FormsAuthPasswordFormat.SHA1: encPassword = HashPasswordForStoringInConfigFile(password, "sha1"); break; case FormsAuthPasswordFormat.MD5: encPassword = HashPasswordForStoringInConfigFile(password, "md5"); break; case FormsAuthPasswordFormat.Clear: encPassword = password; break; default: return(false); } #pragma warning restore 618 ////////////////////////////////////////////////////////////////////// // Step 5: Compare the hashes return(String.Compare(encPassword, pass, ((settings.Forms.Credentials.PasswordFormat != FormsAuthPasswordFormat.Clear) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) == 0); }
public static bool CheckFileAccessForUser(string virtualPath, IntPtr token, string verb) { bool flag; if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } if (token == IntPtr.Zero) { throw new ArgumentNullException("token"); } if (verb == null) { throw new ArgumentNullException("verb"); } VirtualPath path = VirtualPath.Create(virtualPath); if (!path.IsWithinAppRoot) { throw new ArgumentException(System.Web.SR.GetString("Virtual_path_outside_application_not_supported"), "virtualPath"); } if (!s_EnabledDetermined) { if (HttpRuntime.UseIntegratedPipeline) { s_Enabled = true; } else { HttpModulesSection httpModules = RuntimeConfig.GetConfig().HttpModules; int count = httpModules.Modules.Count; for (int i = 0; i < count; i++) { HttpModuleAction action = httpModules.Modules[i]; if (Type.GetType(action.Type, false) == typeof(FileAuthorizationModule)) { s_Enabled = true; break; } } } s_EnabledDetermined = true; } if (!s_Enabled) { return(true); } FileSecurityDescriptorWrapper fileSecurityDescriptorWrapper = GetFileSecurityDescriptorWrapper(path.MapPath(), out flag); int iAccess = 3; if (((verb == "GET") || (verb == "POST")) || ((verb == "HEAD") || (verb == "OPTIONS"))) { iAccess = 1; } bool flag2 = fileSecurityDescriptorWrapper.IsAccessAllowed(token, iAccess); if (flag) { fileSecurityDescriptorWrapper.FreeSecurityDescriptor(); } return(flag2); }
static void Main(string[] args) { StaticCompositeResolver.Instance.Register( MessagePack.Resolvers.ClientAppResolver.Instance, MessagePack.Resolvers.FenixRuntimeResolver.Instance, MessagePack.Resolvers.SharedResolver.Instance, MessagePack.Unity.UnityResolver.Instance, MessagePack.Unity.Extension.UnityBlitResolver.Instance, MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance, MessagePack.Resolvers.StandardResolver.Instance ); if (args.Length == 0) { var cfgList = new List <RuntimeConfig>(); var obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17777; //auto obj.AppName = "Login.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "LoginService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17778; //auto obj.AppName = "Match.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MatchService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17779; //auto obj.AppName = "Master.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MasterService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIp = "auto"; obj.InternalIp = "auto"; obj.Port = 17780; //auto obj.AppName = "Zone.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "ZoneService" }; cfgList.Add(obj); using (var sw = new StreamWriter("app.json", false, Encoding.UTF8)) { var content = JsonConvert.SerializeObject(cfgList, Formatting.Indented); sw.Write(content); } Environment.SetEnvironmentVariable("AppName", "Login.App"); Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit, isMultiProcess: true); //单进程模式 //Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit, isMultiProcess: false); //单进程模式 } else { Parser.Default.ParseArguments <Options>(args) .WithParsed <Options>(o => { //将命令行参数,设置到进程的环境变量 Environment.SetEnvironmentVariable("AppName", o.AppName); using (var sr = new StreamReader(o.Config)) { var cfgList = JsonConvert.DeserializeObject <List <RuntimeConfig> >(sr.ReadToEnd()); Bootstrap.Start(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit, isMultiProcess: true); //分布式 } }); } }
/// <summary> /// Parses a command message and invokes a callback function delegate for status reporting /// </summary> /// <param name="msg">list of messages to parse</param> /// <param name="SendResponse">Callback taking a string as parameter to report return values back to sender</param> /// <param name="service">Service class for invoking application exit</param> public static void Parse(List <string> msg, Action <string> SendResponse, Service service) { AdmConfigBuilder Properties = AdmConfigBuilder.Instance(); RuntimeConfig rtc = RuntimeConfig.Instance(); msg.ForEach(message => { switch (message) { case Command.Switch: Logger.Info("signal received: time based theme switch"); ThemeManager.TimedSwitch(Properties); SendResponse(Command.Ok); break; case Command.Swap: Logger.Info("signal received: swap themes"); if (RegistryHandler.AppsUseLightTheme()) { ThemeManager.SwitchTheme(Properties.Config, Theme.Dark); } else { ThemeManager.SwitchTheme(Properties.Config, Theme.Light); } SendResponse(Command.Ok); break; case Command.AddAutostart: Logger.Info("signal received: adding service to autostart"); RegistryHandler.AddAutoStart(); SendResponse(Command.Ok); break; case Command.RemoveAutostart: Logger.Info("signal received: removing service from autostart"); RegistryHandler.RemoveAutoStart(); SendResponse(Command.Ok); break; case Command.CreateTask: Logger.Info("signal received: creating win scheduler based time switch task"); try { DateTime sunrise = Convert.ToDateTime(Properties.Config.Sunrise); DateTime sunset = Convert.ToDateTime(Properties.Config.Sunset); if (Properties.Config.Location.Enabled) { LocationHandler.GetSunTimesWithOffset(Properties, out sunrise, out sunset); } TaskSchdHandler.CreateSwitchTask(sunrise.Hour, sunrise.Minute, sunset.Hour, sunset.Minute); SendResponse(Command.Ok); } catch (FormatException e) { Logger.Error(e, "could not create win scheduler tasks"); SendResponse(Command.Err); Console.WriteLine(e); } break; case Command.RemoveTask: Logger.Info("signal received: removing win tasks"); TaskSchdHandler.RemoveTasks(); SendResponse(Command.Ok); break; case Command.Location: Logger.Info("signal received: request location update"); Task <bool> geoTask = Task.Run(() => LocationHandler.UpdateGeoposition(AdmConfigBuilder.Instance())); geoTask.Wait(); var result = geoTask.Result; if (result) { SendResponse(Command.Ok); } else { SendResponse(Command.NoLocAccess); } break; case Command.UpdateConfig: Logger.Info("signal received: updating configuration files"); try { AdmConfigBuilder.Instance().Load(); AdmConfigBuilder.Instance().LoadLocationData(); SendResponse(Command.Ok); } catch (Exception e) { Logger.Error(e, "could not read config file"); SendResponse(Command.Err); } break; case Command.Update: Logger.Info("signal received: checking for update"); SendResponse(UpdateHandler.CheckNewVersion()); break; case Command.Shutdown: Logger.Info("signal received, exiting"); SendResponse(Command.Ok); service.Exit(null, null); break; case Command.TestError: Logger.Info("signal received: test error"); SendResponse(Command.Err); break; case Command.Alive: Logger.Info("signal received: request for running status"); SendResponse(Command.Ok); break; case Command.Light: Logger.Info("signal received: force light theme"); rtc.ForcedTheme = Theme.Light; ThemeManager.SwitchTheme(Properties.Config, Theme.Light); SendResponse(Command.Ok); break; case Command.Dark: Logger.Info("signal received: force dark theme"); rtc.ForcedTheme = Theme.Dark; ThemeManager.SwitchTheme(Properties.Config, Theme.Dark); SendResponse(Command.Ok); break; case Command.NoForce: Logger.Info("signal received: resetting forced modes"); rtc.ForcedTheme = Theme.Undefined; ThemeManager.TimedSwitch(Properties); SendResponse(Command.Ok); break; default: Logger.Debug("unknown message received"); SendResponse(Command.Err); break; } }); }
private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) { Debug.Assert(_inputStream == null); _app = (HttpApplication)sender; HttpContext context = _app.Context; HttpRequest request = context.Request; HttpWorkerRequest wr = context.WorkerRequest; HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state); AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode; int contentLength; bool isForm = false; bool isFormMultiPart = false; if (asyncPreloadMode == AsyncPreloadModeFlags.None || request.ReadEntityBodyMode != ReadEntityBodyMode.None || wr == null || !wr.SupportsAsyncRead || !wr.HasEntityBody() || wr.IsEntireEntityBodyIsPreloaded() || context.Handler == null || context.Handler is TransferRequestHandler || context.Handler is DefaultHttpHandler || (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes || ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded")) && (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form) || ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data")) && (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart) || !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm ) { Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** "); httpAsyncResult.Complete(true, null, null); return(httpAsyncResult); } Debug.Trace("AsyncPreload", " *** AsyncPreload started *** "); try { if (_callback == null) { _callback = new AsyncCallback(OnAsyncCompletion); } _inputStream = request.GetBufferedInputStream(); byte[] buffer = _app.EntityBuffer; int bytesRead = 0; // loop to prevent recursive calls and potential stack overflow if/when it completes synchronously do { IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult); if (!readAsyncResult.CompletedSynchronously) { return(httpAsyncResult); } bytesRead = _inputStream.EndRead(readAsyncResult); } while (bytesRead != 0); } catch { Reset(); throw; } httpAsyncResult.Complete(true, null, null); return(httpAsyncResult); }
/// <summary> /// Instantiates a new TimeSwitchModule. /// This module switches themes based on system time and sunrise/sunset /// </summary> /// <param name="name">unique name of the module</param> public ThemeUpdateModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration) { RuntimeConfigInstance = RuntimeConfig.Instance(); }
public ClientController(ILogger <ContactController> logger, IOptions <RuntimeConfig> config) { _log = logger; _runtimeConfig = config.Value; }
/// <devdoc> /// Creates a MailMessage using the body parameter. /// </devdoc> public MailMessage CreateMailMessage(string recipients, IDictionary replacements, string body, Control owner) { if (owner == null) { throw new ArgumentNullException("owner"); } string from = From; if (String.IsNullOrEmpty(from)) { System.Net.Configuration.SmtpSection smtpSection = RuntimeConfig.GetConfig().Smtp; if (smtpSection == null || smtpSection.Network == null || String.IsNullOrEmpty(smtpSection.From)) { throw new HttpException(SR.GetString(SR.MailDefinition_NoFromAddressSpecified)); } else { from = smtpSection.From; } } MailMessage message = null; try { message = new MailMessage(from, recipients); if (!String.IsNullOrEmpty(CC)) { message.CC.Add(CC); } if (!String.IsNullOrEmpty(Subject)) { message.Subject = Subject; } message.Priority = Priority; if (replacements != null && !String.IsNullOrEmpty(body)) { foreach (object key in replacements.Keys) { string fromString = key as string; string toString = replacements[key] as string; if ((fromString == null) || (toString == null)) { throw new ArgumentException(SR.GetString(SR.MailDefinition_InvalidReplacements)); } // DevDiv 151177 // According to http://msdn2.microsoft.com/en-us/library/ewy2t5e0.aspx, some special // constructs (starting with "$") are recognized in the replacement patterns. References of // these constructs will be replaced with predefined strings in the final output. To use the // character "$" as is in the replacement patterns, we need to replace all references of single "$" // with "$$", because "$$" in replacement patterns are replaced with a single "$" in the // final output. toString = toString.Replace("$", "$$"); body = Regex.Replace(body, fromString, toString, RegexOptions.IgnoreCase); } } // If there are any embedded objects, we need to construct an alternate view with text/html // And add all of the embedded objects as linked resouces if (EmbeddedObjects.Count > 0) { string viewContentType = (IsBodyHtml ? MediaTypeNames.Text.Html : MediaTypeNames.Text.Plain); AlternateView view = AlternateView.CreateAlternateViewFromString(body, null, viewContentType); foreach (EmbeddedMailObject part in EmbeddedObjects) { string path = part.Path; if (String.IsNullOrEmpty(path)) { throw ExceptionUtil.PropertyNullOrEmpty("EmbeddedMailObject.Path"); } if (!UrlPath.IsAbsolutePhysicalPath(path)) { VirtualPath virtualPath = VirtualPath.Combine(owner.TemplateControlVirtualDirectory, VirtualPath.Create(path)); path = virtualPath.AppRelativeVirtualPathString; } // The FileStream will be closed by MailMessage.Dispose() LinkedResource lr = null; try { Stream stream = null; try { stream = owner.OpenFile(path); lr = new LinkedResource(stream); } catch { if (stream != null) { ((IDisposable)stream).Dispose(); } throw; } lr.ContentId = part.Name; lr.ContentType.Name = UrlPath.GetFileName(path); view.LinkedResources.Add(lr); } catch { if (lr != null) { lr.Dispose(); } throw; } } message.AlternateViews.Add(view); } else if (!String.IsNullOrEmpty(body)) { message.Body = body; } message.IsBodyHtml = IsBodyHtml; return(message); } catch { if (message != null) { message.Dispose(); } throw; } }
public MailMessage CreateMailMessage(string recipients, IDictionary replacements, string body, Control owner) { MailMessage message2; if (owner == null) { throw new ArgumentNullException("owner"); } string from = this.From; if (string.IsNullOrEmpty(from)) { SmtpSection smtp = RuntimeConfig.GetConfig().Smtp; if (((smtp == null) || (smtp.Network == null)) || string.IsNullOrEmpty(smtp.From)) { throw new HttpException(System.Web.SR.GetString("MailDefinition_NoFromAddressSpecified")); } from = smtp.From; } MailMessage message = null; try { message = new MailMessage(from, recipients); if (!string.IsNullOrEmpty(this.CC)) { message.CC.Add(this.CC); } if (!string.IsNullOrEmpty(this.Subject)) { message.Subject = this.Subject; } message.Priority = this.Priority; if ((replacements != null) && !string.IsNullOrEmpty(body)) { foreach (object obj2 in replacements.Keys) { string pattern = obj2 as string; string replacement = replacements[obj2] as string; if ((pattern == null) || (replacement == null)) { throw new ArgumentException(System.Web.SR.GetString("MailDefinition_InvalidReplacements")); } replacement = replacement.Replace("$", "$$"); body = Regex.Replace(body, pattern, replacement, RegexOptions.IgnoreCase); } } if (this.EmbeddedObjects.Count > 0) { string mediaType = this.IsBodyHtml ? "text/html" : "text/plain"; AlternateView item = AlternateView.CreateAlternateViewFromString(body, null, mediaType); foreach (EmbeddedMailObject obj3 in this.EmbeddedObjects) { string path = obj3.Path; if (string.IsNullOrEmpty(path)) { throw ExceptionUtil.PropertyNullOrEmpty("EmbeddedMailObject.Path"); } if (!UrlPath.IsAbsolutePhysicalPath(path)) { path = VirtualPath.Combine(owner.TemplateControlVirtualDirectory, VirtualPath.Create(path)).AppRelativeVirtualPathString; } LinkedResource resource = null; try { Stream contentStream = null; try { contentStream = owner.OpenFile(path); resource = new LinkedResource(contentStream); } catch { if (contentStream != null) { contentStream.Dispose(); } throw; } resource.ContentId = obj3.Name; resource.ContentType.Name = UrlPath.GetFileName(path); item.LinkedResources.Add(resource); } catch { if (resource != null) { resource.Dispose(); } throw; } } message.AlternateViews.Add(item); } else if (!string.IsNullOrEmpty(body)) { message.Body = body; } message.IsBodyHtml = this.IsBodyHtml; message2 = message; } catch { if (message != null) { message.Dispose(); } throw; } return(message2); }
public static bool CheckFileAccessForUser(String virtualPath, IntPtr token, string verb) { if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } if (token == IntPtr.Zero) { throw new ArgumentNullException("token"); } if (verb == null) { throw new ArgumentNullException("verb"); } VirtualPath vPath = VirtualPath.Create(virtualPath); if (!vPath.IsWithinAppRoot) { throw new ArgumentException(SR.GetString(SR.Virtual_path_outside_application_not_supported), "virtualPath"); } if (!s_EnabledDetermined) { if (HttpRuntime.UseIntegratedPipeline) { s_Enabled = true; // always enabled in Integrated Mode } else { HttpModulesSection modulesSection = RuntimeConfig.GetConfig().HttpModules; int len = modulesSection.Modules.Count; for (int iter = 0; iter < len; iter++) { HttpModuleAction module = modulesSection.Modules[iter]; if (Type.GetType(module.Type, false) == typeof(FileAuthorizationModule)) { s_Enabled = true; break; } } } s_EnabledDetermined = true; } if (!s_Enabled) { return(true); } //////////////////////////////////////////////////////////// // Step 3: Check the cache for the file-security-descriptor // for the requested file bool freeDescriptor; FileSecurityDescriptorWrapper oSecDesc = GetFileSecurityDescriptorWrapper(vPath.MapPath(), out freeDescriptor); //////////////////////////////////////////////////////////// // Step 4: Check if access is allowed int iAccess = 3; if (verb == "GET" || verb == "POST" || verb == "HEAD" || verb == "OPTIONS") { iAccess = 1; } bool fAllowed = oSecDesc.IsAccessAllowed(token, iAccess); //////////////////////////////////////////////////////////// // Step 5: Free the security descriptor if adding to cache failed if (freeDescriptor) { oSecDesc.FreeSecurityDescriptor(); } return(fAllowed); }
/// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected internal override void Render(HtmlTextWriter output) { CacheDependency sqlCacheDep = null; // If the output is cached, use it and do nothing else if (_outputString != null) { output.Write(_outputString); RegisterValidationEvents(); return; } // If caching was turned off, just render the control if (_cachingDisabled || !RuntimeConfig.GetAppConfig().OutputCache.EnableFragmentCache) { _cachedCtrl.RenderControl(output); return; } // Create SQL cache dependency before we render the page if (_sqlDependency != null) { sqlCacheDep = SqlCacheDependency.CreateOutputCacheDependency(_sqlDependency); } _cacheEntry.CssStyleString = GetCssStyleRenderString(output.GetType()); // Create a new HtmlTextWriter, with the same type as the current one (see ASURT 118922) StringWriter tmpWriter = new StringWriter(); HtmlTextWriter tmpHtmlWriter = Page.CreateHtmlTextWriterFromType(tmpWriter, output.GetType()); CacheDependency cacheDep; TextWriter savedWriter = Context.Response.SwitchWriter(tmpWriter); try { // Make sure the Page knows about us while the control's OnPreRender is called Page.PushCachingControl(this); _cachedCtrl.RenderControl(tmpHtmlWriter); Page.PopCachingControl(); } finally { Context.Response.SwitchWriter(savedWriter); } _cacheEntry.OutputString = tmpWriter.ToString(); // Send the output to the response output.Write(_cacheEntry.OutputString); // Cache the output cacheDep = _cacheDependency; if (sqlCacheDep != null) { if (cacheDep == null) { cacheDep = sqlCacheDep; } else { AggregateCacheDependency aggr = new AggregateCacheDependency(); aggr.Add(cacheDep); aggr.Add(sqlCacheDep); cacheDep = aggr; } } ControlCachedVary cachedVary = null; string realItemCacheKey; // If there are no varies, use the non-varying key if (_varyByParamsCollection == null && _varyByControlsCollection == null && _varyByCustom == null) { realItemCacheKey = _cacheKey; } else { string[] varyByParams = null; if (_varyByParamsCollection != null) { varyByParams = _varyByParamsCollection.GetParams(); } cachedVary = new ControlCachedVary(varyByParams, _varyByControlsCollection, _varyByCustom); HashCodeCombiner combinedHashCode = new HashCodeCombiner(_nonVaryHashCode); realItemCacheKey = ComputeVaryCacheKey(combinedHashCode, cachedVary); } // Compute the correct expiration, sliding or absolute DateTime utcExpirationTime; TimeSpan slidingExpiration; if (_useSlidingExpiration) { utcExpirationTime = Cache.NoAbsoluteExpiration; slidingExpiration = _utcExpirationTime - DateTime.UtcNow; } else { utcExpirationTime = _utcExpirationTime; slidingExpiration = Cache.NoSlidingExpiration; } try { OutputCache.InsertFragment(_cacheKey, cachedVary, realItemCacheKey, _cacheEntry, cacheDep /*dependencies*/, utcExpirationTime, slidingExpiration, _provider); } catch { if (cacheDep != null) { cacheDep.Dispose(); } throw; } }
static void Main(string[] args) { StaticCompositeResolver.Instance.Register( MessagePack.Resolvers.ClientAppResolver.Instance, MessagePack.Resolvers.FenixRuntimeResolver.Instance, MessagePack.Resolvers.SharedResolver.Instance, MessagePack.Unity.UnityResolver.Instance, MessagePack.Unity.Extension.UnityBlitResolver.Instance, MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance, MessagePack.Resolvers.StandardResolver.Instance ); if (args.Length == 0) { var cfgList = new List <RuntimeConfig>(); var obj = new RuntimeConfig(); obj.ExternalIP = "auto"; obj.InternalIP = "0.0.0.0"; obj.Port = 17777; //auto obj.AppName = "Login.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "LoginService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIP = "auto"; obj.InternalIP = "0.0.0.0"; obj.Port = 17778; //auto obj.AppName = "Match.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MatchService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIP = "auto"; obj.InternalIP = "0.0.0.0"; obj.Port = 17779; //auto obj.AppName = "Master.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "MasterService" }; cfgList.Add(obj); obj = new RuntimeConfig(); obj.ExternalIP = "auto"; obj.InternalIP = "0.0.0.0"; obj.Port = 17780; //auto obj.AppName = "Zone.App"; obj.HeartbeatIntervalMS = 5000; obj.ClientNetwork = NetworkType.TCP; obj.DefaultActorNames = new List <string>() { "ZoneService" }; cfgList.Add(obj); using (var sw = new StreamWriter("app.json", false, Encoding.UTF8)) { var content = JsonConvert.SerializeObject(cfgList, Formatting.Indented); sw.Write(content); } //for Debug purpose Environment.SetEnvironmentVariable("AppPath", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../")); Bootstrap.StartSingleProcess(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfgList, OnInit); //foreach (var cfg in cfgList) // if (cfg.AppName == "Master.App") // Bootstrap.StartMultiProcess(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfg, OnInit); //锟街诧拷式 } else { Parser.Default.ParseArguments <Options>(args) .WithParsed <Options>(o => { Environment.SetEnvironmentVariable("AppName", o.AppName); using (var sr = new StreamReader(o.Config)) { var cfgList = JsonConvert.DeserializeObject <List <RuntimeConfig> >(sr.ReadToEnd()); foreach (var cfg in cfgList) { if (cfg.AppName == o.AppName) { Bootstrap.StartMultiProcess(new Assembly[] { typeof(UModule.Avatar).Assembly }, cfg, OnInit); } } } }); } }
public void Save() { RuntimeConfig.SaveConfig(); Config.Save(); }
/// <devdoc> /// </devdoc> public virtual IDictionary DetermineUserCapabilities(WebPartManager webPartManager) { if (webPartManager == null) { throw new ArgumentNullException("webPartManager"); } Page page = webPartManager.Page; if (page == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page"), "webPartManager"); } HttpRequest request = page.RequestInternal; if (request == null) { throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "Page.Request"), "webPartManager"); } IPrincipal user = null; if (request.IsAuthenticated) { user = page.User; } if (user != null) { if (_supportedUserCapabilities == null) { _supportedUserCapabilities = CreateSupportedUserCapabilities(); } if ((_supportedUserCapabilities != null) && (_supportedUserCapabilities.Count != 0)) { WebPartsSection configSection = RuntimeConfig.GetConfig().WebParts; if (configSection != null) { WebPartsPersonalizationAuthorization authConfig = configSection.Personalization.Authorization; if (authConfig != null) { IDictionary capabilities = new HybridDictionary(); foreach (WebPartUserCapability capability in _supportedUserCapabilities) { if (authConfig.IsUserAllowed(user, capability.Name)) { capabilities[capability] = capability; } } return(capabilities); } } } } return(new HybridDictionary()); }
public void CompatibilityCheck_Frameworks(string scenario, FrameworkCompatibilityTestData testData) { if (scenario != Scenario.ConfigMultiple && scenario != Scenario.Mixed && scenario != Scenario.NonContextMixedAppHost && scenario != Scenario.NonContextMixedDotnet) { throw new Exception($"Unexpected scenario: {scenario}"); } string frameworkName = testData.Name; string version = testData.Version; string frameworkCompatConfig = Path.Combine(sharedState.BaseDirectory, "frameworkCompat.runtimeconfig.json"); RuntimeConfig.FromFile(frameworkCompatConfig) .WithFramework(new RuntimeConfig.Framework(frameworkName, version)) .WithRollForward(testData.RollForward) .Save(); string appOrConfigPath = scenario == Scenario.ConfigMultiple ? sharedState.RuntimeConfigPath : testData.ExistingContext switch { ExistingContextType.FrameworkDependent => sharedState.AppPath, ExistingContextType.SelfContained_NoIncludedFrameworks => sharedState.SelfContainedAppPath, ExistingContextType.SelfContained_WithIncludedFrameworks => sharedState.SelfContainedWithIncludedFrameworksAppPath, _ => throw new Exception($"Unexpected test data {nameof(testData.ExistingContext)}: {testData.ExistingContext}") }; string hostfxrPath = scenario == Scenario.NonContextMixedDotnet ? sharedState.HostFxrPath // Imitating dotnet - always use the non-self-contained hostfxr : testData.ExistingContext switch { ExistingContextType.FrameworkDependent => sharedState.HostFxrPath, ExistingContextType.SelfContained_NoIncludedFrameworks => sharedState.SelfContainedHostFxrPath, ExistingContextType.SelfContained_WithIncludedFrameworks => sharedState.SelfContainedWithIncludedFrameworksHostFxrPath, _ => throw new Exception($"Unexpected test data {nameof(testData.ExistingContext)}: {testData.ExistingContext}") }; string[] args = { HostContextArg, scenario, CheckProperties.None, hostfxrPath, appOrConfigPath, frameworkCompatConfig }; CommandResult result; try { result = sharedState.CreateNativeHostCommand(args, sharedState.DotNetRoot) .EnvironmentVariable(Constants.HostTracing.VerbosityEnvironmentVariable, "3") .EnvironmentVariable("TEST_BLOCK_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.block") .EnvironmentVariable("TEST_SIGNAL_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.signal") .Execute(); } finally { File.Delete(frameworkCompatConfig); } switch (scenario) { case Scenario.ConfigMultiple: result.Should() .InitializeContextForConfig(appOrConfigPath) .And.CreateDelegateMock_COM(); break; case Scenario.Mixed: result.Should() .InitializeContextForApp(appOrConfigPath) .And.ExecuteAssemblyMock(appOrConfigPath, new string[0]); break; case Scenario.NonContextMixedAppHost: case Scenario.NonContextMixedDotnet: result.Should() .ExecuteAssemblyMock(appOrConfigPath, new string[0]) .And.HaveStdErrContaining($"Mode: {(scenario == Scenario.NonContextMixedAppHost ? "apphost" : "muxer")}"); break; } bool?isCompatibleVersion = testData.IsCompatible; if (isCompatibleVersion.HasValue) { if (isCompatibleVersion.Value) { result.Should().Pass() .And.InitializeSecondaryContext(frameworkCompatConfig, Success_HostAlreadyInitialized) .And.CreateDelegateMock_InMemoryAssembly(); } else { result.Should().Fail() .And.FailToInitializeContextForConfig(CoreHostIncompatibleConfig) .And.HaveStdErrMatching($".*The specified framework '{frameworkName}', version '{version}', apply_patches=[0-1], version_compatibility_range=[^ ]* is incompatible with the previously loaded version '{SharedTestState.NetCoreAppVersion}'.*"); } } else { result.Should().Fail() .And.FailToInitializeContextForConfig(CoreHostIncompatibleConfig) .And.HaveStdErrContaining($"The specified framework '{frameworkName}' is not present in the previously loaded runtime"); } }
public void CompatibilityCheck_Frameworks(string scenario, bool selfContained, bool useIncludedFrameworks, string frameworkName, string version, string rollForward, bool?isCompatibleVersion) { if (scenario != Scenario.ConfigMultiple && scenario != Scenario.Mixed && scenario != Scenario.NonContextMixed) { throw new Exception($"Unexpected scenario: {scenario}"); } string frameworkCompatConfig = Path.Combine(sharedState.BaseDirectory, "frameworkCompat.runtimeconfig.json"); RuntimeConfig.FromFile(frameworkCompatConfig) .WithFramework(new RuntimeConfig.Framework(frameworkName, version)) .WithRollForward(rollForward) .Save(); string appOrConfigPath = scenario == Scenario.ConfigMultiple ? sharedState.RuntimeConfigPath : (selfContained ? (useIncludedFrameworks ? sharedState.SelfContainedWithIncludedFrameworksAppPath : sharedState.SelfContainedAppPath) : sharedState.AppPath); string[] args = { HostContextArg, scenario, CheckProperties.None, selfContained ? (useIncludedFrameworks ? sharedState.SelfContainedWithIncludedFrameworksHostFxrPath : sharedState.SelfContainedHostFxrPath) : sharedState.HostFxrPath, appOrConfigPath, frameworkCompatConfig }; CommandResult result; try { result = sharedState.CreateNativeHostCommand(args, sharedState.DotNetRoot) .EnvironmentVariable("COREHOST_TRACE_VERBOSITY", "3") .EnvironmentVariable("TEST_BLOCK_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.block") .EnvironmentVariable("TEST_SIGNAL_MOCK_EXECUTE_ASSEMBLY", $"{sharedState.AppPath}.signal") .Execute(); } finally { File.Delete(frameworkCompatConfig); } switch (scenario) { case Scenario.ConfigMultiple: result.Should() .InitializeContextForConfig(appOrConfigPath) .And.CreateDelegateMock_COM(); break; case Scenario.Mixed: result.Should() .InitializeContextForApp(appOrConfigPath) .And.ExecuteAssemblyMock(appOrConfigPath, new string[0]); break; case Scenario.NonContextMixed: result.Should() .ExecuteAssemblyMock(appOrConfigPath, new string[0]); break; } if (isCompatibleVersion.HasValue) { if (isCompatibleVersion.Value) { result.Should().Pass() .And.InitializeSecondaryContext(frameworkCompatConfig, Success_HostAlreadyInitialized) .And.CreateDelegateMock_InMemoryAssembly(); } else { result.Should().Fail() .And.FailToInitializeContextForConfig(CoreHostIncompatibleConfig) .And.HaveStdErrMatching($".*The specified framework '{frameworkName}', version '{version}', apply_patches=[0-1], version_compatibility_range=[^ ]* is incompatible with the previously loaded version '{SharedTestState.NetCoreAppVersion}'.*"); } } else { result.Should().Fail() .And.FailToInitializeContextForConfig(CoreHostIncompatibleConfig) .And.HaveStdErrContaining($"The specified framework '{frameworkName}' is not present in the previously loaded runtime"); } }
public SharedTestState() { var dotNet = new DotNetBuilder(BaseDirectory, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "mockRuntime") .AddMicrosoftNETCoreAppFrameworkMockCoreClr(NetCoreAppVersion) .Build(); DotNetRoot = dotNet.BinPath; HostFxrPath = Path.Combine( dotNet.GreatestVersionHostFxrPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")); string appDir = Path.Combine(BaseDirectory, "app"); Directory.CreateDirectory(appDir); AppPath = Path.Combine(appDir, "App.dll"); File.WriteAllText(AppPath, string.Empty); RuntimeConfig.FromFile(Path.Combine(appDir, "App.runtimeconfig.json")) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion)) .WithProperty(AppPropertyName, AppPropertyValue) .Save(); AppPath_MultiProperty = Path.Combine(appDir, "App_MultiProperty.dll"); File.WriteAllText(AppPath_MultiProperty, string.Empty); RuntimeConfig.FromFile(Path.Combine(appDir, "App_MultiProperty.runtimeconfig.json")) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion)) .WithProperty(AppPropertyName, AppPropertyValue) .WithProperty(AppMultiPropertyName, AppMultiPropertyValue) .Save(); CreateSelfContainedApp(dotNet, "SelfContained", out string selfContainedAppPath, out string selfContainedHostFxrPath, out string selfContainedConfigPath); SelfContainedAppPath = selfContainedAppPath; SelfContainedHostFxrPath = selfContainedHostFxrPath; SelfContainedConfigPath = selfContainedConfigPath; CreateSelfContainedApp(dotNet, "SelfContainedWithIncludedFrameworks", out selfContainedAppPath, out selfContainedHostFxrPath, out selfContainedConfigPath); SelfContainedWithIncludedFrameworksAppPath = selfContainedAppPath; SelfContainedWithIncludedFrameworksHostFxrPath = selfContainedHostFxrPath; SelfContainedWithIncludedFrameworksConfigPath = selfContainedConfigPath; RuntimeConfig.FromFile(SelfContainedWithIncludedFrameworksConfigPath) .WithIncludedFramework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion) .Save(); string configDir = Path.Combine(BaseDirectory, "config"); Directory.CreateDirectory(configDir); RuntimeConfigPath = Path.Combine(configDir, "Component.runtimeconfig.json"); RuntimeConfig.FromFile(RuntimeConfigPath) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion)) .WithProperty(ConfigPropertyName, ConfigPropertyValue) .Save(); RuntimeConfigPath_MultiProperty = Path.Combine(configDir, "Component_MultiProperty.runtimeconfig.json"); RuntimeConfig.FromFile(RuntimeConfigPath_MultiProperty) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion)) .WithProperty(ConfigPropertyName, ConfigPropertyValue) .WithProperty(ConfigMultiPropertyName, ConfigMultiPropertyValue) .Save(); string secondaryDir = Path.Combine(BaseDirectory, "secondary"); Directory.CreateDirectory(secondaryDir); SecondaryRuntimeConfigPath = Path.Combine(secondaryDir, "Secondary.runtimeconfig.json"); RuntimeConfig.FromFile(SecondaryRuntimeConfigPath) .WithFramework(new RuntimeConfig.Framework(Constants.MicrosoftNETCoreApp, NetCoreAppVersion)) .WithProperty(SecondaryConfigPropertyName, SecondaryConfigPropertyValue) .Save(); }
static void Main(string[] args) { try { //Set up Logger var config = new NLog.Config.LoggingConfiguration(); var configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AutoDarkMode"); try { Directory.CreateDirectory(configDir); } catch (Exception e) { Logger.Debug(e, "could not create config directory"); } // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = Path.Combine(configDir, "service.log"), Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level} | " + "${callsite:includeNamespace=False:" + "cleanNamesOfAnonymousDelegates=true:" + "cleanNamesOfAsyncContinuations=true}: ${message} ${exception:separator=|}" }; var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole") { Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level} | " + "${callsite:includeNamespace=False:" + "cleanNamesOfAnonymousDelegates=true:" + "cleanNamesOfAsyncContinuations=true}: ${message} ${exception:separator=|}" }; List <string> argsList; if (args.Length > 0) { argsList = new List <string>(args); } else { argsList = new List <string>(); } // Rules for mapping loggers to targets config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); if (argsList.Contains("/debug")) { config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); } else { config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile); } // Apply config LogManager.Configuration = config; if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false)) { Logger.Debug("app instance already open"); return; } //Instantiate Runtime config RuntimeConfig.Instance(); //Populate configuration AdmConfigBuilder Builder = AdmConfigBuilder.Instance(); try { Builder.Load(); Builder.LoadLocationData(); Logger.Debug("config builder instantiated and configuration loaded"); } catch (Exception e) { Logger.Fatal(e, "could not read config file. shutting down application!"); NLog.LogManager.Shutdown(); System.Environment.Exit(-1); } //if a path is set to null, set it to the currently actvie theme for convenience reasons bool configUpdateNeeded = false; if (!File.Exists(Builder.Config.DarkThemePath) || Builder.Config.DarkThemePath == null) { Builder.Config.DarkThemePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\Windows\Themes", ThemeHandler.GetCurrentThemeName() + ".theme"); configUpdateNeeded = true; } if (!File.Exists(Builder.Config.DarkThemePath) || Builder.Config.LightThemePath == null) { Builder.Config.LightThemePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\Windows\Themes", ThemeHandler.GetCurrentThemeName() + ".theme"); configUpdateNeeded = true; } if (configUpdateNeeded) { Logger.Warn("one or more theme paths not set at program start, reinstantiation needed"); try { Builder.Save(); } catch (Exception ex) { Logger.Error(ex, "couldn't save configuration file"); } } int timerMillis = 0; if (args.Length != 0) { Int32.TryParse(args[0], out timerMillis); } timerMillis = (timerMillis == 0) ? TimerFrequency.Short : timerMillis; Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Service = new Service(timerMillis); Application.Run(Service); } finally { //clean shutdown if (Service != null) { Service.Cleanup(); } mutex.Dispose(); } }