////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Private stuff private static void InitializeEnabled(bool initProviders) { if (!s_Initialized || !s_InitializedProviders || !s_InitializeDefaultProvider) { lock (s_Lock) { if (!s_Initialized || !s_InitializedProviders || !s_InitializeDefaultProvider) { try { ProfileSection config = MTConfigUtil.GetProfileAppConfig(); if (!s_InitializedEnabled) { s_Enabled = config.Enabled && HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low); s_AutomaticSaveEnabled = s_Enabled && config.AutomaticSaveEnabled; s_InitializedEnabled = true; } if (initProviders && s_Enabled && (!s_InitializedProviders || !s_InitializeDefaultProvider)) { InitProviders(config); } } catch (Exception e) { s_InitException = e; } s_Initialized = true; } } } }
private static void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams) { bool fDebug = false; if (Util.GetAndRemoveBooleanAttribute(directive, "debug", ref fDebug)) { compilParams.IncludeDebugInformation = fDebug; } if (compilParams.IncludeDebugInformation && !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "debug")); } int warningLevel = 0; if (Util.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref warningLevel)) { compilParams.WarningLevel = warningLevel; if (warningLevel > 0) { compilParams.TreatWarningsAsErrors = true; } } string compilerOptions = Util.GetAndRemoveNonEmptyAttribute( directive, "compileroptions"); if (compilerOptions != null) { CompilationUtil.CheckCompilerOptionsAllowed(compilerOptions, false /*config*/, null, 0); compilParams.CompilerOptions = compilerOptions; } }
internal Object Create() { // HACKHACK: for now, let uncreatable types through and error later (for .soap factory) // This design should change - developers will want to know immediately // when they misspell a type if (_type == null) { Type t = Type.GetType(_typename, true); // throw for bad types in deferred case if (!IsTypeHandlerOrFactory(t)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_not_factory_or_handler, _typename)); } if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted)) { if (!IsTypeFromAssemblyWithAPTCA(t) && IsTypeFromAssemblyWithStrongName(t)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_from_untrusted_assembly, _typename)); } } _type = t; } return(HttpRuntime.CreateNonPublicInstance(_type)); }
private void Initialize(string persistedState) { _persistedState = persistedState; HttpContext context = HttpContext.Current; HttpRequest request = context != null ? context.Request : null; HttpResponse response = context != null ? context.Response : null; // Return the generic viewstate error if the request does not have permission to ServerVariables if (request == null || response == null || !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low)) { _message = ShortMessage; return; } _isConnected = response.IsClientConnected; _remoteAddr = request.ServerVariables["REMOTE_ADDR"]; _remotePort = request.ServerVariables["REMOTE_PORT"]; _userAgent = request.ServerVariables["HTTP_USER_AGENT"]; _referer = request.ServerVariables["HTTP_REFERER"]; _path = request.ServerVariables["PATH_INFO"]; string debugInfo = String.Format(CultureInfo.InvariantCulture, _format, _remoteAddr, _remotePort, _referer, _path, _userAgent, _persistedState); _message = SR.GetString(SR.ViewState_InvalidViewStatePlus, debugInfo); }
private static void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams) { bool val = false; if (Util.GetAndRemoveBooleanAttribute(directive, "debug", ref val)) { compilParams.IncludeDebugInformation = val; } if (compilParams.IncludeDebugInformation && !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(System.Web.SR.GetString("Insufficient_trust_for_attribute", new object[] { "debug" })); } int num = 0; if (Util.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref num)) { compilParams.WarningLevel = num; if (num > 0) { compilParams.TreatWarningsAsErrors = true; } } string andRemoveNonEmptyAttribute = Util.GetAndRemoveNonEmptyAttribute(directive, "compileroptions"); if (andRemoveNonEmptyAttribute != null) { CompilationUtil.CheckCompilerOptionsAllowed(andRemoveNonEmptyAttribute, false, null, 0); compilParams.CompilerOptions = andRemoveNonEmptyAttribute; } }
public override bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) { if (HostingEnvironment.IsHosted) { return(HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted)); } return(base.Host.IsFullTrustSectionWithoutAptcaAllowed(configRecord)); }
private static bool CheckTrustLevel(SessionStateSection config) { switch (config.Mode) { case SessionStateMode.StateServer: case SessionStateMode.SQLServer: return(HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)); } return(true); }
private void ParseTransactionAttribute(string name, string value) { object obj2 = System.Web.UI.Util.GetEnumAttribute(name, value, typeof(TransactionOption)); if (obj2 != null) { this._transactionMode = (int)obj2; if (this._transactionMode != 0) { if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(System.Web.SR.GetString("Insufficient_trust_for_attribute", new object[] { "transaction" })); } base.AddAssemblyDependency(typeof(TransactionOption).Assembly); } } }
// This must be in its own method to avoid jitting System.EnterpriseServices.dll // when it is not needed (ASURT 71868) private void ParseTransactionAttribute(string name, string value) { object tmpObj = Util.GetEnumAttribute(name, value, typeof(TransactionOption)); if (tmpObj != null) { _transactionMode = (int)tmpObj; // Add a reference to the transaction assembly only if needed if (_transactionMode != 0 /*TransactionOption.Disabled*/) { if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "transaction")); } AddAssemblyDependency(typeof(TransactionOption).Assembly); } } }
// This must be in its own method to avoid jitting System.EnterpriseServices.dll // when it is not needed (ASURT 71868) private void ParseTransactionAttribute(IDictionary directive) { object tmpObj = Util.GetAndRemoveEnumAttribute( directive, typeof(TransactionOption), "transaction"); if (tmpObj != null) { _transactionMode = (int)tmpObj; // Add a reference to the transaction assembly only if needed if (_transactionMode != 0 /*TransactionOption.Disabled*/) { if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Insufficient_trust_for_attribute, "transaction")); } AddAssemblyDependency(typeof(TransactionOption).Assembly); } } }
private static void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams) { bool fDebug = false; if (Util.GetAndRemoveBooleanAttribute(directive, "debug", ref fDebug)) { compilParams.IncludeDebugInformation = fDebug; } if (compilParams.IncludeDebugInformation && !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Insufficient_trust_for_attribute, "debug")); } int warningLevel = 0; if (Util.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref warningLevel)) { compilParams.WarningLevel = warningLevel; if (warningLevel > 0) { compilParams.TreatWarningsAsErrors = true; } } string compilerOptions = Util.GetAndRemoveNonEmptyAttribute( directive, "compileroptions"); if (compilerOptions != null) { // Only allow the use of compilerOptions when we have UnmanagedCode access (ASURT 73678) if (!HttpRuntime.HasUnmanagedPermission()) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Insufficient_trust_for_attribute, "CompilerOptions")); } compilParams.CompilerOptions = compilerOptions; } }
private void Initialize(string persistedState) { this._persistedState = persistedState; HttpContext current = HttpContext.Current; HttpRequest request = (current != null) ? current.Request : null; HttpResponse response = (current != null) ? current.Response : null; if (((request == null) || (response == null)) || !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low)) { this._message = this.ShortMessage; } else { this._isConnected = response.IsClientConnected; this._remoteAddr = request.ServerVariables["REMOTE_ADDR"]; this._remotePort = request.ServerVariables["REMOTE_PORT"]; this._userAgent = request.ServerVariables["HTTP_USER_AGENT"]; this._referer = request.ServerVariables["HTTP_REFERER"]; this._path = request.ServerVariables["PATH_INFO"]; string str = string.Format(CultureInfo.InvariantCulture, "\r\n\tClient IP: {0}\r\n\tPort: {1}\r\n\tReferer: {2}\r\n\tPath: {3}\r\n\tUser-Agent: {4}\r\n\tViewState: {5}", new object[] { this._remoteAddr, this._remotePort, this._referer, this._path, this._userAgent, this._persistedState }); this._message = System.Web.SR.GetString("ViewState_InvalidViewStatePlus", new object[] { str }); } }
internal HandlerMapping(String requestType, String path, String typeName, bool defer) { // Remove all spaces from verbs before wildcard parsing. // - We don't want get in "POST, GET" to be parsed into " GET". requestType = requestType.Replace(" ", ""); // replace all " " with "" in requestType _requestType = new Wildcard(requestType, false); // case-sensitive wildcard _path = new WildcardUrl(path, true); // case-insensitive URL wildcard // if validate="false" is marked on a handler, then the type isn't created until a request // is actually made that requires the handler. This (1) allows us to list handlers that // aren't present without throwing errors at init time and (2) speeds up init by avoiding // loading types until they are needed. if (defer) { _type = null; _typename = typeName; } else { _type = Type.GetType(typeName, true); if (!IsTypeHandlerOrFactory(_type)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_not_factory_or_handler, typeName)); } if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted)) { if (IsTypeFromAssemblyWithStrongName(_type) && !IsTypeFromAssemblyWithAPTCA(_type)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_from_untrusted_assembly, typeName)); } } } }
////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// static private void InitializeStatic() { if (!ProfileManager.Enabled || s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } return; } lock (s_InitializeLock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } return; } try { ProfileSection config = MTConfigUtil.GetProfileAppConfig(); bool fAnonEnabled = (HostingEnvironment.IsHosted ? AnonymousIdentificationModule.Enabled : true); Type baseType = ProfileBase.InheritsFromType; bool hasLowTrust = HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low); s_Properties = new SettingsPropertyCollection(); // Step 0: Add all dynamic profile properties set programatically during PreAppStart ProfileBase.AddPropertySettingsFromConfig(baseType, fAnonEnabled, hasLowTrust, ProfileManager.DynamicProfileProperties, null); ////////////////////////////////////////////////////////////////////// // Step 1: Add Properties from the base class (if not ProfileBase) if (baseType != typeof(ProfileBase)) { ////////////////////////////////////////////////////////////////////// // Step 2: Construct a hashtable containing a list of all the property-names in the ProfileBase type PropertyInfo[] baseProps = typeof(ProfileBase).GetProperties(); NameValueCollection baseProperties = new NameValueCollection(baseProps.Length); foreach (PropertyInfo baseProp in baseProps) { baseProperties.Add(baseProp.Name, String.Empty); } ////////////////////////////////////////////////////////////////////// // Step 3: For each property in the derived class, add it to the s_Properties class. PropertyInfo[] props = baseType.GetProperties(); foreach (PropertyInfo prop in props) { if (baseProperties[prop.Name] == null) //not in the base class { ProfileProvider prov = hasLowTrust ? ProfileManager.Provider : null; bool readOnly = false; SettingsSerializeAs serializeAs = SettingsSerializeAs.ProviderSpecific; string defaultValue = String.Empty; bool allowAnonymous = false; string customData = null; ////////////////////////////////////////////////////////////////////// // Step 4: For the property, get the attributes Attribute[] attribs = Attribute.GetCustomAttributes(prop, true); foreach (Attribute attrib in attribs) { if (attrib is SettingsSerializeAsAttribute) { serializeAs = ((SettingsSerializeAsAttribute)attrib).SerializeAs; } else if (attrib is SettingsAllowAnonymousAttribute) { allowAnonymous = ((SettingsAllowAnonymousAttribute)attrib).Allow; if (!fAnonEnabled && allowAnonymous) { throw new ConfigurationErrorsException(SR.GetString(SR.Annoymous_id_module_not_enabled, prop.Name), config.ElementInformation.Properties["inherits"].Source, config.ElementInformation.Properties["inherits"].LineNumber); } } else if (attrib is System.ComponentModel.ReadOnlyAttribute) { readOnly = ((System.ComponentModel.ReadOnlyAttribute)attrib).IsReadOnly; } else if (attrib is DefaultSettingValueAttribute) { defaultValue = ((DefaultSettingValueAttribute)attrib).Value; } else if (attrib is CustomProviderDataAttribute) { customData = ((CustomProviderDataAttribute)attrib).CustomProviderData; } else if (hasLowTrust && attrib is ProfileProviderAttribute) { prov = ProfileManager.Providers[((ProfileProviderAttribute)attrib).ProviderName]; if (prov == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Profile_provider_not_found, ((ProfileProviderAttribute)attrib).ProviderName), config.ElementInformation.Properties["inherits"].Source, config.ElementInformation.Properties["inherits"].LineNumber); } } } ////////////////////////////////////////////////////////////////////// // Step 5: Add the property to the s_Properties SettingsAttributeDictionary settings = new SettingsAttributeDictionary(); settings.Add("AllowAnonymous", allowAnonymous); if (!string.IsNullOrEmpty(customData)) { settings.Add("CustomProviderData", customData); } SettingsProperty sp = new SettingsProperty(prop.Name, prop.PropertyType, prov, readOnly, defaultValue, serializeAs, settings, false, true); s_Properties.Add(sp); } } } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Step 6: Add all properties from config if (config.PropertySettings != null) { AddPropertySettingsFromConfig(baseType, fAnonEnabled, hasLowTrust, config.PropertySettings, null); foreach (ProfileGroupSettings pgs in config.PropertySettings.GroupSettings) { AddPropertySettingsFromConfig(baseType, fAnonEnabled, hasLowTrust, pgs.PropertySettings, pgs.Name); } } } catch (Exception e) { if (s_InitializeException == null) { s_InitializeException = e; } } // If there are no properties, create an empty collection. if (s_Properties == null) { s_Properties = new SettingsPropertyCollection(); } // Make the properties collection read-only s_Properties.SetReadOnly(); s_Initialized = true; } // Throw an exception if there was an exception during initialization if (s_InitializeException != null) { throw s_InitializeException; } }
private static void EnsureSqlExpressDBFile(string connectionString) { string str = null; string path = null; string dataDirectory = GetDataDirectory(); bool flag = true; bool flag2 = true; string[] strArray = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); bool flag3 = true; bool flag4 = true; foreach (string str4 in strArray) { string str5 = str4.ToUpper(CultureInfo.InvariantCulture).Trim(); if (flag && str5.Contains("|DATADIRECTORY|")) { flag = false; connectionString = connectionString.Replace(str4, "Pooling=false"); int startIndex = str5.IndexOf("|DATADIRECTORY|", StringComparison.Ordinal) + "|DATADIRECTORY|".Length; str = str5.Substring(startIndex).Trim(); while (str.StartsWith(@"\", StringComparison.Ordinal)) { str = str.Substring(1); } if (str.Contains("..")) { str = null; } else { path = Path.Combine(dataDirectory, str); } if (flag2) { continue; } break; } if (flag2 && (str5.StartsWith("INITIAL CATALOG", StringComparison.Ordinal) || str5.StartsWith("DATABASE", StringComparison.Ordinal))) { flag2 = false; connectionString = connectionString.Replace(str4, "Database=master"); if (flag) { continue; } break; } if (flag3 && str5.StartsWith("USER INSTANCE", StringComparison.Ordinal)) { flag3 = false; int index = str5.IndexOf('='); if ((index >= 0) && !(str5.Substring(index + 1).Trim() != "TRUE")) { continue; } return; } if (flag4 && str5.StartsWith("CONNECT TIMEOUT", StringComparison.Ordinal)) { flag4 = false; } } if (!flag3) { if (path == null) { throw new ProviderException(System.Web.SR.GetString("SqlExpress_file_not_found_in_connection_string")); } if (!File.Exists(path)) { if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.High)) { throw new ProviderException(System.Web.SR.GetString("Provider_can_not_create_file_in_this_trust_level")); } if (!connectionString.Contains("Database=master")) { connectionString = connectionString + ";Database=master"; } if (flag4) { connectionString = connectionString + ";Connect Timeout=45"; } using (new ApplicationImpersonationContext()) { lock (s_lock) { if (!File.Exists(path)) { CreateMdfFile(path, dataDirectory, connectionString); } } } } } }
private static void InitializeStatic() { if (!ProfileManager.Enabled || s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } } else { lock (s_InitializeLock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } return; } try { ProfileSection profileAppConfig = MTConfigUtil.GetProfileAppConfig(); bool fAnonEnabled = HostingEnvironment.IsHosted ? AnonymousIdentificationModule.Enabled : true; Type inheritsFromType = InheritsFromType; bool hasLowTrust = HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low); s_Properties = new SettingsPropertyCollection(); AddPropertySettingsFromConfig(inheritsFromType, fAnonEnabled, hasLowTrust, ProfileManager.DynamicProfileProperties, null); if (inheritsFromType != typeof(ProfileBase)) { PropertyInfo[] properties = typeof(ProfileBase).GetProperties(); NameValueCollection values = new NameValueCollection(properties.Length); foreach (PropertyInfo info in properties) { values.Add(info.Name, string.Empty); } foreach (PropertyInfo info2 in inheritsFromType.GetProperties()) { if (values[info2.Name] == null) { ProfileProvider provider = hasLowTrust ? ProfileManager.Provider : null; bool isReadOnly = false; SettingsSerializeAs providerSpecific = SettingsSerializeAs.ProviderSpecific; string defaultValue = string.Empty; bool allow = false; string customProviderData = null; foreach (Attribute attribute in Attribute.GetCustomAttributes(info2, true)) { if (attribute is SettingsSerializeAsAttribute) { providerSpecific = ((SettingsSerializeAsAttribute)attribute).SerializeAs; } else if (attribute is SettingsAllowAnonymousAttribute) { allow = ((SettingsAllowAnonymousAttribute)attribute).Allow; if (!fAnonEnabled && allow) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Annoymous_id_module_not_enabled", new object[] { info2.Name }), profileAppConfig.ElementInformation.Properties["inherits"].Source, profileAppConfig.ElementInformation.Properties["inherits"].LineNumber); } } else if (attribute is ReadOnlyAttribute) { isReadOnly = ((ReadOnlyAttribute)attribute).IsReadOnly; } else if (attribute is DefaultSettingValueAttribute) { defaultValue = ((DefaultSettingValueAttribute)attribute).Value; } else if (attribute is CustomProviderDataAttribute) { customProviderData = ((CustomProviderDataAttribute)attribute).CustomProviderData; } else if (hasLowTrust && (attribute is ProfileProviderAttribute)) { provider = ProfileManager.Providers[((ProfileProviderAttribute)attribute).ProviderName]; if (provider == null) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Profile_provider_not_found", new object[] { ((ProfileProviderAttribute)attribute).ProviderName }), profileAppConfig.ElementInformation.Properties["inherits"].Source, profileAppConfig.ElementInformation.Properties["inherits"].LineNumber); } } } SettingsAttributeDictionary attributes = new SettingsAttributeDictionary(); attributes.Add("AllowAnonymous", allow); if (!string.IsNullOrEmpty(customProviderData)) { attributes.Add("CustomProviderData", customProviderData); } SettingsProperty property = new SettingsProperty(info2.Name, info2.PropertyType, provider, isReadOnly, defaultValue, providerSpecific, attributes, false, true); s_Properties.Add(property); } } } if (profileAppConfig.PropertySettings != null) { AddPropertySettingsFromConfig(inheritsFromType, fAnonEnabled, hasLowTrust, profileAppConfig.PropertySettings, null); foreach (ProfileGroupSettings settings in profileAppConfig.PropertySettings.GroupSettings) { AddPropertySettingsFromConfig(inheritsFromType, fAnonEnabled, hasLowTrust, settings.PropertySettings, settings.Name); } } } catch (Exception exception) { if (s_InitializeException == null) { s_InitializeException = exception; } } if (s_Properties == null) { s_Properties = new SettingsPropertyCollection(); } s_Properties.SetReadOnly(); s_Initialized = true; } if (s_InitializeException != null) { throw s_InitializeException; } } }
internal override bool ProcessMainDirectiveAttribute(string deviceName, string name, string value, IDictionary parseData) { switch (name) { case "errorpage": _errorPage = Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return(false); case "contenttype": // Check validity Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return(false); case "theme": if (IsExpressionBuilderValue(value)) { return(false); } // Check validity Util.CheckThemeAttribute(value); // Return false to let the generic attribute processing continue return(false); case "stylesheettheme": // Make sure no device filter or expression builder was specified ValidateBuiltInAttribute(deviceName, name, value); // Check validity Util.CheckThemeAttribute(value); _styleSheetTheme = value; return(true); case "enablesessionstate": flags[requiresSessionState] = true; flags[readOnlySessionState] = false; if (Util.IsFalseString(value)) { flags[requiresSessionState] = false; } else if (StringUtil.EqualsIgnoreCase(value, "readonly")) { flags[readOnlySessionState] = true; } else if (!Util.IsTrueString(value)) { ProcessError(SR.GetString(SR.Enablesessionstate_must_be_true_false_or_readonly)); } if (flags[requiresSessionState]) { // Session state is only available for compiled pages OnFoundAttributeRequiringCompilation(name); } break; case "culture": _culture = Util.GetNonEmptyAttribute(name, value); // Setting culture requires medium permission if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "culture")); } //do not verify at parse time if potentially using browser AutoDetect if (StringUtil.EqualsIgnoreCase(value, HttpApplication.AutoCulture)) { return(false); } // Create a CultureInfo just to verify validity CultureInfo cultureInfo; try { if (StringUtil.StringStartsWithIgnoreCase(value, HttpApplication.AutoCulture)) { //safe to trim leading "auto:", string used elsewhere for null check _culture = _culture.Substring(5); } cultureInfo = HttpServerUtility.CreateReadOnlyCultureInfo(_culture); } catch { ProcessError(SR.GetString(SR.Invalid_attribute_value, _culture, "culture")); return(false); } // Don't allow neutral cultures (ASURT 77930) if (cultureInfo.IsNeutralCulture) { ProcessError(SR.GetString(SR.Invalid_culture_attribute, Util.GetSpecificCulturesFormattedList(cultureInfo))); } // Return false to let the generic attribute processing continue return(false); case "lcid": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) { return(false); } _lcid = Util.GetNonNegativeIntegerAttribute(name, value); // Create a CultureInfo just to verify validity try { HttpServerUtility.CreateReadOnlyCultureInfo(_lcid); } catch { ProcessError(SR.GetString(SR.Invalid_attribute_value, _lcid.ToString(CultureInfo.InvariantCulture), "lcid")); } // Return false to let the generic attribute processing continue return(false); case "uiculture": // Check validity Util.GetNonEmptyAttribute(name, value); // Return false to let the generic attribute processing continue return(false); case "responseencoding": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) { return(false); } _responseEncoding = Util.GetNonEmptyAttribute(name, value); // Call Encoding.GetEncoding just to verify validity Encoding.GetEncoding(_responseEncoding); // Return false to let the generic attribute processing continue return(false); case "codepage": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) { return(false); } _codePage = Util.GetNonNegativeIntegerAttribute(name, value); // Call Encoding.GetEncoding just to verify validity Encoding.GetEncoding(_codePage); // Return false to let the generic attribute processing continue return(false); case "transaction": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); ParseTransactionAttribute(name, value); break; case "aspcompat": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); flags[aspCompatMode] = Util.GetBooleanAttribute(name, value); // Only allow the use of aspcompat when we have UnmanagedCode access (ASURT 76694) if (flags[aspCompatMode] && !HttpRuntime.HasUnmanagedPermission()) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "AspCompat")); } break; case "async": // This only makes sense for compiled pages OnFoundAttributeRequiringCompilation(name); flags[asyncMode] = Util.GetBooleanAttribute(name, value); // Async requires Medium trust if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "async")); } break; case "tracemode": // We use TraceModeInternal instead of TraceMode to disallow the 'default' value (ASURT 75783) object tmpObj = Util.GetEnumAttribute(name, value, typeof(TraceModeInternal)); _traceMode = (TraceMode)tmpObj; break; case "trace": bool traceEnabled = Util.GetBooleanAttribute(name, value); if (traceEnabled) { _traceEnabled = TraceEnable.Enable; } else { _traceEnabled = TraceEnable.Disable; } break; case "smartnavigation": // Make sure no device filter or expression builder was specified, since it doesn't make much // sense for smartnav (which only works on IE5.5+) (VSWhidbey 85876) ValidateBuiltInAttribute(deviceName, name, value); // Ignore it if it has default value. Otherwise, let the generic // attribute processing continue bool smartNavigation = Util.GetBooleanAttribute(name, value); return(smartNavigation == Page.SmartNavigationDefault); case "maintainscrollpositiononpostback": bool maintainScrollPosition = Util.GetBooleanAttribute(name, value); return(maintainScrollPosition == Page.MaintainScrollPositionOnPostBackDefault); case "validaterequest": flags[validateRequest] = Util.GetBooleanAttribute(name, value); break; case "clienttarget": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) { return(false); } // Check validity HttpCapabilitiesDefaultProvider.GetUserAgentFromClientTarget(CurrentVirtualPath, value); // Return false to let the generic attribute processing continue return(false); case "masterpagefile": // Skip validity check for expression builder (e.g. <%$ ... %>) if (IsExpressionBuilderValue(value)) { return(false); } if (value.Length > 0) { // Add dependency on the Type by calling this method Type type = GetReferencedType(value); // Make sure it has the correct base type if (!typeof(MasterPage).IsAssignableFrom(type)) { ProcessError(SR.GetString(SR.Invalid_master_base, value)); } if (deviceName.Length > 0) { // Make sure the masterPageFile definition from config // is applied before filtered masterPageFile attributes. EnsureMasterPageFileFromConfigApplied(); } } //VSWhidbey 479064 Remember the masterPageFile had been set even if it's empty string _mainDirectiveMasterPageSet = true; // Return false to let the generic attribute processing continue return(false); default: // We didn't handle the attribute. Try the base class return(base.ProcessMainDirectiveAttribute(deviceName, name, value, parseData)); } // The attribute was handled // Make sure no device filter or resource expression was specified ValidateBuiltInAttribute(deviceName, name, value); return(true); }
internal override bool ProcessMainDirectiveAttribute(string deviceName, string name, string value, IDictionary parseData) { switch (name) { case "errorpage": this._errorPage = System.Web.UI.Util.GetNonEmptyAttribute(name, value); return(false); case "contenttype": System.Web.UI.Util.GetNonEmptyAttribute(name, value); return(false); case "theme": if (!base.IsExpressionBuilderValue(value)) { System.Web.UI.Util.CheckThemeAttribute(value); return(false); } return(false); case "stylesheettheme": base.ValidateBuiltInAttribute(deviceName, name, value); System.Web.UI.Util.CheckThemeAttribute(value); this._styleSheetTheme = value; return(true); case "enablesessionstate": this.flags[0x100000] = true; this.flags[0x200000] = false; if (!System.Web.UI.Util.IsFalseString(value)) { if (StringUtil.EqualsIgnoreCase(value, "readonly")) { this.flags[0x200000] = true; } else if (!System.Web.UI.Util.IsTrueString(value)) { base.ProcessError(System.Web.SR.GetString("Enablesessionstate_must_be_true_false_or_readonly")); } break; } this.flags[0x100000] = false; break; case "culture": this._culture = System.Web.UI.Util.GetNonEmptyAttribute(name, value); if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(System.Web.SR.GetString("Insufficient_trust_for_attribute", new object[] { "culture" })); } if (!StringUtil.EqualsIgnoreCase(value, HttpApplication.AutoCulture)) { CultureInfo info; try { if (StringUtil.StringStartsWithIgnoreCase(value, HttpApplication.AutoCulture)) { this._culture = this._culture.Substring(5); } info = HttpServerUtility.CreateReadOnlyCultureInfo(this._culture); } catch { base.ProcessError(System.Web.SR.GetString("Invalid_attribute_value", new object[] { this._culture, "culture" })); return(false); } if (info.IsNeutralCulture) { base.ProcessError(System.Web.SR.GetString("Invalid_culture_attribute", new object[] { System.Web.UI.Util.GetSpecificCulturesFormattedList(info) })); } } return(false); case "lcid": if (!base.IsExpressionBuilderValue(value)) { this._lcid = System.Web.UI.Util.GetNonNegativeIntegerAttribute(name, value); try { HttpServerUtility.CreateReadOnlyCultureInfo(this._lcid); } catch { base.ProcessError(System.Web.SR.GetString("Invalid_attribute_value", new object[] { this._lcid.ToString(CultureInfo.InvariantCulture), "lcid" })); } return(false); } return(false); case "uiculture": System.Web.UI.Util.GetNonEmptyAttribute(name, value); return(false); case "responseencoding": if (!base.IsExpressionBuilderValue(value)) { this._responseEncoding = System.Web.UI.Util.GetNonEmptyAttribute(name, value); Encoding.GetEncoding(this._responseEncoding); return(false); } return(false); case "codepage": if (!base.IsExpressionBuilderValue(value)) { this._codePage = System.Web.UI.Util.GetNonNegativeIntegerAttribute(name, value); Encoding.GetEncoding(this._codePage); return(false); } return(false); case "transaction": base.OnFoundAttributeRequiringCompilation(name); this.ParseTransactionAttribute(name, value); goto Label_05CF; case "aspcompat": base.OnFoundAttributeRequiringCompilation(name); this.flags[0x40] = System.Web.UI.Util.GetBooleanAttribute(name, value); if (this.flags[0x40] && !HttpRuntime.HasUnmanagedPermission()) { throw new HttpException(System.Web.SR.GetString("Insufficient_trust_for_attribute", new object[] { "AspCompat" })); } goto Label_05CF; case "async": base.OnFoundAttributeRequiringCompilation(name); this.flags[0x800000] = System.Web.UI.Util.GetBooleanAttribute(name, value); if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(System.Web.SR.GetString("Insufficient_trust_for_attribute", new object[] { "async" })); } goto Label_05CF; case "tracemode": { object obj2 = System.Web.UI.Util.GetEnumAttribute(name, value, typeof(TraceModeInternal)); this._traceMode = (System.Web.TraceMode)obj2; goto Label_05CF; } case "trace": if (!System.Web.UI.Util.GetBooleanAttribute(name, value)) { this._traceEnabled = TraceEnable.Disable; } else { this._traceEnabled = TraceEnable.Enable; } goto Label_05CF; case "smartnavigation": base.ValidateBuiltInAttribute(deviceName, name, value); return(!System.Web.UI.Util.GetBooleanAttribute(name, value)); case "maintainscrollpositiononpostback": return(!System.Web.UI.Util.GetBooleanAttribute(name, value)); case "validaterequest": this.flags[0x400000] = System.Web.UI.Util.GetBooleanAttribute(name, value); goto Label_05CF; case "clienttarget": if (!base.IsExpressionBuilderValue(value)) { HttpCapabilitiesDefaultProvider.GetUserAgentFromClientTarget(base.CurrentVirtualPath, value); return(false); } return(false); case "masterpagefile": if (!base.IsExpressionBuilderValue(value)) { if (value.Length > 0) { Type referencedType = base.GetReferencedType(value); if (!typeof(MasterPage).IsAssignableFrom(referencedType)) { base.ProcessError(System.Web.SR.GetString("Invalid_master_base", new object[] { value })); } if (deviceName.Length > 0) { this.EnsureMasterPageFileFromConfigApplied(); } } this._mainDirectiveMasterPageSet = true; return(false); } return(false); default: return(base.ProcessMainDirectiveAttribute(deviceName, name, value, parseData)); } if (this.flags[0x100000]) { base.OnFoundAttributeRequiringCompilation(name); } Label_05CF: base.ValidateBuiltInAttribute(deviceName, name, value); return(true); }
private static void EnsureDBFile(string connectionString) { string partialFileName = null; string fullFileName = null; string dataDir = GetDataDirectory(); bool lookingForDataDir = true; bool lookingForDB = true; string[] splitedConnStr = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); bool lookingForUserInstance = !connectionString.ToUpperInvariant().Contains(s_localDbName); // We don't require UserInstance=True for LocalDb bool lookingForTimeout = true; foreach (string str in splitedConnStr) { string strUpper = str.ToUpper(CultureInfo.InvariantCulture).Trim(); if (lookingForDataDir && strUpper.Contains(s_strUpperDataDirWithToken)) { lookingForDataDir = false; // Replace the AttachDBFilename part with "Pooling=false" connectionString = connectionString.Replace(str, "Pooling=false"); // Extract the filenames int startPos = strUpper.IndexOf(s_strUpperDataDirWithToken, StringComparison.Ordinal) + s_strUpperDataDirWithToken.Length; partialFileName = strUpper.Substring(startPos).Trim(); while (partialFileName.StartsWith("\\", StringComparison.Ordinal)) { partialFileName = partialFileName.Substring(1); } if (partialFileName.Contains("..")) // don't allow it to traverse-up { partialFileName = null; } else { fullFileName = Path.Combine(dataDir, partialFileName); } if (!lookingForDB) { break; // done } } else if (lookingForDB && (strUpper.StartsWith("INITIAL CATALOG", StringComparison.Ordinal) || strUpper.StartsWith("DATABASE", StringComparison.Ordinal))) { lookingForDB = false; connectionString = connectionString.Replace(str, "Database=master"); if (!lookingForDataDir) { break; // done } } else if (lookingForUserInstance && strUpper.StartsWith(s_strUpperUserInstance, StringComparison.Ordinal)) { lookingForUserInstance = false; int pos = strUpper.IndexOf('='); if (pos < 0) { return; } string strTemp = strUpper.Substring(pos + 1).Trim(); if (strTemp != "TRUE") { return; } } else if (lookingForTimeout && strUpper.StartsWith("CONNECT TIMEOUT", StringComparison.Ordinal)) { lookingForTimeout = false; } } if (lookingForUserInstance) { return; } if (fullFileName == null) { throw new ProviderException(SR.GetString(SR.SqlExpress_file_not_found_in_connection_string)); } if (File.Exists(fullFileName)) { return; } if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.High)) { throw new ProviderException(SR.GetString(SR.Provider_can_not_create_file_in_this_trust_level)); } if (!connectionString.Contains("Database=master")) { connectionString += ";Database=master"; } if (lookingForTimeout) { connectionString += ";Connect Timeout=45"; } using (new ApplicationImpersonationContext()) lock (s_lock) if (!File.Exists(fullFileName)) { CreateMdfFile(fullFileName, dataDir, connectionString); } }