﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

namespace MetaCode.ConfigTools
{
    public class ConfigTools
    {

        /// <summary>
        /// Encrypt web.config. 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="section"></param>
        /// <param name="provider">RsaProtectedConfigurationProvider, DataProtectionConfigurationProvider. DataProtectionConfigurationProvider</param>
        /// /// <param name="save_as"></param>
        public static void encryptWebConfigSection(string path, string section, string provider = "DataProtectionConfigurationProvider", string save_as = null)
        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
            ConfigurationSection configSect = config.GetSection(section);
            if (!configSect.SectionInformation.IsProtected)
            {
                configSect.SectionInformation.ProtectSection(provider);                
                if (!String.IsNullOrEmpty(save_as))
                    config.SaveAs(save_as);
                else
                    config.Save();
            }
        }
        /// <summary>
        /// Decerypt web.config
        /// </summary>
        /// <param name="path"></param>
        /// <param name="section"></param>
        /// <param name="save_as"></param>
        public static void decryptWebConfigSection(string path, string section, string save_as = null)
        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
            ConfigurationSection configSect = config.GetSection(section);
            if (configSect.SectionInformation.IsProtected)
            {
                configSect.SectionInformation.UnprotectSection();
                if (!String.IsNullOrEmpty(save_as))
                    config.SaveAs(save_as);
                else
                    config.Save();

            }
        }
    }
}
