internal static SqlCacheDependencyDatabase GetDatabaseConfig(string database)
        {
            object obj2 = RuntimeConfig.GetAppConfig().SqlCacheDependency.Databases[database];

            if (obj2 == null)
            {
                throw new HttpException(System.Web.SR.GetString("Database_not_found", new object[] { database }));
            }
            return((SqlCacheDependencyDatabase)obj2);
        }
Example #2
0
        void OneTimeInit()
        {
            SessionStateSection config = RuntimeConfig.GetAppConfig().SessionState;

            s_appPath = HostingEnvironment.ApplicationVirtualPathObject.VirtualPathString;

            // s_iSessionId is pointing to the starting "("
            s_iSessionId = s_appPath.Length;

            s_config = config;
        }
Example #3
0
        internal static VirtualPath GetScriptLocation()
        {
            string format = (string)RuntimeConfig.GetAppConfig().WebControls["clientScriptsLocation"];

            if (format.IndexOf("{0}", StringComparison.Ordinal) >= 0)
            {
                string str2 = "system_web";
                string str3 = VersionInfo.EngineVersion.Substring(0, VersionInfo.EngineVersion.LastIndexOf('.')).Replace('.', '_');
                format = string.Format(CultureInfo.InvariantCulture, format, new object[] { str2, str3 });
            }
            return(VirtualPath.Create(format));
        }
Example #4
0
        public override void Initialize(string name, NameValueCollection config)
        {
            bool isPublic = _isPublic;

            if (Boolean.TryParse(config["isPublic"], out isPublic))
            {
                _isPublic = isPublic;
            }

            CacheSection cacheSection = RuntimeConfig.GetAppConfig().Cache;

            _cacheInternal.ReadCacheInternalConfig(cacheSection);
        }
Example #5
0
 private static void Initialize()
 {
     if (!s_Initialized || !s_InitializedDefaultProvider)
     {
         if (s_InitializeException != null)
         {
             throw s_InitializeException;
         }
         if (HostingEnvironment.IsHosted)
         {
             HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level");
         }
         lock (s_lock)
         {
             if (!s_Initialized || !s_InitializedDefaultProvider)
             {
                 if (s_InitializeException != null)
                 {
                     throw s_InitializeException;
                 }
                 bool initializeGeneralSettings = !s_Initialized;
                 bool initializeDefaultProvider = !s_InitializedDefaultProvider && (!HostingEnvironment.IsHosted || (BuildManager.PreStartInitStage == PreStartInitStage.AfterPreStartInit));
                 if (initializeDefaultProvider || initializeGeneralSettings)
                 {
                     bool flag3;
                     bool flag4 = false;
                     try
                     {
                         RuntimeConfig     appConfig  = RuntimeConfig.GetAppConfig();
                         MembershipSection membership = appConfig.Membership;
                         flag3 = InitializeSettings(initializeGeneralSettings, appConfig, membership);
                         flag4 = InitializeDefaultProvider(initializeDefaultProvider, membership);
                     }
                     catch (Exception exception)
                     {
                         s_InitializeException = exception;
                         throw;
                     }
                     if (flag3)
                     {
                         s_Initialized = true;
                     }
                     if (flag4)
                     {
                         s_InitializedDefaultProvider = true;
                     }
                 }
             }
         }
     }
 }
        public void Init(HttpApplication app)
        {
            bool flag = false;
            SessionStateSection sessionState = RuntimeConfig.GetAppConfig().SessionState;

            if (!this.s_oneTimeInit)
            {
                s_lock.AcquireWriterLock();
                try
                {
                    if (!this.s_oneTimeInit)
                    {
                        this.InitModuleFromConfig(app, sessionState);
                        flag = true;
                        if (!CheckTrustLevel(sessionState))
                        {
                            s_trustLevelInsufficient = true;
                        }
                        s_timeout            = (int)sessionState.Timeout.TotalMinutes;
                        s_useHostingIdentity = sessionState.UseHostingIdentity;
                        if ((sessionState.Mode == SessionStateMode.InProc) && this._usingAspnetSessionIdManager)
                        {
                            s_allowInProcOptimization = true;
                        }
                        if (((sessionState.Mode != SessionStateMode.Custom) && (sessionState.Mode != SessionStateMode.Off)) && !sessionState.RegenerateExpiredSessionId)
                        {
                            s_allowDelayedStateStoreItemCreation = true;
                        }
                        s_configExecutionTimeout           = RuntimeConfig.GetConfig().HttpRuntime.ExecutionTimeout;
                        s_configRegenerateExpiredSessionId = sessionState.RegenerateExpiredSessionId;
                        s_configCookieless = sessionState.Cookieless;
                        s_configMode       = sessionState.Mode;
                        this.s_oneTimeInit = true;
                    }
                }
                finally
                {
                    s_lock.ReleaseWriterLock();
                }
            }
            if (!flag)
            {
                this.InitModuleFromConfig(app, sessionState);
            }
            if (s_trustLevelInsufficient)
            {
                throw new HttpException(System.Web.SR.GetString("Session_state_need_higher_trust"));
            }
        }
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        // Methods for internal implementation

        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        void OnEnter(Object source, EventArgs eventArgs)
        {
            if (_fAuthChecked && !_fAuthRequired)
            {
                return;
            }

            HttpApplication app;
            HttpContext     context;

            app     = (HttpApplication)source;
            context = app.Context;

            if (!_fAuthChecked)
            {
                AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
                _fAuthRequired = (AuthenticationConfig.Mode == AuthenticationMode.Passport);
                _LoginUrl      = settings.Passport.RedirectUrl;
                _fAuthChecked  = true;
            }

            if (!_fAuthRequired)
            {
                return;
            }

            ////////////////////////////////////////////////////////
            // Step 1: See if this request is valid or not
            // VSWhidbey 442515: We no longer need to do this check, always proceed

            ////////////////////////////////////////////////////////
            // Step 2: Create a Passport Identity from the credentials
            //     from IIS
            PassportIdentity identity = new PassportIdentity();

            ////////////////////////////////////////////////////////
            // Step 4: Call OnAuthenticate virtual method to create
            //    an IPrincipal for this request
            OnAuthenticate(new PassportAuthenticationEventArgs(identity, context));

            ////////////////////////////////////////////////////////
            // Skip AuthZ if accessing the login page
            context.SetSkipAuthorizationNoDemand(AuthenticationConfig.AccessingLoginPage(context, _LoginUrl), false /*managedOnly*/);

            if (!context.SkipAuthorization)
            {
                context.SkipAuthorization = AssemblyResourceLoader.IsValidWebResourceRequest(context);
            }
        }
Example #8
0
 private static void EnsureResourceProviderFactory()
 {
     if (s_resourceProviderFactory == null)
     {
         Type resourceProviderFactoryTypeInternal = null;
         resourceProviderFactoryTypeInternal = RuntimeConfig.GetAppConfig().Globalization.ResourceProviderFactoryTypeInternal;
         if (resourceProviderFactoryTypeInternal == null)
         {
             s_resourceProviderFactory = new ResXResourceProviderFactory();
         }
         else
         {
             s_resourceProviderFactory = (ResourceProviderFactory)HttpRuntime.CreatePublicInstance(resourceProviderFactoryTypeInternal);
         }
     }
 }
Example #9
0
        private static bool InternalAuthenticate(string name, string password)
        {
            AuthenticationSection authentication;
            string str;
            string str2;

            if ((name != null) && (password != null))
            {
                Initialize();
                authentication = RuntimeConfig.GetAppConfig().Authentication;
                authentication.ValidateAuthenticationMode();
                FormsAuthenticationUserCollection users = authentication.Forms.Credentials.Users;
                if (users == null)
                {
                    return(false);
                }
                FormsAuthenticationUser user = users[name.ToLower(CultureInfo.InvariantCulture)];
                if (user == null)
                {
                    return(false);
                }
                str = user.Password;
                if (str == null)
                {
                    return(false);
                }
                switch (authentication.Forms.Credentials.PasswordFormat)
                {
                case FormsAuthPasswordFormat.Clear:
                    str2 = password;
                    goto Label_00A3;

                case FormsAuthPasswordFormat.SHA1:
                    str2 = HashPasswordForStoringInConfigFile(password, "sha1");
                    goto Label_00A3;

                case FormsAuthPasswordFormat.MD5:
                    str2 = HashPasswordForStoringInConfigFile(password, "md5");
                    goto Label_00A3;
                }
            }
            return(false);

Label_00A3:
            return(string.Compare(str2, str, (authentication.Forms.Credentials.PasswordFormat != FormsAuthPasswordFormat.Clear) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0);
        }
Example #10
0
        private static HttpEncoder GetCustomEncoderFromConfig()
        {
            // App since this is static per AppDomain
            RuntimeConfig      config          = RuntimeConfig.GetAppConfig();
            HttpRuntimeSection runtimeSection  = config.HttpRuntime;
            string             encoderTypeName = runtimeSection.EncoderType;

            // validate the type
            Type encoderType = ConfigUtil.GetType(encoderTypeName, "encoderType", runtimeSection);

            ConfigUtil.CheckBaseType(typeof(HttpEncoder) /* expectedBaseType */, encoderType, "encoderType", runtimeSection);

            // instantiate
            HttpEncoder encoder = (HttpEncoder)HttpRuntime.CreatePublicInstance(encoderType);

            return(encoder);
        }
        private static RequestValidator GetCustomValidatorFromConfig()
        {
            // App since this is static per AppDomain
            RuntimeConfig      config            = RuntimeConfig.GetAppConfig();
            HttpRuntimeSection runtimeSection    = config.HttpRuntime;
            string             validatorTypeName = runtimeSection.RequestValidationType;

            // validate the type
            Type validatorType = ConfigUtil.GetType(validatorTypeName, "requestValidationType", runtimeSection);

            ConfigUtil.CheckBaseType(typeof(RequestValidator) /* expectedBaseType */, validatorType, "requestValidationType", runtimeSection);

            // instantiate
            RequestValidator validator = (RequestValidator)HttpRuntime.CreatePublicInstance(validatorType);

            return(validator);
        }
Example #12
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        // Initialize this

        /// <devdoc>
        ///    Initializes FormsAuthentication by reading
        ///    configuration and getting the cookie values and encryption keys for the given
        ///    application.
        /// </devdoc>
        public static void Initialize()
        {
            if (_Initialized)
            {
                return;
            }

            lock (_lockObject) {
                if (_Initialized)
                {
                    return;
                }

                AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
                settings.ValidateAuthenticationMode();
                _FormsName         = settings.Forms.Name;
                _RequireSSL        = settings.Forms.RequireSSL;
                _SlidingExpiration = settings.Forms.SlidingExpiration;
                if (_FormsName == null)
                {
                    _FormsName = CONFIG_DEFAULT_COOKIE;
                }

                _Protection      = settings.Forms.Protection;
                _Timeout         = (int)settings.Forms.Timeout.TotalMinutes;
                _FormsCookiePath = settings.Forms.Path;
                _LoginUrl        = settings.Forms.LoginUrl;
                if (_LoginUrl == null)
                {
                    _LoginUrl = "login.aspx";
                }
                _DefaultUrl = settings.Forms.DefaultUrl;
                if (_DefaultUrl == null)
                {
                    _DefaultUrl = "default.aspx";
                }
                _CookieMode              = settings.Forms.Cookieless;
                _CookieDomain            = settings.Forms.Domain;
                _EnableCrossAppRedirects = settings.Forms.EnableCrossAppRedirects;
                _TicketCompatibilityMode = settings.Forms.TicketCompatibilityMode;
                _cookieSameSite          = settings.Forms.CookieSameSite;

                _Initialized = true;
            }
        }
Example #13
0
        void OneTimeInit()
        {
            SessionStateSection config = RuntimeConfig.GetAppConfig().SessionState;

            s_configPartitionResolverType           = config.PartitionResolverType;
            s_configStateConnectionString           = config.StateConnectionString;
            s_configStateConnectionStringFileName   = config.ElementInformation.Properties["stateConnectionString"].Source;
            s_configStateConnectionStringLineNumber = config.ElementInformation.Properties["stateConnectionString"].LineNumber;
            s_configCompressionEnabled = config.CompressionEnabled;

            if (_partitionResolver == null)
            {
                String stateConnectionString = config.StateConnectionString;

                SessionStateModule.ReadConnectionString(config, ref stateConnectionString, "stateConnectionString");

                s_singlePartitionInfo = (StateServerPartitionInfo)CreatePartitionInfo(stateConnectionString);
            }
            else
            {
                s_usePartition     = true;
                s_partitionManager = new PartitionManager(new CreatePartitionInfo(CreatePartitionInfo));
            }

            s_networkTimeout = (int)config.StateNetworkTimeout.TotalSeconds;

            string appId  = HttpRuntime.AppDomainAppId;
            string idHash = Convert.ToBase64String(CryptoUtil.ComputeSHA256Hash(Encoding.UTF8.GetBytes(appId)));

            // Make sure that we have a absolute URI, some hosts(Cassini) don't provide this.
            if (appId.StartsWith("/", StringComparison.Ordinal))
            {
                s_uribase = appId + "(" + idHash + ")/";
            }
            else
            {
                s_uribase = "/" + appId + "(" + idHash + ")/";
            }

            // We only need to do this in one instance
            s_onAppDomainUnload = new EventHandler(OnAppDomainUnload);
            Thread.GetDomain().DomainUnload += s_onAppDomainUnload;

            s_oneTimeInited = true;
        }
Example #14
0
 private static void EnsureInitialized()
 {
     if (!s_inited)
     {
         lock (s_initLock)
         {
             if (!s_inited)
             {
                 OutputCacheSection outputCache = RuntimeConfig.GetAppConfig().OutputCache;
                 s_providers                            = outputCache.CreateProviderCollection();
                 s_defaultProvider                      = outputCache.GetDefaultProvider(s_providers);
                 s_entryRemovedCallback                 = new CacheItemRemovedCallback(OutputCache.EntryRemovedCallback);
                 s_dependencyRemovedCallback            = new CacheItemRemovedCallback(OutputCache.DependencyRemovedCallback);
                 s_dependencyRemovedCallbackForFragment = new CacheItemRemovedCallback(OutputCache.DependencyRemovedCallbackForFragment);
                 s_inited = true;
             }
         }
     }
 }
Example #15
0
        internal static void UrlMappingRewritePath(HttpContext context)
        {
            HttpRequest        request         = context.Request;
            UrlMappingsSection urlMappings     = RuntimeConfig.GetAppConfig().UrlMappings;
            string             path            = request.Path;
            string             str2            = null;
            string             queryStringText = request.QueryStringText;

            if (!string.IsNullOrEmpty(queryStringText))
            {
                str2 = urlMappings.HttpResolveMapping(path + "?" + queryStringText);
            }
            if (str2 == null)
            {
                str2 = urlMappings.HttpResolveMapping(path);
            }
            if (!string.IsNullOrEmpty(str2))
            {
                context.RewritePath(str2, false);
            }
        }
Example #16
0
 public static void Initialize()
 {
     if (!_Initialized)
     {
         lock (_lockObject)
         {
             if (!_Initialized)
             {
                 AuthenticationSection authentication = RuntimeConfig.GetAppConfig().Authentication;
                 authentication.ValidateAuthenticationMode();
                 _FormsName         = authentication.Forms.Name;
                 _RequireSSL        = authentication.Forms.RequireSSL;
                 _SlidingExpiration = authentication.Forms.SlidingExpiration;
                 if (_FormsName == null)
                 {
                     _FormsName = ".ASPXAUTH";
                 }
                 _Protection      = authentication.Forms.Protection;
                 _Timeout         = (int)authentication.Forms.Timeout.TotalMinutes;
                 _FormsCookiePath = authentication.Forms.Path;
                 _LoginUrl        = authentication.Forms.LoginUrl;
                 if (_LoginUrl == null)
                 {
                     _LoginUrl = "login.aspx";
                 }
                 _DefaultUrl = authentication.Forms.DefaultUrl;
                 if (_DefaultUrl == null)
                 {
                     _DefaultUrl = "default.aspx";
                 }
                 _CookieMode              = authentication.Forms.Cookieless;
                 _CookieDomain            = authentication.Forms.Domain;
                 _EnableCrossAppRedirects = authentication.Forms.EnableCrossAppRedirects;
                 _TicketCompatibilityMode = authentication.Forms.TicketCompatibilityMode;
                 _Initialized             = true;
             }
         }
     }
 }
        private static void EnsureResourceProviderFactory()
        {
            if (s_resourceProviderFactory != null)
            {
                return;
            }

            Type t = null;
            GlobalizationSection globConfig = RuntimeConfig.GetAppConfig().Globalization;

            t = globConfig.ResourceProviderFactoryTypeInternal;

            // If we got a type from config, use it.  Otherwise, use default factory
            if (t == null)
            {
                s_resourceProviderFactory = new ResXResourceProviderFactory();
            }
            else
            {
                s_resourceProviderFactory = (ResourceProviderFactory)HttpRuntime.CreatePublicInstance(t);
            }
        }
 private static void Initialize()
 {
     HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level");
     if (!_initialized)
     {
         lock (_initializationLock)
         {
             if (!_initialized)
             {
                 WebPartsPersonalization personalization = RuntimeConfig.GetAppConfig().WebParts.Personalization;
                 _providers = new PersonalizationProviderCollection();
                 ProvidersHelper.InstantiateProviders(personalization.Providers, _providers, typeof(PersonalizationProvider));
                 _providers.SetReadOnly();
                 _provider = _providers[personalization.DefaultProvider];
                 if (_provider == null)
                 {
                     throw new ConfigurationErrorsException(System.Web.SR.GetString("Config_provider_must_exist", new object[] { personalization.DefaultProvider }), personalization.ElementInformation.Properties["defaultProvider"].Source, personalization.ElementInformation.Properties["defaultProvider"].LineNumber);
                 }
                 _initialized = true;
             }
         }
     }
 }
        private static void Initialize()
        {
            if (_providers != null)
            {
                return;
            }

            HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level);

            lock (_lockObject) {
                if (_providers != null)
                {
                    return;
                }

                SiteMapSection config = RuntimeConfig.GetAppConfig().SiteMap;
                if (config == null)
                {
                    // just return an empty collection so that designer will work.
                    _providers = new SiteMapProviderCollection();
                    return;
                }

                if (!config.Enabled)
                {
                    throw new InvalidOperationException(SR.GetString(SR.SiteMap_feature_disabled, SiteMap.SectionName));
                }

                // Make sure the default provider exists.
                config.ValidateDefaultProvider();

                _providers = config.ProvidersInternal;
                _provider  = _providers[config.DefaultProvider];
                _providers.SetReadOnly();
            }
        }
Example #20
0
        internal static string GetConnectionString(string specifiedConnectionString, bool lookupConnectionString, bool appLevel)
        {
            if ((specifiedConnectionString == null) || (specifiedConnectionString.Length < 1))
            {
                return(null);
            }
            string connectionString = null;

            if (lookupConnectionString)
            {
                RuntimeConfig            config   = appLevel ? RuntimeConfig.GetAppConfig() : RuntimeConfig.GetConfig();
                ConnectionStringSettings settings = config.ConnectionStrings.ConnectionStrings[specifiedConnectionString];
                if (settings != null)
                {
                    connectionString = settings.ConnectionString;
                }
                if (connectionString != null)
                {
                    return(connectionString);
                }
                return(null);
            }
            return(specifiedConnectionString);
        }
Example #21
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        // Static functions
        private static void Initialize()
        {
            if (s_Initialized)
            {
                return;
            }

            lock (s_InitLock) {
                if (s_Initialized)
                {
                    return;
                }

                AnonymousIdentificationSection settings = RuntimeConfig.GetAppConfig().AnonymousIdentification;
                s_Enabled           = settings.Enabled;
                s_CookieName        = settings.CookieName;
                s_CookiePath        = settings.CookiePath;
                s_CookieTimeout     = (int)settings.CookieTimeout.TotalMinutes;
                s_RequireSSL        = settings.CookieRequireSSL;
                s_SlidingExpiration = settings.CookieSlidingExpiration;
                s_Protection        = settings.CookieProtection;
                s_CookieMode        = settings.Cookieless;
                s_Domain            = settings.Domain;

                s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification");
                if (s_CookieTimeout < 1)
                {
                    s_CookieTimeout = 1;
                }
                if (s_CookieTimeout > 60 * 24 * 365 * 2)
                {
                    s_CookieTimeout = 60 * 24 * 365 * 2; // 2 years
                }
                s_Initialized = true;
            }
        }
Example #22
0
        private void OneTimeInit()
        {
            SessionStateSection sessionState = RuntimeConfig.GetAppConfig().SessionState;

            s_configPartitionResolverType           = sessionState.PartitionResolverType;
            s_configStateConnectionString           = sessionState.StateConnectionString;
            s_configStateConnectionStringFileName   = sessionState.ElementInformation.Properties["stateConnectionString"].Source;
            s_configStateConnectionStringLineNumber = sessionState.ElementInformation.Properties["stateConnectionString"].LineNumber;
            s_configCompressionEnabled = sessionState.CompressionEnabled;
            if (this._partitionResolver == null)
            {
                string stateConnectionString = sessionState.StateConnectionString;
                SessionStateModule.ReadConnectionString(sessionState, ref stateConnectionString, "stateConnectionString");
                s_singlePartitionInfo = (StateServerPartitionInfo)this.CreatePartitionInfo(stateConnectionString);
            }
            else
            {
                s_usePartition     = true;
                s_partitionManager = new PartitionManager(new System.Web.CreatePartitionInfo(this.CreatePartitionInfo));
            }
            s_networkTimeout = (int)sessionState.StateNetworkTimeout.TotalSeconds;
            string appDomainAppIdInternal = HttpRuntime.AppDomainAppIdInternal;
            string str3 = MachineKeySection.HashAndBase64EncodeString(appDomainAppIdInternal);

            if (appDomainAppIdInternal.StartsWith("/", StringComparison.Ordinal))
            {
                s_uribase = appDomainAppIdInternal + "(" + str3 + ")/";
            }
            else
            {
                s_uribase = "/" + appDomainAppIdInternal + "(" + str3 + ")/";
            }
            s_onAppDomainUnload = new EventHandler(this.OnAppDomainUnload);
            Thread.GetDomain().DomainUnload += s_onAppDomainUnload;
            s_oneTimeInited = true;
        }
Example #23
0
        static private 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, SR.Feature_not_supported_at_this_level);
                    }

                    RoleManagerSection settings = RuntimeConfig.GetAppConfig().RoleManager;
                    //s_InitializeException = new ProviderException(SR.GetString(SR.Roles_feature_not_enabled));
                    if (!s_EnabledSet)
                    {
                        s_Enabled = settings.Enabled;
                    }
                    s_CookieName              = settings.CookieName;
                    s_CacheRolesInCookie      = settings.CacheRolesInCookie;
                    s_CookieTimeout           = (int)settings.CookieTimeout.TotalMinutes;
                    s_CookiePath              = settings.CookiePath;
                    s_CookieRequireSSL        = settings.CookieRequireSSL;
                    s_CookieSlidingExpiration = settings.CookieSlidingExpiration;
                    s_CookieProtection        = settings.CookieProtection;
                    s_Domain = settings.Domain;
                    s_CreatePersistentCookie = settings.CreatePersistentCookie;
                    s_MaxCachedResults       = settings.MaxCachedResults;
                    if (s_Enabled)   // Instantiate providers only if feature is enabled
                    {
                        if (s_MaxCachedResults < 0)
                        {
                            throw new ProviderException(SR.GetString(SR.Value_must_be_non_negative_integer, "maxCachedResults"));
                        }
                        InitializeSettings(settings);
                        InitializeDefaultProvider(settings);
                    }
                } catch (Exception e) {
                    s_InitializeException = e;
                }
                s_Initialized = true;
            }

            if (s_InitializeException != null)
            {
                throw s_InitializeException;
            }
        }
        /// <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;
            }
        }
        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;
                }
            }
        }
Example #26
0
        internal LowPhysicalMemoryMonitor()
        {
            /*
             * The chart below shows physical memory in megabytes, and the 1, 3, and 10% values.
             *
             * RAM     1%      3%      10%
             * -----------------------------
             * 128     1.28    3.84    12.8
             * 256     2.56    7.68    25.6
             * 512     5.12    15.36   51.2
             * 1024    10.24   30.72   102.4
             * 2048    20.48   61.44   204.8
             * 4096    40.96   122.88  409.6
             * 8192    81.92   245.76  819.2
             *
             * Low memory notifications from CreateMemoryResourceNotification are calculated as follows
             * (.\base\ntos\mm\initsup.c):
             *
             * MiInitializeMemoryEvents() {
             * ...
             * //
             * // Scale the threshold so on servers the low threshold is
             * // approximately 32MB per 4GB, capping it at 64MB.
             * //
             *
             * MmLowMemoryThreshold = MmPlentyFreePages;
             *
             * if (MmNumberOfPhysicalPages > 0x40000) {
             *    MmLowMemoryThreshold = MI_MB_TO_PAGES (32);
             *    MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x40000) >> 7);
             * }
             * else if (MmNumberOfPhysicalPages > 0x8000) {
             *    MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x8000) >> 5);
             * }
             *
             * if (MmLowMemoryThreshold > MI_MB_TO_PAGES (64)) {
             *    MmLowMemoryThreshold = MI_MB_TO_PAGES (64);
             * }
             * ...
             *
             * E.g.
             *
             * RAM(mb) low      %
             * -------------------
             * 256	  20	  92%
             * 512	  24	  95%
             * 768	  28	  96%
             * 1024	  32	  97%
             * 2048	  40	  98%
             * 3072	  48	  98%
             * 4096	  56	  99%
             * 5120	  64	  99%
             */

            long memory = AspNetMemoryMonitor.s_totalPhysical;

            Debug.Assert(memory != 0, "memory != 0");
            if (memory >= 0x100000000)
            {
                _pressureHigh = 99;
            }
            else if (memory >= 0x80000000)
            {
                _pressureHigh = 98;
            }
            else if (memory >= 0x40000000)
            {
                _pressureHigh = 97;
            }
            else if (memory >= 0x30000000)
            {
                _pressureHigh = 96;
            }
            else
            {
                _pressureHigh = 95;
            }

            _pressureLow = _pressureHigh - 9;

            InitHistory();

            _appManager = ApplicationManager.GetApplicationManager();

            _observers = new List <IObserver <LowPhysicalMemoryInfo> >();

            CacheSection  cacheConfig  = null;
            RuntimeConfig lkgAppConfig = RuntimeConfig.GetAppLKGConfig();
            RuntimeConfig appConfig    = null;

            try {
                appConfig   = RuntimeConfig.GetAppConfig();
                cacheConfig = appConfig.Cache;
            }
            catch (Exception) {
                cacheConfig = lkgAppConfig.Cache;
            }
            ReadConfig(cacheConfig);

            // PerfCounter: Cache Percentage Machine Memory Limit Used
            //    = total physical memory used / total physical memory used limit
            PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_MACH_MEM_LIMIT_USED_BASE, _pressureHigh);

            // start timer with initial poll interval
            _timer = new Timer(new TimerCallback(this.MonitorThread), null, Timeout.Infinite, _currentPollInterval);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "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", System.Web.SR.GetString("RoleAuthStoreProvider_description"));
            }
            base.Initialize(name, config);
            this._CacheRefreshInterval = SecUtility.GetIntValue(config, "cacheRefreshInterval", 60, false, 0);
            this._ScopeName            = config["scopeName"];
            if ((this._ScopeName != null) && (this._ScopeName.Length == 0))
            {
                this._ScopeName = null;
            }
            this._ConnectionString = config["connectionStringName"];
            if ((this._ConnectionString == null) || (this._ConnectionString.Length < 1))
            {
                throw new ProviderException(System.Web.SR.GetString("Connection_name_not_specified"));
            }
            ConnectionStringSettings settings = RuntimeConfig.GetAppConfig().ConnectionStrings.ConnectionStrings[this._ConnectionString];

            if (settings == null)
            {
                throw new ProviderException(System.Web.SR.GetString("Connection_string_not_found", new object[] { this._ConnectionString }));
            }
            if (string.IsNullOrEmpty(settings.ConnectionString))
            {
                throw new ProviderException(System.Web.SR.GetString("Connection_string_not_found", new object[] { this._ConnectionString }));
            }
            this._ConnectionString = settings.ConnectionString;
            this._AppName          = config["applicationName"];
            if (string.IsNullOrEmpty(this._AppName))
            {
                this._AppName = SecUtility.GetDefaultAppName();
            }
            if (this._AppName.Length > 0x100)
            {
                throw new ProviderException(System.Web.SR.GetString("Provider_application_name_too_long"));
            }
            config.Remove("connectionStringName");
            config.Remove("cacheRefreshInterval");
            config.Remove("applicationName");
            config.Remove("scopeName");
            if (config.Count > 0)
            {
                string key = config.GetKey(0);
                if (!string.IsNullOrEmpty(key))
                {
                    throw new ProviderException(System.Web.SR.GetString("Provider_unrecognized_attribute", new object[] { key }));
                }
            }
        }
Example #28
0
        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);
                    // VSO #265267 log warning in event log when using clear password and encrypted password in Membership provider
                    // VSO #433626 In order to minimize the behavior change, we are going to read the password format from the config settings only instead of getting from the provider class
                    // Also allow user to opt-out this feature.
                    if (AppSettings.LogMembershipPasswordFormatWarning)
                    {
                        CheckedPasswordFormat(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;
                }
            }
        }
Example #29
0
        /// <summary>
        /// Verifies that the moniker is valid, and that the version is 4.0 and above.
        /// </summary>
        private static void ValidateTargetFrameworkMoniker(string targetFrameworkMoniker)
        {
            CompilationSection compConfig = RuntimeConfig.GetAppConfig().Compilation;
            int    lineNumber             = compConfig.ElementInformation.LineNumber;
            string source = compConfig.ElementInformation.Source;

            try {
                string moniker = targetFrameworkMoniker;
                // Try treating it as a version, eg "4.0" first.
                Version v = GetVersion(targetFrameworkMoniker);
                if (v != null)
                {
                    // If it is of the form "4.0", construct the full moniker string,
                    // eg ".NETFramework,Version=v4.0"
                    moniker = ".NETFramework,Version=v" + moniker;
                }
                s_targetFrameworkName = CreateFrameworkName(moniker);
            }
            catch (ArgumentException e) {
                throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_target_framework_version,
                                                                    s_configTargetFrameworkAttributeName, targetFrameworkMoniker, e.Message), source, lineNumber);
            }
            Version ver = GetFrameworkNameVersion(s_targetFrameworkName);

            if (ver < Version40)
            {
                throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_lower_target_version, s_configTargetFrameworkAttributeName),
                                                       source, lineNumber);
            }

            // Check the specified version is no higher than the latest known framework for which we have
            // reference assemblies installed.
            Version latestVersion = GetFrameworkNameVersion(LatestFrameworkName);

            if (latestVersion != null && latestVersion >= ver)
            {
                // If the specified version is lower than the latest version installed,
                // we are fine.
                return;
            }

            // NOTE: This check is not entirely correct. See comments in GetInstalledTargetVersion().
            // It might be possible that the actual installed (runtime) version is of a higher version,
            // but the reference assemblies are not installed, so latestFrameworkName might be lower.
            // In that case we also need to check the registry key.
            int     majorVersion           = ver.Major;
            Version installedTargetVersion = GetInstalledTargetVersion(majorVersion);

            if (installedTargetVersion != null && installedTargetVersion >= ver)
            {
                return;
            }

            if (IsSupportedVersion(s_targetFrameworkName))
            {
                return;
            }

            // If the above checks failed, report that the version is invalid, higher than expected
            throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_higher_target_version, s_configTargetFrameworkAttributeName), source, lineNumber);
        }
Example #30
0
        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);
        }