Exemple #1
0
        public TraceManager()
        {
            try {
                mode = TraceMode.SortByTime;
                TraceSection config = WebConfigurationManager.GetWebApplicationSection("system.web/trace") as TraceSection;
                if (config == null)
                {
                    config = new TraceSection();
                }

                if (config == null)
                {
                    return;
                }

                enabled     = config.Enabled;
                local_only  = config.LocalOnly;
                page_output = config.PageOutput;
                if (config.TraceMode == TraceDisplayMode.SortByTime)
                {
                    mode = TraceMode.SortByTime;
                }
                else
                {
                    mode = TraceMode.SortByCategory;
                }
                request_limit = config.RequestLimit;
            } catch (Exception ex) {
                initialException = ex;
            }
        }
Exemple #2
0
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            string email = null;

            AuthenticationSection authSection =
                (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication");
            FormsAuthenticationUser user = authSection.Forms.Credentials.Users[username.ToLower()];

            if (user != null)
            {
                NameValueCollection emailsSection =
                    (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("emails");
                email = emailsSection[user.Name];
                return(new MembershipUser(
                           "FormsProvider",
                           username,
                           null,
                           email,
                           null,
                           null,
                           true,
                           false,
                           // do not use DateTime.MinValue because some WebDAV clients may not properly parse it.
                           new DateTime(2000, 1, 1),
                           new DateTime(2000, 1, 1),
                           new DateTime(2000, 1, 1),
                           new DateTime(2000, 1, 1),
                           new DateTime(2000, 1, 1)));
            }

            return(null);
        }
Exemple #3
0
        internal HashAlgorithm GetAlgo()
        {
            if (algo != null)
            {
                return(algo);
            }
            if (!EnableMac)
            {
                return(null);
            }

            byte [] algoKey;
            if (page != null)
            {
#if NET_2_0
                MachineKeySection mconfig = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey");
                algoKey = MachineKeySectionUtils.ValidationKeyBytes(mconfig);
#else
                MachineKeyConfig mconfig = HttpContext.GetAppConfig("system.web/machineKey") as MachineKeyConfig;
                algoKey = mconfig.ValidationKey;
#endif
            }
            else
            {
                algoKey = vkey;
            }

            algo = new HMACSHA1(algoKey);
            return(algo);
        }
Exemple #4
0
        /// <summary>
        /// Gets the configuration section.
        /// </summary>
        /// <typeparam name="T">The type parameter name</typeparam>
        /// <param name="sectionName">Name of the section.</param>
        /// <returns>Returns the the configuration section.</returns>
        public T GetConfigSection <T>(string sectionName)
            where T : class
        {
            var section = WebConfigurationManager.GetWebApplicationSection(sectionName) as T;

            return(section);
        }
Exemple #5
0
        public ActionResult Single()
        {
            PlaceSection section      = WebConfigurationManager.GetWebApplicationSection("customDefaults/places") as PlaceSection;
            Place        defaultPlace = section.Places[section.Default];

            return(this.View("~/Views/Home/DisplaySingle.cshtml", (object)string.Format($"The default place is: {defaultPlace.City}")));
        }
Exemple #6
0
        static FormsAuthenticationTicket Decrypt2(byte [] bytes)
        {
            if (protection == FormsProtectionEnum.None)
            {
                return(FormsAuthenticationTicket.FromByteArray(bytes));
            }

            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);

            byte [] result = null;
            if (protection == FormsProtectionEnum.All)
            {
                result = MachineKeySectionUtils.VerifyDecrypt(config, bytes);
            }
            else if (protection == FormsProtectionEnum.Encryption)
            {
                result = MachineKeySectionUtils.Decrypt(config, bytes);
            }
            else if (protection == FormsProtectionEnum.Validation)
            {
                result = MachineKeySectionUtils.Verify(config, bytes);
            }

            return(FormsAuthenticationTicket.FromByteArray(result));
        }
        private void SetAuthCookie(string username, bool createPersistentCookie, string userData)
        {
            var authenticationConfig =
                (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication");
            var timeout = (int)authenticationConfig.Forms.Timeout.TotalMinutes;
            var expiry  = DateTime.Now.AddMinutes((double)timeout);
            var uData   = userData ?? string.Empty;
            var ticket  = new FormsAuthenticationTicket(2,
                                                        username,
                                                        DateTime.Now,
                                                        expiry,
                                                        createPersistentCookie,
                                                        uData,
                                                        FormsAuthentication.FormsCookiePath);

            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var    cookie          = new HttpCookie(FormsAuthentication.FormsCookieName)
            {
                Value    = encryptedTicket,
                HttpOnly = true,
                Secure   = authenticationConfig.Forms.RequireSSL
            };

            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }

            Response.Cookies.Add(cookie);
        }
        static bool cacheProfileExists(string cacheProfileName)
        {
            var outputCacheSettings = (OutputCacheSettingsSection)WebConfigurationManager.GetWebApplicationSection("system.web/caching/outputCacheSettings");
            var profile             = outputCacheSettings.OutputCacheProfiles[cacheProfileName];

            return(profile != null);
        }
Exemple #9
0
        static void SetHostingEnvironment()
        {
            bool shadow_copy_enabled     = true;
            HostingEnvironmentSection he = WebConfigurationManager.GetWebApplicationSection("system.web/hostingEnvironment") as HostingEnvironmentSection;

            if (he != null)
            {
                shadow_copy_enabled = he.ShadowCopyBinAssemblies;
            }

            if (shadow_copy_enabled)
            {
                AppDomain current = AppDomain.CurrentDomain;

                // We disable the obsolete warnings here, because we want to keep this code as close to the original one
                // We got theese obsolete methods in the original one, so we keep it
#pragma warning disable 0618
                current.SetShadowCopyFiles();
                current.SetShadowCopyPath(current.SetupInformation.PrivateBinPath);
#pragma warning restore 0618
            }

            // Black magic below to access internal setters
            // This MAY break with future Mono releases, but the related code wasn't changed in the last 8 years, so highly unlikely it will break

            // HostingEnvironment.IsHosted = true;
            PropertyInfo property = typeof(HostingEnvironment).GetProperty("IsHosted");
            property.DeclaringType.GetProperty("IsHosted");
            property.GetSetMethod(true).Invoke(null, new object[] { true });

            // HostingEnvironment.SiteName = HostingEnvironment.ApplicationID;
            property = typeof(HostingEnvironment).GetProperty("SiteName");
            property.DeclaringType.GetProperty("SiteName");
            property.GetSetMethod(true).Invoke(null, new object[] { HostingEnvironment.ApplicationID });
        }
Exemple #10
0
        public static string Encrypt(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Initialize();
            byte [] ticket_bytes = ticket.ToByteArray();
            if (protection == FormsProtectionEnum.None)
            {
                return(Convert.ToBase64String(ticket_bytes));
            }

            byte []           result = null;
            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);

            if (protection == FormsProtectionEnum.All)
            {
                result = MachineKeySectionUtils.EncryptSign(config, ticket_bytes);
            }
            else if (protection == FormsProtectionEnum.Encryption)
            {
                result = MachineKeySectionUtils.Encrypt(config, ticket_bytes);
            }
            else if (protection == FormsProtectionEnum.Validation)
            {
                result = MachineKeySectionUtils.Sign(config, ticket_bytes);
            }

            return(Convert.ToBase64String(result));
        }
        public CustomErrorsSection GetCustomErrorSection()
        {
            var customErrorsSection =
                WebConfigurationManager.GetWebApplicationSection("system.web/customErrors") as CustomErrorsSection;

            return(customErrorsSection ?? new CustomErrorsSection());
        }
Exemple #12
0
        static void Init()
        {
            if (initialized)
            {
                return;
            }

            lock (initLock) {
                if (initialized)
                {
                    return;
                }

                var cfg = WebConfigurationManager.GetWebApplicationSection("system.web/caching/outputCache") as OutputCacheSection;
                ProviderSettingsCollection cfgProviders = cfg.Providers;

                defaultProviderName = cfg.DefaultProviderName;
                if (cfgProviders != null && cfgProviders.Count > 0)
                {
                    var coll = new OutputCacheProviderCollection();

                    foreach (ProviderSettings ps in cfgProviders)
                    {
                        coll.Add(LoadProvider(ps));
                    }

                    coll.SetReadOnly();
                    providers = coll;
                }

                initialized = true;
            }
        }
Exemple #13
0
        // </Snippet5>

        // <Snippet6>

        // Show the use of GetWebApplicationSection(string).
        // to get the connectionStrings section.
        static void GetWebApplicationSection()
        {
            // Get the default connectionStrings section,
            ConnectionStringsSection connectionStringsSection =
                WebConfigurationManager.GetWebApplicationSection(
                    "connectionStrings") as ConnectionStringsSection;

            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                connectionStringsSection.ConnectionStrings;

            // Get the collection enumerator.
            IEnumerator connectionStringsEnum =
                connectionStrings.GetEnumerator();

            // Loop through the collection and
            // display the connectionStrings key, value pairs.
            int i = 0;

            Console.WriteLine("[Display connectionStrings]");
            while (connectionStringsEnum.MoveNext())
            {
                string name = connectionStrings[i].Name;
                Console.WriteLine("Name: {0} Value: {1}",
                                  name, connectionStrings[name]);
                i += 1;
            }

            Console.WriteLine();
        }
Exemple #14
0
        private void ApplicationSettings()
        {
            /*
             * 1. Application Settings
             **/

            // reading app settings by index
            var index0 = WebConfigurationManager.AppSettings[0];
            var index1 = WebConfigurationManager.AppSettings[1];

            // reading app settings by key
            var y1 = WebConfigurationManager.AppSettings["ClientValidationEnabled"];
            var y2 = WebConfigurationManager.AppSettings["webpages:Enabled"];
            var y3 = WebConfigurationManager.AppSettings["unknown"];

            var keys = WebConfigurationManager.AppSettings.AllKeys;

            var a1 = WebConfigurationManager.GetWebApplicationSection("appSettings");
            var a2 = WebConfigurationManager.GetWebApplicationSection("runtime");
            var a3 = WebConfigurationManager.GetWebApplicationSection("system.web");
            var a4 = WebConfigurationManager.GetWebApplicationSection("runtime");

            // exception: can not cast object to string
            // string displaySetting = a4;

            // exception: The configuration is read only.
            // WebConfigurationManager.AppSettings.Add("MyCustomWebConfigSetting", "test");
            // WebConfigurationManager.AppSettings.Add("TestRemove", "B");
            // WebConfigurationManager.AppSettings.Remove("TestRemove");
        }
        private static void Initialize()
        {
            if (!_initialized)
            {
                lock (_initLock)
                {
                    if (!_initialized)
                    {
                        SitemapSection sitemapSection = (SitemapSection)WebConfigurationManager.GetWebApplicationSection("sitemaps");

                        if (sitemapSection != null)
                        {
                            _formatting          = sitemapSection.Formatting;
                            _useFileModifiedDate = sitemapSection.UseFileModifiedDate;
                        }
                        else
                        {
                            _formatting          = Formatting.Indented;
                            _useFileModifiedDate = false;
                        }

                        _initialized = true;
                    }
                }
            }
        }
Exemple #16
0
        internal static CodeDomProvider CreateProvider(HttpContext context, string lang, out CompilerParameters par, out string tempdir)
        {
            CodeDomProvider ret = null;

            par = null;

            CompilationSection config = (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation");
            Compiler           comp   = config.Compilers[lang];

            if (comp == null)
            {
                CompilerInfo info = CodeDomProvider.GetCompilerInfo(lang);
                if (info != null && info.IsCodeDomProviderTypeValid)
                {
                    ret = info.CreateProvider();
                    par = info.CreateDefaultCompilerParameters();
                }
            }
            else
            {
                Type t = HttpApplication.LoadType(comp.Type, true);
                ret = Activator.CreateInstance(t) as CodeDomProvider;

                par = new CompilerParameters();
                par.CompilerOptions = comp.CompilerOptions;
                par.WarningLevel    = comp.WarningLevel;
            }
            tempdir = config.TempDirectory;

            return(ret);
        }
        private static bool GetDebugFromConfig()
        {
            CompilationSection section =
                (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation");

            return(section.Debug);
        }
Exemple #18
0
        public static string Encode(byte[] data, MachineKeyProtection protectionOption)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var config = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;

            byte[] result;
            switch (protectionOption)
            {
            case MachineKeyProtection.All:
                result = MachineKeySectionUtils.EncryptSign(config, data);
                break;

            case MachineKeyProtection.Encryption:
                result = MachineKeySectionUtils.Encrypt(config, data);
                break;

            case MachineKeyProtection.Validation:
                result = MachineKeySectionUtils.Sign(config, data);
                break;

            default:
                return(String.Empty);
            }

            return(MachineKeySectionUtils.GetHexString(result));
        }
Exemple #19
0
        public static byte[] Unprotect(byte[] protectedData, params string[] purposes)
        {
            if (protectedData == null)
            {
                throw new ArgumentNullException("protectedData");
            }

            foreach (var purpose in purposes)
            {
                if (string.IsNullOrWhiteSpace(purpose))
                {
                    throw new ArgumentException("all purpose parameters must contain text");
                }
            }

            var config        = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;
            var purposeJoined = string.Join(";", purposes);
            var purposeBytes  = GetHashed(purposeJoined);
            var unprotected   = MachineKeySectionUtils.Decrypt(config, protectedData);

            for (int i = 0; i < purposeBytes.Length; i++)
            {
                if (purposeBytes [i] != unprotected [i])
                {
                    throw new CryptographicException();
                }
            }

            var dataLength = unprotected.Length - purposeBytes.Length;
            var result     = new byte [dataLength];

            Array.Copy(unprotected, purposeBytes.Length, result, 0, dataLength);
            return(result);
        }
Exemple #20
0
        /// <summary>
        /// 将DataTable添加到L3DataSet,将数据发送到服务器指定方法
        /// </summary>
        /// <param name="type"></param>
        /// <param name="tb"></param>
        /// <returns></returns>
        public int SendToMES(string type, DataTable tb)
        {
            MESIFDataConfigSection webApplicationSection = WebConfigurationManager.GetWebApplicationSection("MESIFDataConfigSection") as MESIFDataConfigSection;

            if (webApplicationSection == null)
            {
                return(-1);
            }
            MESIFDataConfigElement element = webApplicationSection.MESIFDatas[type];

            if (element == null)
            {
                return(-2);
            }
            string str    = element.Target.Trim();
            string target = element.Method.Trim();

            if (((str == null) || (target == null)) || ((str.Length < 1) || (target.Length < 1)))
            {
                return(-3);
            }
            int num = this.m_Session.Open();

            if (num != 0)
            {
                return(num);
            }
            Command cmd = null;

            num = this.m_Session.CreateCommand(5, str, target, ref cmd);
            if (num != 0)
            {
                return(num);
            }
            if (cmd.ParameterCount != 1)
            {
                return(-3);
            }

            //L3DataSet
            DataSet   set   = new DataSet("L3DataSet");
            DataTable table = tb.Clone();

            table.Merge(tb);
            table.TableName = "L3DataTable";
            set.Tables.Add(table);
            cmd.set_Parameters(0, set);
            num = this.m_Session.Execute(cmd);
            if (num != 0)
            {
                return(num);
            }
            if (!Convert.ToBoolean(cmd.Return))
            {
                return((int)cmd.ErrorCode);
            }
            this.m_Session.Close();
            return(0);
        }
Exemple #21
0
        public void DefaultProviderName()
        {
            Assert.AreEqual("AspNetInternalProvider", OutputCache.DefaultProviderName, "#A1");

            var ocs = WebConfigurationManager.GetWebApplicationSection("system.web/caching/outputCache") as OutputCacheSection;

            Assert.AreEqual(ocs.DefaultProviderName, OutputCache.DefaultProviderName, "#B1");
        }
Exemple #22
0
        public void Providers()
        {
            var ocs = WebConfigurationManager.GetWebApplicationSection("system.web/caching/outputCache") as OutputCacheSection;
            OutputCacheProviderCollection coll = OutputCache.Providers;

            Assert.IsNull(coll, "#A1");
            Assert.IsNotNull(ocs.Providers, "#B1-1");
            Assert.AreEqual(0, ocs.Providers.Count, "#B1-2");
        }
Exemple #23
0
        public PipelineHandler(IContentPipeline pipeline)
        {
            _pipeline = pipeline;

            var settings = WebConfigurationManager.GetWebApplicationSection(
                "system.web/caching/outputCacheSettings") as OutputCacheSettingsSection;

            _cacheProfile = settings.OutputCacheProfiles[CacheProfileName] ?? CreateDefaultCacheProfile();
        }
Exemple #24
0
        public static byte[] Decode(string encodedData, MachineKeyProtection protectionOption)
        {
            if (encodedData == null)
            {
                throw new ArgumentNullException("encodedData");
            }

            int dlen = encodedData.Length;

            if (dlen == 0 || dlen % 2 == 1)
            {
                throw new ArgumentException("encodedData");
            }

            byte[] data = MachineKeySectionUtils.GetBytes(encodedData, dlen);
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("encodedData");
            }

            var config = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;

            byte[]    result = null;
            Exception ex     = null;

            try
            {
                switch (protectionOption)
                {
                case MachineKeyProtection.All:
                    result = MachineKeySectionUtils.VerifyDecrypt(config, data);
                    break;

                case MachineKeyProtection.Encryption:
                    result = MachineKeySectionUtils.Decrypt(config, data);
                    break;

                case MachineKeyProtection.Validation:
                    result = MachineKeySectionUtils.Verify(config, data);
                    break;

                default:
                    return(MachineKeySectionUtils.GetBytes(encodedData, dlen));
                }
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (result == null || ex != null)
            {
                throw new HttpException("Unable to verify passed data.", ex);
            }

            return(result);
        }
Exemple #25
0
        static BaseResponseHeader()
        {
#if NET_2_0
            HttpRuntimeSection section = WebConfigurationManager.GetWebApplicationSection("system.web/httpRuntime") as HttpRuntimeSection;
#else
            HttpRuntimeConfig section = HttpContext.GetAppConfig("system.web/httpRuntime") as HttpRuntimeConfig;
#endif
            headerCheckingEnabled = section == null || section.EnableHeaderChecking;
        }
Exemple #26
0
        public SqlResourceProvider(string path)
        {
            var parts = path.Split('/');

            projectName   = parts[0];
            namespaceName = parts[1];
            className     = parts[2];

            config = WebConfigurationManager.GetWebApplicationSection("sqlResourceProvider") as SqlResourceProviderSection;
        }
Exemple #27
0
        public void RedirectUrl(object src, EventArgs args)
        {
            RedirectSection section = (RedirectSection)WebConfigurationManager.GetWebApplicationSection("redirects");

            foreach (Redirect redirect in section.Redirects)
            {
                if (redirect.Old == _context.Request.RequestContext.HttpContext.Request.RawUrl)
                {
                    _context.Response.Redirect(redirect.New);
                }
            }
        }
        public static void RegisterModule(Type moduleType)
        {
            if (moduleType == null)
            {
                return;
            }

            string typeName = moduleType.AssemblyQualifiedName;
            var    cfg      = WebConfigurationManager.GetWebApplicationSection("system.web/httpModules") as HttpModulesSection;

            cfg.Modules.Add(new HttpModuleAction("__Dynamic_Module_" + typeName, typeName));
        }
Exemple #29
0
        public ActionResult Index()
        {
            Dictionary <string, string> configData = new Dictionary <string, string>();
            PlaceSection section = WebConfigurationManager.GetWebApplicationSection("places") as PlaceSection;

            foreach (Place place in section.Places)
            {
                configData.Add(place.Code, $"{place.City} {place.Country}");
            }

            return(View("~/Views/Home/Ccs.cshtml", configData));
        }
        public void Application_RequestHandler(object sender, EventArgs args)
        {
            var section = (RedirectSection)WebConfigurationManager.GetWebApplicationSection("redirect");

            foreach (RedirectElement item in section.Elements)
            {
                if (item.Old == _context.Request.Url.AbsolutePath)
                {
                    _context.Response.Redirect(item.Current);
                }
            }
        }