/* * Return a reader which holds the contents of a file. If a context is passed * in, try to get a config encoding from it (use the configPath if provided) */ internal /*public*/ static TextReader ReaderFromFile(string filename, HttpContext context, string configPath) { TextReader reader; // Check if a file encoding is specified in the config Encoding fileEncoding = null; if (context != null) { GlobalizationConfig globConfig; if (configPath == null) { globConfig = (GlobalizationConfig)context.GetConfig("system.web/globalization"); } else { globConfig = (GlobalizationConfig)context.GetConfig("system.web/globalization", configPath); } if (globConfig != null) { fileEncoding = globConfig.FileEncoding; } } // If not, use the default encoding if (fileEncoding == null) { fileEncoding = Encoding.Default; } try { // Create a reader on the file, using the encoding // Throws an exception if the file can't be opened. reader = new StreamReader(filename, fileEncoding, true /*detectEncodingFromByteOrderMarks*/, 4096); } catch (UnauthorizedAccessException) { // AccessException might mean two very different things: it could be a real // access problem, or it could be that it's actually a directory. // It's a directory: give a specific error. if (FileUtil.DirectoryExists(filename)) { throw new HttpException( HttpRuntime.FormatResourceString(SR.Unexpected_Directory, HttpRuntime.GetSafePath(filename))); } // It's a real access problem, so just rethrow it throw; } return(reader); }
private string GetPhysicalDataFilePath() { string dataFile = this.DataFile; if (dataFile.Length == 0) { return(null); } if (!UrlPath.IsAbsolutePhysicalPath(dataFile)) { if (base.DesignMode) { throw new NotSupportedException(System.Web.SR.GetString("AccessDataSource_DesignTimeRelativePathsNotSupported", new object[] { this.ID })); } dataFile = this.Context.Request.MapPath(dataFile, base.AppRelativeTemplateSourceDirectory, true); } HttpRuntime.CheckFilePermission(dataFile, true); if (!HttpRuntime.HasPathDiscoveryPermission(dataFile)) { throw new HttpException(System.Web.SR.GetString("AccessDataSource_NoPathDiscoveryPermission", new object[] { HttpRuntime.GetSafePath(dataFile), this.ID })); } return(dataFile); }
protected void EnsureDiskCacheDirectoryCreated() { // Create the disk cache directory if it's not already there if (!FileUtil.DirectoryExists(_cacheDir)) { try { Directory.CreateDirectory(_cacheDir); } catch (IOException e) { throw new HttpException(SR.GetString(SR.Failed_to_create_temp_dir, HttpRuntime.GetSafePath(_cacheDir)), e); } } }
protected void EnsureDiskCacheDirectoryCreated() { if (!FileUtil.DirectoryExists(this._cacheDir)) { try { Directory.CreateDirectory(this._cacheDir); } catch (IOException exception) { throw new HttpException(System.Web.SR.GetString("Failed_to_create_temp_dir", new object[] { HttpRuntime.GetSafePath(this._cacheDir) }), exception); } } }
private void InitApp() { try { using (new ApplicationImpersonationContext()) { if (this._InitAppDone) { if (DateTime.Now > this._LastUpdateCacheDate.AddMinutes((double)this.CacheRefreshInterval)) { this._LastUpdateCacheDate = DateTime.Now; this.CallMethod(this._ObjAzAuthorizationStoreClass, "UpdateCache", null); } } else { lock (this) { if (!this._InitAppDone) { if (this._ConnectionString.ToLower(CultureInfo.InvariantCulture).StartsWith("msxml://", StringComparison.Ordinal)) { if (this._ConnectionString.Contains("/~/")) { string newValue = null; if (HostingEnvironment.IsHosted) { newValue = HttpRuntime.AppDomainAppPath; } else { Process currentProcess = Process.GetCurrentProcess(); ProcessModule module = (currentProcess != null) ? currentProcess.MainModule : null; string str2 = (module != null) ? module.FileName : null; if (str2 != null) { newValue = Path.GetDirectoryName(str2); } if ((newValue == null) || (newValue.Length < 1)) { newValue = Environment.CurrentDirectory; } } newValue = newValue.Replace('\\', '/'); this._ConnectionString = this._ConnectionString.Replace("~", newValue); } string path = this._ConnectionString.Substring("msxml://".Length).Replace('/', '\\'); if (HostingEnvironment.IsHosted) { HttpRuntime.CheckFilePermission(path, false); } if (!System.Web.Util.FileUtil.FileExists(path)) { throw new FileNotFoundException(System.Web.SR.GetString("AuthStore_policy_file_not_found", new object[] { HttpRuntime.GetSafePath(path) })); } this._XmlFileName = path; } Type type = null; try { this._NewAuthInterface = true; type = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false); if (type == null) { type = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false); } if (type == null) { this._NewAuthInterface = false; type = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", true); } } catch (FileNotFoundException exception) { HttpContext current = HttpContext.Current; if (current == null) { throw new ProviderException(System.Web.SR.GetString("AuthStoreNotInstalled_Title"), exception); } current.Response.Clear(); current.Response.StatusCode = 500; current.Response.Write(AuthStoreErrorFormatter.GetErrorText()); current.Response.End(); } if (HostingEnvironment.IsHosted && (this._XmlFileName != null)) { InternalSecurityPermissions.Unrestricted.Assert(); } this._ObjAzAuthorizationStoreClass = Activator.CreateInstance(type); object[] objArray3 = new object[3]; objArray3[0] = 0; objArray3[1] = this._ConnectionString; object[] args = objArray3; this.CallMethod(this._ObjAzAuthorizationStoreClass, "Initialize", args); args = new object[] { this._AppName, null }; if (this._NewAuthInterface) { this._ObjAzApplication = this.CallMethod(this._ObjAzAuthorizationStoreClass, "OpenApplication2", args); } else { this._ObjAzApplication = this.CallMethod(this._ObjAzAuthorizationStoreClass, "OpenApplication", args); } if (this._ObjAzApplication == null) { throw new ProviderException(System.Web.SR.GetString("AuthStore_Application_not_found")); } this._ObjAzScope = null; if (!string.IsNullOrEmpty(this._ScopeName)) { args[0] = this._ScopeName; args[1] = null; this._ObjAzScope = this.CallMethod(this._ObjAzApplication, "OpenScope", args); if (this._ObjAzScope == null) { throw new ProviderException(System.Web.SR.GetString("AuthStore_Scope_not_found")); } } this._LastUpdateCacheDate = DateTime.Now; this._InitAppDone = true; } } } } } catch { throw; } }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // BuildProvider implementation public override void GenerateCode(AssemblyBuilder assemblyBuilder) { Hashtable properties = ProfileBase.GetPropertiesForCompilation(); CodeCompileUnit compileUnit = new CodeCompileUnit(); Hashtable groups = new Hashtable(); Type baseType = Type.GetType(ProfileBase.InheritsFromTypeString, false); // namespace ASP { // CodeNamespace ns = new CodeNamespace(); // ns.Name = BaseCodeDomTreeGenerator.defaultNamespace; //GEN: using System; ns.Imports.Add(new CodeNamespaceImport("System")); //GEN: using System.Web; ns.Imports.Add(new CodeNamespaceImport("System.Web")); //GEN: using System.Web.Profile; ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile")); // class Profile : System.Web.Security.ProfileBase { // CodeTypeDeclaration type = new CodeTypeDeclaration(); type.Name = ProfileTypeName; if (baseType != null) { type.BaseTypes.Add(new CodeTypeReference(baseType)); assemblyBuilder.AddAssemblyReference(baseType.Assembly, compileUnit); } else { type.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString)); ProfileSection config = MTConfigUtil.GetProfileAppConfig(); if (config != null) { PropertyInformation prop = config.ElementInformation.Properties["inherits"]; if (prop != null && prop.Source != null && prop.LineNumber > 0) { type.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(prop.Source), prop.LineNumber); } } } // tell the assemblyBuilder to generate a fast factory for this type assemblyBuilder.GenerateTypeFactory(/*ns.Name + "." + */ ProfileTypeName); foreach (DictionaryEntry de in properties) { ProfileNameTypeStruct property = (ProfileNameTypeStruct)de.Value; if (property.PropertyType != null) { assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, compileUnit); } int pos = property.Name.IndexOf('.'); if (pos < 0) { // public string Color { get { return (string) GetProperty("Color"); } set { SetProperty("Color", value); } } CreateCodeForProperty(assemblyBuilder, type, property); } else { string grpName = property.Name.Substring(0, pos); if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(grpName)) { throw new ConfigurationErrorsException(SR.GetString(SR.Profile_bad_group, grpName), property.FileName, property.LineNumber); } if (groups[grpName] == null) { groups.Add(grpName, property.Name); } else { groups[grpName] = ((string)groups[grpName]) + ";" + property.Name; } } } foreach (DictionaryEntry de in groups) { // public ProfileGroupFooClass Foo { get { return ProfileGroupSomething; }} // // public class ProfileGroupFoo : ProfileGroup { // Properties // } AddPropertyGroup(assemblyBuilder, (string)de.Key, (string)de.Value, properties, type, ns); } // public ASP.Profile GetProfileForUser(string username) { // return (ASP.Profile) this.GetUserProfile(username); // } AddCodeForGetProfileForUser(type); // } // ns.Types.Add(type); compileUnit.Namespaces.Add(ns); assemblyBuilder.AddCodeCompileUnit(this, compileUnit); }
/// <devdoc> /// Gets the appropriate mapped path for the DataFile. /// </devdoc> private string GetPhysicalDataFilePath() { string filename = DataFile; if (filename.Length == 0) { return(null); } if (!System.Web.Util.UrlPath.IsAbsolutePhysicalPath(filename)) { // Root relative path if (DesignMode) { // This exception should never be thrown - the designer always maps paths // before using the runtime control. throw new NotSupportedException(SR.GetString(SR.AccessDataSource_DesignTimeRelativePathsNotSupported, ID)); } filename = Context.Request.MapPath(filename, AppRelativeTemplateSourceDirectory, true); } HttpRuntime.CheckFilePermission(filename, true); // We also need to check for path discovery permissions for the // file since the page developer will be able to see the physical // path in the ConnectionString property. if (!HttpRuntime.HasPathDiscoveryPermission(filename)) { throw new HttpException(SR.GetString(SR.AccessDataSource_NoPathDiscoveryPermission, HttpRuntime.GetSafePath(filename), ID)); } return(filename); }
internal static string GetAssemblySafePathFromType(Type t) { return(HttpRuntime.GetSafePath(GetAssemblyPathFromType(t))); }
internal static StreamReader ReaderFromFile(string filename, VirtualPath configPath) { StreamReader reader; Encoding encodingFromConfigPath = Encoding.Default; if (configPath != null) { encodingFromConfigPath = GetEncodingFromConfigPath(configPath); } try { reader = new StreamReader(filename, encodingFromConfigPath, true, 0x1000); } catch (UnauthorizedAccessException) { if (FileUtil.DirectoryExists(filename)) { throw new HttpException(System.Web.SR.GetString("Unexpected_Directory", new object[] { HttpRuntime.GetSafePath(filename) })); } throw; } return(reader); }
////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// private void InitApp() { try { using (new ApplicationImpersonationContext()) { if (_InitAppDone) { if (DateTime.Now > _LastUpdateCacheDate.AddMinutes(CacheRefreshInterval)) { _LastUpdateCacheDate = DateTime.Now; CallMethod(_ObjAzAuthorizationStoreClass, "UpdateCache", null); } return; } lock (this) { if (_InitAppDone) { return; } if (_ConnectionString.ToLower(CultureInfo.InvariantCulture).StartsWith("msxml://", StringComparison.Ordinal)) { if (_ConnectionString.Contains("/~/")) { string appPath = null; if (HostingEnvironment.IsHosted) { appPath = HttpRuntime.AppDomainAppPath; } else { #if !FEATURE_PAL // FEATURE_PAL does not enable the ProcessModule class Process p = Process.GetCurrentProcess(); ProcessModule pm = (p != null ? p.MainModule : null); string exeName = (pm != null ? pm.FileName : null); if (exeName != null) { appPath = System.IO.Path.GetDirectoryName(exeName); } #endif // !FEATURE_PAL if (appPath == null || appPath.Length < 1) { appPath = Environment.CurrentDirectory; } } appPath = appPath.Replace('\\', '/'); _ConnectionString = _ConnectionString.Replace("~", appPath); } string fileName = _ConnectionString.Substring("msxml://".Length).Replace('/', '\\'); if (HostingEnvironment.IsHosted) { HttpRuntime.CheckFilePermission(fileName, false); } if (!FileUtil.FileExists(fileName)) { throw new FileNotFoundException(SR.GetString(SR.AuthStore_policy_file_not_found, HttpRuntime.GetSafePath(fileName))); } _XmlFileName = fileName; } Type typeAzAuthorizationStoreClass = null; try { _NewAuthInterface = true; typeAzAuthorizationStoreClass = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false /*throwOnError*/); if (typeAzAuthorizationStoreClass == null) { typeAzAuthorizationStoreClass = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false /*throwOnError*/); } if (typeAzAuthorizationStoreClass == null) { _NewAuthInterface = false; typeAzAuthorizationStoreClass = Type.GetType("Microsoft.Interop.Security.AzRoles.AzAuthorizationStoreClass, Microsoft.Interop.Security.AzRoles, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", true /*throwOnError*/); } } catch (FileNotFoundException e) { HttpContext context = HttpContext.Current; if (context == null) { throw new ProviderException(SR.GetString(SR.AuthStoreNotInstalled_Title), e); } context.Response.Clear(); context.Response.StatusCode = 500; context.Response.Write(AuthStoreErrorFormatter.GetErrorText()); context.Response.End(); } if (HostingEnvironment.IsHosted && _XmlFileName != null) { InternalSecurityPermissions.Unrestricted.Assert(); } _ObjAzAuthorizationStoreClass = Activator.CreateInstance(typeAzAuthorizationStoreClass); object[] args = new object[] { 0, _ConnectionString, null }; CallMethod(_ObjAzAuthorizationStoreClass, "Initialize", args); args = new object[2]; args[0] = _AppName; args[1] = null; if (_NewAuthInterface) { _ObjAzApplication = CallMethod(_ObjAzAuthorizationStoreClass, "OpenApplication2", args); } else { _ObjAzApplication = CallMethod(_ObjAzAuthorizationStoreClass, "OpenApplication", args); } if (_ObjAzApplication == null) { throw new ProviderException(SR.GetString(SR.AuthStore_Application_not_found)); } _ObjAzScope = null; if (!string.IsNullOrEmpty(_ScopeName)) { args[0] = _ScopeName; args[1] = null; _ObjAzScope = CallMethod(_ObjAzApplication, "OpenScope", args); if (_ObjAzScope == null) { throw new ProviderException(SR.GetString(SR.AuthStore_Scope_not_found)); } } _LastUpdateCacheDate = DateTime.Now; _InitAppDone = true; } } } catch { throw; } }
/* * Perform initialization work that should only be done once (per app domain). */ private static void DoFirstTimeInit(HttpContext context) { // Find out how many recompilations we allow before restarting the appdomain s_maxRecompilations = CompilationConfiguration.GetRecompilationsBeforeAppRestarts(context); // Create the temp files directory if it's not already there string tempFilePath = HttpRuntime.CodegenDirInternal; if (!FileUtil.DirectoryExists(tempFilePath)) { try { Directory.CreateDirectory(tempFilePath); } catch (IOException e) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Failed_to_create_temp_dir, HttpRuntime.GetSafePath(tempFilePath)), e); } } long specialFilesCombinedHash = ReadPreservedSpecialFilesCombinedHash(); Debug.Trace("PreservedAssemblyEntry", "specialFilesCombinedHash=" + specialFilesCombinedHash); // Delete all the non essential files left over in the codegen dir, unless // specialFilesCombinedHash is 0, in which case we delete *everything* further down if (specialFilesCombinedHash != 0) { RemoveOldTempFiles(); } // Use a DateTimeCombiner object to handle the time stamps of all the 'special' // files that all compilations depend on: // - The config files (excluding the ones from subdirectories) // - global.asax // - System.Web.dll (in case there is a newer version of ASP.NET) DateTimeCombiner specialFilesDateTimeCombiner = new DateTimeCombiner(); // Add a check for the app's physical path, in case it changes (ASURT 12975) specialFilesDateTimeCombiner.AddObject(context.Request.PhysicalApplicationPath); // Process the config files. Note that this only includes the top level ones, // namely the machine one, and the one in the root of the app. The others are // handled as regular dependencies. string appPath = context.Request.ApplicationPath; string[] configFiles = context.GetConfigurationDependencies(appPath); _numTopLevelConfigFiles = configFiles.Length; for (int i = 0; i < _numTopLevelConfigFiles; i++) { specialFilesDateTimeCombiner.AddFile(configFiles[i]); } // Process global.asax string appFileName = HttpApplicationFactory.GetApplicationFile(context); specialFilesDateTimeCombiner.AddFile(appFileName); // Process System.Web.dll string aspBinaryFileName = typeof(HttpRuntime).Module.FullyQualifiedName; specialFilesDateTimeCombiner.AddFile(aspBinaryFileName); // If they don't match, cleanup everything and write the new hash file if (specialFilesDateTimeCombiner.CombinedHash != specialFilesCombinedHash) { Debug.Trace("PreservedAssemblyEntry", "EnsureFirstTimeInit: hash codes don't match. Old=" + specialFilesCombinedHash + " New=" + specialFilesDateTimeCombiner.CombinedHash); RemoveAllCodeGenFiles(); WritePreservedSpecialFilesCombinedHash(specialFilesDateTimeCombiner.CombinedHash); } else { Debug.Trace("PreservedAssemblyEntry", "PreservedAssemblyEntry: the special files are up to date"); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { Hashtable propertiesForCompilation = ProfileBase.GetPropertiesForCompilation(); CodeCompileUnit ccu = new CodeCompileUnit(); Hashtable hashtable2 = new Hashtable(); Type type = Type.GetType(ProfileBase.InheritsFromTypeString, false); CodeNamespace ns = new CodeNamespace(); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Web")); ns.Imports.Add(new CodeNamespaceImport("System.Web.Profile")); CodeTypeDeclaration declaration = new CodeTypeDeclaration { Name = "ProfileCommon" }; if (type != null) { declaration.BaseTypes.Add(new CodeTypeReference(type)); assemblyBuilder.AddAssemblyReference(type.Assembly, ccu); } else { declaration.BaseTypes.Add(new CodeTypeReference(ProfileBase.InheritsFromTypeString)); ProfileSection profileAppConfig = MTConfigUtil.GetProfileAppConfig(); if (profileAppConfig != null) { PropertyInformation information = profileAppConfig.ElementInformation.Properties["inherits"]; if (((information != null) && (information.Source != null)) && (information.LineNumber > 0)) { declaration.LinePragma = new CodeLinePragma(HttpRuntime.GetSafePath(information.Source), information.LineNumber); } } } assemblyBuilder.GenerateTypeFactory("ProfileCommon"); foreach (DictionaryEntry entry in propertiesForCompilation) { ProfileNameTypeStruct property = (ProfileNameTypeStruct)entry.Value; if (property.PropertyType != null) { assemblyBuilder.AddAssemblyReference(property.PropertyType.Assembly, ccu); } int index = property.Name.IndexOf('.'); if (index < 0) { this.CreateCodeForProperty(assemblyBuilder, declaration, property); } else { string str = property.Name.Substring(0, index); if (!assemblyBuilder.CodeDomProvider.IsValidIdentifier(str)) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Profile_bad_group", new object[] { str }), property.FileName, property.LineNumber); } if (hashtable2[str] == null) { hashtable2.Add(str, property.Name); } else { hashtable2[str] = ((string)hashtable2[str]) + ";" + property.Name; } } } foreach (DictionaryEntry entry2 in hashtable2) { this.AddPropertyGroup(assemblyBuilder, (string)entry2.Key, (string)entry2.Value, propertiesForCompilation, declaration, ns); } this.AddCodeForGetProfileForUser(declaration); ns.Types.Add(declaration); ccu.Namespaces.Add(ns); assemblyBuilder.AddCodeCompileUnit(this, ccu); }