/// <summary>
    /// Initialize the session state provider
    /// </summary>
    public override void Initialize(string name, NameValueCollection config)
    {
        
        if (config == null)
            throw new ArgumentNullException("config");

        if (name == null || name.Length == 0)
            name = "SqlSessionStateProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "Sql session state provider");
        }

        // Initialize the abstract base class.
        base.Initialize(name, config);

        // Set the application name
        this.applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

        // Get the session state configuration
        Configuration cfg = WebConfigurationManager.OpenWebConfiguration(this.applicationName);
        sessionStateConfiguration = (SessionStateSection)cfg.GetSection("system.web/sessionState");

    } // End of the Initialize method
示例#2
0
        public override void Initialize(string name, NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (name == null || name.Length == 0)
            {
                name = "RedisSessionStateStore";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Redis Session State Provider");
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            // Get <sessionState> configuration element.
            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);

            sessionStateConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");


            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                {
                    this.writeExceptionsToLog = true;
                }
            }

            if (config["server"] != null)
            {
                this.redisServer = config["server"];
            }

            if (config["port"] != null)
            {
                int.TryParse(config["port"], out this.redisPort);
            }

            if (config["password"] != null)
            {
                this.redisPassword = config["password"];
            }
        }
示例#3
0
        protected override ProviderSettings GetMachineSettings()
        {
            Configuration       machineConfig = ConfigurationManager.OpenMachineConfiguration();
            SessionStateSection section       = (SessionStateSection)machineConfig.SectionGroups["system.web"].Sections[sectionName];

            foreach (ProviderSettings p in section.Providers)
            {
                if (p.Type.Contains(typeName))
                {
                    return(p);
                }
            }
            return(null);
        }
        private void ConfigureSessionOptions(SessionStateSection sessCfg)
        {
            RedisSessionConfig.SessionAccessConcurrencyLevel = 1;

            try
            {
                // Get <sessionState> configuration element from web.config, store the cookie name
                RedisSessionConfig.SessionHttpCookieName = sessCfg.CookieName;
                RedisSessionConfig.SessionTimeout        = sessCfg.Timeout;
            }
            catch (Exception)
            {
            }
        }
示例#5
0
        private void GetConfigSettings(NameValueCollection config)
        {
            this._accessKey        = config[CONFIG_ACCESSKEY];
            this._secretKey        = config[CONFIG_SECRETKEY];
            this._profileName      = config[CONFIG_PROFILENAME];
            this._profilesLocation = config[CONFIG_PROFILESLOCATION];
            this._regionName       = config[CONFIG_REGION];
            this._serviceURL       = config[CONFIG_SERVICE_URL];

            if (!string.IsNullOrEmpty(config[CONFIG_TABLE]))
            {
                this._tableName = config[CONFIG_TABLE];
            }

            if (!string.IsNullOrEmpty(config[CONFIG_APPLICATION]))
            {
                this._application = config[CONFIG_APPLICATION];
            }

            if (!string.IsNullOrEmpty(config[CONFIG_CREATE_TABLE_IF_NOT_EXIST]))
            {
                this._createIfNotExist = bool.Parse(config[CONFIG_CREATE_TABLE_IF_NOT_EXIST]);
            }

            if (!string.IsNullOrEmpty(config[CONFIG_INITIAL_READ_UNITS]))
            {
                this._initialReadUnits = int.Parse(config[CONFIG_INITIAL_READ_UNITS]);
            }

            if (!string.IsNullOrEmpty(config[CONFIG_INITIAL_WRITE_UNITS]))
            {
                this._initialWriteUnits = int.Parse(config[CONFIG_INITIAL_WRITE_UNITS]);
            }


            string applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            if (applicationName != null)
            {
                Configuration cfg = WebConfigurationManager.OpenWebConfiguration(applicationName);
                if (cfg != null)
                {
                    SessionStateSection sessionConfig = cfg.GetSection("system.web/sessionState") as SessionStateSection;
                    if (sessionConfig != null)
                    {
                        this._timeout = sessionConfig.Timeout;
                    }
                }
            }
        }
示例#6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Session.Clear();

            SessionStateSection sessionState = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");

            var cookie = HttpContext.Current.Request.Cookies[sessionState.CookieName];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-3);
                Response.Cookies.Add(cookie);
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (name == null || name.Length == 0)
            {
                name = "MongoSessionStore";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "MongoDB Session State Store provider");
            }
            // Initialize the abstract base class.
            base.Initialize(name, config);

            if (config["connectionString"] == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            _connectionString = config["connectionString"];

            if (config["applicationName"] != null)
            {
                _applicationName = config["applicationName"];
            }
            else
            {
                _applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            }

            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);

            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                {
                    _logExceptions = true;
                }
            }

            sessionStore = new SessionStore(_applicationName, _connectionString);
        }
        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"));
            }
        }
        /// <summary>
        /// Initialize the module
        /// </summary>
        /// <param name="app"></param>
        public void Init(HttpApplication app)
        {
            bool initModuleCalled = false;

            if (!s_oneTimeInit)
            {
                lock (LockObject)
                {
                    if (!s_oneTimeInit)
                    {
                        s_config = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
                        if (s_config == null)
                        {
                            throw new ConfigurationErrorsException(string.Format(SR.Error_Occured_Reading_Config_Secion, "system.web/sessionState"));
                        }

                        InitModuleFromConfig(app, s_config);
                        initModuleCalled = true;

                        s_timeout = (int)s_config.Timeout.TotalMinutes;

                        var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                        if (section == null)
                        {
                            throw new ConfigurationErrorsException(string.Format(SR.Error_Occured_Reading_Config_Secion, "system.web/httpRuntime"));
                        }

                        s_configExecutionTimeout = section.ExecutionTimeout;

                        s_configRegenerateExpiredSessionId = s_config.RegenerateExpiredSessionId;
                        s_configCookieless = s_config.Cookieless;
                        s_configMode       = s_config.Mode;

                        if (!s_pollIntervalRegLookedUp)
                        {
                            LookUpRegForPollInterval();
                        }

                        // The last thing to set in this if-block.
                        s_oneTimeInit = true;
                    }
                }
            }

            if (!initModuleCalled)
            {
                InitModuleFromConfig(app, s_config);
            }
        }
示例#10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Session["Reset"] = true;
            Configuration       config  = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
            SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
            int timeout = (int)section.Timeout.TotalMinutes * 1000 * 60;

            ScriptManager.RegisterStartupScript(this, this.GetType(), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);
            if (Session["UserId"] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            lblName.Text = Session["UserName"].ToString();
        }
        private SessionStateSection CreateSessionStateSection(double?timeoutInSecond = null, bool?compressionEnabled = null)
        {
            var ssc = new SessionStateSection();

            if (timeoutInSecond.HasValue)
            {
                ssc.SqlCommandTimeout = TimeSpan.FromSeconds(timeoutInSecond.Value);
            }
            if (compressionEnabled.HasValue)
            {
                ssc.CompressionEnabled = compressionEnabled.Value;
            }

            return(ssc);
        }
        /// <summary>
        /// Creates a new instance of the <see cref="AdaptiveSessionStorageProvider" /> class with the specified settings.
        /// </summary>
        /// <param name="settings">The <see cref="SessionStorageProviderElement" /> object that holds the configuration settings.</param>
        public AdaptiveSessionStorageProvider(SessionStorageProviderElement settings)
            : base(settings)
        {
            // TODO: error handle?
            SessionStateSection section = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");

            if (section.Mode == SessionStateMode.Off || section.Mode == SessionStateMode.InProc)
            {
                _provider = new InProcSessionStorageProvider(settings);
            }
            else
            {
                _provider = new SessionStateSessionStorageProvider(settings);
            }
        }
        /// <summary>
        /// System.Configuration.Provider.ProviderBase.Initialize Method
        /// </summary>
        public override void Initialize(string name, NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config", Properties.Resources.ErrArgumentNull);
            }

            if (string.IsNullOrEmpty(name))
            {
                name = Properties.Resources.SessionStoreProviderDefaultName;
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", Properties.Resources.SessionStoreProviderDefaultDescription);
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            m_applicationName = PgMembershipProvider.GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);

            // Get connection string.
            m_connectionString = PgMembershipProvider.GetConnectionString(config["connectionStringName"]);

            // Get <sessionState> configuration element.
            m_config = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

            // Should automatic session garbage collection be turned on?
            bool enableExpiredSessionAutoDeletion = Convert.ToBoolean(PgMembershipProvider.GetConfigValue(config["enableExpiredSessionAutoDeletion"], "false"), CultureInfo.InvariantCulture);

            if (!enableExpiredSessionAutoDeletion)
            {
                return;
            }

            m_enableExpireCallback = Convert.ToBoolean(PgMembershipProvider.GetConfigValue(config["enableSessionExpireCallback"], "false"), CultureInfo.InvariantCulture);

            // Load session garbage collection configuration and setup garbage collection interval timer
            double expiredSessionAutoDeletionInterval = Convert.ToDouble(PgMembershipProvider.GetConfigValue(config["expiredSessionAutoDeletionInterval"], "1800000"), CultureInfo.InvariantCulture); //default: 30 minutes

            m_expiredSessionDeletionTimer           = new System.Timers.Timer(expiredSessionAutoDeletionInterval);
            m_expiredSessionDeletionTimer.Elapsed  += new System.Timers.ElapsedEventHandler(ExpiredSessionDeletionTimer_Elapsed);
            m_expiredSessionDeletionTimer.Enabled   = true;
            m_expiredSessionDeletionTimer.AutoReset = true;
        }
        // for unit tests
        internal void Initialize(string name, NameValueCollection config, SessionStateSection ssc,
                                 ConnectionStringSettings connectionString,
                                 bool shouldCreateTable = false)
        {
            base.Initialize(name, config);

            if (!s_oneTimeInited)
            {
                lock (s_lock)
                {
                    if (!s_oneTimeInited)
                    {
                        s_compressionEnabled = ssc.CompressionEnabled;

                        s_sqlSessionStateRepository = new PostgresSessionStateRepository(
                            connectionString.ConnectionString,
                            (int)ssc.SqlCommandTimeout.TotalSeconds, GetRetryInterval(config),
                            GetMaxRetryNum(config));

                        //if (ShouldUseInMemoryTable(config))
                        //{
                        //    s_sqlSessionStateRepository = new SqlInMemoryTableSessionStateRepository(
                        //        connectionString.ConnectionString,
                        //        (int)ssc.SqlCommandTimeout.TotalSeconds, GetRetryInterval(config),
                        //        GetMaxRetryNum(config));
                        //}
                        //else
                        //{
                        //    s_sqlSessionStateRepository = new PostgresSessionStateRepository(
                        //        connectionString.ConnectionString,
                        //        (int)ssc.SqlCommandTimeout.TotalSeconds, GetRetryInterval(config),
                        //        GetMaxRetryNum(config));
                        //}

                        if (shouldCreateTable)
                        {
                            s_sqlSessionStateRepository.CreateSessionStateTable();
                        }

                        var appId = AppId ?? HttpRuntime.AppDomainAppId;
                        Debug.Assert(appId != null);
                        s_appSuffix = appId.GetHashCode().ToString("X8", CultureInfo.InvariantCulture);

                        s_oneTimeInited = true;
                    }
                }
            }
        }
示例#15
0
        public override void Initialize(string name, NameValueCollection config)
        {
            this.config = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            if (String.IsNullOrEmpty(name))
            {
                name = "Session Server handler";
            }
            RemotingConfiguration.Configure(null);
            string cons = null, proto = null, server = null, port = null;

            GetConData(out proto, out server, out port);
            cons        = String.Format("{0}://{1}:{2}/StateServer", proto, server, port);
            stateServer = Activator.GetObject(typeof(RemoteStateServer), cons) as RemoteStateServer;

            base.Initialize(name, config);
        }
示例#16
0
        protected void Session_Start(Object sender, EventArgs e)
        {
            Request.Cookies.Clear();
            SessionStateSection sessionState =
                (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
            string sidCookieName = sessionState.CookieName;

            if (Request.Cookies[sidCookieName] != null)
            {
                System.Web.HttpCookie sidCookie = Response.Cookies[sidCookieName];
                sidCookie.Value    = Session.SessionID;
                sidCookie.HttpOnly = true;
                sidCookie.Secure   = true;
                sidCookie.Path     = "/";
            }
        }
        private SessionStateStoreProviderBase InitCustomStore(SessionStateSection config)
        {
            string customProvider = config.CustomProvider;

            if (string.IsNullOrEmpty(customProvider))
            {
                throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_session_custom_provider", new object[] { customProvider }), config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }
            ProviderSettings settings = config.Providers[customProvider];

            if (settings == null)
            {
                throw new ConfigurationErrorsException(System.Web.SR.GetString("Missing_session_custom_provider", new object[] { customProvider }), config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }
            return(this.SecureInstantiateProvider(settings));
        }
示例#18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //int timeOut = GeneralFuncs.GetSettingByKey("TimeOut");

            if (User.Identity.IsAuthenticated)
            {
                // Refresh this page 60 seconds before session timeout, effectively resetting the session timeout counter.

                Configuration       config  = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
                SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
                int timeout = (int)section.Timeout.TotalMinutes * 60;
                idtimeout.Text = timeout.ToString();
                Label1.Text    = (Session.Timeout * 60).ToString();
                MetaRefresh.Attributes["content"] = Convert.ToString(timeout - 60) + ";url=/KeepSessionAlive.aspx?q=" + DateTime.Now.Ticks;
            }
        }
示例#19
0
        /// <summary>
        /// Loads settings from the regular sessionState section in web.config.
        /// </summary>
        public void LoadFromWebConfig()
        {
            SessionStateSection section = (SessionStateSection)WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath).GetSection("system.web/sessionState");
            string connectionString     = section.StateConnectionString;

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                string[] strArray = connectionString.Split(new char[2]
                {
                    '=',
                    ':'
                });
                this.Host = ((IEnumerable <string>)strArray).ElementAtOrDefault <string>(1) ?? "localhost";
                this.Port = int.Parse(((IEnumerable <string>)strArray).ElementAtOrDefault <string>(2) ?? "6379");
            }
            this.SessionTimeout = (int)section.Timeout.TotalMinutes;
        }
示例#20
0
        public string ApplyAppPathModifier(string virtualPath)
        {
            if (virtualPath == null)
            {
                return(null);
            }

            if (virtualPath.Length == 0)
            {
                return(context.Request.RootVirtualDir);
            }

            if (UrlUtils.IsRelativeUrl(virtualPath))
            {
                virtualPath = UrlUtils.Combine(context.Request.RootVirtualDir, virtualPath);
            }
            else if (UrlUtils.IsRooted(virtualPath))
            {
                virtualPath = UrlUtils.Canonic(virtualPath);
            }

            bool cookieless = false;

#if NET_2_0
            SessionStateSection config = WebConfigurationManager.GetWebApplicationSection("system.web/sessionState") as SessionStateSection;
            cookieless = SessionStateModule.IsCookieLess(context, config);
#else
            SessionConfig config = HttpContext.GetAppConfig("system.web/sessionState") as SessionConfig;
            cookieless = config.CookieLess;
#endif
            if (!cookieless)
            {
                return(virtualPath);
            }

            if (app_path_mod != null && virtualPath.IndexOf(app_path_mod) < 0)
            {
                if (UrlUtils.HasSessionId(virtualPath))
                {
                    virtualPath = UrlUtils.RemoveSessionId(VirtualPathUtility.GetDirectory(virtualPath), virtualPath);
                }
                return(UrlUtils.InsertSessionId(app_path_mod, virtualPath));
            }

            return(virtualPath);
        }
        public void Init(HttpApplication app)
        {
            if (this.initialized)
            {
                return;
            }
            lock (typeof(RedisSessionStateModule))
            {
                if (this.initialized)
                {
                    return;
                }
                this.redisConfig         = RedisSessionStateConfiguration.GetConfiguration();
                app.AcquireRequestState += new EventHandler(this.OnAcquireRequestState);
                app.ReleaseRequestState += new EventHandler(this.OnReleaseRequestState);
                app.EndRequest          += new EventHandler(this.OnEndRequest);

                SessionStateSection sessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;

                string            sessionIdManagerType = sessionState?.SessionIDManagerType;
                ISessionIDManager sessionIdManager;

                if (string.IsNullOrEmpty(sessionIdManagerType))
                {
                    sessionIdManager = new SessionIDManager();
                }
                else
                {
                    Type type = Type.GetType(sessionIdManagerType, false);
                    if (type != null)
                    {
                        sessionIdManager = Activator.CreateInstance(type) as ISessionIDManager ?? new SessionIDManager();
                    }
                    else
                    {
                        sessionIdManager = new SessionIDManager();
                    }
                }

                this.sessionIDManager = sessionIdManager;
                this.sessionIDManager.Initialize();
                this.redisConnection = new RedisConnection(this.redisConfig.Host, this.redisConfig.Port, -1, (string)null, int.MaxValue, false, 10000);
                this.initialized     = true;
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            // Initialize values from web.config.
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (name == null || name.Length == 0)
            {
                name = "VauctionSessionStateStore";
            }
            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Vauction Session State Store provider");
            }
            // Initialize the abstract base class.
            base.Initialize(name, config);
            // Initialize the ApplicationName property.

            // Get <sessionState> configuration element.
            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
            pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            // Initialize connection string.
            pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }
            connectionString = pConnectionStringSettings.ConnectionString;

            // Initialize WriteExceptionsToEventLog
            pWriteExceptionsToEventLog = false;
            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                {
                    pWriteExceptionsToEventLog = true;
                }
            }
            pApplicationName = (config["application"] != null) ? config["application"] : System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            eventSource      = (!String.IsNullOrEmpty(config["eventLogSource"])) ? config["eventLogSource"] : "VauctionSessionStateStore";
        }
示例#23
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;
        }
        public static void LimparRegistroAutenticacao()
        {
            SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

            var cookieName = sessionStateSection.CookieName;

            _context.Session.Abandon();
            _context.Session.Clear();
            _context.Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
            _context.Request.Cookies.Remove(cookieName);
            _context.Request.Cookies.Remove(MatrizCookieName);
            _context.GetOwinContext().Authentication.SignOut();
            _context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            _context.Session[".ASPXAUTH"]          = null;
            _context.Session[".ASP.NET_SessionId"] = null;
            FormsAuthentication.SignOut();
            //DeletePermissionSession();
        }
示例#25
0
        protected void lbSignOut_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");

            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            HttpCookie          cookie2             = new HttpCookie(sessionStateSection.CookieName, "");

            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            Response.Redirect("/Admin/Login.aspx");
        }
        public string IsAuthorized(string username, string roleName)
        {
            MembershipUser      user               = Membership.GetAllUsers()[username];
            Configuration       config             = ConfigurationManager.OpenExeConfiguration(HostingEnvironment.MapPath("~") + "\\web.config");
            SessionStateSection sessionStateConfig = (SessionStateSection)config.SectionGroups.Get("system.web").Sections.Get("sessionState");

            // Check for session state timeout (could use a constant here instead if you don't want to rely on the config).
            if (user.LastLoginDate.AddMinutes(sessionStateConfig.Timeout.TotalMinutes) < DateTime.Now)
            {
                return("User Unauthorized - login has expired!");
            }
            // Check for role membership.
            if (!Roles.GetUsersInRole(roleName).Contains(user.UserName))
            {
                return("User Unauthorized - Does not belong in that role!");
            }
            return("Success - User is Authorized!");
        }
示例#27
0
        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            // Clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");

            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            HttpCookie          cookie2             = new HttpCookie(sessionStateSection.CookieName, "");

            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            return(RedirectToAction("Index", "Home"));
        }
示例#28
0
        internal static bool IsCookieLess(HttpContext context, SessionStateSection config)
        {
            if (config.Cookieless == HttpCookieMode.UseCookies)
            {
                return(false);
            }
            if (config.Cookieless == HttpCookieMode.UseUri)
            {
                return(true);
            }
            object cookieless = context.Items [CookielessFlagName];

            if (cookieless == null)
            {
                return(false);
            }
            return((bool)cookieless);
        }
示例#29
0
        private void ClearCookie()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");

            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            HttpCookie          cookie2             = new HttpCookie(sessionStateSection.CookieName, "");

            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);
        }
        private void InitModuleFromConfig(HttpApplication app, SessionStateSection config)
        {
            if (config.Mode != SessionStateMode.Off)
            {
                app.AddOnAcquireRequestStateAsync(new BeginEventHandler(this.BeginAcquireState), new EndEventHandler(this.EndAcquireState));
                app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
                app.EndRequest          += new EventHandler(this.OnEndRequest);
                this._partitionResolver  = this.InitPartitionResolver(config);
                switch (config.Mode)
                {
                case SessionStateMode.InProc:
                    if (HttpRuntime.UseIntegratedPipeline)
                    {
                        s_canSkipEndRequestCall = true;
                    }
                    this._store = new InProcSessionStateStore();
                    this._store.Initialize(null, null);
                    break;

                case SessionStateMode.StateServer:
                    if (HttpRuntime.UseIntegratedPipeline)
                    {
                        s_canSkipEndRequestCall = true;
                    }
                    this._store = new OutOfProcSessionStateStore();
                    ((OutOfProcSessionStateStore)this._store).Initialize(null, null, this._partitionResolver);
                    break;

                case SessionStateMode.SQLServer:
                    this._store = new SqlSessionStateStore();
                    ((SqlSessionStateStore)this._store).Initialize(null, null, this._partitionResolver);
                    break;

                case SessionStateMode.Custom:
                    this._store = this.InitCustomStore(config);
                    break;
                }
                this._idManager = this.InitSessionIDManager(config);
                if (((config.Mode == SessionStateMode.InProc) || (config.Mode == SessionStateMode.StateServer)) && this._usingAspnetSessionIdManager)
                {
                    this._ignoreImpersonation = true;
                }
            }
        }
示例#31
0
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (string.IsNullOrEmpty(name))
            {
                name = "FbSessionStateStore";
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "FB Session State Store");
            }

            base.Initialize(name, config);

            if (config["applicationName"] == null || config["applicationName"].Trim() == "")
            {
                this.applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            }
            else
            {
                this.applicationName = config["applicationName"];
            }


            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);

            this.config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (connectionStringSettings == null || string.IsNullOrEmpty(connectionStringSettings.ConnectionString))
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            this.connectionString = connectionStringSettings.ConnectionString;
        }
示例#32
0
        /// <summary>
        /// Initializes the provider with the property values specified in the ASP.NET application configuration file
        /// </summary>
        /// <param name="name">The name of the provider instance to initialize.</param>
        /// <param name="config">Object that contains the names and values of configuration options for the provider.
        /// </param>
        public override void Initialize(string name, NameValueCollection config)
        {
            //Initialize values from web.config.
            if (config == null)
                throw new ArgumentException("config");
            if (name == null || name.Length == 0)
                throw new ArgumentException("name");
            if (String.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config["description"] = "Silversite Session State Store Provider";
            }
            base.Initialize(name, config);
            string applicationName = HostingEnvironment.ApplicationVirtualPath;
            if (!String.IsNullOrEmpty(config["applicationName"]))
                applicationName = config["applicationName"];

            // Get <sessionState> configuration element.
            Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateConfig = (SessionStateSection)webConfig.SectionGroups["system.web"].Sections["sessionState"];

            // Initialize connection.
            var conStrName = config["connectionStringName"];
            if (string.IsNullOrEmpty(conStrName)) db = Data.Database.Default;
            else {
                connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
                db =  Data.Database.Custom(connectionStringSettings.ProviderName, connectionStringSettings.ConnectionString);
            }

            writeExceptionsToEventLog = false;
            if (config["writeExceptionsToEventLog"] != null) {
                writeExceptionsToEventLog = (config["writeExceptionsToEventLog"].ToUpper() == "TRUE");
            }

            // Make sure we have the correct schema.
            app = new Application(applicationName, base.Description);

            // Get the application id.
            try {
                using (MySqlConnection conn = new MySqlConnection(connectionString)) {
                    conn.Open();
                    app.EnsureId(conn);
                    CheckStorageEngine(conn);
                    cleanupInterval = GetCleanupInterval(conn);
                }
            } catch (MySqlException e) {
                HandleMySqlException(e, "Initialize");
            }

            // Setup the cleanup timer
            if (cleanupInterval <= 0)
                cleanupInterval = 1;
            cleanupTimer = new Timer(new TimerCallback(CleanupOldSessions), null, 0,
                cleanupInterval * 1000 * 60);
        }
    /// <summary>
    /// Initializes the provider.
    /// </summary>
    /// <param name="name">A friednly name for the provider.</param>
    /// <param name="config">A config object for the provider.</param>
    public override void Initialize(String name, System.Collections.Specialized.NameValueCollection config)
    {
        // Initialize values from Web.Config
        if (config == null) throw new ArgumentNullException("config");

        if (name == null || name.Length == 0) name = "MemcachedSessionStateStore";

        if (String.IsNullOrEmpty(config["description"])) {
            config.Remove("description");
            config.Add("description", "BeITMemcached based Session Store");
        }

        if (!String.IsNullOrEmpty(config["pool"])) {
            pool = config["pool"];
        }

        // Initialize the abstract base class
        base.Initialize(name, config);

        // Initialize the ApplicationName property
        ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

        // Get <sessionState> configuration element
        Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
        ConfigurationSection sec = cfg.GetSection("system.web/sessionState");
        sessionConfig = (SessionStateSection)sec;
    }