protected override void RefreshAndValidateSections(IDictionary <string, string> localSectionsToRefresh, IDictionary <string, string> externalSectionsToRefresh, out ICollection <string> sectionsToNotify, out IDictionary <string, string> sectionsWithChangedConfigSource)
        {
            UpdateCache();

            sectionsToNotify = new List <string>();
            sectionsWithChangedConfigSource = new Dictionary <string, string>();

            // refresh local sections and determine what to do.
            foreach (KeyValuePair <string, string> sectionMapping in localSectionsToRefresh)
            {
                System.Configuration.ConfigurationSection section = cachedConfiguration.GetSection(sectionMapping.Key) as System.Configuration.ConfigurationSection;
                string refreshedConfigSource = section != null ? section.SectionInformation.ConfigSource : NullConfigSource;
                if (!sectionMapping.Value.Equals(refreshedConfigSource))
                {
                    sectionsWithChangedConfigSource.Add(sectionMapping.Key, refreshedConfigSource);
                }

                // notify anyway, since it might have been updated.
                sectionsToNotify.Add(sectionMapping.Key);
            }

            // refresh external sections and determine what to do.
            foreach (KeyValuePair <string, string> sectionMapping in externalSectionsToRefresh)
            {
                System.Configuration.ConfigurationSection section = cachedConfiguration.GetSection(sectionMapping.Key) as System.Configuration.ConfigurationSection;
                string refreshedConfigSource = section != null ? section.SectionInformation.ConfigSource : NullConfigSource;
                if (!sectionMapping.Value.Equals(refreshedConfigSource))
                {
                    sectionsWithChangedConfigSource.Add(sectionMapping.Key, refreshedConfigSource);

                    // notify only if che config source changed
                    sectionsToNotify.Add(sectionMapping.Key);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// 初始化WCF元数据
        /// </summary>
        /// <param name="config"></param>
        private static WCFServiceMeta InitializeWCFServiceMeta(string contextName, System.Configuration.Configuration config)
        {
            WCFServiceMeta  wm      = new WCFServiceMeta();
            ServicesSection sconfig = config.GetSection(GlobalParams.ServiceHostSession) as ServicesSection;

            if (sconfig != null)
            {
                if (sconfig.Services.Count > 0)
                {
                    wm.IsExistService        = true;
                    wm.ServicesConfiguration = sconfig;
                    wm.ContextName           = contextName.ToLower();
                    wm.ChildConfiguration    = config;
                }
                else
                {
                    wm.IsExistService = false;
                }
            }
            BehaviorsSection bconfig = config.GetSection(GlobalParams.BehaviorSession) as BehaviorsSection;

            if (bconfig != null)
            {
                wm.BehaviorsConfiguration = bconfig;
            }
            return(wm);
        }
コード例 #3
0
        public static ExpressionEditor GetExpressionEditor(string expressionPrefix, IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                return(null);
            }

            IWebApplication webApp = (IWebApplication)serviceProvider.GetService(typeof(IWebApplication));

            if (webApp == null)
            {
                return(null);
            }

            _Configuration config = webApp.OpenWebConfiguration(true);

            if (config == null)
            {
                return(null);
            }

            CompilationSection sec = (CompilationSection)config.GetSection("system.web/compilation");

            System.Web.Configuration.ExpressionBuilder builder = sec.ExpressionBuilders [expressionPrefix];

            if (builder == null)
            {
                return(null);
            }

            return(GetExpressionEditor(Type.GetType(builder.Type), serviceProvider));
        }
コード例 #4
0
        public static string GetMaxAllowedFileSize()
        {
            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

            return(string.Format("{0} kB", section.MaxRequestLength));
        }
コード例 #5
0
ファイル: Utilities.cs プロジェクト: dlemstra/potobooks.com
        /// <summary>
        /// Redirect to 404 page
        /// </summary>
        public static void RedirectToErrorPage()
        {
            System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

            HttpContext.Current.Response.Redirect(section.Errors["404"].Redirect);
        }
コード例 #6
0
ファイル: Utilities.cs プロジェクト: dlemstra/potobooks.com
        /// <summary>
        /// GetErrorPage reads custom errors pages section from web.config and gets the default error page url
        /// </summary>
        /// <returns></returns>
        public static string GetErrorPage()
        {
            System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

            return(section.DefaultRedirect.ToString());
        }
コード例 #7
0
        private ServiceEndpoint GetServiceEndpointByConfig(string configName, string endpointConfigurationName)
        {
            ServiceEndpoint        serviceEndpoint = null;
            DsConfigurationManager dcm             = new DsConfigurationManager();

            System.Configuration.Configuration config = dcm.Get <System.Configuration.Configuration>(ConfigurationFileHelper.GetAddinConfigurationFilePath(configName));
            ClientSection cconfig = config.GetSection(GlobalParams.ClientHostSession) as ClientSection;

            if (cconfig != null)
            {
                if (cconfig.Endpoints.Count > 0)
                {
                    foreach (ChannelEndpointElement e in cconfig.Endpoints)
                    {
                        if (e.Name != endpointConfigurationName)
                        {
                            continue;
                        }
                        channelType     = TypeResolutionUtils.ResolveType(e.Contract);
                        serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(channelType), WCFMateHelper.BindingFactory(config, e), new EndpointAddress(e.Address));
                    }
                }
            }
            if (serviceEndpoint == null)
            {
                throw new ArgumentNullException("The configuration file{0},The client access to WCF configuration information is not correct".FormatString(configName));
            }
            return(serviceEndpoint);
        }
コード例 #8
0
        public override void OnException(ExceptionContext filterContext)
        {
            StringBuilder routeValues = new StringBuilder();

            foreach (var val in filterContext.RouteData.Values)
            {
                routeValues.AppendFormat(@"({0}:{1})/", val.Key, val.Value);
            }

            string url = "NULL";

            if (filterContext.HttpContext.Request.Url != null)
            {
                url = filterContext.HttpContext.Request.Url.ToString();
            }

            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
            CustomErrorsSection errorsSection         = (CustomErrorsSection)config.GetSection("system.web/customErrors");

            if (errorsSection.Mode == CustomErrorsMode.On || (errorsSection.Mode == CustomErrorsMode.RemoteOnly && !HttpContext.Current.Request.IsLocal))
            {
                filterContext.ExceptionHandled = true;
                SingalElmah(filterContext);
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "Index" }));
            }
            else
            {
                base.OnException(filterContext);
                SingalElmah(filterContext);
            }
        }
コード例 #9
0
        private void Context_Error(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;

            int statusCode = ((HttpException)context.Error).GetHttpCode();

            if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException))) && (statusCode == 404 || statusCode == 500))
            {
                // Get the Web application configuration.
                System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config");
                // Get the section.
                CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
                // Get the collection
                CustomErrorCollection customErrorsCollection = customErrorsSection.Errors;


                //Clears existing response headers and sets the desired ones.
                context.Response.ClearHeaders();
                context.Response.StatusCode = statusCode;

                if ((customErrorsCollection.Get(statusCode.ToString()) != null))
                {
                    context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString()).Redirect);
                }

                else
                {
                    context.Response.Flush();
                }
            }
        }
コード例 #10
0
 private MachineKeySection GetMachineKeySection()
 {
     System.Configuration.Configuration cfg =
         WebConfigurationManager.OpenWebConfiguration(
             System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
     return(cfg.GetSection("system.web/machineKey") as MachineKeySection);
 }
コード例 #11
0
ファイル: FirstClass.cs プロジェクト: ewin66/dev
        public void Init(HttpApplication context)
        {
            // Below is an example of how you can handle LogRequest event and provide
            // custom logging implementation for it
            //context.LogRequest += new EventHandler(OnLogRequest);

            // For authentication and authorization, detemine which authentication option goes which functionality
            System.Configuration.Configuration configuration =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/WebModule");
            _AutheSection = (AuthenticationSection)configuration.GetSection("system.web/authentication");
            AuthenticationMode _AutheMode = _AutheSection.Mode;

            switch (_AutheMode)
            {
            case AuthenticationMode.Forms:
                //For custom authenticating
                context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
                //For custom authorization
                context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
                //
                context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);

                break;

            // future : for windows domain case, refer to Active Directory programming later.
            case AuthenticationMode.Windows:

                break;
            }
        }
コード例 #12
0
ファイル: ErrorHandler.cs プロジェクト: JustynaJuza/HomeHUD
        public void Init(HttpApplication application)
        {
            System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            CustomErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

            application.EndRequest += Application_EndRequest;
        }
コード例 #13
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public void Initialize()
        {
            AttachmentsDataGrid.Columns[0].HeaderText = GetLocalResourceObject("AttachmentsGrid.FileNameHeader.Text").ToString();
            AttachmentsDataGrid.Columns[1].HeaderText = GetLocalResourceObject("AttachmentsGrid.SizeHeader.Text").ToString();
            AttachmentsDataGrid.Columns[2].HeaderText = GetLocalResourceObject("AttachmentsGrid.Description.Text").ToString();

            BindAttachments();

            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            HttpRuntimeSection section     = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
            double             maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1);

            FileSizeLimit.Text = string.Format("Make sure your file is under {0:0.#} MB.", maxFileSize);

            //check users role permission for adding an attachment
            if (!Page.User.Identity.IsAuthenticated || !UserManager.HasPermission(ProjectId, Common.Permission.AddAttachment.ToString()))
            {
                pnlAddAttachment.Visible = false;
            }

            if (!Page.User.Identity.IsAuthenticated || !UserManager.HasPermission(ProjectId, Common.Permission.DeleteAttachment.ToString()))
            {
                AttachmentsDataGrid.Columns[5].Visible = false;
            }
        }
コード例 #14
0
        internal RedirectSection GetElement()
        {
            System.Configuration.Configuration configuration = Support.GetConfigurationContainingSectionGroupName("fiftyOne/redirect");

            if (configuration == null)
            {
                return(null);
            }

            RedirectSection element = configuration.GetSection("fiftyOne/redirect") as RedirectSection;

            if (element != null)
            {
                element.DevicesFile              = DevicesFile;
                element.Timeout                  = Timeout;
                element.FirstRequestOnly         = FirstRequestOnly;
                element.OriginalUrlAsQueryString = OriginalUrlAsQueryString;
                element.MobileHomePageUrl        = MobileHomePageUrl;
                element.MobilePagesRegex         = MobilePagesRegex;

                element.Locations.Clear();
                foreach (LocationData item in this)
                {
                    element.Locations.Add(item.GetElement());
                }
            }

            return(element);
        }
コード例 #15
0
        void initData()
        {
            client = new MemcachedClient();

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
コード例 #16
0
        private ClientSettingsSection GetConfigSection(System.Configuration.Configuration config, string sectionName, bool declare)
        {
            string str = "userSettings/" + sectionName;
            ClientSettingsSection section = null;

            if (config != null)
            {
                section = config.GetSection(str) as ClientSettingsSection;
                if ((section == null) && declare)
                {
                    this.DeclareSection(config, sectionName);
                    section = config.GetSection(str) as ClientSettingsSection;
                }
            }
            return(section);
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ConfigurationScope"/>.
        /// </summary>
        /// <param name="configurationFile">The file path to the configuration file.</param>
        /// <param name="sectionName">The name of the <typeparamref name="T"/> <see cref="ConfigurationSection"/> to load.</param>
        /// <exception cref="ArgumentNullException">thrown if the <paramref name="configurationFile"/> parameter or the <paramref name="sectionName"/> parmeter is <c>Null</c> or <c>Empty</c>.</exception>
        /// <exception cref="FileNotFoundException">thrown if the configuration file is not found.</exception>
        public ConfigurationScope(string configurationFile, string sectionName)
        {
            if (string.IsNullOrWhiteSpace(configurationFile))
            {
                throw new ArgumentNullException("configurationFile");
            }

            if (!System.IO.File.Exists(configurationFile))
            {
                throw new FileNotFoundException("Configuration file not found.", configurationFile);
            }

            if (string.IsNullOrWhiteSpace("sectionName"))
            {
                throw new ArgumentNullException("sectionName");
            }

            ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();

            configMap.ExeConfigFilename = configurationFile;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            this.configuration = config.GetSection <T>(sectionName);
            this.sectionName   = sectionName;
        }
コード例 #18
0
        /*
         * 方法名称:RunLabApp
         * 方法功能描述:用于启动“试验室软件”
         *
         * 创建人:关启学
         * 创建时间:20090309
         *
         * 修改人:
         * 修改时间:
         * 修改内容:
         *
         */
        public void RunLabApp()
        {
            //获取配置文件
            System.Configuration.Configuration config =
                System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

            //获取配置文件中的“appSettings”节
            System.Configuration.AppSettingsSection appSettings =
                (System.Configuration.AppSettingsSection)config.GetSection("appSettings");


            if (appSettings != null)
            {
                System.Diagnostics.Process labProcess = new System.Diagnostics.Process();
                labProcess.StartInfo.FileName = appSettings.Settings["LabAppPath"].Value;

                bool fileIsExists = System.IO.File.Exists(labProcess.StartInfo.FileName);

                //判断“试验室软件”是否安装在配置文件中相应的路径
                if (fileIsExists)
                {
                    labProcess.Start();
                }
                else
                {
                    MessageBox.Show("请确认“试验室软件”的安装路径是否为:'" + labProcess.StartInfo.FileName + "'", "路径错误!");
                }
            }
        }
コード例 #19
0
        private static MachineKeySection GetMachineKey()
        {
            string applicationPath = new ApplicationUrl("~/").Path;

            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(applicationPath);
            return((MachineKeySection)config.GetSection("system.web/machineKey"));
        }
コード例 #20
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            System.Configuration.Configuration configuration =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

            System.Web.Configuration.CustomErrorsSection section =
                (CustomErrorsSection)configuration.GetSection("system.web/customErrors");

            var inner            = actionExecutedContext.Exception.InnerException;
            var exceptionMessage = (inner == null) ? actionExecutedContext.Exception.Message : inner.Message;

            CustomErrorsMode mode = section.Mode;

            if (mode == CustomErrorsMode.Off)
            {
                exceptionMessage = actionExecutedContext.Exception.StackTrace.ToString();
            }
            // TODO Alvaro implementar log
            // Por cada excepción no controlada devolvemos un error 500 con una lista de errores.

            log.Error("ERROR: " + exceptionMessage);
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError,
                                                                                          new ErrorResult {
                Error = exceptionMessage
            });
            Task.FromResult <object>(null);
            //actionExecutedContext.Response.Headers.Add("X-Error", actionExecutedContext.Exception.Message);
        }
コード例 #21
0
ファイル: InterfaceFactory.cs プロジェクト: zmm623/Log4Grid
        private Log4GridSection GetConfigSection(string sectionName)
        {
            Log4GridSection result = null;

            System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
            fm.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "Log4Grid.config";
            System.Configuration.Configuration mDomainConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None);
            result = (Log4GridSection)mDomainConfig.GetSection(sectionName);
            return(result);
        }
コード例 #22
0
        /// <summary>
        /// Returns the specified <see cref="ConfigurationSection"/> object.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of the specified <see cref="ConfigurationSection"/>.</typeparam>
        /// <param name="configuration">The <see cref="Configuration"/> instance.</param>
        /// <param name="sectionName">The path to the section to be returned.</param>
        /// <returns></returns>
        public static T GetSection <T>(this System.Configuration.Configuration configuration, string sectionName)
            where T : ConfigurationSection
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                throw new ArgumentNullException("sectionName");
            }

            return((T)configuration.GetSection(sectionName));
        }
        public override System.Configuration.ConfigurationSection GetSection(string sectionName)
        {
            System.Configuration.Configuration configuration = GetConfiguration();

            System.Configuration.ConfigurationSection configurationSection = configuration.GetSection(sectionName) as System.Configuration.ConfigurationSection;

            SetConfigurationWatchers(sectionName, configurationSection);

            return(configurationSection);
        }
コード例 #24
0
        private void SaveConfiguration()
        {
            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration("~");

            HostSection host = (HostSection)cfg.GetSection("n2/host");

            host.RootID      = RootId;
            host.StartPageID = StartId;

            cfg.Save();
        }
コード例 #25
0
ファイル: Security.cs プロジェクト: ffhighwind/Utilities
 /// <summary>
 /// Generates an encrypted section in the app.config file. This should only be used once before deployment.
 /// </summary>
 /// <param name="sectionKey">The section to encrypt.</param>
 public static void EncryptConfig(string sectionKey = "configuration")
 {
     System.Configuration.Configuration        config  = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
     System.Configuration.ConfigurationSection section = config.GetSection(sectionKey);
     if (section != null && !section.SectionInformation.IsProtected && !section.ElementInformation.IsLocked)
     {
         section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
         section.SectionInformation.ForceSave = true;
         config.Save(System.Configuration.ConfigurationSaveMode.Full);
     }
 }
コード例 #26
0
ファイル: Manager.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Get the specified client settings section.
        /// </summary>
        /// <param name="assemblyFilePath">The assembly file name and path assocciated with the configuration file.</param>
        /// <param name="sectionName">The path to the section to be returned.</param>
        /// <returns>Represents a group of user-scoped application settings in a configuration file.</returns>
        public static System.Configuration.ClientSettingsSection GetClientSettings(string assemblyFilePath, string sectionName)
        {
            // Get assembly configuration file.
            System.Configuration.Configuration config = Configuration(assemblyFilePath);

            // Get the section settings.
            System.Configuration.ClientSettingsSection configSetting = config.GetSection(sectionName) as System.Configuration.ClientSettingsSection;

            // Return the configuration type.
            return(configSetting);
        }
コード例 #27
0
ファイル: Manager.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Get the specified section type.
        /// </summary>
        /// <typeparam name="T">The configuration section type.</typeparam>
        /// <param name="assemblyFilePath">The assembly file name and path assocciated with the configuration file.</param>
        /// <param name="sectionName">The path to the section to be returned.</param>
        /// <returns>The section type</returns>
        public static T GetSection <T>(string assemblyFilePath, string sectionName) where T : System.Configuration.ConfigurationSection
        {
            // Get assembly configuration file.
            System.Configuration.Configuration config = Configuration(assemblyFilePath);

            // Get the section settings.
            T configSetting = config.GetSection(sectionName) as T;

            // Return the configuration type.
            return(configSetting);
        }
        public override System.Configuration.ConfigurationSection GetSection(string sectionName)
        {
            System.Configuration.Configuration        configuration = GetConfiguration();
            System.Configuration.ConfigurationSection configurationSection;

            try
            {
                configurationSection = configuration.GetSection(sectionName) as System.Configuration.ConfigurationSection;
            }
            catch (System.Configuration.ConfigurationException ex)
            {
                // retry once
                UpdateCache();
                configuration        = GetConfiguration();
                configurationSection = configuration.GetSection(sectionName) as System.Configuration.ConfigurationSection;
            }

            SetConfigurationWatchers(sectionName, configurationSection);

            return(configurationSection);
        }
コード例 #29
0
        internal static IEnumerator <Type> Process(System.Configuration.Configuration config)
        {
            ControllerSection controllersection = config.GetSection("RegisterControllers") as ControllerSection;

            if (controllersection.IsNotNull())
            {
                foreach (Controller controller in controllersection.Controllers)
                {
                    yield return(Type.GetType(controller.Class));
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Updates this instance.
        /// </summary>
        public bool Update()
        {
            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

            HostSettingManager.UpdateHostSetting(HostSettingNames.AllowAttachments, AllowAttachments.Checked.ToString());
            HostSettingManager.UpdateHostSetting(HostSettingNames.AttachmentStorageType, AttachmentStorageType.SelectedValue);
            HostSettingManager.UpdateHostSetting(HostSettingNames.AllowedFileExtensions, AllowedFileExtentions.Text.Trim());
            HostSettingManager.UpdateHostSetting(HostSettingNames.FileSizeLimit, section.MaxRequestLength.ToString());
            HostSettingManager.UpdateHostSetting(HostSettingNames.AttachmentUploadPath, txtUploadPath.Text.Trim().EndsWith(@"\") ? txtUploadPath.Text.Trim() : txtUploadPath.Text.Trim() + @"\");
            return(true);
        }