Exemplo n.º 1
0
        /// <summary>
        /// Gets an instance of <see cref="WebConfigEntity"/> that contains commonly referenced settings from web.config. The
        /// entity can be updated with new values and then passed to the <see cref="Save"/> method for persisting back to the file system.
        /// </summary>
        /// <returns>Returns an instance of <see cref="WebConfigEntity"/> that contains commonly referenced settings from web.config.</returns>
        public static WebConfigEntity GetWebConfigEntity()
        {
            WebConfigEntity wce = new WebConfigEntity();

            using (FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/web.config"), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    XmlReader r = XmlReader.Create(sr);
                    while (r.Read())
                    {
                        if (r.Name == "connectionStrings")
                        {
                            XmlReader cnStrings = r.ReadSubtree();
                            while (cnStrings.Read())
                            {
                                if ((cnStrings.Name == "add") && cnStrings.MoveToAttribute("name"))
                                {
                                    if ((cnStrings.Value == Constants.SQLITE_CN_STRING_NAME) && cnStrings.MoveToAttribute("connectionString"))
                                    {
                                        wce.SQLiteConnectionStringValue = cnStrings.Value;
                                    }

                                    if ((cnStrings.Value == Constants.SQL_SERVER_CN_STRING_NAME) && cnStrings.MoveToAttribute("connectionString"))
                                    {
                                        wce.SqlServerConnectionStringValue = cnStrings.Value;
                                    }
                                }
                            }
                        }

                        if ((r.Name == "membership") && r.MoveToAttribute("defaultProvider"))
                        {
                            wce.MembershipDefaultProvider = r.Value;
                        }

                        if ((r.Name == "roleManager") && r.MoveToAttribute("defaultProvider"))
                        {
                            wce.RoleDefaultProvider = r.Value;
                        }

                        if ((r.Name == "profile") && r.MoveToAttribute("defaultProvider"))
                        {
                            wce.ProfileDefaultProvider = r.Value;
                        }
                    }
                }
            }

            return(wce);
        }
        private static ProviderDataStore GetDataProvider(WebConfigEntity wce)
        {
            // Update the data provider. Each provider (membership, roles, and gallery data) could theoretically use a different
            // database technology, but we are most interested in where the gallery data is stored, so use that one.
            ProviderDataStore dataProvider = ProviderDataStore.Unknown;

            switch (wce.GalleryDataDefaultProvider)
            {
            case GalleryDataProvider.SQLiteGalleryServerProProvider:
                dataProvider = ProviderDataStore.SQLite;
                break;

            case GalleryDataProvider.SqlCeGalleryServerProProvider:
                dataProvider = ProviderDataStore.SqlCe;
                break;

            case GalleryDataProvider.SqlServerGalleryServerProProvider:
                dataProvider = ProviderDataStore.SqlServer;
                break;
            }
            return(dataProvider);
        }
        /// <summary>
        /// Gets an instance of <see cref="WebConfigEntity"/> that contains commonly referenced settings from web.config. The
        /// entity can be updated with new values and then passed to the <see cref="Save"/> method for persisting back to the file system.
        /// </summary>
        /// <returns>Returns an instance of <see cref="WebConfigEntity"/> that contains commonly referenced settings from web.config.</returns>
        public static WebConfigEntity GetWebConfigEntity()
        {
            WebConfigEntity wce = new WebConfigEntity();

            XmlDocument    webConfig = GetWebConfigXmlDoc();
            XPathNavigator xpathNav  = webConfig.CreateNavigator();

            wce.SQLiteConnectionStringValue = GetSQLiteConnectionString(xpathNav);

            wce.SqlCeConnectionStringValue = GetSqlCeConnectionString(xpathNav);

            wce.SqlCeConnectionStringProviderName = GetSqlCeConnectionProviderName(xpathNav);

            wce.SqlServerConnectionStringValue = GetSqlServerConnectionString(xpathNav);

            wce.GalleryServerProConfigSection = GetGalleryServerProConfigSection(xpathNav);

            wce.MembershipConfigSection = GetMembershipConfigSection(xpathNav);

            wce.RoleConfigSection = GetRoleConfigSection(xpathNav);

            wce.DbProviderFactoriesConfigSection = GetDbProviderFactoriesConfigSection(xpathNav);

            wce.MembershipDefaultProvider = GetMembershipProvider(xpathNav);

            wce.RoleDefaultProvider = GetRoleProvider(xpathNav);

            wce.GalleryDataDefaultProvider = GetGalleryDataProvider(xpathNav);

            wce.DataProvider = GetDataProvider(wce);

            wce.CachingConfigSection = GetCachingConfigSection(xpathNav);

            wce.IsWritable = IsWebConfigUpdateable();

            return(wce);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Persist the configuration data to web.config.
        /// </summary>
        /// <param name="webConfigEntity">An instance of <see cref="WebConfigEntity"/> that contains data to save to web.config.</param>
        /// <exception cref="UnauthorizedAccessException">Thrown when the IIS application pool identity does not have
        /// write access to web.config.</exception>
        public static void Save(WebConfigEntity webConfigEntity)
        {
            #region Load web.config and configure namespace

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_webConfigPath);

            if (xmlDoc == null)
            {
                throw new WebException(string.Format("Could not load {0}.", _webConfigPath));
            }

            if (xmlDoc.DocumentElement == null)
            {
                throw new WebException(string.Format("Could not find the root element of {0}.", _webConfigPath));
            }

            // If the root element has a namespace, save it to a temporary variable and then set it to an empty string.
            // This will allow us to locate nodes without having to specify a namespace in the xpath. Normally there shouldn't
            // be a namespace on the <configuration> element of web.config, but versions of the ASP.NET Configuration Tool
            // before VS 2008 incorrectly added the following: xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"
            // We'll add it back before saving it so there isn't any change to the file as stored on disk.
            string ns = String.Empty;
            if (xmlDoc.DocumentElement.HasAttribute("xmlns"))
            {
                ns = xmlDoc.DocumentElement.Attributes["xmlns"].Value;
                xmlDoc.DocumentElement.Attributes["xmlns"].Value = "";
                xmlDoc.LoadXml(xmlDoc.DocumentElement.OuterXml);
            }

            #endregion

            #region Update connection strings

            // Update SQLite and SQL Server connection strings.
            WriteConnectionStringToWebConfig(xmlDoc, WebConfigEntity.SQLiteConnectionStringName, webConfigEntity.SQLiteConnectionStringValue);
            WriteConnectionStringToWebConfig(xmlDoc, WebConfigEntity.SqlServerConnectionStringName, webConfigEntity.SqlServerConnectionStringValue);

            #endregion

            #region Update membership, role and profile

            // Update membership
            XmlNode membershipNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/membership");

            if (membershipNode == null)
            {
                throw new WebException("Could not find the membership section in web.config.");
            }

            membershipNode.Attributes["defaultProvider"].Value = webConfigEntity.MembershipDefaultProvider;

            // Update roles
            XmlNode roleNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/roleManager");

            if (roleNode == null)
            {
                throw new WebException("Could not find the roleManager section in web.config.");
            }

            roleNode.Attributes["defaultProvider"].Value = webConfigEntity.RoleDefaultProvider;

            // Update profile
            XmlNode profileNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/profile");

            if (profileNode == null)
            {
                throw new WebException("Could not find the profile section in web.config.");
            }

            profileNode.Attributes["defaultProvider"].Value = webConfigEntity.ProfileDefaultProvider;

            #endregion

            #region Save to disk

            // If the config file had a root namespace, restore it now.
            if (!String.IsNullOrEmpty(ns))
            {
                xmlDoc.DocumentElement.Attributes["xmlns"].Value = ns;
            }

            // Persist changes to disk.
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent   = true;
            xws.Encoding = new UTF8Encoding(false);

            XmlWriter writer = XmlWriter.Create(_webConfigPath, xws);

            xmlDoc.Save(writer);

            #endregion
        }
        /// <summary>
        /// Persist the configuration data to web.config.
        /// </summary>
        /// <param name="webConfigEntity">An instance of <see cref="WebConfigEntity"/> that contains data to save to web.config.</param>
        /// <exception cref="UnauthorizedAccessException">Thrown when the IIS application pool identity does not have
        /// write access to web.config.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="webConfigEntity" /> is null.</exception>
        public static void Save(WebConfigEntity webConfigEntity)
        {
            if (webConfigEntity == null)
            {
                throw new ArgumentNullException("webConfigEntity");
            }

            string      ns;        // Holds the xmlns attribute (will be empty in most cases)
            XmlDocument xmlDoc = GetWebConfigXmlDoc(out ns);

            #region Update connection strings

            // Update SQL CE and SQL Server connection strings.
            WriteConnectionStringToWebConfig(xmlDoc, WebConfigEntity.SQLiteConnectionStringName, webConfigEntity.SQLiteConnectionStringValue, String.Empty);
            WriteConnectionStringToWebConfig(xmlDoc, WebConfigEntity.SqlCeConnectionStringName, webConfigEntity.SqlCeConnectionStringValue, webConfigEntity.SqlCeConnectionStringProviderName);
            WriteConnectionStringToWebConfig(xmlDoc, WebConfigEntity.SqlServerConnectionStringName, webConfigEntity.SqlServerConnectionStringValue, String.Empty);

            #endregion

            #region Gallery Server Pro config section

            if (webConfigEntity.GalleryServerProConfigSectionHasChanges)
            {
                XmlNode galleryServerProNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/galleryServerPro");

                if (galleryServerProNode == null)
                {
                    throw new WebException("Could not find the galleryServerPro section in web.config.");
                }

                if (galleryServerProNode.ParentNode == null)
                {
                    throw new WebException("The galleryServerPro section in web.config does not have a parent.");
                }

                // Get a fragment and slide the changed data into it.
                XmlDocumentFragment frag = xmlDoc.CreateDocumentFragment();
                frag.InnerXml = webConfigEntity.GalleryServerProConfigSection;

                galleryServerProNode.ParentNode.ReplaceChild(frag, galleryServerProNode);
            }

            #endregion

            #region Membership config section

            if (webConfigEntity.MembershipConfigSectionHasChanges)
            {
                XmlNode membershipNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/membership");

                if (membershipNode == null)
                {
                    throw new WebException("Could not find the membership section in web.config.");
                }

                if (membershipNode.ParentNode == null)
                {
                    throw new WebException("The membership section in web.config does not have a parent.");
                }

                // Get a fragment and slide the changed data into it.
                XmlDocumentFragment frag = xmlDoc.CreateDocumentFragment();
                frag.InnerXml = webConfigEntity.MembershipConfigSection;

                membershipNode.ParentNode.ReplaceChild(frag, membershipNode);
            }

            #endregion

            #region Role config section

            if (webConfigEntity.RoleConfigSectionHasChanges)
            {
                XmlNode roleNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/roleManager");

                if (roleNode == null)
                {
                    throw new WebException("Could not find the roleManager section in web.config.");
                }

                if (roleNode.ParentNode == null)
                {
                    throw new WebException("The roleManager section in web.config does not have a parent.");
                }

                // Get a fragment and slide the changed data into it.
                XmlDocumentFragment frag = xmlDoc.CreateDocumentFragment();
                frag.InnerXml = webConfigEntity.RoleConfigSection;

                roleNode.ParentNode.ReplaceChild(frag, roleNode);
            }

            #endregion

            #region DbProviderFactories config section

            if (webConfigEntity.DbProviderFactoriesConfigSectionHasChanges)
            {
                XmlNode systemDataNode = xmlDoc.SelectSingleNode(@"/configuration/system.data");
                XmlNode parentNode     = xmlDoc.SelectSingleNode(@"/configuration");

                if (parentNode == null)
                {
                    throw new WebException("Could not find the configuration section in web.config.");
                }

                // Get a fragment and slide the changed data into it.
                XmlDocumentFragment frag = xmlDoc.CreateDocumentFragment();
                frag.InnerXml = webConfigEntity.DbProviderFactoriesConfigSection;

                if (systemDataNode != null)
                {
                    parentNode.ReplaceChild(frag, systemDataNode);
                }
                else
                {
                    parentNode.AppendChild(frag);
                }
            }

            #endregion

            #region cachingConfiguration section

            if (webConfigEntity.MarkCachingConfigSectionAsDeleted)
            {
                // Delete the caching configuration section
                XmlNode cachingNode = xmlDoc.SelectSingleNode(@"/configuration/cachingConfiguration");

                if ((cachingNode != null) && (cachingNode.ParentNode != null))
                {
                    cachingNode.ParentNode.RemoveChild(cachingNode);
                }

                XmlNode cachingDefNode = xmlDoc.SelectSingleNode("/configuration/configSections/section[@name=\"cachingConfiguration\"]");

                if ((cachingDefNode != null) && (cachingDefNode.ParentNode != null))
                {
                    cachingDefNode.ParentNode.RemoveChild(cachingDefNode);
                }
            }

            #endregion

            #region Update membership, role and gallery data

            if (webConfigEntity.MembershipDefaultProvider != MembershipDataProvider.Unknown)
            {
                // Update membership
                XmlNode membershipNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/membership");

                if (membershipNode == null)
                {
                    throw new WebException("Could not find the membership section in web.config.");
                }

                membershipNode.Attributes["defaultProvider"].Value = webConfigEntity.MembershipDefaultProvider.ToString();
            }

            if (webConfigEntity.RoleDefaultProvider != RoleDataProvider.Unknown)
            {
                // Update roles provider
                XmlNode roleNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/roleManager");

                if (roleNode == null)
                {
                    throw new WebException("Could not find the roleManager section in web.config.");
                }

                roleNode.Attributes["defaultProvider"].Value = webConfigEntity.RoleDefaultProvider.ToString();
            }

            // Update gallery data provider
            if (webConfigEntity.GalleryDataDefaultProvider != GalleryDataProvider.Unknown)
            {
                XmlNode galleryDataNode = xmlDoc.SelectSingleNode(@"/configuration/system.web/galleryServerPro/dataProvider");

                if (galleryDataNode == null)
                {
                    throw new WebException("Could not find the galleryServerPro/dataProvider section in web.config.");
                }

                galleryDataNode.Attributes["defaultProvider"].Value = webConfigEntity.GalleryDataDefaultProvider.ToString();
            }

            #endregion

            #region Save to disk

            // If the config file had a root namespace, restore it now.
            if (!String.IsNullOrEmpty(ns))
            {
                xmlDoc.DocumentElement.Attributes["xmlns"].Value = ns;
            }

            // Persist changes to disk.
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent   = true;
            xws.Encoding = new UTF8Encoding(false);

            using (XmlWriter writer = XmlWriter.Create(_webConfigPath, xws))
            {
                xmlDoc.Save(writer);
            }

            #endregion
        }