File: ApplicationSettingsBase.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (820 lines) | stat: -rw-r--r-- 33,855 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//------------------------------------------------------------------------------
// <copyright file="ApplicationSettingsBase.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System.Diagnostics.CodeAnalysis;

// These aren't valid violations - caused by HostProtectionAttribute.
[assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.Configuration.ApplicationSettingsBase.add_PropertyChanged(System.ComponentModel.PropertyChangedEventHandler):System.Void")]
[assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.Configuration.ApplicationSettingsBase.remove_PropertyChanged(System.ComponentModel.PropertyChangedEventHandler):System.Void")]
[assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.TypeDescriptor.GetConverter(System.Type):System.ComponentModel.TypeConverter")]


// Reviewed and found to be safe.
[assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.Configuration.LocalFileSettingsProvider..ctor()")]

namespace System.Configuration {

    using System.ComponentModel;
    using System.Collections;
    using System.Diagnostics;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Security.Permissions;

    /// <devdoc>
    ///     Base settings class for client applications.
    /// </devdoc>
    public abstract class ApplicationSettingsBase : SettingsBase, INotifyPropertyChanged {
        private bool                            _explicitSerializeOnClass = false;
        private object[]                        _classAttributes;
        private IComponent                      _owner;
        private PropertyChangedEventHandler     _onPropertyChanged;
        private SettingsContext                 _context;
        private SettingsProperty                _init;
        private SettingsPropertyCollection      _settings;
        private SettingsProviderCollection      _providers;
        private SettingChangingEventHandler     _onSettingChanging;
        private SettingsLoadedEventHandler      _onSettingsLoaded;
        private SettingsSavingEventHandler      _onSettingsSaving;
        private string                          _settingsKey = String.Empty;
        private bool                            _firstLoad = true;
        private bool                            _initialized = false;
        
        /// <devdoc>
        ///     Default constructor without a concept of "owner" component.
        /// </devdoc>
        protected ApplicationSettingsBase() : base() {
        }

        /// <devdoc>
        ///     Constructor that takes an IComponent. The IComponent acts as the "owner" of this settings class. One
        ///     of the things we do is query the component's site to see if it has a SettingsProvider service. If it 
        ///     does, we allow it to override the providers specified in the metadata.
        /// </devdoc>
        protected ApplicationSettingsBase(IComponent owner) : this(owner, String.Empty) {
        }

        /// <devdoc>
        ///     Convenience overload that takes the settings key
        /// </devdoc>
        protected ApplicationSettingsBase(string settingsKey) {
            _settingsKey = settingsKey;
        }

        /// <devdoc>
        ///     Convenience overload that takes the owner component and settings key.
        /// </devdoc>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        protected ApplicationSettingsBase(IComponent owner, string settingsKey) : this(settingsKey) {
            if (owner == null) {
                throw new ArgumentNullException("owner");
            }

            _owner = owner;

            if (owner.Site != null) {
                ISettingsProviderService provSvc = owner.Site.GetService(typeof(ISettingsProviderService)) as ISettingsProviderService;
                if (provSvc != null) {
                    // The component's site has a settings provider service. We pass each SettingsProperty to it
                    // to see if it wants to override the current provider.
                    foreach (SettingsProperty sp in Properties) {
                        SettingsProvider prov = provSvc.GetSettingsProvider(sp);
                        if (prov != null) {
                            sp.Provider = prov;
                        }
                    }

                    ResetProviders();
                }
            }
        }
        
        /// <devdoc>
        ///     The Context to pass on to the provider. Currently, this will just contain the settings group name.
        /// </devdoc>
        [Browsable(false)]
        public override SettingsContext Context {
            get {
                if (_context == null) {
                    if (IsSynchronized) {
                        lock (this) {
                            if (_context == null) {
                                _context = new SettingsContext();
                                EnsureInitialized();
                            }
                        }
                    }
                    else {
                        _context = new SettingsContext();
                        EnsureInitialized();
                    }
                    
                }

                return _context;
            }
        }
        
        /// <devdoc>
        ///     The SettingsBase class queries this to get the collection of SettingsProperty objects. We reflect over 
        ///     the properties defined on the current object's type and use the metadata on those properties to form 
        ///     this collection.
        /// </devdoc>
        [Browsable(false)]
        public override SettingsPropertyCollection Properties {
            get {
                if (_settings == null) {
                    if (IsSynchronized) {
                        lock (this) {
                            if (_settings == null) {
                                _settings = new SettingsPropertyCollection();
                                EnsureInitialized();
                            }
                        }
                    }
                    else {
                        _settings = new SettingsPropertyCollection();
                        EnsureInitialized();
                    }
                    
                }

                return _settings;
            }
        }

        /// <devdoc>
        ///     Just overriding to add attributes.
        /// </devdoc>
        [Browsable(false)]
        public override SettingsPropertyValueCollection PropertyValues {
            get {
                return base.PropertyValues;
            }
        }

        /// <devdoc>
        ///     Provider collection
        /// </devdoc>
        [Browsable(false)]
        public override SettingsProviderCollection Providers {
            get {
                if (_providers == null) {
                    if (IsSynchronized) {
                        lock (this) {
                            if (_providers == null) {
                                _providers = new SettingsProviderCollection();
                                EnsureInitialized();
                            }
                        }
                    }
                    else {
                        _providers = new SettingsProviderCollection();
                        EnsureInitialized();
                    }
                }

                return _providers;
            }
        }

        /// <devdoc>
        ///     Derived classes should use this to uniquely identify separate instances of settings classes.
        /// </devdoc>
        [Browsable(false)]
        public string SettingsKey {
            get {
                return _settingsKey;
            }
            set {
                _settingsKey = value;
                Context["SettingsKey"] = _settingsKey;
            }
        }

        /// <devdoc>
        ///     Fires when the value of a setting is changed. (INotifyPropertyChanged implementation.)
        /// </devdoc>
        public event PropertyChangedEventHandler PropertyChanged {
            add {
                _onPropertyChanged += value;
            }
            remove {
                _onPropertyChanged -= value;
            }

        }

        /// <devdoc>
        ///     Fires when the value of a setting is about to change. This is a cancellable event.
        /// </devdoc>
        public event SettingChangingEventHandler SettingChanging {
            add {
                _onSettingChanging += value;
            }
            remove {
                _onSettingChanging -= value;
            }
        }

        /// <devdoc>
        ///     Fires when settings are retrieved from a provider. It fires once for each provider.
        /// </devdoc>
        public event SettingsLoadedEventHandler SettingsLoaded {
            add {
                _onSettingsLoaded += value;
            }
            remove {
                _onSettingsLoaded -= value;
            }
        }

        /// <devdoc>
        ///     Fires when Save() is called. This is a cancellable event.
        /// </devdoc>
        public event SettingsSavingEventHandler SettingsSaving {
            add {
                _onSettingsSaving += value;
            }
            remove {
                _onSettingsSaving -= value;
            }
        }

        /// <devdoc>
        ///     Used in conjunction with Upgrade - retrieves the previous value of a setting from the provider.
        ///     Provider must implement IApplicationSettingsProvider to support this.
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        public object GetPreviousVersion(string propertyName) {
           if (Properties.Count == 0)
               throw new SettingsPropertyNotFoundException();

           SettingsProperty sp = Properties[propertyName];
           SettingsPropertyValue value = null;

           if (sp == null)
               throw new SettingsPropertyNotFoundException();

           IApplicationSettingsProvider clientProv = sp.Provider as IApplicationSettingsProvider;
           
           if (clientProv != null) {
               value = clientProv.GetPreviousVersion(Context, sp);
           }

           if (value != null) {
               return value.PropertyValue;
           }

           return null;
        }

        /// <devdoc>
        ///     Fires the PropertyChanged event.
        /// </devdoc>
        protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) {
            if(_onPropertyChanged != null) {
                _onPropertyChanged(this, e); 
            }
        }

        /// <devdoc>
        ///     Fires the SettingChanging event.
        /// </devdoc>
        protected virtual void OnSettingChanging(object sender, SettingChangingEventArgs e) {
            if(_onSettingChanging != null) {
                _onSettingChanging(this, e); 
            }
        }

        /// <devdoc>
        ///     Fires the SettingsLoaded event.
        /// </devdoc>
        protected virtual void OnSettingsLoaded(object sender, SettingsLoadedEventArgs e) {
            if(_onSettingsLoaded != null) {
                _onSettingsLoaded(this, e);
            }
        }

        /// <devdoc>
        ///     Fires the SettingsSaving event.
        /// </devdoc>
        protected virtual void OnSettingsSaving(object sender, CancelEventArgs e) {
            if(_onSettingsSaving != null) {
                _onSettingsSaving(this, e); 
            }
        }

        /// <devdoc>
        ///     Causes a reload to happen on next setting access, by clearing the cached values.
        /// </devdoc>
        public void Reload() {
            if (PropertyValues != null) {
                PropertyValues.Clear();
            }

            foreach (SettingsProperty sp in Properties) {
                PropertyChangedEventArgs pe = new PropertyChangedEventArgs(sp.Name);
                OnPropertyChanged(this, pe);
            }
        }

        /// <devdoc>
        ///     Calls Reset on the providers.
        ///     Providers must implement IApplicationSettingsProvider to support this.
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        public void Reset() {
            if (Properties != null) {
                foreach(SettingsProvider provider in Providers) {
                    IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider;
                    if (clientProv != null) {
                        clientProv.Reset(Context);
                    }
                }
            }

            Reload();
        }

        /// <devdoc>
        ///     Overriden from SettingsBase to support validation event.
        /// </devdoc>
        public override void Save() {
            CancelEventArgs e= new CancelEventArgs(false);
            OnSettingsSaving(this, e);

            if (!e.Cancel) {
                base.Save();
            }
        }

        /// <devdoc>
        ///     Overriden from SettingsBase to support validation event.
        /// </devdoc>
        public override object this[string propertyName] {
            get {
                if (IsSynchronized) {
                    lock (this) {
                        return GetPropertyValue(propertyName);
                    }
                }
                else {
                    return GetPropertyValue(propertyName);
                }
                
            }
            set {
                SettingChangingEventArgs e = new SettingChangingEventArgs(propertyName, this.GetType().FullName, SettingsKey, value, false);
                OnSettingChanging(this, e);
        
                if (!e.Cancel) {
                    base[propertyName] = value;
                    //
                    PropertyChangedEventArgs pe = new PropertyChangedEventArgs(propertyName);
                    OnPropertyChanged(this, pe);
                }
            }
        }

        /// <devdoc>
        ///     Called when the app is upgraded so that we can instruct the providers to upgrade their settings.
        ///     Providers must implement IApplicationSettingsProvider to support this.
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        public virtual void Upgrade() {
            if (Properties != null) {
                foreach(SettingsProvider provider in Providers) {
                    IApplicationSettingsProvider clientProv = provider as IApplicationSettingsProvider;
                    if (clientProv != null) {
                        clientProv.Upgrade(Context, GetPropertiesForProvider(provider));
                    }
                }
            }

            Reload();
        }

        /// <devdoc>
        ///     Creates a SettingsProperty object using the metadata on the given property 
        ///     and returns it.
        ///
        ///     Implementation note: Initialization method - be careful not to access properties here
        ///                          to prevent stack overflow.
        /// </devdoc>
        private SettingsProperty CreateSetting(PropertyInfo propInfo) {
            object[] attributes = propInfo.GetCustomAttributes(false); 
            SettingsProperty sp = new SettingsProperty(Initializer);
            bool explicitSerialize = _explicitSerializeOnClass;

            sp.Name = propInfo.Name; 
            sp.PropertyType = propInfo.PropertyType;
            
            for (int i = 0; i < attributes.Length; i ++) {
                Attribute attr = attributes[i] as Attribute;
                if (attr != null) {
                    if (attr is DefaultSettingValueAttribute) {
                        sp.DefaultValue = ((DefaultSettingValueAttribute)attr).Value;
                    }
                    else if (attr is ReadOnlyAttribute) {
                        sp.IsReadOnly = true;
                    }
                    else if (attr is SettingsProviderAttribute) {
                        string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName;
                        Type providerType = Type.GetType(providerTypeName);
                        if (providerType != null) {
                            SettingsProvider spdr = SecurityUtils.SecureCreateInstance(providerType) as SettingsProvider;

                            if (spdr != null) {
                                spdr.Initialize(null, null);
                                spdr.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName;

                                // See if we already have a provider of the same name in our collection. If so,
                                // re-use the existing instance, since we cannot have multiple providers of the same name.
                                SettingsProvider existing = _providers[spdr.Name];
                                if (existing != null) {
                                    spdr = existing;
                                }
                                
                                sp.Provider = spdr;
                            }
                            else {
                                throw new ConfigurationErrorsException(SR.GetString(SR.ProviderInstantiationFailed, providerTypeName));
                            }
                        }
                        else {
                            throw new ConfigurationErrorsException(SR.GetString(SR.ProviderTypeLoadFailed, providerTypeName));
                        }
                    }
                    else if (attr is SettingsSerializeAsAttribute) {
                        sp.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs;
                        explicitSerialize = true;
                    }
                    else {
                        // This isn't an attribute we care about, so simply pass it on
                        // to the SettingsProvider.
                        // NOTE: The key is the type. So if an attribute was found at class
                        //       level and also property level, the latter overrides the former
                        //       for a given setting. This is exactly the behavior we want.
                        
                        sp.Attributes.Add(attr.GetType(), attr);
                    }
                }
            }

            if (!explicitSerialize) {
                sp.SerializeAs = GetSerializeAs(propInfo.PropertyType);
            }

            return sp;

        }

        /// <devdoc>
        ///     Ensures this class is initialized. Initialization involves reflecting over properties and building
        ///     a list of SettingsProperty's.
        /// 
        ///     Implementation note: Initialization method - be careful not to access properties here
        ///                          to prevent stack overflow.
        /// </devdoc>
        private void EnsureInitialized() {
            if (!_initialized) {
                _initialized = true;

                Type type = this.GetType();
                
                if (_context == null) {
                    _context = new SettingsContext();
                }
                _context["GroupName"] = type.FullName;
                _context["SettingsKey"] = SettingsKey;
                _context["SettingsClassType"] = type; 

                PropertyInfo[] properties = SettingsFilter(type.GetProperties(BindingFlags.Instance | BindingFlags.Public));
                _classAttributes = type.GetCustomAttributes(false); 

                if (_settings == null) {
                    _settings = new SettingsPropertyCollection();
                }

                if (_providers == null) {
                    _providers = new SettingsProviderCollection();
                }
                
                for (int i = 0; i < properties.Length; i++) {
                    SettingsProperty sp = CreateSetting(properties[i]);
                    if (sp != null) {
                        _settings.Add(sp);

                        if (sp.Provider != null && _providers[sp.Provider.Name] == null) {
                            _providers.Add(sp.Provider);
                        }
                    }
                }
            }
        }

        /// <devdoc>
        ///     Returns a SettingsProperty used to initialize settings. We initialize a setting with values
        ///     derived from class level attributes, if present. Otherwise, we initialize to
        ///     reasonable defaults.
        ///
        ///     Implementation note: Initialization method - be careful not to access properties here
        ///                          to prevent stack overflow.
        /// </devdoc>
        private SettingsProperty Initializer {
            get {
                if (_init == null) {
                    _init = new SettingsProperty("");
                    _init.DefaultValue = null;
                    _init.IsReadOnly = false;
                    _init.PropertyType = null;

                    SettingsProvider provider = new LocalFileSettingsProvider();
                    
                    if (_classAttributes != null) {
                        for (int i = 0; i < _classAttributes.Length; i ++) {
                            Attribute attr = _classAttributes[i] as Attribute;
                            if (attr != null) {
                                if (attr is ReadOnlyAttribute) {
                                    _init.IsReadOnly = true;
                                }
                                else if (attr is SettingsGroupNameAttribute) {
                                    if (_context == null) {
                                        _context = new SettingsContext();
                                    }
                                    _context["GroupName"] = ((SettingsGroupNameAttribute)attr).GroupName;
                                }
                                else if (attr is SettingsProviderAttribute) {
                                    string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName;
                                    Type providerType = Type.GetType(providerTypeName);
                                    if (providerType != null) {
                                        SettingsProvider spdr = SecurityUtils.SecureCreateInstance(providerType) as SettingsProvider;
                                        if (spdr != null) {
                                            provider = spdr;
                                        }
                                        else {
                                            throw new ConfigurationErrorsException(SR.GetString(SR.ProviderInstantiationFailed, providerTypeName));
                                        }
                                    }
                                    else {
                                        throw new ConfigurationErrorsException(SR.GetString(SR.ProviderTypeLoadFailed, providerTypeName));
                                    }
                                }
                                else if (attr is SettingsSerializeAsAttribute) {
                                    _init.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs;
                                    _explicitSerializeOnClass = true;
                                }
                                else {
                                    // This isn't an attribute we care about, so simply pass it on
                                    // to the SettingsProvider.
                                    // NOTE: The key is the type. So if an attribute was found at class
                                    //       level and also property level, the latter overrides the former
                                    //       for a given setting. This is exactly the behavior we want.
                                    _init.Attributes.Add(attr.GetType(), attr);
                                }
                            }
                        }
                    }

                    //Initialize the SettingsProvider
                    provider.Initialize(null, null);
                    provider.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName;
                    _init.Provider = provider;

                }

                return _init;
            }
        }

        /// <devdoc>
        ///     Gets all the settings properties for this provider.
        /// </devdoc>
        private SettingsPropertyCollection GetPropertiesForProvider(SettingsProvider provider) {
           SettingsPropertyCollection properties = new SettingsPropertyCollection();
           foreach (SettingsProperty sp in Properties) {
               if (sp.Provider == provider) {
                   properties.Add(sp);
               }
           }

           return properties;
        }

        /// <devdoc>
        ///     Retrieves the value of a setting. We need this method so we can fire the SettingsLoaded event 
        ///     when settings are loaded from the providers.Ideally, this should be fired from SettingsBase, 
        ///     but unfortunately that will not happen in Whidbey. Instead, we check to see if the value has already 
        ///     been retrieved. If not, we fire the load event, since we expect SettingsBase to load all the settings 
        ///     from this setting's provider.
        /// </devdoc>
        private object GetPropertyValue(string propertyName) {
            if (PropertyValues[propertyName] == null) {

                // If this is our first load and we are part of a Clickonce app, call Upgrade.
                if (_firstLoad) {
                    _firstLoad = false;

                    if (IsFirstRunOfClickOnceApp()) {
                        Upgrade();
                    }
                }

                object temp = base[propertyName];
                SettingsProperty setting = Properties[propertyName];
                SettingsProvider provider = setting != null ? setting.Provider : null;

                Debug.Assert(provider != null, "Could not determine provider from which settings were loaded");

                SettingsLoadedEventArgs e = new SettingsLoadedEventArgs(provider);
                OnSettingsLoaded(this, e);

                // Note: we need to requery the value here in case someone changed it while
                // handling SettingsLoaded.
                return base[propertyName];
            }
            else {
                return base[propertyName];
            }
        }

        /// <devdoc>
        ///     When no explicit SerializeAs attribute is provided, this routine helps to decide how to
        ///     serialize. 
        /// </devdoc>
        private SettingsSerializeAs GetSerializeAs(Type type) {
            //First check whether this type has a TypeConverter that can convert to/from string
            //If so, that's our first choice
            TypeConverter tc = TypeDescriptor.GetConverter(type);
            bool toString = tc.CanConvertTo(typeof(string));
            bool fromString = tc.CanConvertFrom(typeof(string));
            if (toString && fromString) {
                return SettingsSerializeAs.String;
            }

            //Else fallback to Xml Serialization 
            return SettingsSerializeAs.Xml;
        }

        /// <devdoc>
        ///     Returns true if this is a clickonce deployed app and this is the first run of the app
        ///     since deployment or last upgrade.
        /// </devdoc>
        private bool IsFirstRunOfClickOnceApp() {
            // NOTE: For perf & servicing reasons, we don't want to introduce a dependency on
            //       System.Deployment.dll here. The following code is an alternative to calling
            //       ApplicationDeployment.CurrentDeployment.IsFirstRun.
         
            // First check if the app is ClickOnce deployed
            ActivationContext actCtx = AppDomain.CurrentDomain.ActivationContext;
            
            if (IsClickOnceDeployed(AppDomain.CurrentDomain)) {
                // Now check if this is the first run since deployment or last upgrade
                return System.Deployment.Internal.InternalActivationContextHelper.IsFirstRun(actCtx);
            }

            return false;
        }

        /// <devdoc>
        ///     Returns true if this is a clickonce deployed app.
        /// </devdoc>
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts")]
        [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
        internal static bool IsClickOnceDeployed(AppDomain appDomain) {
            // NOTE: For perf & servicing reasons, we don't want to introduce a dependency on
            //       System.Deployment.dll here. The following code is an alternative to calling
            //       ApplicationDeployment.IsNetworkDeployed.
            // Security Note: This is also why we need the security assert above.

            ActivationContext actCtx = appDomain.ActivationContext;

            // Ensures the app is running with a context from the store.
            if (actCtx != null && actCtx.Form == ActivationContext.ContextForm.StoreBounded) {
                string fullAppId = actCtx.Identity.FullName;
                if (!String.IsNullOrEmpty(fullAppId)) {
                    return true;
                }
            }

            return false;
        }

        /// <devdoc>
        ///     Only those settings class properties that have a SettingAttribute on them are 
        ///     treated as settings. This routine filters out other properties.
        /// </devdoc>
        private PropertyInfo[] SettingsFilter(PropertyInfo[] allProps) {
            ArrayList settingProps = new ArrayList();
            object[] attributes;
            Attribute attr;
            
            for (int i = 0; i < allProps.Length; i ++) {
                attributes = allProps[i].GetCustomAttributes(false); 
                for (int j = 0; j < attributes.Length; j ++) {
                    attr = attributes[j] as Attribute;
                    if (attr is SettingAttribute) {
                        settingProps.Add(allProps[i]);
                        break;
                    }
                }
            }

            return (PropertyInfo[]) settingProps.ToArray(typeof(PropertyInfo));
        }

        /// <devdoc>
        ///     Resets the provider collection. This needs to be called when providers change after
        ///     first being set. 
        /// </devdoc>
        private void ResetProviders() {
            Providers.Clear();

            foreach (SettingsProperty sp in Properties) {
                if (Providers[sp.Provider.Name] == null) {
                    Providers.Add(sp.Provider);
                }
            }
        }
    }

    /// <devdoc>
    ///     Event handler for the SettingsLoaded event.
    /// </devdoc>
    public delegate void SettingsLoadedEventHandler(object sender, SettingsLoadedEventArgs e);

    /// <devdoc>
    ///     Event handler for the SettingsSaving event.
    /// </devdoc>
    public delegate void SettingsSavingEventHandler(object sender, CancelEventArgs e);

    /// <devdoc>
    ///     Event handler for the SettingChanging event.
    /// </devdoc>
    public delegate void SettingChangingEventHandler(object sender, SettingChangingEventArgs e);

    /// <devdoc>
    ///     Event args for the SettingChanging event.
    /// </devdoc>
    public class SettingChangingEventArgs : CancelEventArgs {

        private string _settingClass;
        private string _settingName;
        private string _settingKey;
        private object _newValue;

        public SettingChangingEventArgs(string settingName, string settingClass, string settingKey, object newValue, bool cancel) : base(cancel) {
            _settingName = settingName;
            _settingClass = settingClass;
            _settingKey = settingKey;
            _newValue = newValue;
        }

        public object NewValue {
            get {
                return _newValue;
            }
        }

        public string SettingClass {
            get {
                return _settingClass;
            }
        }

        public string SettingName {
            get {
                return _settingName;
            }
        }

        public string SettingKey {
            get {
                return _settingKey;
            }
        }
    }

    /// <devdoc>
    ///     Event args for the SettingLoaded event.
    /// </devdoc>
    public class SettingsLoadedEventArgs : EventArgs {

        private SettingsProvider _provider;
        
        public SettingsLoadedEventArgs(SettingsProvider provider) {
            _provider = provider;
        }

        public SettingsProvider Provider {
            get {
                return _provider;
            }
        }
    }
}