Esempio n. 1
0
        private static void InitializeDefaultProvider(RoleManagerSection settings)
        {
            bool canInitializeDefaultProvider = (!HostingEnvironment.IsHosted || BuildManager.PreStartInitStage == PreStartInitStage.AfterPreStartInit);

            if (!s_InitializedDefaultProvider && canInitializeDefaultProvider)
            {
                Debug.Assert(s_Providers != null);
                s_Providers.SetReadOnly();

                if (settings.DefaultProvider == null)
                {
                    s_InitializeException = new ProviderException(SR.GetString(SR.Def_role_provider_not_specified));
                }
                else
                {
                    try {
                        s_Provider = s_Providers[settings.DefaultProvider];
                    }
                    catch { }
                }

                if (s_Provider == null)
                {
                    s_InitializeException = new ConfigurationErrorsException(SR.GetString(SR.Def_role_provider_not_found), settings.ElementInformation.Properties["defaultProvider"].Source, settings.ElementInformation.Properties["defaultProvider"].LineNumber);
                }

                s_InitializedDefaultProvider = true;
            }
        }
Esempio n. 2
0
        private static void InitializeSettings(RoleManagerSection settings)
        {
            if (!s_Initialized)
            {
                s_Providers = new RoleProviderCollection();

                if (HostingEnvironment.IsHosted)
                {
                    ProvidersHelper.InstantiateProviders(settings.Providers, s_Providers, typeof(RoleProvider));
                }
                else
                {
                    foreach (ProviderSettings ps in settings.Providers)
                    {
                        Type t = Type.GetType(ps.Type, true, true);
                        if (!typeof(RoleProvider).IsAssignableFrom(t))
                        {
                            throw new ArgumentException(SR.GetString(SR.Provider_must_implement_type, typeof(RoleProvider).ToString()));
                        }
                        RoleProvider        provider    = (RoleProvider)Activator.CreateInstance(t);
                        NameValueCollection pars        = ps.Parameters;
                        NameValueCollection cloneParams = new NameValueCollection(pars.Count, StringComparer.Ordinal);
                        foreach (string key in pars)
                        {
                            cloneParams[key] = pars[key];
                        }
                        provider.Initialize(ps.Name, cloneParams);
                        s_Providers.Add(provider);
                    }
                }
            }
        }
        public void Init(HttpApplication app)
        {
            _config = (RoleManagerSection)WebConfigurationManager.GetSection("system.web/roleManager");

            app.PostAuthenticateRequest += OnPostAuthenticateRequest;
            app.EndRequest += OnEndRequest;
        }
Esempio n. 4
0
        /// <summary>
        /// Get the connection string for the provider.
        /// </summary>
        /// <param name="providerName">The name of the provider.</param>
        /// <returns>The connection string.</returns>
        private string GetConnectionString(string providerName)
        {
            string connStr = string.Empty;

            try
            {
                RoleManagerSection configSection = (RoleManagerSection)HttpContext.Current.GetSection("system.web/roleManager");

                ProviderSettings providerItem = configSection.Providers[providerName];
                if (providerItem != null)
                {
                    string connStrName = providerItem.Parameters["connectionStringName"];
                    if (!string.IsNullOrEmpty(connStrName))
                    {
                        connStr = WebConfigurationManager.ConnectionStrings[connStrName].ConnectionString;
                    }
                }
            }
            catch (Exception e)
            {
                ULS.LogError("SqlSiteRoleProvider.GetConnectionString", "No Connection String Retrieved for provider name: " + providerName + "\n" + e.ToString(), "RoleProvider");
                throw new ProviderException(e.ToString());
            }

            return(connStr);
        }
Esempio n. 5
0
 private static void InitializeSettings(RoleManagerSection settings)
 {
     if (!s_Initialized)
     {
         s_Providers = new RoleProviderCollection();
         if (HostingEnvironment.IsHosted)
         {
             ProvidersHelper.InstantiateProviders(settings.Providers, s_Providers, typeof(RoleProvider));
         }
         else
         {
             foreach (ProviderSettings settings2 in settings.Providers)
             {
                 Type c = Type.GetType(settings2.Type, true, true);
                 if (!typeof(RoleProvider).IsAssignableFrom(c))
                 {
                     throw new ArgumentException(System.Web.SR.GetString("Provider_must_implement_type", new object[] { typeof(RoleProvider).ToString() }));
                 }
                 RoleProvider        provider   = (RoleProvider)Activator.CreateInstance(c);
                 NameValueCollection parameters = settings2.Parameters;
                 NameValueCollection config     = new NameValueCollection(parameters.Count, StringComparer.Ordinal);
                 foreach (string str in parameters)
                 {
                     config[str] = parameters[str];
                 }
                 provider.Initialize(settings2.Name, config);
                 s_Providers.Add(provider);
             }
         }
     }
 }
Esempio n. 6
0
        private void RegisterProviders(IUnityContainer container)
        {
            // 身份
            MembershipProviderCollection mProviders = new MembershipProviderCollection();
            MembershipSection            mSection   =
                (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");

            foreach (ProviderSettings settings in mSection.Providers)
            {
                if (settings.Parameters["connectionStringName"] != null)
                {
                    settings.Parameters["connectionStringName"] = D.NamedSection.DataConnection;
                }
            }

            ProvidersHelper.InstantiateProviders(
                mSection.Providers, mProviders, typeof(MembershipProvider));
            MembershipProvider mProvider = mProviders[mSection.DefaultProvider];

            // 角色

            RoleProviderCollection rProviders = new RoleProviderCollection();
            RoleManagerSection     rSection   =
                (RoleManagerSection)WebConfigurationManager.GetSection("system.web/roleManager");

            foreach (ProviderSettings settings in rSection.Providers)
            {
                if (settings.Parameters["connectionStringName"] != null)
                {
                    settings.Parameters["connectionStringName"] = D.NamedSection.DataConnection;
                }
            }

            ProvidersHelper.InstantiateProviders(
                rSection.Providers, rProviders, typeof(RoleProvider));
            RoleProvider rProvider = rProviders[rSection.DefaultProvider];

            // 配置

            ProfileProviderCollection pProviders = new ProfileProviderCollection();
            ProfileSection            pSection   =
                (ProfileSection)WebConfigurationManager.GetSection("system.web/profile");

            foreach (ProviderSettings settings in pSection.Providers)
            {
                if (settings.Parameters["connectionStringName"] != null)
                {
                    settings.Parameters["connectionStringName"] = D.NamedSection.DataConnection;
                }
            }

            ProvidersHelper.InstantiateProviders(
                pSection.Providers, pProviders, typeof(ProfileProvider));
            ProfileProvider pProvider = pProviders[pSection.DefaultProvider];

            container.RegisterInstance <MembershipProvider>(mProvider);
            container.RegisterInstance <RoleProvider>(rProvider);
            container.RegisterInstance <ProfileProvider>(pProvider);
        }
Esempio n. 7
0
        public static ProviderSettings GetRoleProvider(string providerName)
        {
            Configuration              config      = WebConfigurationManager.OpenWebConfiguration("~/");
            RoleManagerSection         section     = (RoleManagerSection)config.GetSection("system.web/roleManager");
            ProviderSettingsCollection settingsCol = section.Providers;

            return(settingsCol[providerName]);
        }
        protected override void SetupDependencies()
        {
            base.SetupDependencies();

            var roleManagerSection = new RoleManagerSection();

            RegisterDependency(roleManagerSection);
        }
Esempio n. 9
0
        public MemberShipService()
        {
            _membershipSection = (MembershipSection)ConfigurationManager.GetSection("system.web/membership");

            _memberShipSettingsProvider = _membershipSection.Providers[_membershipSection.DefaultProvider];
            _roleManagerSection         = (RoleManagerSection)ConfigurationManager.GetSection("system.web/roleManager");
            _roleProviderSettings       = _roleManagerSection.Providers[_roleManagerSection.DefaultProvider];

            _membershipParameters  = _memberShipSettingsProvider.Parameters;
            _rolemanagerParameters = _roleProviderSettings.Parameters;
        }
Esempio n. 10
0
        protected override void LoadStaticConfiguration()
        {
            base.LoadStaticConfiguration();

            ConnectionStringSettings css = new ConnectionStringSettings();

            css.ConnectionString = String.Format(
                "server={0};uid={1};password={2};database={3};pooling=false",
                BaseTest.host, BaseTest.user, BaseTest.password, BaseTest.database0);
            css.Name = "LocalMySqlServer";
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.ConnectionStrings.ConnectionStrings.Add(css);

            MembershipSection ms = (MembershipSection)config.SectionGroups["system.web"].Sections["membership"];

            ms.DefaultProvider = "MySQLMembershipProvider";
            ProviderSettings ps = new ProviderSettings();

            ps.Name = "MySQLMembershipProvider";
            Assembly a = Assembly.GetAssembly(typeof(MySQLMembershipProvider));

            ps.Type = "MySql.Web.Security.MySQLMembershipProvider, " + a.FullName;
            ps.Parameters.Add("connectionStringName", "LocalMySqlServer");
            ps.Parameters.Add("enablePasswordRetrieval", "false");
            ps.Parameters.Add("enablePasswordReset", "true");
            ps.Parameters.Add("requiresQuestionAndAnswer", "true");
            ps.Parameters.Add("applicationName", "/");
            ps.Parameters.Add("requiresUniqueEmail", "false");
            ps.Parameters.Add("passwordFormat", "Hashed");
            ps.Parameters.Add("maxInvalidPasswordAttempts", "5");
            ps.Parameters.Add("minRequiredPasswordLength", "7");
            ps.Parameters.Add("minRequiredNonalphanumericCharacters", "1");
            ps.Parameters.Add("passwordAttemptWindow", "10");
            ps.Parameters.Add("passwordStrengthRegularExpression", "");
            ms.Providers.Add(ps);

            RoleManagerSection rs = (RoleManagerSection)config.SectionGroups["system.web"].Sections["roleManager"];

            rs.DefaultProvider = "MySQLRoleProvider";
            rs.Enabled         = true;
            ps      = new ProviderSettings();
            ps.Name = "MySQLRoleProvider";
            a       = Assembly.GetAssembly(typeof(MySQLRoleProvider));
            ps.Type = "MySql.Web.Security.MySQLRoleProvider, " + a.FullName;
            ps.Parameters.Add("connectionStringName", "LocalMySqlServer");
            ps.Parameters.Add("applicationName", "/");
            rs.Providers.Add(ps);

            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");
            ConfigurationManager.RefreshSection("system.web/membership");
            ConfigurationManager.RefreshSection("system.web/roleManager");
        }
Esempio n. 11
0
 public bool IsRoleManagerEnabled()
 {
     try {
         RoleManagerSection roleSection = null;
         Configuration      config      = OpenWebConfiguration(ApplicationPath);
         roleSection = (RoleManagerSection)config.GetSection("system.web/roleManager");
         return(roleSection.Enabled);
     } catch {
         return(false);
     }
 }
Esempio n. 12
0
        protected override ProviderSettings GetMachineSettings()
        {
            Configuration      machineConfig = ConfigurationManager.OpenMachineConfiguration();
            RoleManagerSection section       = (RoleManagerSection)machineConfig.SectionGroups["system.web"].Sections[sectionName];

            foreach (ProviderSettings p in section.Providers)
            {
                if (p.Type.Contains(typeName))
                {
                    return(p);
                }
            }
            return(null);
        }
        // It test all existing (as of r61933) configuration
        // sections that use PropertyHelper.NonEmptyStringValidator.
        public void NullableStringProperties()
        {
            new AnonymousIdentificationSection().CookieName = null;
            new AnonymousIdentificationSection().CookiePath = null;
            new AssemblyInfo(null);
            new BufferModeSettings(null, 0x10000, 0x1000, 10,
                                   TimeSpan.FromMinutes(1),
                                   TimeSpan.FromSeconds(30), 10);
            new BuildProvider(null, null);
            new ClientTarget(null, null);
            new CodeSubDirectory(null);
            new EventMappingSettings(null, null);
            new ExpressionBuilder(null, null);
            FormsAuthenticationConfiguration fac =
                new FormsAuthenticationConfiguration();

            // I don't like this test though.
            fac.DefaultUrl = null;
            fac.LoginUrl   = null;
            fac.Name       = null;
            fac.Path       = null;
            new HttpHandlerAction(null, null, null);
            new HttpModuleAction(null, null);
            MachineKeySection mks = new MachineKeySection();

            // algorithms are limited
            // mks.Decryption = null;
            mks.DecryptionKey = null;
            mks.ValidationKey = null;
            new MembershipSection().DefaultProvider = null;
            new NamespaceInfo(null);
            new OutputCacheProfile(null);
            new ProfileSettings(null);
            RoleManagerSection rms = new RoleManagerSection();

            rms.CookieName      = null;
            rms.CookiePath      = null;
            rms.DefaultProvider = null;
            new RuleSettings(null, null, null);
            new SqlCacheDependencyDatabase(null, null);
            new TagMapInfo(null, null);
            new TagPrefixInfo(null, null, null, null, null);
            new TransformerInfo(null, null);
            new TrustLevel(null, null);
            new TrustSection().Level = null;
            new UrlMapping(null, null);
            // WebControlsSection.ClientScriptsLocation is not settable
            new WebPartsPersonalization().DefaultProvider = null;
        }
Esempio n. 14
0
        protected void EnsureApplicationNameSpecified(out string appName)
        {
            string mem   = null;
            string roles = null;

            // Membership
            try
            {
                MembershipSection section          = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
                string            defaultProvider  = section.DefaultProvider;
                ProviderSettings  providerSettings = section.Providers[defaultProvider];
                mem = providerSettings.Parameters["applicationName"];
            }
            catch (Exception)
            {
                throw new Exception(Membership_missing_application_name);
            }
            if (null == mem)
            {
                throw new Exception(Membership_missing_application_name);
            }


            // Roles
            try
            {
                RoleManagerSection section          = (RoleManagerSection)WebConfigurationManager.GetSection("system.web/roleManager");
                string             defaultProvider  = section.DefaultProvider;
                ProviderSettings   providerSettings = section.Providers[defaultProvider];
                roles = providerSettings.Parameters["applicationName"];
            }
            catch (Exception)
            {
                throw new Exception(Roles_missing_application_name);
            }
            if (null == roles)
            {
                throw new Exception(Roles_missing_application_name);
            }


            // match?
            if (roles != mem)
            {
                throw new Exception(Application_names_must_match);
            }

            appName = mem;
        }
        void ProcessReplace(RoleManagerSection section, SettingsMappingWhatContents how)
        {
            string name, type;

            if (!GetCommonAttributes(how, out name, out type))
            {
                return;
            }

            ProviderSettings provider = section.Providers [name];

            if (provider != null)
            {
                SetProviderProperties(how, provider);
            }
        }
Esempio n. 16
0
        internal static void EnableRoleManager()
        {
            try
            {
                //Get the role manager section.
                RoleManagerSection roleManagerSection = (RoleManagerSection)ConfigurationManager.GetSection("system.web/roleManager");

                //Use reflection to enable changing it
                FieldInfo fieldInfo = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
                fieldInfo.SetValue(roleManagerSection, false);

                roleManagerSection.Enabled = true;
            }
            catch
            {}
        }
Esempio n. 17
0
        private ConfigurationRoleManagerModel ProcessRoleManager(RoleManagerSection roleManagerSection)
        {
            if (roleManagerSection == null)
            {
                return(null);
            }

            var result = new ConfigurationRoleManagerModel
            {
                CacheRolesInCookie      = roleManagerSection.CacheRolesInCookie,
                CookieName              = roleManagerSection.CookieName,
                CookiePath              = roleManagerSection.CookiePath,
                CookieProtection        = roleManagerSection.CookieProtection.ToString(),
                CookieRequireSSL        = roleManagerSection.CookieRequireSSL,
                CookieSlidingExpiration = roleManagerSection.CookieSlidingExpiration,
                CookieTimeout           = roleManagerSection.CookieTimeout,
                CreatePersistentCookie  = roleManagerSection.CreatePersistentCookie,
                DefaultProvider         = roleManagerSection.DefaultProvider,
                Domain           = roleManagerSection.Domain,
                Enabled          = roleManagerSection.Enabled,
                MaxCachedResults = roleManagerSection.MaxCachedResults
            };

            var providerSection = roleManagerSection.Providers;

            if (providerSection != null)
            {
                var resultProviders = new List <ConfigurationRoleManagerProviderSettingsModel>();
                foreach (ProviderSettings provider in providerSection)
                {
                    var resultProvider = new ConfigurationRoleManagerProviderSettingsModel
                    {
                        Name       = provider.Name,
                        Type       = provider.Type,
                        Parameters = provider.Parameters.ToDictionary()
                    };

                    resultProviders.Add(resultProvider);
                }

                result.Providers = resultProviders;
            }

            return(result);
        }
        public object MapSection(object _section, List <SettingsMappingWhat> whats)
        {
            RoleManagerSection section = _section as RoleManagerSection;

            if (section == null)
            {
                return(_section);
            }

            List <SettingsMappingWhatContents> contents;

            foreach (SettingsMappingWhat what in whats)
            {
                contents = what.Contents;
                if (contents == null || contents.Count == 0)
                {
                    continue;
                }

                foreach (SettingsMappingWhatContents item in contents)
                {
                    switch (item.Operation)
                    {
                    case SettingsMappingWhatOperation.Add:
                        ProcessAdd(section, item);
                        break;

                    case SettingsMappingWhatOperation.Clear:
                        ProcessClear(section, item);
                        break;

                    case SettingsMappingWhatOperation.Replace:
                        ProcessReplace(section, item);
                        break;

                    case SettingsMappingWhatOperation.Remove:
                        ProcessRemove(section, item);
                        break;
                    }
                }
            }

            return(section);
        }
        void ProcessRemove(RoleManagerSection section, SettingsMappingWhatContents how)
        {
            string name, type;

            if (!GetCommonAttributes(how, out name, out type))
            {
                return;
            }

            ProviderSettingsCollection providers = section.Providers;
            ProviderSettings           provider  = providers [name];

            if (provider != null)
            {
                if (provider.Type != type)
                {
                    return;
                }
                providers.Remove(name);
            }
        }
        void ProcessAdd(RoleManagerSection section, SettingsMappingWhatContents how)
        {
            string name, type;

            if (!GetCommonAttributes(how, out name, out type))
            {
                return;
            }

            ProviderSettingsCollection providers = section.Providers;
            ProviderSettings           provider  = providers [name];

            if (provider != null)
            {
                return;
            }

            ProviderSettings prov = new ProviderSettings(name, type);

            SetProviderProperties(how, prov);

            providers.Add(prov);
        }
Esempio n. 21
0
 private static void Initialize()
 {
     if (s_Initialized)
     {
         if (s_InitializeException != null)
         {
             throw s_InitializeException;
         }
         if (s_InitializedDefaultProvider)
         {
             return;
         }
     }
     lock (s_lock)
     {
         if (s_Initialized)
         {
             if (s_InitializeException != null)
             {
                 throw s_InitializeException;
             }
             if (s_InitializedDefaultProvider)
             {
                 return;
             }
         }
         try
         {
             if (HostingEnvironment.IsHosted)
             {
                 HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level");
             }
             RoleManagerSection roleManager = RuntimeConfig.GetAppConfig().RoleManager;
             if (!s_EnabledSet)
             {
                 s_Enabled = roleManager.Enabled;
             }
             s_CookieName              = roleManager.CookieName;
             s_CacheRolesInCookie      = roleManager.CacheRolesInCookie;
             s_CookieTimeout           = (int)roleManager.CookieTimeout.TotalMinutes;
             s_CookiePath              = roleManager.CookiePath;
             s_CookieRequireSSL        = roleManager.CookieRequireSSL;
             s_CookieSlidingExpiration = roleManager.CookieSlidingExpiration;
             s_CookieProtection        = roleManager.CookieProtection;
             s_Domain = roleManager.Domain;
             s_CreatePersistentCookie = roleManager.CreatePersistentCookie;
             s_MaxCachedResults       = roleManager.MaxCachedResults;
             if (s_Enabled)
             {
                 if (s_MaxCachedResults < 0)
                 {
                     throw new ProviderException(System.Web.SR.GetString("Value_must_be_non_negative_integer", new object[] { "maxCachedResults" }));
                 }
                 InitializeSettings(roleManager);
                 InitializeDefaultProvider(roleManager);
             }
         }
         catch (Exception exception)
         {
             s_InitializeException = exception;
         }
         s_Initialized = true;
     }
     if (s_InitializeException != null)
     {
         throw s_InitializeException;
     }
 }
Esempio n. 22
0
        static private void Initialize()
        {
            if (s_Initialized)
            {
                if (s_InitializeException != null)
                {
                    throw s_InitializeException;
                }
                if (s_InitializedDefaultProvider)
                {
                    return;
                }
            }

            lock (s_lock) {
                if (s_Initialized)
                {
                    if (s_InitializeException != null)
                    {
                        throw s_InitializeException;
                    }
                    if (s_InitializedDefaultProvider)
                    {
                        return;
                    }
                }

                try
                {
                    if (HostingEnvironment.IsHosted)
                    {
                        HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level);
                    }

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

            if (s_InitializeException != null)
            {
                throw s_InitializeException;
            }
        }
 public RoleManager(RoleProvider roleProvider, RoleManagerSection roleSection)
 {
     this.roleProvider = roleProvider;
     this.roleSection  = roleSection;
 }
Esempio n. 24
0
        static void Main(string[] args)
        {
            string inputStr = String.Empty;
            string option   = String.Empty;

            // Define a regular expression to allow only
            // alphanumeric inputs that are at most 20 character
            // long. For instance "/iii:".
            Regex rex = new Regex(@"[^\/w]{1,20}:");

            // Parse the user's input.
            if (args.Length < 1)
            {
                // No option entered.
                Console.Write("Input parameter missing.");
                return;
            }
            else
            {
                // Get the user's option.
                inputStr = args[0].ToLower();
                if (!(rex.Match(inputStr)).Success)
                {
                    // Wrong option format used.
                    Console.Write("Input parameter format not allowed.");
                    return;
                }
            }

            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the <system.web> group.
            SystemWebSectionGroup systemWeb =
                (SystemWebSectionGroup)configuration.GetSectionGroup("system.web");

            // </Snippet1>


            try
            {
                switch (inputStr)
                {
                case "/anonymous:":
                    // <Snippet2>
                    // Get the anonymousIdentification section.
                    AnonymousIdentificationSection
                        anonymousIdentification =
                        systemWeb.AnonymousIdentification;
                    // Read section information.
                    info =
                        anonymousIdentification.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet2>

                    Console.Write(msg);
                    break;

                case "/authentication:":

                    // <Snippet3>
                    // Get the authentication section.
                    AuthenticationSection authentication =
                        systemWeb.Authentication;
                    // Read section information.
                    info =
                        authentication.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet3>

                    Console.Write(msg);
                    break;

                case "/authorization:":

                    // <Snippet4>
                    // Get the authorization section.
                    AuthorizationSection authorization =
                        systemWeb.Authorization;
                    // Read section information.
                    info =
                        authorization.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet4>

                    Console.Write(msg);
                    break;

                case "/compilation:":

                    // <Snippet5>
                    // Get the compilation section.
                    CompilationSection compilation =
                        systemWeb.Compilation;
                    // Read section information.
                    info =
                        compilation.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet5>

                    Console.Write(msg);
                    break;


                case "/customerrors:":

                    // <Snippet6>
                    // Get the customerrors section.
                    CustomErrorsSection customerrors =
                        systemWeb.CustomErrors;
                    // Read section information.
                    info =
                        customerrors.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet6>

                    Console.Write(msg);
                    break;

                case "/globalization:":

                    // <Snippet7>
                    // Get the globalization section.
                    GlobalizationSection globalization =
                        systemWeb.Globalization;
                    // Read section information.
                    info =
                        globalization.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet7>

                    Console.Write(msg);
                    break;

                case "/httpcookies:":
                    // <Snippet8>
                    // Get the httpCookies section.
                    HttpCookiesSection httpCookies =
                        systemWeb.HttpCookies;
                    // Read section information.
                    info =
                        httpCookies.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet8>

                    Console.Write(msg);
                    break;

                case "/httphandlers:":

                    // <Snippet9>
                    // Get the httpHandlers section.
                    HttpHandlersSection httpHandlers =
                        systemWeb.HttpHandlers;
                    // Read section information.
                    info =
                        httpHandlers.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet9>

                    Console.Write(msg);
                    break;

                case "/httpmodules:":

                    // <Snippet10>
                    // Get the httpModules section.
                    HttpModulesSection httpModules =
                        systemWeb.HttpModules;
                    // Read section information.
                    info =
                        httpModules.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet10>

                    Console.Write(msg);
                    break;

                case "/httpruntime:":

                    // <Snippet11>
                    // Get the httpRuntime section.
                    HttpRuntimeSection httpRuntime =
                        systemWeb.HttpRuntime;
                    // Read section information.
                    info =
                        httpRuntime.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet11>

                    Console.Write(msg);
                    break;

                case "/identity:":

                    // <Snippet12>
                    // Get the identity section.
                    IdentitySection identity =
                        systemWeb.Identity;
                    // Read section information.
                    info =
                        identity.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet12>

                    Console.Write(msg);
                    break;

                case "/machinekey:":

                    // <Snippet13>
                    // Get the machineKey section.
                    MachineKeySection machineKey =
                        systemWeb.MachineKey;
                    // Read section information.
                    info =
                        machineKey.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet13>

                    Console.Write(msg);
                    break;

                case "/membership:":
                    // <Snippet14>
                    // Get the membership section.
                    MembershipSection membership =
                        systemWeb.Membership;
                    // Read section information.
                    info =
                        membership.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet14>

                    Console.Write(msg);
                    break;

                case "/pages:":
                    // <Snippet15>
                    // Get the pages section.
                    PagesSection pages =
                        systemWeb.Pages;
                    // Read section information.
                    info =
                        pages.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet15>

                    Console.Write(msg);
                    break;

                case "/processModel:":
                    // <Snippet16>
                    // Get the processModel section.
                    ProcessModelSection processModel =
                        systemWeb.ProcessModel;
                    // Read section information.
                    info =
                        processModel.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet16>

                    Console.Write(msg);
                    break;

                case "/profile:":
                    // <Snippet17>
                    // Get the profile section.
                    ProfileSection profile =
                        systemWeb.Profile;
                    // Read section information.
                    info =
                        profile.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet17>

                    Console.Write(msg);
                    break;

                case "/roleManager:":
                    // <Snippet18>
                    // Get the roleManager section.
                    RoleManagerSection roleManager =
                        systemWeb.RoleManager;
                    // Read section information.
                    info =
                        roleManager.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet18>

                    Console.Write(msg);
                    break;

                case "/securityPolicy:":
                    // <Snippet19>
                    // Get the securityPolicy section.
                    SecurityPolicySection securityPolicy =
                        systemWeb.SecurityPolicy;
                    // Read section information.
                    info =
                        securityPolicy.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet19>

                    Console.Write(msg);
                    break;

                case "/sessionState:":
                    // <Snippet20>
                    // Get the sessionState section.
                    SessionStateSection sessionState =
                        systemWeb.SessionState;
                    // Read section information.
                    info =
                        sessionState.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet20>

                    Console.Write(msg);
                    break;

                case "/sitemap:":
                    // <Snippet21>
                    // Get the siteMap section.
                    SiteMapSection siteMap =
                        systemWeb.SiteMap;
                    // Read section information.
                    info =
                        siteMap.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet21>

                    Console.Write(msg);
                    break;

                case "/trace:":
                    // <Snippet22>
                    // Get the trace section.
                    TraceSection trace =
                        systemWeb.Trace;
                    // Read section information.
                    info =
                        trace.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet22>

                    Console.Write(msg);
                    break;

                case "/trust:":
                    // <Snippet23>
                    // Get the trust section.
                    TrustSection trust =
                        systemWeb.Trust;
                    // Read section information.
                    info =
                        trust.SectionInformation;
                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet23>

                    Console.Write(msg);
                    break;

                case "/browserCaps:":
                    // <Snippet24>
                    // Get the browserCaps section.
                    DefaultSection browserCaps =
                        systemWeb.BrowserCaps;
                    // Read section information.
                    info =
                        browserCaps.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet24>

                    Console.Write(msg);
                    break;

                case "/clientTarget:":
                    // <Snippet25>
                    // Get the clientTarget section.
                    ClientTargetSection clientTarget =
                        systemWeb.ClientTarget;
                    // Read section information.
                    info =
                        clientTarget.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet25>

                    Console.Write(msg);
                    break;


                case "/deployment:":
                    // <Snippet26>
                    // Get the deployment section.
                    DeploymentSection deployment =
                        systemWeb.Deployment;
                    // Read section information.
                    info =
                        deployment.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet26>

                    Console.Write(msg);
                    break;


                case "/deviceFilters:":
                    // <Snippet27>
                    // Get the deviceFilters section.
                    DefaultSection deviceFilters =
                        systemWeb.DeviceFilters;
                    // Read section information.
                    info =
                        deviceFilters.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet27>

                    Console.Write(msg);
                    break;

                case "/healthMonitoring:":
                    // <Snippet28>
                    // Get the healthMonitoring section.
                    HealthMonitoringSection healthMonitoring =
                        systemWeb.HealthMonitoring;
                    // Read section information.
                    info =
                        healthMonitoring.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet28>

                    Console.Write(msg);
                    break;

                case "/hostingEnvironment:":
                    // <Snippet29>
                    // Get the hostingEnvironment section.
                    HostingEnvironmentSection hostingEnvironment =
                        systemWeb.HostingEnvironment;
                    // Read section information.
                    info =
                        hostingEnvironment.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet29>

                    Console.Write(msg);
                    break;

                case "/mobileControls:":
                    // <Snippet30>
                    // Get the mobileControls section.
                    ConfigurationSection mobileControls =
                        systemWeb.MobileControls;
                    // Read section information.
                    info =
                        mobileControls.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet30>

                    Console.Write(msg);
                    break;

                case "/protocols:":
                    // <Snippet31>
                    // Get the protocols section.
                    DefaultSection protocols =
                        systemWeb.Protocols;
                    // Read section information.
                    info =
                        protocols.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet31>

                    Console.Write(msg);
                    break;

                case "/urlMappings:":
                    // <Snippet32>
                    // Get the urlMappings section.
                    UrlMappingsSection urlMappings =
                        systemWeb.UrlMappings;
                    // Read section information.
                    info =
                        urlMappings.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet32>

                    Console.Write(msg);
                    break;

                case "/webControls:":
                    // <Snippet33>
                    // Get the webControls section.
                    WebControlsSection webControls =
                        systemWeb.WebControls;
                    // Read section information.
                    info =
                        webControls.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet33>

                    Console.Write(msg);
                    break;

                case "/webParts:":
                    // <Snippet34>
                    // Get the webParts section.
                    WebPartsSection webParts =
                        systemWeb.WebParts;
                    // Read section information.
                    info =
                        webParts.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet34>

                    Console.Write(msg);
                    break;

                case "/webServices:":
                    // <Snippet35>
                    // Get the webServices section.
                    WebServicesSection webServices =
                        systemWeb.WebServices;
                    // Read section information.
                    info =
                        webServices.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();
                    msg      = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet35>

                    Console.Write(msg);
                    break;

                case "/XhtmlConformance:":
                    // <Snippet36>
                    // Get the xhtmlConformance section.
                    XhtmlConformanceSection xhtmlConformance =
                        systemWeb.XhtmlConformance;
                    // Read section information.
                    info =
                        xhtmlConformance.SectionInformation;

                    name     = info.SectionName;
                    type     = info.Type;
                    declared = info.IsDeclared.ToString();

                    msg = String.Format(
                        "Name:     {0}\nDeclared: {1}\nType:     {2}\n",
                        name, declared, type);
                    // </Snippet36>

                    Console.Write(msg);
                    break;


                case "/all:":
                    StringBuilder             allSections    = new StringBuilder();
                    ConfigurationSectionGroup systemWebGroup =
                        configuration.GetSectionGroup("system.web");
                    int i = 0;
                    foreach (ConfigurationSection section in
                             systemWebGroup.Sections)
                    {
                        i       += 1;
                        info     = section.SectionInformation;
                        name     = info.SectionName;
                        type     = info.Type;
                        declared = info.IsDeclared.ToString();
                        if (i < 10)
                        {
                            msg = String.Format(
                                "{0})Name:   {1}\nDeclared: {2}\nType:     {3}\n",
                                i.ToString(), name, declared, type);
                        }
                        else
                        {
                            msg = String.Format(
                                "{0})Name:  {1}\nDeclared: {2}\nType:     {3}\n",
                                i.ToString(), name, declared, type);
                        }
                        allSections.AppendLine(msg);
                    }

                    // Console.WriteLine(systemWebGroup.Name);
                    // Console.WriteLine(systemWebGroup.SectionGroupName);

                    Console.Write(allSections.ToString());
                    break;

                default:
                    // Option is not allowed..
                    Console.Write("Input not allowed.");
                    break;
                }
            }
            catch (ArgumentException e)
            {
                // Never display this. Use it for
                // debugging purposes.
                msg = e.ToString();
            }
        }
        static void Main(string[] args)
        {
            try
            {
                // Set the path of the config file.
                string configPath = "";

                // Get the Web application configuration object.
                Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

                // Get the section related object.
                RoleManagerSection configSection =
                    (RoleManagerSection)config.GetSection("system.web/roleManager");

                // Display title and info.
                Console.WriteLine("ASP.NET Configuration Info");
                Console.WriteLine();

                // Display Config details.
                Console.WriteLine("File Path: {0}",
                                  config.FilePath);
                Console.WriteLine("Section Path: {0}",
                                  configSection.SectionInformation.Name);

                // Display CacheRolesInCookie property.
                Console.WriteLine("CacheRolesInCookie: {0}",
                                  configSection.CacheRolesInCookie);

                // Set CacheRolesInCookie property.
                configSection.CacheRolesInCookie = false;

                // Display CookieName property.
                Console.WriteLine("CookieName: {0}", configSection.CookieName);

                // Set CookieName property.
                configSection.CookieName = ".ASPXROLES";

                // Display CookiePath property.
                Console.WriteLine("CookiePath: {0}", configSection.CookiePath);

                // Set CookiePath property.
                configSection.CookiePath = "/";

                // Display CookieProtection property.
                Console.WriteLine("CookieProtection: {0}",
                                  configSection.CookieProtection);

                // Set CookieProtection property.
                configSection.CookieProtection =
                    System.Web.Security.CookieProtection.All;

                // Display CookieRequireSSL property.
                Console.WriteLine("CookieRequireSSL: {0}",
                                  configSection.CookieRequireSSL);

                // Set CookieRequireSSL property.
                configSection.CookieRequireSSL = false;

                // Display CookieSlidingExpiration property.
                Console.WriteLine("CookieSlidingExpiration: {0}",
                                  configSection.CookieSlidingExpiration);

                // Set CookieSlidingExpiration property.
                configSection.CookieSlidingExpiration = true;

                // Display CookieTimeout property.
                Console.WriteLine("CookieTimeout: {0}", configSection.CookieTimeout);

                // Set CookieTimeout property.
                configSection.CookieTimeout = TimeSpan.FromMinutes(30);

                // Display CreatePersistentCookie property.
                Console.WriteLine("CreatePersistentCookie: {0}",
                                  configSection.CreatePersistentCookie);

                // Set CreatePersistentCookie property.
                configSection.CreatePersistentCookie = false;

                // Display DefaultProvider property.
                Console.WriteLine("DefaultProvider: {0}",
                                  configSection.DefaultProvider);

                // Set DefaultProvider property.
                configSection.DefaultProvider = "AspNetSqlRoleProvider";

                // Display Domain property.
                Console.WriteLine("Domain: {0}", configSection.Domain);

                // Set Domain property.
                configSection.Domain = "";

                // Display Enabled property.
                Console.WriteLine("Enabled: {0}", configSection.Enabled);

                // Set Enabled property.
                configSection.Enabled = false;

                // Display the number of Providers
                Console.WriteLine("Providers Collection Count: {0}",
                                  configSection.Providers.Count);

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

                // Update if not locked.
                if (!configSection.SectionInformation.IsLocked)
                {
                    config.Save();
                    Console.WriteLine("** Configuration updated.");
                }
                else
                {
                    Console.WriteLine("** Could not update, section is locked.");
                }
            }

            catch (Exception e)
            {
                // Unknown error.
                Console.WriteLine(e.ToString());
            }

            // Display and wait
            Console.ReadLine();
        }
Esempio n. 26
0
 static Roles()
 {
     config = (RoleManagerSection)WebConfigurationManager.GetSection("system.web/roleManager");
 }
        /// <summary>
        /// Update the web.config membership related config sections, membership, profile, and roleManager.
        /// And also set the roleManager Enabled property to true.
        /// </summary>
        /// <param name="configSection"></param>
        /// <param name="config"></param>
        private void UpdateMembershipProviders(Configuration configSection, InstallerConfig config)
        {
            if (config.Membership.Create)
            {
                MembershipSection  membership  = configSection.GetSection("system.web/membership") as MembershipSection;
                ProfileSection     profile     = configSection.GetSection("system.web/profile") as ProfileSection;
                RoleManagerSection roleManager = configSection.GetSection("system.web/roleManager") as RoleManagerSection;

                string connString = config.Database.ConnectionStringName;
                if (!string.IsNullOrEmpty(config.Database.EntityFrameworkEntitiesName))
                {
                    connString = "MembershipConnection";
                }

                // Update the membership section.
                bool isCustomMembershipProvider = (config.Membership.ProviderName == "AspNetSqlMembershipProvider") ? false : true;
                membership.DefaultProvider = config.Membership.ProviderName;

                for (int i = 0; i < membership.Providers.Count; i++)
                {
                    if (membership.Providers[i].Name == "AspNetSqlMembershipProvider")
                    {
                        membership.Providers[i].Parameters["connectionStringName"] = connString;
                        membership.Providers[i].Parameters["name"]            = "AspNetSqlMembershipProvider";
                        membership.Providers[i].Parameters["type"]            = "System.Web.Security.SqlMembershipProvider";
                        membership.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                    }
                }

                if (isCustomMembershipProvider)
                {
                    bool exists = false;
                    for (int i = 0; i < membership.Providers.Count; i++)
                    {
                        if (membership.Providers[i].Name == config.Membership.ProviderName)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        // Create a new provider.
                        ProviderSettings p = new ProviderSettings();
                        p.Parameters["connectionStringName"] = connString;
                        p.Parameters["name"]            = config.Membership.ProviderName;
                        p.Parameters["type"]            = config.Membership.type;
                        p.Parameters["applicationName"] = config.ApplicationName;
                        membership.Providers.Add(p);
                    }
                }


                // Update the profile section.
                bool isCustomProfileProvider = (config.Profile.ProviderName == "AspNetSqlProfileProvider") ? false : true;
                profile.DefaultProvider = config.Profile.ProviderName;
                for (int i = 0; i < profile.Providers.Count; i++)
                {
                    if (profile.Providers[i].Name == "AspNetSqlProfileProvider")
                    {
                        profile.Providers[i].Parameters["connectionStringName"] = connString;
                        profile.Providers[i].Parameters["name"]            = "AspNetSqlProfileProvider";
                        profile.Providers[i].Parameters["type"]            = "System.Web.Profile.SqlProfileProvider";
                        profile.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                    }
                }

                if (isCustomProfileProvider)
                {
                    bool exists = false;
                    for (int i = 0; i < profile.Providers.Count; i++)
                    {
                        if (profile.Providers[i].Name == config.Profile.ProviderName)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        ProviderSettings p = new ProviderSettings();
                        p.Parameters["connectionStringName"] = connString;
                        p.Parameters["name"]            = config.Profile.ProviderName;
                        p.Parameters["type"]            = config.Profile.type;
                        p.Parameters["applicationName"] = config.ApplicationName;
                        profile.Providers.Add(p);
                    }
                }


                // Update the roleManager section.
                bool isCustomRoleProvider = (config.RoleManager.ProviderName == "AspNetSqlRoleProvider") ? false : true;
                roleManager.DefaultProvider = config.RoleManager.ProviderName;
                for (int i = 0; i < roleManager.Providers.Count; i++)
                {
                    if (roleManager.Providers[i].Name == "AspNetSqlRoleProvider")
                    {
                        roleManager.Providers[i].Parameters["connectionStringName"] = connString;
                        roleManager.Providers[i].Parameters["name"]            = "AspNetSqlRoleProvider";
                        roleManager.Providers[i].Parameters["type"]            = "System.Web.Security.SqlRoleProvider";
                        roleManager.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                    }
                }

                if (isCustomRoleProvider)
                {
                    bool exists = false;
                    for (int i = 0; i < roleManager.Providers.Count; i++)
                    {
                        if (roleManager.Providers[i].Name == config.RoleManager.ProviderName)
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        ProviderSettings p = new ProviderSettings();
                        p.Parameters["connectionStringName"] = connString;
                        p.Parameters["name"]            = config.RoleManager.ProviderName;
                        p.Parameters["type"]            = config.RoleManager.type;
                        p.Parameters["applicationName"] = config.ApplicationName;
                        roleManager.Providers.Add(p);
                    }
                }

                roleManager.Enabled = true;
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Update the web.config membership related config sections, membership, profile, and roleManager.
        /// And also set the roleManager Enabled property to true.
        /// This is updated for the new System.Web.Providers namespace.
        /// </summary>
        /// <param name="configSection"></param>
        /// <param name="config"></param>
        private void UpdateMembershipProviders(Configuration configSection, InstallerConfig config)
        {
            if (config.Membership.Create)
            {
                MembershipSection   membership   = configSection.GetSection("system.web/membership") as MembershipSection;
                ProfileSection      profile      = configSection.GetSection("system.web/profile") as ProfileSection;
                RoleManagerSection  roleManager  = configSection.GetSection("system.web/roleManager") as RoleManagerSection;
                SessionStateSection sessionState = configSection.GetSection("system.web/sessionState") as SessionStateSection;

                string connString = config.Database.ConnectionStringName;
                if (!string.IsNullOrEmpty(config.Database.EntityFrameworkEntitiesName))
                {
                    connString = "MembershipConnection";
                }

                // Update the membership section.
                bool isCustomMembershipProvider = (config.Membership.ProviderName == "DefaultMembershipProvider") ? false : true;
                membership.DefaultProvider = config.Membership.ProviderName;

                // Let's first check to see if this is a VS 2012 application which doesn't provide the membership sections, but
                // in the background it's getting the machine web.config sections which include the standard AspNet providers.
                // So account for them and proceed accordingly.
                // If it is a VS 2012 application then the membership sections will be missing from the local web.config
                // but the Providers.Count will return 1 for the machine web.config and reference the AspNetSqlMembershipProvider.
                // Since this won't work for the new System.Web.Providers namespace, we want to handle that and replace it with
                // the correct values.
                if (membership.Providers.Count == 1 && membership.Providers[0].Name == "AspNetSqlMembershipProvider")
                {
                    ProviderSettings p = new ProviderSettings();
                    p.Parameters["connectionStringName"] = connString;
                    p.Parameters["name"]                                 = config.Membership.ProviderName;
                    p.Parameters["type"]                                 = config.Membership.type;
                    p.Parameters["applicationName"]                      = config.ApplicationName;
                    p.Parameters["enablePasswordRetrieval"]              = "false";
                    p.Parameters["enablePasswordReset"]                  = "true";
                    p.Parameters["requiresQuestionAndAnswer"]            = "false";
                    p.Parameters["requiresUniqueEmail"]                  = "false";
                    p.Parameters["maxInvalidPasswordAttempts"]           = "5";
                    p.Parameters["minRequiredPasswordLength"]            = "6";
                    p.Parameters["minRequiredNonalphanumericCharacters"] = "0";
                    p.Parameters["passwordAttemptWindow"]                = "10";
                    membership.Providers.Add(p);
                }
                else
                {
                    // At least one membership section exists, so we will update it to use the DefaultMembershipProvider types.
                    for (int i = 0; i < membership.Providers.Count; i++)
                    {
                        if (membership.Providers[i].Name == "DefaultMembershipProvider")
                        {
                            membership.Providers[i].Parameters["connectionStringName"] = connString;
                            membership.Providers[i].Parameters["name"]            = "DefaultMembershipProvider";
                            membership.Providers[i].Parameters["type"]            = "System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
                            membership.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                        }
                    }

                    // If the user has created their own custom provider and entered it into the install.config file,
                    // grab the values and change the appropriate attributes.
                    if (isCustomMembershipProvider)
                    {
                        bool exists = false;
                        for (int i = 0; i < membership.Providers.Count; i++)
                        {
                            if (membership.Providers[i].Name == config.Membership.ProviderName)
                            {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists)
                        {
                            // Create a new provider.
                            ProviderSettings p = new ProviderSettings();
                            p.Parameters["connectionStringName"] = connString;
                            p.Parameters["name"]            = config.Membership.ProviderName;
                            p.Parameters["type"]            = config.Membership.type;
                            p.Parameters["applicationName"] = config.ApplicationName;
                            membership.Providers.Add(p);
                        }
                    }
                }



                // Update the profile section.
                bool isCustomProfileProvider = (config.Profile.ProviderName == "DefaultProfileProvider") ? false : true;
                profile.DefaultProvider = config.Profile.ProviderName;

                // Check for the existence of the profile section.
                if (profile.Providers.Count == 1 && profile.Providers[0].Name == "AspNetSqlProfileProvider")
                {
                    ProviderSettings p = new ProviderSettings();
                    p.Parameters["connectionStringName"] = connString;
                    p.Parameters["name"]            = config.Profile.ProviderName;
                    p.Parameters["type"]            = config.Profile.type;
                    p.Parameters["applicationName"] = config.ApplicationName;
                    profile.Providers.Add(p);
                }
                else
                {
                    for (int i = 0; i < profile.Providers.Count; i++)
                    {
                        if (profile.Providers[i].Name == "DefaultProfileProvider")
                        {
                            profile.Providers[i].Parameters["connectionStringName"] = connString;
                            profile.Providers[i].Parameters["name"]            = "DefaultProfileProvider";
                            profile.Providers[i].Parameters["type"]            = "System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
                            profile.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                        }
                    }

                    if (isCustomProfileProvider)
                    {
                        bool exists = false;
                        for (int i = 0; i < profile.Providers.Count; i++)
                        {
                            if (profile.Providers[i].Name == config.Profile.ProviderName)
                            {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists)
                        {
                            ProviderSettings p = new ProviderSettings();
                            p.Parameters["connectionStringName"] = connString;
                            p.Parameters["name"]            = config.Profile.ProviderName;
                            p.Parameters["type"]            = config.Profile.type;
                            p.Parameters["applicationName"] = config.ApplicationName;
                            profile.Providers.Add(p);
                        }
                    }
                }



                // Update the roleManager section.
                bool isCustomRoleProvider = (config.RoleManager.ProviderName == "DefaultRoleProvider") ? false : true;
                roleManager.DefaultProvider = config.RoleManager.ProviderName;
                roleManager.Enabled         = true;

                // Check for the existence of the roleManager section.
                if (roleManager.Providers.Count == 2 && roleManager.Providers[0].Name == "AspNetSqlRoleProvider")
                {
                    ProviderSettings p = new ProviderSettings();
                    p.Parameters["connectionStringName"] = connString;
                    p.Parameters["name"]            = config.RoleManager.ProviderName;
                    p.Parameters["type"]            = config.RoleManager.type;
                    p.Parameters["applicationName"] = config.ApplicationName;
                    roleManager.Providers.Add(p);
                }
                else
                {
                    for (int i = 0; i < roleManager.Providers.Count; i++)
                    {
                        if (roleManager.Providers[i].Name == "DefaultRoleProvider")
                        {
                            roleManager.Providers[i].Parameters["connectionStringName"] = connString;
                            roleManager.Providers[i].Parameters["name"]            = "DefaultRoleProvider";
                            roleManager.Providers[i].Parameters["type"]            = "System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
                            roleManager.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                        }
                    }

                    if (isCustomRoleProvider)
                    {
                        bool exists = false;
                        for (int i = 0; i < roleManager.Providers.Count; i++)
                        {
                            if (roleManager.Providers[i].Name == config.RoleManager.ProviderName)
                            {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists)
                        {
                            ProviderSettings p = new ProviderSettings();
                            p.Parameters["connectionStringName"] = connString;
                            p.Parameters["name"]            = config.RoleManager.ProviderName;
                            p.Parameters["type"]            = config.RoleManager.type;
                            p.Parameters["applicationName"] = config.ApplicationName;
                            roleManager.Providers.Add(p);
                        }
                    }
                }



                // Update new SessionState section.
                bool isCustomSessionStateProvider = (config.SessionState.ProviderName == "DefaultSessionProvider") ? false : true;
                sessionState.CustomProvider = config.SessionState.ProviderName;

                // Check for the existence of the sessionState section.
                // This will work since the machine web.config doesn't contain this section.
                if (sessionState.Providers.Count == 0)
                {
                    ProviderSettings p = new ProviderSettings();
                    p.Parameters["connectionStringName"] = connString;
                    p.Parameters["name"]            = config.SessionState.ProviderName;
                    p.Parameters["type"]            = config.SessionState.type;
                    p.Parameters["applicationName"] = config.ApplicationName;
                    sessionState.Providers.Add(p);
                    sessionState.Mode = System.Web.SessionState.SessionStateMode.InProc;
                }
                else
                {
                    for (int i = 0; i < sessionState.Providers.Count; i++)
                    {
                        if (sessionState.Providers[i].Name == "DefaultSessionProvider")
                        {
                            sessionState.Providers[i].Parameters["connectionStringName"] = connString;
                            sessionState.Providers[i].Parameters["name"]            = "DefaultSessionProvider";
                            sessionState.Providers[i].Parameters["type"]            = "System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
                            sessionState.Providers[i].Parameters["applicationName"] = config.ApplicationName;
                        }
                    }

                    if (isCustomSessionStateProvider)
                    {
                        bool exists = false;
                        for (int i = 0; i < sessionState.Providers.Count; i++)
                        {
                            if (sessionState.Providers[i].Name == config.SessionState.ProviderName)
                            {
                                exists = true;
                                break;
                            }
                        }

                        if (!exists)
                        {
                            ProviderSettings p = new ProviderSettings();
                            p.Parameters["connectionStringName"] = connString;
                            p.Parameters["name"]            = config.SessionState.ProviderName;
                            p.Parameters["type"]            = config.SessionState.type;
                            p.Parameters["applicationName"] = config.ApplicationName;
                            sessionState.Providers.Add(p);
                        }
                    }
                }
            }
        }
 void ProcessClear(RoleManagerSection section, SettingsMappingWhatContents how)
 {
     section.Providers.Clear();
 }