Example #1
0
        internal static String GetDirectory(String path)
        {
            if (path == null || path.Length == 0)
            {
                throw new ArgumentException(HttpRuntime.FormatResourceString(SR.Empty_path_has_no_directory));
            }

            if (path[0] != '/')
            {
                throw new ArgumentException(HttpRuntime.FormatResourceString(SR.Path_must_be_rooted));
            }

            // Make sure there is a filename after the last '/'
            Debug.Assert(path[path.Length - 1] != '/', "Path should not end with a /");

            string dir = path.Substring(0, path.LastIndexOf('/'));

            // If it's the root dir, we would end up with "".  Return "/" instead
            if (dir.Length == 0)
            {
                return("/");
            }

            return(dir);
        }
        internal /*public*/ void WaitOne()
        {
            if (_mutexHandle.Handle == IntPtr.Zero)
            {
                throw new InvalidOperationException(HttpRuntime.FormatResourceString(SR.CompilationMutex_Null));
            }

            // check the lock status
            for (;;)
            {
                int lockStatus = _lockStatus;

                if (lockStatus == -1 || _draining)
                {
                    throw new InvalidOperationException(HttpRuntime.FormatResourceString(SR.CompilationMutex_Drained));
                }

                if (Interlocked.CompareExchange(ref _lockStatus, lockStatus + 1, lockStatus) == lockStatus)
                {
                    break; // got the lock
                }
            }

            Debug.Trace("Mutex", "Waiting for mutex " + MutexDebugName);

            if (UnsafeNativeMethods.InstrumentedMutexGetLock(_mutexHandle, -1) == -1)
            {
                // failed to get the lock
                Interlocked.Decrement(ref _lockStatus);
                throw new InvalidOperationException(HttpRuntime.FormatResourceString(SR.CompilationMutex_Failed));
            }

            Debug.Trace("Mutex", "Got mutex " + MutexDebugName);
        }
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        // Helper functions: Hash a password
        /// <include file='doc\FormsAuthentication.uex' path='docs/doc[@for="FormsAuthentication.HashPasswordForStoringInConfigFile"]/*' />
        /// <devdoc>
        ///    Initializes FormsAuthentication by reading
        ///    configuration and getting the cookie values and encryption keys for the given
        ///    application.
        /// </devdoc>
        public static String HashPasswordForStoringInConfigFile(String password, String passwordFormat)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (passwordFormat == null)
            {
                throw new ArgumentNullException("passwordFormat");
            }

            byte [] bBlob;
            if (String.Compare(passwordFormat, "sha1", true, CultureInfo.InvariantCulture) == 0)
            {
                bBlob = GetMacFromBlob(Encoding.UTF8.GetBytes(password));
            }
            else if (String.Compare(passwordFormat, "md5", true, CultureInfo.InvariantCulture) == 0)
            {
                bBlob = GetMD5FromBlob(Encoding.UTF8.GetBytes(password));
            }
            else
            {
                throw new ArgumentException(HttpRuntime.FormatResourceString(SR.InvalidArgumentValue, "passwordFormat"));
            }


            return(MachineKey.ByteArrayToHexString(bBlob, 0));
        }
Example #4
0
        private void SendResponseFromFileStream(FileStream f, long offset, long length)
        {
            long fileSize = f.Length;

            if (length == -1)
            {
                length = fileSize - offset;
            }

            if (offset < 0 || length > fileSize - offset)
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_range));
            }

            if (length > 0)
            {
                if (offset > 0)
                {
                    f.Seek(offset, SeekOrigin.Begin);
                }

                byte[] fileBytes = new byte[(int)length];
                f.Read(fileBytes, 0, (int)length);
                WriteBytes(fileBytes, (int)length);
            }
        }
Example #5
0
        /// <include file='doc\HTTPNotFoundHandler.uex' path='docs/doc[@for="HttpForbiddenHandler.ProcessRequest"]/*' />
        /// <devdoc>
        ///    <para>Drives web processing execution.</para>
        /// </devdoc>
        public void ProcessRequest(HttpContext context)
        {
            PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_NOT_FOUND);

            throw new HttpException(403,
                                    HttpRuntime.FormatResourceString(SR.Path_forbidden, context.Request.Path));
        }
Example #6
0
        /// <include file='doc\DropDownList.uex' path='docs/doc[@for="DropDownList.RenderContents"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// <para>Displays the <see cref='System.Web.UI.WebControls.DropDownList'/> control on the client.</para>
        /// </devdoc>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            ListItemCollection liCollection = Items;
            int  n        = Items.Count;
            bool selected = false;

            if (n > 0)
            {
                for (int i = 0; i < n; i++)
                {
                    ListItem li = liCollection[i];
                    writer.WriteBeginTag("option");
                    if (li.Selected)
                    {
                        if (selected)
                        {
                            throw new HttpException(HttpRuntime.FormatResourceString(SR.Cant_Multiselect_In_DropDownList));
                        }
                        selected = true;
                        writer.WriteAttribute("selected", "selected", false);
                    }

                    writer.WriteAttribute("value", li.Value, true /*fEncode*/);
                    writer.Write(HtmlTextWriter.TagRightChar);
                    HttpUtility.HtmlEncode(li.Text, writer);
                    writer.WriteEndTag("option");
                    writer.WriteLine();
                }
            }
        }
        /*
         * Return a CompilerInfo that a language maps to.
         */
        internal CompilerInfo GetCompilerInfoFromLanguage(string language)
        {
            CompilerInfo compilerInfo = (CompilerInfo)CompilerLanguages[language];

            if (compilerInfo == null)
            {
                // Unsupported language: throw an exception
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_lang, language));
            }

            // Only allow the use of compilerOptions when we have UnmanagedCode access (ASURT 73678)
            if (compilerInfo.CompilParams.CompilerOptions != null)
            {
                if (!HttpRuntime.HasUnmanagedPermission())
                {
                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Insufficient_trust_for_attribute, "compilerOptions"),
                              compilerInfo.ConfigFileName, compilerInfo.ConfigFileLineNumber);
                }
            }

            // Clone it so the original is not modified
            compilerInfo = compilerInfo.Clone();

            // Set the value of the debug flag in the copy
            compilerInfo.CompilParams.IncludeDebugInformation = _debug;

            return(compilerInfo);
        }
        /*
         * Process the contents of the <%@ OutputCache ... %> directive
         */
        internal virtual void ProcessOutputCacheDirective(string directiveName, IDictionary directive)
        {
            bool fHasDuration = Util.GetAndRemovePositiveIntegerAttribute(directive, "duration", ref _duration);

            if (!fHasDuration && FDurationRequiredOnOutputCache)
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Missing_attr, "duration"));
            }

            _varyByCustom = Util.GetAndRemoveNonEmptyAttribute(directive, "varybycustom");

            _varyByParams = Util.GetAndRemoveNonEmptyAttribute(directive, "varybyparam");

            // VaryByParams is required (ASURT 76763)
            if (_varyByParams == null && FVaryByParamsRequiredOnOutputCache)
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Missing_varybyparam_attr));
            }

            // If it's "none", set it to null
            if (string.Compare(_varyByParams, "none", true, CultureInfo.InvariantCulture) == 0)
            {
                _varyByParams = null;
            }

            // If there are some attributes left, fail
            Util.CheckUnknownDirectiveAttributes(directiveName, directive);
        }
        public virtual object Create(Object parent, Object configContextObj, XmlNode section)
        {
            // if called through client config don't even load HttpRuntime
            if (!HandlerBase.IsServerConfiguration(configContextObj))
            {
                return(null);
            }


            HttpConfigurationContext configContext = configContextObj as HttpConfigurationContext;

            // section handlers can run in client mode with ConfigurationSettings.GetConfig("sectionName")
            // detect this case and return null to be ensure no exploits from secure client scenarios
            // see ASURT 123738
            if (configContext == null)
            {
                return(null);
            }

            if (HandlerBase.IsPathAtAppLevel(configContext.VirtualPath) == PathLevel.BelowApp)
            {
                throw new ConfigurationException(
                          HttpRuntime.FormatResourceString(SR.Cannot_specify_below_app_level, section.Name),
                          section);
            }

            return(new SecurityPolicyConfig((SecurityPolicyConfig)parent, section, ConfigurationException.GetXmlNodeFilename(section)));
        }
        internal static string GetUserAgent(HttpRequest request)
        {
            if (request.ClientTarget.Length > 0)
            {
                // Lookup ClientTarget section in config.
                ClientTargetConfiguration clientTargetConfig     = (ClientTargetConfiguration)request.Context.GetConfig("system.web/clientTarget");
                NameValueCollection       clientTargetDictionary = null;
                if (clientTargetConfig != null)
                {
                    clientTargetDictionary = clientTargetConfig.Configuration;
                }

                if (clientTargetDictionary != null)
                {
                    // Found it
                    // Try to map the alias
                    string useUserAgent = clientTargetDictionary[request.ClientTarget];
                    if (useUserAgent != null)
                    {
                        return(useUserAgent);
                    }
                }

                throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_client_target, request.ClientTarget));
            }

            // Protect against attacks with long User-Agent headers
            String userAgent = request.UserAgent;

            if (userAgent != null && userAgent.Length > 256)
            {
                userAgent = String.Empty;
            }
            return(userAgent);
        }
Example #11
0
        /// <include file='doc\CompareValidator.uex' path='docs/doc[@for="CompareValidator.ControlPropertiesValid"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para> Checks the properties of a the control for valid values.</para>
        /// </devdoc>
        protected override bool ControlPropertiesValid()
        {
            // Check the control id references
            if (ControlToCompare.Length > 0)
            {
                CheckControlValidationProperty(ControlToCompare, "ControlToCompare");

                if (string.Compare(ControlToValidate, ControlToCompare, true, CultureInfo.InvariantCulture) == 0)
                {
                    throw new HttpException(HttpRuntime.FormatResourceString(SR.Validator_bad_compare_control,
                                                                             ID,
                                                                             ControlToCompare));
                }
            }
            else
            {
                // Check Values
                if (Operator != ValidationCompareOperator.DataTypeCheck &&
                    !CanConvert(ValueToCompare, Type))
                {
                    throw new HttpException(
                              HttpRuntime.FormatResourceString(
                                  SR.Validator_value_bad_type,
                                  new string [] {
                        ValueToCompare,
                        "ValueToCompare",
                        ID,
                        PropertyConverter.EnumToString(typeof(ValidationDataType), Type),
                    }));
                }
            }
            return(base.ControlPropertiesValid());
        }
Example #12
0
        ReadWriteSpinLock _lockTargets;                     /* lock for targets */



        /*
         * ctor.
         */

        internal CacheEntry(
            String key,
            Object value,
            CacheDependency dependency,
            CacheItemRemovedCallback onRemovedHandler,
            DateTime utcAbsoluteExpiration,
            TimeSpan slidingExpiration,
            CacheItemPriority priority,
            bool isPublic) :

            base(key, isPublic)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (slidingExpiration < TimeSpan.Zero || OneYear < slidingExpiration)
            {
                throw new ArgumentOutOfRangeException("slidingExpiration");
            }

            if (utcAbsoluteExpiration != Cache.NoAbsoluteExpiration && slidingExpiration != Cache.NoSlidingExpiration)
            {
                throw new ArgumentException(HttpRuntime.FormatResourceString(SR.Invalid_expiration_combination));
            }

            if (priority < CacheItemPriorityMin || CacheItemPriorityMax < priority)
            {
                throw new ArgumentOutOfRangeException("priority");
            }

            _value            = value;
            _dependency       = dependency;
            _onRemovedTargets = onRemovedHandler;

            _utcCreated        = DateTime.UtcNow;
            _slidingExpiration = slidingExpiration;
            if (_slidingExpiration > TimeSpan.Zero)
            {
                _utcExpires = _utcCreated + _slidingExpiration;
            }
            else
            {
                _utcExpires = utcAbsoluteExpiration;
            }

            _expiresIndex  = -1;
            _expiresBucket = 0xff;

            _usageIndex = -1;
            if (priority == CacheItemPriority.NotRemovable)
            {
                _usageBucket = 0xff;
            }
            else
            {
                _usageBucket = (byte)(priority - 1);
            }
        }
        /*public*/ void IStateClientManager.ConfigInit(SessionStateSectionHandler.Config config, SessionOnEndTarget onEndTarget)
        {
            /*
             * Parse the connection string for errors. We want to ensure
             * that the user's connection string doesn't contain an
             * Initial Catalog entry, so we must first create a dummy connection.
             */
            SqlConnection dummyConnection;

            try {
                dummyConnection = new SqlConnection(config._sqlConnectionString);
            }
            catch (Exception e) {
                throw new ConfigurationException(e.Message, e, config._configFileName, config._sqlLine);
            }

            string database = dummyConnection.Database;

            if (database != null && database.Length > 0)
            {
                throw new ConfigurationException(
                          HttpRuntime.FormatResourceString(SR.No_database_allowed_in_sqlConnectionString),
                          config._configFileName, config._sqlLine);
            }

            s_useIntegratedSecurity = DetectIntegratedSecurity(config._sqlConnectionString);
            s_sqlConnectionString   = config._sqlConnectionString + ";Initial Catalog=ASPState";
            s_rpool = new ResourcePool(new TimeSpan(0, 0, 5), int.MaxValue);
        }
Example #14
0
        /// <include file='doc\DataBinder.uex' path='docs/doc[@for="DataBinder.GetPropertyValue"]/*' />
        /// <devdoc>
        /// </devdoc>
        public static object GetPropertyValue(object container, string propName)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            if ((propName == null) || (propName.Length == 0))
            {
                throw new ArgumentNullException("propName");
            }

            object prop = null;

            // get a PropertyDescriptor using case-insensitive lookup
            PropertyDescriptor pd = TypeDescriptor.GetProperties(container).Find(propName, true);

            if (pd != null)
            {
                prop = pd.GetValue(container);
            }
            else
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.DataBinder_Prop_Not_Found, container.GetType().FullName, propName));
            }

            return(prop);
        }
Example #15
0
        static internal Table CreateTable(DataTable datatable)
        {
            if (datatable.Rows.Count == 0)
            {
                return(null);
            }

            IEnumerator en;
            bool        isAlt = false;

            Object[]  cells;
            Table     table = new Table();
            TableRow  trow;
            TableCell tcell;


            table.Width       = Unit.Percentage(100);
            table.CellPadding = 0;
            table.CellSpacing = 0;

            // add a title for the table - same as table name
            trow                  = AddRow(table);
            tcell                 = AddHeaderCell(trow, "<h3><b>" + HttpRuntime.FormatResourceString(datatable.TableName) + "</b></h3>");
            tcell.CssClass        = "alt";
            tcell.ColumnSpan      = 10;
            tcell.HorizontalAlign = HorizontalAlign.Left;

            // add the header information - same as column names
            trow                 = AddRow(table);
            trow.CssClass        = "subhead";
            trow.HorizontalAlign = HorizontalAlign.Left;
            en = datatable.Columns.GetEnumerator();
            while (en.MoveNext())
            {
                AddHeaderCell(trow, HttpRuntime.FormatResourceString(((DataColumn)en.Current).ColumnName));
            }

            // now fill in the values, but don't display null values
            en = datatable.Rows.GetEnumerator();
            while (en.MoveNext())
            {
                cells = ((DataRow)en.Current).ItemArray;
                trow  = AddRow(table);

                for (int i = 0; i < cells.Length; i++)
                {
                    string temp = HttpUtility.HtmlEncode(cells[i].ToString());
                    AddCell(trow, (temp.Length != 0) ? temp : "&nbsp;");
                }

                // alternate colors
                if (isAlt)
                {
                    trow.CssClass = "alt";
                }
                isAlt = !isAlt;
            }

            return(table);
        }
Example #16
0
        private static XmlNode GetAndRemoveIntegerAttributeInternal(XmlNode node, string attrib, bool fRequired, ref int val)
        {
            XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired);

            if (a != null)
            {
                if (a.Value.Trim() != a.Value)
                {
                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Invalid_integer_attribute, a.Name),
                              a);
                }

                try {
                    val = int.Parse(a.Value, CultureInfo.InvariantCulture);
                }
                catch (Exception e) {
                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Invalid_integer_attribute, a.Name),
                              e, a);
                }
            }

            return(a);
        }
        internal Object Create()
        {
            // HACKHACK: for now, let uncreatable types through and error later (for .soap factory)
            // This design should change - developers will want to know immediately
            // when they misspell a type

            if (_type == null)
            {
                Type t = Type.GetType(_typename, true);

                // throw for bad types in deferred case
                if (!IsTypeHandlerOrFactory(t))
                {
                    throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_not_factory_or_handler, _typename));
                }

                if (!HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted))
                {
                    if (!IsTypeFromAssemblyWithAPTCA(t) && IsTypeFromAssemblyWithStrongName(t))
                    {
                        throw new HttpException(HttpRuntime.FormatResourceString(SR.Type_from_untrusted_assembly, _typename));
                    }
                }

                _type = t;
            }

            return(HttpRuntime.CreateNonPublicInstance(_type));
        }
Example #18
0
        internal static bool GetAndRemovePositiveIntegerAttribute(IDictionary directives,
                                                                  string key, ref int val)
        {
            string s = Util.GetAndRemove(directives, key);

            if (s == null)
            {
                return(false);
            }

            try {
                val = int.Parse(s);
            }
            catch (Exception) {
                throw new HttpException(
                          HttpRuntime.FormatResourceString(SR.Invalid_positive_integer_attribute, key));
            }

            // Make sure it's positive
            if (val <= 0)
            {
                throw new HttpException(
                          HttpRuntime.FormatResourceString(SR.Invalid_positive_integer_attribute, key));
            }

            return(true);
        }
Example #19
0
        internal static string GetScriptLocation(HttpContext context)
        {
            // prepare script include
            string      location          = null;
            IDictionary webControlsConfig = (IDictionary)context.GetConfig("system.web/webControls");

            if (webControlsConfig != null)
            {
                location = (string)webControlsConfig["clientScriptsLocation"];
            }

            if (location == null)
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Missing_clientScriptsLocation));
            }

            // If there is a formatter, as there will be for the default machine.config, insert the assembly name and version.
            if (location.IndexOf("{0}") >= 0)
            {
                string assembly = "system_web";
                string version  = VersionInfo.IsapiVersion.Substring(0, VersionInfo.IsapiVersion.LastIndexOf('.')).Replace('.', '_');
                location = String.Format(location, assembly, version);
            }
            return(location);
        }
        private void CompileSourceCode()
        {
            // Return if there is nothing to compile
            if (_sourceString == null)
            {
                return;
            }

            // Put in some context so that the file can be debugged.
            CodeLinePragma linePragma = new CodeLinePragma(_inputFile, _lineNumber);

            try {
                // Compile the string, and get a type
                _compiledType = _sourceCompiler.CompileSourceStringIntoType(_sourceString,
                                                                            _className, linePragma, _linkedAssemblies, _compilerType, _compilParams);
            }
            catch {
                // Throw a specific error if the type was not found
                if (_sourceCompiler.TypeNotFoundInAssembly)
                {
                    throw new HttpParseException(
                              HttpRuntime.FormatResourceString(SR.Type_not_found_in_src, _className),
                              null, _inputFile, _sourceString, _lineNumber);
                }
                else
                {
                    // Just rethrow
                    throw;
                }
            }
        }
Example #21
0
        // Async patern

        internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData)
        {
            InternalSecurityPermissions.UnmanagedCode.Demand();

            if (IsInAspCompatMode)
            {
                // already in AspCompatMode -- execute synchronously
                bool      sync  = true;
                Exception error = _app.ExecuteStep(this, ref sync);
                _ar         = new HttpAsyncResult(cb, extraData, true, null, error);
                _syncCaller = true;
            }
            else
            {
                _ar         = new HttpAsyncResult(cb, extraData);
                _syncCaller = (cb == null);
                _rootedThis = GCHandle.Alloc(this);

                if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this) != 1)
                {
                    // failed to queue up the execution in ASP compat mode
                    _rootedThis.Free();
                    _ar.Complete(true, null, new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_access_AspCompat)));
                }
            }

            return(_ar);
        }
Example #22
0
        /*
         * Add a new StateItem or update an existing StateItem in the bag.
         */
        /// <include file='doc\StateBag.uex' path='docs/doc[@for="StateBag.Add"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public StateItem Add(string key, object value)
        {
            if (key == null || key.Length == 0)
            {
                throw new ArgumentException(HttpRuntime.FormatResourceString(SR.Key_Cannot_Be_Null));
            }

            StateItem item = bag[key] as StateItem;

            if (item == null)
            {
                if (value != null || marked)
                {
                    item = new StateItem(value);
                    bag.Add(key, item);
                }
            }
            else
            {
                if (value == null && !marked)
                {
                    bag.Remove(key);
                }
                else
                {
                    item.Value = value;
                }
            }
            if (item != null && marked)
            {
                item.IsDirty = true;
            }
            return(item);
        }
        /*
         * Compile a web handler file into a Type.
         */
        private Type GetCompiledTypeInternal()
        {
            DateTime utcStart = DateTime.UtcNow;

            // Add all the assemblies specified in the config files
            AppendConfigAssemblies();

            ParseReader();

            // Compile the inline source code in the file, if any
            CompileSourceCode();

            if (_compiledType == null)
            {
                _compiledType = GetType(_className);

                // Even though we didn't compile anything, cache the type to avoid
                // having to reparse the file every time (ASURT 67802)
                _sourceCompiler.CacheType(_compiledType, utcStart);
            }

            if (_compiledType == null)
            {
                throw new HttpException(
                          HttpRuntime.FormatResourceString(SR.Could_not_create_type, _className));
            }

            return(_compiledType);
        }
        static XmlNode GetAndRemoveIntegerOrInfiniteAttribute(XmlNode node, string attrib, ref int val)
        {
            string  sValue = null;
            XmlNode a      = HandlerBase.GetAndRemoveStringAttribute(node, attrib, ref sValue);

            if (a != null)
            {
                if (sValue == "Infinite")
                {
                    val = int.MaxValue;
                }
                else
                {
                    try {
                        val = int.Parse(sValue, NumberStyles.None, CultureInfo.InvariantCulture);
                    }
                    catch (Exception e) {
                        throw new ConfigurationException(
                                  HttpRuntime.FormatResourceString(SR.Invalid_integer_attribute, a.Name),
                                  e, a);
                    }
                }
            }

            return(a);
        }
Example #25
0
        internal void CheckAndUpdate(XmlNode section, string [] lockableAttrList)
        {
            // verify the attributes at this level have not been locked
            CheckForLocked(section);


            string  stringlockList = null;
            XmlNode attr           = HandlerBase.GetAndRemoveStringAttribute(section, "lockAttributes", ref stringlockList);

            if (stringlockList == null)
            {
                return;
            }

            // comma-delimited list of attributes
            string [] attributesToLock = stringlockList.Split(new char [] { ',', ';' });
            foreach (string s in attributesToLock)
            {
                string attributeToLock = s.Trim(' ');

                if (HandlerBase.IndexOfCultureInvariant(lockableAttrList, attributeToLock) == -1)
                {
                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Invalid_lockAttributes, attributeToLock, HandlerBase.CombineStrings(lockableAttrList)),
                              attr);
                }

                _lockedAttributes[attributeToLock] = "";
            }
        }
Example #26
0
 internal static void ThrowUnrecognizedElement(XmlNode node)
 {
     CheckBreakOnUnrecognizedElement();
     throw new ConfigurationException(
               HttpRuntime.FormatResourceString(SR.Config_base_unrecognized_element),
               node);
 }
Example #27
0
        private static XmlNode GetAndRemoveEnumAttributeInternal(XmlNode node, string attrib, bool isRequired, string [] values, ref int val)
        {
            XmlNode a = GetAndRemoveAttribute(node, attrib, isRequired);

            if (a == null)
            {
                return(null);
            }
            for (int i = 0; i < values.Length; ++i)
            {
                if (values[i] == a.Value)   // case sensitive
                //if (string.Compare(values[i], a.Value, false, CultureInfo.InvariantCulture) == 0) { // ignore case
                {
                    val = i;
                    return(a);
                }
            }

            string names = null;

            foreach (string name in values)
            {
                if (names == null)
                {
                    names = name;
                }
                else
                {
                    names += ", " + name;
                }
            }
            throw new ConfigurationException(HttpRuntime.FormatResourceString(SR.Invalid_enum_attribute, attrib, names), a);
        }
        /// <include file='doc\HyperLinkColumn.uex' path='docs/doc[@for="HyperLinkColumn.OnDataBindColumn"]/*' />
        /// <devdoc>
        /// </devdoc>
        private void OnDataBindColumn(object sender, EventArgs e)
        {
            Debug.Assert((DataTextField.Length != 0) || (DataNavigateUrlField.Length != 0),
                         "Shouldn't be DataBinding without a DataTextField and DataNavigateUrlField");

            HyperLink    boundControl = (HyperLink)sender;
            DataGridItem item         = (DataGridItem)boundControl.NamingContainer;
            object       dataItem     = item.DataItem;

            if ((textFieldDesc == null) && (urlFieldDesc == null))
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dataItem);
                string fieldName;

                fieldName = DataTextField;
                if (fieldName.Length != 0)
                {
                    textFieldDesc = props.Find(fieldName, true);
                    if ((textFieldDesc == null) && !DesignMode)
                    {
                        throw new HttpException(HttpRuntime.FormatResourceString(SR.Field_Not_Found, fieldName));
                    }
                }

                fieldName = DataNavigateUrlField;
                if (fieldName.Length != 0)
                {
                    urlFieldDesc = props.Find(fieldName, true);
                    if ((urlFieldDesc == null) && !DesignMode)
                    {
                        throw new HttpException(HttpRuntime.FormatResourceString(SR.Field_Not_Found, fieldName));
                    }
                }
            }

            if (textFieldDesc != null)
            {
                object data      = textFieldDesc.GetValue(dataItem);
                string dataValue = FormatDataTextValue(data);

                boundControl.Text = dataValue;
            }
            else if (DesignMode && (DataTextField.Length != 0))
            {
                boundControl.Text = SR.GetString(SR.Sample_Databound_Text);
            }

            if (urlFieldDesc != null)
            {
                object data      = urlFieldDesc.GetValue(dataItem);
                string dataValue = FormatDataNavigateUrlValue(data);

                boundControl.NavigateUrl = dataValue;
            }
            else if (DesignMode && (DataNavigateUrlField.Length != 0))
            {
                boundControl.NavigateUrl = "url";
            }
        }
        //
        // Create a rulelist from an element's children
        //
        static ArrayList RuleListFromElement(ParseState parseState, XmlNode node, bool top)
        {
            ArrayList result = new ArrayList();

            foreach (XmlNode child in node.ChildNodes)
            {
                switch (child.NodeType)
                {
                case XmlNodeType.Text:
                case XmlNodeType.CDATA:
                    top = false;
                    AppendLines(result, child.Value, node);
                    break;

                case XmlNodeType.Element:
                    switch (child.Name)
                    {
                    case "result":
                        if (top)
                        {
                            ProcessResult(parseState.Evaluator, child);
                        }
                        else
                        {
                            throw new ConfigurationException(
                                      HttpRuntime.FormatResourceString(SR.Result_must_be_at_the_top_browser_section),
                                      child);
                        }
                        break;

                    case "file":
                        if (parseState.IsExternalFile)
                        {
                            throw new ConfigurationException(
                                      HttpRuntime.FormatResourceString(SR.File_element_only_valid_in_config),
                                      child);
                        }
                        ProcessFile(parseState.FileList, child);
                        break;

                    default:
                        result.Add(RuleFromElement(parseState, child));
                        break;
                    }
                    top = false;
                    break;

                case XmlNodeType.Comment:
                case XmlNodeType.Whitespace:
                    break;

                default:
                    HandlerBase.ThrowUnrecognizedElement(child);
                    break;
                }
            }

            return(result);
        }
Example #30
0
 internal static void CheckAssignableType(Type baseType, Type type)
 {
     if (!baseType.IsAssignableFrom(type))
     {
         throw new HttpException(
                   HttpRuntime.FormatResourceString(SR.Type_doesnt_inherit_from_type,
                                                    type.FullName, baseType.FullName));
     }
 }