private void SetConfigurationProperties(NameValueCollection config)
 {
     ApplicationName = string.IsNullOrEmpty(config["applicationName"])
                           ? HostingEnvironment.ApplicationVirtualPath
                           : config["applicationName"];
     _sessionStateConfig = (SessionStateSection) ConfigurationManager.GetSection("system.web/sessionState");
 }
示例#2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpSessionState httpss = HttpContext.Current.Session;


        SessionStateSection sss = new SessionStateSection();

        LabelSessionSate.Text += "SqlCommandTimeout : " + sss.Mode + "<br>";
        LabelSessionSate.Text += "CookieName : " + sss.CookieName + "<br>";
        LabelSessionSate.Text += "Cookieless : " + sss.Cookieless + "<br>";
        LabelSessionSate.Text += "<br>";
        LabelSessionSate.Text += "SqlCommandTimeout : " + sss.SqlCommandTimeout + "<br>";
        LabelSessionSate.Text += "StateNetworkTimeout : " + sss.StateNetworkTimeout + "<br>";
        LabelSessionSate.Text += "Timeout : " + sss.Timeout + "<br>";


        LabelSessionSate.Text += "<br>";
        LabelSessionSate.Text += "<br>";

        // Get the Web application configuration object.
        System.Configuration.Configuration configuration =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);

        // Get the section related object.
        System.Web.Configuration.SessionStateSection sessSS = ( SessionStateSection )configuration.GetSection("system.web/sessionState");

        LabelSessionSate.Text += "SqlCommandTimeout : " + sessSS.Mode + "<br>";
        LabelSessionSate.Text += "CookieName : " + sessSS.CookieName + "<br>";
        LabelSessionSate.Text += "Cookieless : " + sessSS.Cookieless + "<br>";
        LabelSessionSate.Text += "<br>";
        LabelSessionSate.Text += "SqlCommandTimeout : " + sessSS.SqlCommandTimeout + "<br>";
        LabelSessionSate.Text += "StateNetworkTimeout : " + sessSS.StateNetworkTimeout + "<br>";
        LabelSessionSate.Text += "Timeout : " + sessSS.Timeout + "<br>";
    }
    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";
    }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null) {
            throw new ArgumentException("config");
             }

             if (String.IsNullOrWhiteSpace(name)) {
            name = "CookieSessionStateStore";
             }

             if (String.IsNullOrWhiteSpace(config["description"])) {
            config.Remove("description");
            config.Add("description", "Cookie session state store provider");
             }

             _cookieName = config.ReadValue("cookieName", _cookieName);
             _httpOnly = config.ReadBool("httpOnly", _httpOnly);
             _secureOnly = config.ReadBool("secureOnly", _secureOnly);
             _setExpiration = config.ReadBool("setExpiration", _setExpiration);

             base.Initialize(name, config);

             Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
             _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            // Initialize values from web.config
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                name = "DacheSessionStateProvider";
            }

            if (string.IsNullOrWhiteSpace(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Dache Session State Store Provider");
            }

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

            // Initialize the application name
            _applicationName = HostingEnvironment.ApplicationVirtualPath;

            // Get <sessionState> configuration element
            var webConfig = WebConfigurationManager.OpenWebConfiguration(_applicationName);
            _sessionStateSection = (SessionStateSection)webConfig.GetSection("system.web/sessionState");

            // Initialize WriteExceptionsToEventLog
            if (string.Equals(config["writeExceptionsToEventLog"], bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Inject custom logging to the cache client?
            }
        }
        void initData()
        {
            client = new MemcachedClient();

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = "RiakSessionStateStore";

            base.Initialize(name, config);

            ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
            _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            var container = UnityBootstrapper.Bootstrap();
            _client = container.Resolve<IRiakClient>();

            var riakSessionConfiguration = container.Resolve<RiakSessionStateConfiguration>();
            int expiredSessionDeletionInterval = riakSessionConfiguration.TimeoutInMilliseconds;

            _expiredSessionDeletionTimer = new System.Timers.Timer(expiredSessionDeletionInterval);
            _expiredSessionDeletionTimer.Elapsed += ExpiredSessionDeletionTimerElapsed;
            _expiredSessionDeletionTimer.Enabled = true;
            _expiredSessionDeletionTimer.AutoReset = true;
        }
        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);

            _applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
            if (config["writeExceptionsToEventLog"] != null)
            {
                if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
                    _logExceptions = true;
            }
        }
示例#9
0
		public static void CacheTests_Initialize(TestContext testContext)
		{
			_SessionIdManager = new System.Web.SessionState.SessionIDManager();

			_SessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
			_ProviderSettings = (ProviderSettings)_SessionStateSection.Providers[_SessionStateSection.CustomProvider];
			_TimeoutInSeconds = (int)_SessionStateSection.Timeout.TotalSeconds;

			UpdateHostingEnvironment();
		}
        void initData() {
            _providerSettings = SessionProviderSettings.GetSettings();

            var url = new MongoUrl(ConfigurationManager.ConnectionStrings["SessionDB"].ConnectionString);
            var client = new MongoClient(url);
            var database = client.GetServer().GetDatabase(url.DatabaseName);
            collection = database.GetCollection<MongoDBSessionDo>(_providerSettings.SessionProfix, WriteConcern.Unacknowledged);

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            var configuration = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            this.sessionStateSection = configuration.GetSection("system.web/sessionState") as SessionStateSection;

            this.mongoCollection = MongoServer.Create(config["connectionString"] ?? "mongodb://localhost").GetDatabase(config["database"] ?? "ASPNETDB").GetCollection(config["collection"] ?? "SessionState");
            this.mongoCollection.EnsureIndex("applicationVirtualPath", "id");
            this.mongoCollection.EnsureIndex("applicationVirtualPath", "id", "lockId");

            base.Initialize(name, config);
        }
        public override void Initialize(string name, NameValueCollection settings)
        {
            var config = DependencyResolver.Current.GetService<IConfig>();

            var configuration = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            this.sessionStateSection = configuration.GetSection("system.web/sessionState") as SessionStateSection;

            this.mongoCollection = ConnectionUtils.GetCollection(settings, config, "SessionState");
            this.mongoCollection.EnsureIndex("applicationVirtualPath", "id");
            this.mongoCollection.EnsureIndex("applicationVirtualPath", "id", "lockId");

            base.Initialize(name, settings);
        }
        private static void Validate(object value) {
            if (value == null) {
                throw new ArgumentNullException("sessionState");
            }
            Debug.Assert(value is SessionStateSection);

            SessionStateSection elem = (SessionStateSection)value;

            if (elem.Timeout.TotalMinutes > SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES &&
                (elem.Mode == SessionStateMode.InProc ||
                elem.Mode == SessionStateMode.StateServer)) {
                throw new ConfigurationErrorsException(
                    SR.GetString(SR.Invalid_cache_based_session_timeout),
                    elem.ElementInformation.Properties["timeout"].Source,
                    elem.ElementInformation.Properties["timeout"].LineNumber);
            }
        }
        /// <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;
        }
示例#15
0
		public void Init (HttpApplication app)
		{
			config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");

			ProviderSettings settings;
			switch (config.Mode) {
				case SessionStateMode.Custom:
					settings = config.Providers [config.CustomProvider];
					if (settings == null)
						throw new HttpException (String.Format ("Cannot find '{0}' provider.", config.CustomProvider));
					break;
				case SessionStateMode.Off:
					return;
				case SessionStateMode.InProc:
					settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
					break;

				case SessionStateMode.SQLServer:
					settings = new ProviderSettings (null, typeof (SessionSQLServerHandler).AssemblyQualifiedName);
					break;

				case SessionStateMode.StateServer:
					settings = new ProviderSettings (null, typeof (SessionStateServerHandler).AssemblyQualifiedName);
					break;

				default:
					throw new NotImplementedException (String.Format ("The mode '{0}' is not implemented.", config.Mode));
			
			}

			handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));

			if (String.IsNullOrEmpty(config.SessionIDManagerType)) {
				idManager = new SessionIDManager ();
			} else {
				Type idManagerType = HttpApplication.LoadType (config.SessionIDManagerType, true);
				idManager = (ISessionIDManager)Activator.CreateInstance (idManagerType);
			}

			try {				
				idManager.Initialize ();
			} catch (Exception ex) {
				throw new HttpException ("Failed to initialize session ID manager.", ex);
			}

			supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
			HttpRuntimeSection runtime = HttpRuntime.Section;
			executionTimeout = runtime.ExecutionTimeout;
			//executionTimeoutMS = executionTimeout.Milliseconds;

			this.app = app;

			app.BeginRequest += new EventHandler (OnBeginRequest);
			app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
			app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
			app.EndRequest += new EventHandler (OnEndRequest);
		}
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            try
            {
                if (config == null)
                    throw new ArgumentNullException("config");

                Logger.Debug("Beginning Initialize. Name= {0}. Config={1}.",
                    name, config.AllKeys.Aggregate("", (aggregate, next) => aggregate + next + ":" + config[next]));

                if (string.IsNullOrEmpty(name))
                    name = "RavenSessionStateStore";

                base.Initialize(name, config);

                if (config["retriesOnConcurrentConflicts"] != null)
                {
                    int retriesOnConcurrentConflicts;
                    if (int.TryParse(config["retriesOnConcurrentConflicts"], out retriesOnConcurrentConflicts))
                        _retriesOnConcurrentConflicts = retriesOnConcurrentConflicts;
                }

                if (string.IsNullOrEmpty(ApplicationName))
                    ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

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

                if (_documentStore == null)
                {
                    if (string.IsNullOrEmpty(config["connectionStringName"]))
                        throw new ConfigurationErrorsException("Must supply a connectionStringName.");

                    _documentStore = new DocumentStore
                                         {
                                             ConnectionStringName = config["connectionStringName"],
                                             Conventions = {FindIdentityProperty = q => q.Name == "SessionId"}
                                         };
                    _documentStore.Initialize();
                }

                Logger.Debug("Completed Initalize.");

            }
            catch(Exception ex)
            {
                Logger.ErrorException("Error while initializing.", ex);
                throw;
            }
        }
    /// <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"] = "MySQL 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.
      connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
      if (connectionStringSettings == null || connectionStringSettings.ConnectionString.Trim() == "")
        throw new HttpException("Connection string can not be blank");
      connectionString = connectionStringSettings.ConnectionString;

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

      enableExpireCallback = false;

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

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

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

      // Add  cleanup interval
      MySqlTransaction mySqlTransaction = null;
      try
      {
        using (MySqlConnection conn = new MySqlConnection(connectionString))
        {
          MySqlCommand cmd = new MySqlCommand(
              "INSERT IGNORE INTO my_aspnet_sessioncleanup SET" +
              " ApplicationId = @ApplicationId, " +
              " LastRun = NOW(), " +
              " IntervalMinutes = 10",
             conn);
          cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId);
          conn.Open();
          mySqlTransaction = conn.BeginTransaction();
          cmd.ExecuteNonQuery();
          mySqlTransaction.Commit();
          cleanupInterval = GetCleanupInterval(conn, ApplicationId);
        }
      }
      catch (MySqlException e)
      {
        if (mySqlTransaction != null)
        {
          try
          {
            Trace.WriteLine("Initialize: Attempt to rollback");
            mySqlTransaction.Rollback();
          }
          catch (MySqlException ex)
          {
            HandleMySqlException(ex, "Initialize: Rollback Failed");
          }
        }
        HandleMySqlException(e, "Initialize");
      }
      finally
      {
        if (mySqlTransaction != null)
          mySqlTransaction.Dispose();
      }

   
      // Setup the cleanup timer
      if (cleanupInterval <= 0)
        cleanupInterval = 1;
      cleanupTimer = new Timer(new TimerCallback(CleanupOldSessions), null, 0,
          cleanupInterval * 1000 * 60);
    }
        /// <summary>
        /// ProviderBase.Initialize メソッド
        /// http://msdn.microsoft.com/ja-jp/library/system.configuration.provider.providerbase.initialize.aspx
        /// SessionStateStoreProviderを初期化する。
        /// web.configのsessionStateのprovidersのadd要素から初期化
        /// </summary>
        /// <param name="name">名称属性</param>
        /// <param name="config">追加属性の取得</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            // web.configのsessionStateの
            // providersのadd要素から初期化する。

            // config引数がnullの時、
            if (config == null)
            {
                // 例外
                throw new ArgumentNullException("config");
            }

            // 名称属性がNullOrEmptyの時、
            if (string.IsNullOrEmpty(name))
            {
                // デフォルトの設定
                name = "CstSqlSessionStateProvider";
            }

            // 追加属性(description)がNullOrEmptyの時、
            if (String.IsNullOrEmpty(config["description"]))
            {
                // デフォルトの設定
                config.Remove("description");
                config.Add("description", "Custom Sql Session State Provider");
            }

            // ベースの初期化
            base.Initialize(name, config);

            // アプリケーション名
            this._applicationName =
              System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

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

            this._sessionStateConfig =
              (SessionStateSection)configuration.GetSection("system.web/sessionState");

            // 接続文字列を初期化
            this._connectionStringSettings =
              ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

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

            this.ConnectionString = this._connectionStringSettings.ConnectionString;

            // ログの出力
            this._writeExceptionsToEventLog = false;

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

            // 定期的にデータを削除するスレッドを起動
            DeleteExpireSessionPeriodicallyStart();
        }
示例#19
0
        IPartitionResolver InitPartitionResolver(SessionStateSection config) {
            string  partitionResolverType = config.PartitionResolverType;
            Type    resolverType;
            IPartitionResolver  iResolver;

            if (String.IsNullOrEmpty(partitionResolverType)) {
                return null;
            }

            if (config.Mode != SessionStateMode.StateServer &&
                config.Mode != SessionStateMode.SQLServer) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Cant_use_partition_resolve),
                        config.ElementInformation.Properties["partitionResolverType"].Source, config.ElementInformation.Properties["partitionResolverType"].LineNumber);
            }


            resolverType = ConfigUtil.GetType(partitionResolverType, "partitionResolverType", config);
            ConfigUtil.CheckAssignableType(typeof(IPartitionResolver), resolverType, config, "partitionResolverType");

            iResolver = (IPartitionResolver)HttpRuntime.CreatePublicInstance(resolverType);
            iResolver.Initialize();

            return iResolver;
        }
示例#20
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);
		}
 private void OneTimeInit()
 {
     SessionStateSection sessionState = RuntimeConfig.GetAppConfig().SessionState;
     s_appPath = HostingEnvironment.ApplicationVirtualPathObject.VirtualPathString;
     s_iSessionId = s_appPath.Length;
     s_config = sessionState;
 }
        /// <summary>
        /// 공급자를 초기화합니다.
        /// </summary>
        /// <param name="name">공급자의 이름입니다.</param><param name="config">이 공급자에 대해 구성에 지정된 공급자별 특성을 나타내는 이름/값 쌍의 컬렉션입니다.</param>
        /// <exception cref="T:System.ArgumentNullException">공급자 이름이 null인 경우</exception><exception cref="T:System.ArgumentException">공급자 이름의 길이가 0인 경우</exception>
        /// <exception cref="T:System.InvalidOperationException">공급자가 이미 초기화된 후 공급자에 대해 <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/>를 호출하려고 한 경우</exception>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {
            if(IsDebugEnabled)
                log.Debug("MemcachedSessionStateStoreProvider를 초기화를 시작합니다... name=[{0}], config=[{1}]", name,
                          config.CollectionToString());

            if(name.IsWhiteSpace())
                name = GetType().Name;

            base.Initialize(name, config);

            var applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            _sessionStateSection =
                (SessionStateSection)WebConfigurationManager.OpenWebConfiguration(applicationName).GetSection(SessionStateSectionNode);

            _sessionTimeout = _sessionStateSection.Timeout;

            if(log.IsInfoEnabled)
                log.Info("MemcachedSessionStateStoreProvider 초기화를 완료했습니다!!! applicationName=[{0}], _sessionStateSection=[{1}]",
                         applicationName, _sessionStateSection);
        }
 public void Initialize()
 {
     if (pConfig == null)
     {
         Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
         pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");
     }
 }
示例#24
0
        static bool CheckTrustLevel(SessionStateSection config) {
            switch (config.Mode) {
                case SessionStateMode.SQLServer:
                case SessionStateMode.StateServer:
                    return HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium);

                default:
                case SessionStateMode.Off:
                case SessionStateMode.InProc: // In-proc session doesn't require any trust level (part of ASURT 124513)
                    return true;
            }
        }
示例#25
0
        void InitModuleFromConfig(HttpApplication app, SessionStateSection config) {
            if (config.Mode == SessionStateMode.Off) {
                return;
            }

            app.AddOnAcquireRequestStateAsync(
                    new BeginEventHandler(this.BeginAcquireState),
                    new EndEventHandler(this.EndAcquireState));

            app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
            app.EndRequest += new EventHandler(this.OnEndRequest);

            _partitionResolver = InitPartitionResolver(config);

            switch (config.Mode) {
                case SessionStateMode.InProc:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new InProcSessionStateStore();
                    _store.Initialize(null, null);
                    break;

#if !FEATURE_PAL // FEATURE_PAL does not enable out of proc session state
                case SessionStateMode.StateServer:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new OutOfProcSessionStateStore();
                    ((OutOfProcSessionStateStore)_store).Initialize(null, null, _partitionResolver);
                    break;

                case SessionStateMode.SQLServer:
                    _store = new SqlSessionStateStore();
                    ((SqlSessionStateStore)_store).Initialize(null, null, _partitionResolver);
#if DBG
                    ((SqlSessionStateStore)_store).SetModule(this);
#endif
                    break;
#else // !FEATURE_PAL
                case SessionStateMode.StateServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;

                case SessionStateMode.SQLServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;
#endif // !FEATURE_PAL

                case SessionStateMode.Custom:
                    _store = InitCustomStore(config);
                    break;

                default:
                    break;
            }

            // We depend on SessionIDManager to manage session id
            _idManager = InitSessionIDManager(config);

            if ((config.Mode == SessionStateMode.InProc || config.Mode == SessionStateMode.StateServer) &&
                _usingAspnetSessionIdManager) {
                // If we're using InProc mode or StateServer mode, and also using our own session id module,
                // we know we don't care about impersonation in our all session state store read/write
                // and session id read/write.
                _ignoreImpersonation = true;
            }

        }
示例#26
0
        ISessionIDManager InitSessionIDManager(SessionStateSection config) {
            string  sessionIDManagerType = config.SessionIDManagerType;
            ISessionIDManager  iManager;

            if (String.IsNullOrEmpty(sessionIDManagerType)) {
                iManager = new SessionIDManager();
                _usingAspnetSessionIdManager = true;
            }
            else {
                Type    managerType;

                managerType = ConfigUtil.GetType(sessionIDManagerType, "sessionIDManagerType", config);
                ConfigUtil.CheckAssignableType(typeof(ISessionIDManager), managerType, config, "sessionIDManagerType");

                iManager = (ISessionIDManager)HttpRuntime.CreatePublicInstance(managerType);
            }

            iManager.Initialize();

            return iManager;
        }
示例#27
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;
		}
示例#28
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"] = "MySQL 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.
              connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
              if (connectionStringSettings == null || connectionStringSettings.ConnectionString.Trim() == "")
            throw new HttpException("Connection string can not be blank");
              connectionString = connectionStringSettings.ConnectionString;

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

              // Make sure we have the correct schema.
              SchemaManager.CheckSchema(connectionString, config);
              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>
        /// Initialise the session state store.
        /// </summary>
        /// <param name="name">session state store name. Defaults to "MongoSessionStateStore" if not supplied</param>
        /// <param name="config">configuration settings</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 = "MongoSessionStateStore";

            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);

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

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

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

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

            _connectionString = _connectionStringSettings.ConnectionString;

            // Initialize WriteExceptionsToEventLog
            _writeExceptionsToEventLog = false;

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

            // Initialise safe mode options. Defaults to Safe Mode=true, fsynch=false, w=0 (replicas to write to before returning)
            bool safeModeEnabled = true;

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

            int replicasToWrite = 0;
            if (config["replicasToWrite"] != null)
            {
                if (!int.TryParse(config["replicasToWrite"], out replicasToWrite))
                    throw new ProviderException("Replicas To Write must be a valid integer");
            }

            _safeMode = SafeMode.Create(safeModeEnabled, fsync, replicasToWrite);
        }
        public static void Main()
        {
            try
            {
                // <Snippet1>
                // Get the Web application configuration object.
                System.Configuration.Configuration configuration =
                    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnetTest");

                // Get the section related object.
                System.Web.Configuration.SessionStateSection sessionStateSection =
                    (System.Web.Configuration.SessionStateSection)
                    configuration.GetSection("system.web/sessionState");
                // </Snippet1>

                // <Snippet2>
                // Display the current AllowCustomSqlDatabase property value.
                Console.WriteLine("AllowCustomSqlDatabase: {0}",
                                  sessionStateSection.AllowCustomSqlDatabase);
                // </Snippet2>

                // <Snippet3>
                // Display the current RegenerateExpiredSessionId property value.
                Console.WriteLine("RegenerateExpiredSessionId: {0}",
                                  sessionStateSection.RegenerateExpiredSessionId);
                // </Snippet3>

                // <Snippet4>
                // Display the current CustomProvider property value.
                Console.WriteLine("CustomProvider: {0}",
                                  sessionStateSection.CustomProvider);
                // </Snippet4>

                // <Snippet5>
                // Display the current CookieName property value.
                Console.WriteLine("CookieName: {0}",
                                  sessionStateSection.CookieName);
                // </Snippet5>

                // <Snippet6>
                // Display the current StateNetworkTimeout property value.
                Console.WriteLine("StateNetworkTimeout: {0}",
                                  sessionStateSection.StateNetworkTimeout);
                // </Snippet6>

                // <Snippet7>
                // Display the current Cookieless property value.
                Console.WriteLine("Cookieless: {0}",
                                  sessionStateSection.Cookieless);
                // </Snippet7>

                // <Snippet8>
                // Display the current SqlConnectionString property value.
                Console.WriteLine("SqlConnectionString: {0}",
                                  sessionStateSection.SqlConnectionString);
                // </Snippet8>

                // <Snippet9>
                // Display the current StateConnectionString property value.
                Console.WriteLine("StateConnectionString: {0}",
                                  sessionStateSection.StateConnectionString);
                // </Snippet9>

                // <Snippet10>
                // Display elements of the Providers collection property.
                foreach (ProviderSettings providerItem in sessionStateSection.Providers)
                {
                    Console.WriteLine();
                    Console.WriteLine("Provider Details:");
                    Console.WriteLine("Name: {0}", providerItem.Name);
                    Console.WriteLine("Type: {0}", providerItem.Type);
                }
                // </Snippet10>

                // <Snippet11>
                // Display the current Timeout property value.
                Console.WriteLine("Timeout: {0}",
                                  sessionStateSection.Timeout);
                // </Snippet11>

                // <Snippet13>
                // Display the current SqlCommandTimeout property value.
                Console.WriteLine("SqlCommandTimeout: {0}",
                                  sessionStateSection.SqlCommandTimeout);
                // </Snippet13>

                // <Snippet14>
                // Display the current Mode property value.
                Console.WriteLine("Mode: {0}",
                                  sessionStateSection.Mode);
                // </Snippet14>
            }
            catch (System.ArgumentException)
            {
                // Unknown error.
                Console.WriteLine("A invalid argument exception detected in " +
                                  "UsingSessionStateSection Main. Check your command line" +
                                  "for errors.");
            }
            Console.ReadLine();
        }
    /// <summary>
    /// Initializes the provider.
    /// </summary>
    /// <param name="name">The friendly name of the provider.</param>
    /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
    /// <exception cref="System.Configuration.ConfigurationErrorsException">
    /// Both parmeters connectionString and connectionStringName can not be specified
    /// or
    /// Either connectionString or connectionStringName parameter must be specified
    /// or
    /// </exception>
    public override void Initialize(string name, NameValueCollection config)
    {
      var configuration = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
      SessionStateSection = configuration.GetSection("system.web/sessionState") as SessionStateSection;

      var connString = config["connectionString"];
      var connStringName = config["connectionStringName"];

      if ((connString != null) && (connStringName != null))
      {
        throw new ConfigurationErrorsException("Both parmeters connectionString and connectionStringName can not be specified");
      }

      if (connString == null)
      {
        if (connStringName == null)
        {
          throw new ConfigurationErrorsException("Either connectionString or connectionStringName parameter must be specified");
        }

        var settings = ConfigurationManager.ConnectionStrings[connStringName];
        if (settings == null)
        {
          throw new ConfigurationErrorsException(string.Format("Connection string {0} not found", connStringName));
        }
        connString = settings.ConnectionString;
      }

      MongoCollection = new MongoClient(connString).GetServer().GetDatabase(config["database"] ?? "ASPNETDB").GetCollection(config["collection"] ?? "SessionState");
      MongoCollection.CreateIndex("applicationVirtualPath", "id");
      MongoCollection.CreateIndex("applicationVirtualPath", "id", "lockId");

      base.Initialize(name, config);
    }
        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"];
            }
        }
示例#33
0
        // Create an instance of the custom store as specified in the config file
        SessionStateStoreProviderBase InitCustomStore(SessionStateSection config) {
            string          providerName = config.CustomProvider;
            ProviderSettings  ps;

            if (String.IsNullOrEmpty(providerName)) {
                throw new ConfigurationErrorsException(
                        SR.GetString(SR.Invalid_session_custom_provider, providerName),
                        config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }

            ps = config.Providers[providerName];
            if (ps == null) {
                throw new ConfigurationErrorsException(
                        SR.GetString(SR.Missing_session_custom_provider, providerName),
                        config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }

            return SecureInstantiateProvider(ps);
        }