none
You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection

    Question

  • Hi,

    I've tried to use the sample provided for ConfigurationCollection attribute from msdn - http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx

    When I tried to serialize the class using XmlSerializer, the following exception occurred.

    System.InvalidOperationException was unhandled
      Message="There was an error reflecting type 'Qss.Common.UrlsSection'."
      Source="System.Xml"
      StackTrace:
           at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel)
           at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace)
           at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
           at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
           at System.Xml.Serialization.XmlSerializer..ctor(Type type)
           at Client.Program.Main(String[] args) in D:\Kiran Projects\ConfigFactoryPOCA2\Client\Program.cs:line 23
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.InvalidOperationException
           Message="You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection."
           Source="System.Xml"
           StackTrace:
                at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)
                at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
                at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
                at System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo)
                at System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo)
                at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a)
                at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a)
                at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a)
                at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel)
           InnerException:


    Here is the code that I've used for Serialization.

    XmlSerializer xs = new XmlSerializer(typeof(UrlsSection));
    FileStream fs = new FileStream(@"C:\Testxml.txt", FileMode.Create);
    xs.Serialize(fs, urlConfig);
    fs.Close();

    What could be wrong with the UrlsSection class?
    TIA.
    Kiran Kumar. Dasika
    Monday, July 20, 2009 7:10 AM

All replies

  • It complains because it cannot find the indexer property (this[int index]).  Did you provide one?

    Hans Passant.
    Monday, July 20, 2009 1:08 PM
  • Yes. It is there. Here is the code (from MSDN).


    // Set assembly name to "ConfigurationCollectionAttribute" to match
    // the section declaration in the sample app.config file.
    using System;
    using System.Configuration;


    namespace Samples.AspNet
    {
        class TestingConfigurationCollectionAttribute
        {
            static void Main(string[] args)
            {
                // Call ConfigurationManager to read the custom UrlsSection
                // of the app.config file and put its contents into an
                // instance of the custom class created for it.
                UrlsSection myUrlsSection =
                   ConfigurationManager.GetSection("MyUrls") as UrlsSection;

                if (myUrlsSection == null)
                    Console.WriteLine("Failed to load UrlsSection.");
                else
                {
                    Console.WriteLine("URLs defined in app.config:");
                    for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                    {
                        Console.WriteLine("  Name={0} URL={1} Port={2}",
                            myUrlsSection.Urls[i].Name,
                            myUrlsSection.Urls[i].Url,
                            myUrlsSection.Urls[i].Port);
                    }
                }
                Console.ReadLine();
            }
        }

        // Define a custom section named UrlsSection containing a
        // UrlsCollection collection of UrlConfigElement elements.
        // The collection is wrapped in an element named "urls" in the
        // app.config file.
        // UrlsCollection and UrlsConfigElement classes are defined below.
        public class UrlsSection : ConfigurationSection
        {
            // Declare the urls collection property.
            // Note: the "IsDefaultCollection = false" instructs
            // .NET Framework to build a nested section of
            // the kind <urls>...</urls>.
            [ConfigurationProperty("urls", IsDefaultCollection = false)]
            [ConfigurationCollection(typeof(UrlsCollection),
                AddItemName = "add",
                ClearItemsName = "clear",
                RemoveItemName = "remove")]
            public UrlsCollection Urls
            {
                get
                {
                    UrlsCollection urlsCollection =
                        (UrlsCollection)base["urls"];
                    return urlsCollection;
                }
            }

        }

        // Define the UrlsCollection that will contain the UrlsConfigElement
        // elements.
        public class UrlsCollection : ConfigurationElementCollection
        {
            public UrlsCollection()
            {
                // When the collection is created, always add one element
                // with the default values. (This is not necessary; it is
                // here only to illustrate what can be done; you could
                // also create additional elements with other hard-coded
                // values here.)
                UrlConfigElement url = (UrlConfigElement)CreateNewElement();
                Add(url);
            }

            public override ConfigurationElementCollectionType CollectionType
            {
                get
                {
                    return ConfigurationElementCollectionType.AddRemoveClearMap;
                }
            }

            protected override ConfigurationElement CreateNewElement()
            {
                return new UrlConfigElement();
            }

            protected override Object GetElementKey(ConfigurationElement element)
            {
                return ((UrlConfigElement)element).Name;
            }

            public UrlConfigElement this[int index]
            {
                get
                {
                    return (UrlConfigElement)BaseGet(index);
                }
                set
                {
                    if (BaseGet(index) != null)
                    {
                        BaseRemoveAt(index);
                    }
                    BaseAdd(index, value);
                }
            }

            new public UrlConfigElement this[string Name]
            {
                get
                {
                    return (UrlConfigElement)BaseGet(Name);
                }
            }

            public int IndexOf(UrlConfigElement url)
            {
                return BaseIndexOf(url);
            }

            public void Add(UrlConfigElement url)
            {
                BaseAdd(url);
            }
            protected override void BaseAdd(ConfigurationElement element)
            {
                BaseAdd(element, false);
            }

            public void Remove(UrlConfigElement url)
            {
                if (BaseIndexOf(url) >= 0)
                    BaseRemove(url.Name);
            }

            public void RemoveAt(int index)
            {
                BaseRemoveAt(index);
            }

            public void Remove(string name)
            {
                BaseRemove(name);
            }

            public void Clear()
            {
                BaseClear();
            }
        }

        // Define the element type contained by the UrlsCollection
        // collection.
        public class UrlConfigElement : ConfigurationElement
        {
            public UrlConfigElement(String name, String url)
            {
                this.Name = name;
                this.Url = url;
            }

            public UrlConfigElement()
            {
                // Attributes on the properties provide default values.
            }

            [ConfigurationProperty("name", DefaultValue = "Microsoft",
                IsRequired = true, IsKey = true)]
            public string Name
            {
                get
                {
                    return (string)this["name"];
                }
                set
                {
                    this["name"] = value;
                }
            }

            [ConfigurationProperty("url", DefaultValue = "http://www.microsoft.com",
                IsRequired = true)]
            [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
            public string Url
            {
                get
                {
                    return (string)this["url"];
                }
                set
                {
                    this["url"] = value;
                }
            }

            [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
            [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
            public int Port
            {
                get
                {
                    return (int)this["port"];
                }
                set
                {
                    this["port"] = value;
                }
            }
        }
    }


    Kiran Kumar. Dasika
    Tuesday, July 21, 2009 4:45 AM
  • Any ideas!


    Kiran Kumar. Dasika
    Monday, July 27, 2009 5:41 AM
  • I am also facing same problem.

    Server Error in '/' Application.


    You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.InvalidOperationException: You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.

    Source Error:

    Line 122:            leftMenuCollection.Add(menu);
    Line 123:            StringWriter stringWriter = new StringWriter();
    Line 124:            XmlSerializer xmlSerializer = new XmlSerializer(typeof(MenuCollection));//typeof(MenuCollection),types
    Line 125:            xmlSerializer.Serialize(stringWriter, leftMenuCollection);
    Line 126:            string serializedXML = stringWriter.ToString();


    Source File: .aspx.cs    Line: 124

    Stack Trace:

    [InvalidOperationException: You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.]
       System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo) +860417
       System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference) +860
       System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError) +150
       System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo) +71
       System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo) +118
       System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a) +1824
       System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a) +848
       System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel) +734
     
    [InvalidOperationException: There was an error reflecting type CrossCuttingServices.Configuration.XMLMapping.Menu'.]
       System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel) +1638
       System.Xml.Serialization.XmlReflectionImporter.CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, String arrayElementNs) +283
       System.Xml.Serialization.XmlReflectionImporter.ImportArrayLikeMapping(ArrayModel model, String ns) +315
       System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel) +435
     
    [InvalidOperationException: There was an error reflecting type 'CrossCuttingServices.Configuration.XMLMapping.MenuCollection'.]
       System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel) +1638
       System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace) +115
       System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace) +76
       System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace) +320
       System.Xml.Serialization.XmlSerializer..ctor(Type type) +6
       UI.WebUI.Views.Pricing.PricingLayerView.Page_Load(Object sender, EventArgs e) in D:\Shailendra\SourceCode\Stage1\UI\WebUI\Views\Pricing\PricingLayerView.aspx.cs:124
       System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
       System.Web.UI.Control.OnLoad(EventArgs e) +99
       System.Web.UI.Control.LoadRecursive() +47
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436

     


    Version Information: Microsoft .NET Framework Version:2.0.50727.1873; ASP.NET Version:2.0.50727.1433

    Tuesday, December 29, 2009 6:16 AM