File: LocalFileSettingsProvider.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 (553 lines) | stat: -rw-r--r-- 24,506 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
//------------------------------------------------------------------------------
// <copyright file="LocalFileSettingsProvider.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System.Diagnostics.CodeAnalysis;

namespace System.Configuration {
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Configuration;
    using System.Configuration.Provider;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Runtime.Versioning;
    
    /// <devdoc>
    ///    <para>
    ///         This is a provider used to store configuration settings locally for client applications.
    ///    </para>
    /// </devdoc>
    [
     PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"),
     PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")
    ]
    public class LocalFileSettingsProvider : SettingsProvider, IApplicationSettingsProvider
    {
        private string              _appName                    = String.Empty;
        private ClientSettingsStore  _store                     = null;
        private string              _prevLocalConfigFileName    = null;
        private string              _prevRoamingConfigFileName  = null;
        private XmlEscaper          _escaper                    = null;
        
        /// <devdoc>
        ///     Abstract SettingsProvider property.
        /// </devdoc>
        public override string ApplicationName { 
            get { 
                return _appName;
            } 
            set {
                _appName = value;
            }
        }

        private XmlEscaper Escaper {
            get {
                if (_escaper == null) {
                    _escaper = new XmlEscaper();
                }

                return _escaper;
            }
        }

        /// <devdoc>
        ///     We maintain a single instance of the ClientSettingsStore per instance of provider.
        /// </devdoc>
        private ClientSettingsStore Store {
            get {
                if (_store == null) {
                    _store = new ClientSettingsStore();
                }

                return _store;
            }
        }

        /// <devdoc>
        ///     Abstract ProviderBase method.
        /// </devdoc>
        public override void Initialize(string name, NameValueCollection values) {
            if (String.IsNullOrEmpty(name)) {
                name = "LocalFileSettingsProvider";
            }

            base.Initialize(name, values);
        }

        /// <devdoc>
        ///     Abstract SettingsProvider method
        /// </devdoc>
        public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties) {
            SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();
            string sectionName = GetSectionName(context);

            //<--Look for this section in both applicationSettingsGroup and userSettingsGroup-->
            IDictionary appSettings = Store.ReadSettings(sectionName, false);
            IDictionary userSettings = Store.ReadSettings(sectionName, true);
            ConnectionStringSettingsCollection connStrings = Store.ReadConnectionStrings();

            //<--Now map each SettingProperty to the right StoredSetting and deserialize the value if found.-->
            foreach (SettingsProperty setting in properties) {
                string settingName = setting.Name;
                SettingsPropertyValue value = new SettingsPropertyValue(setting);
                
                // First look for and handle "special" settings
                SpecialSettingAttribute attr = setting.Attributes[typeof(SpecialSettingAttribute)] as SpecialSettingAttribute;
                bool isConnString =  (attr != null) ? (attr.SpecialSetting == SpecialSetting.ConnectionString) : false;
                
                if (isConnString) { 
                    string connStringName = sectionName + "." + settingName; 
                    if (connStrings != null && connStrings[connStringName] != null) {
                        value.PropertyValue = connStrings[connStringName].ConnectionString;
                    }
                    else if (setting.DefaultValue != null && setting.DefaultValue is string) {
                        value.PropertyValue = setting.DefaultValue;
                    }
                    else {
                        //No value found and no default specified 
                        value.PropertyValue = String.Empty;
                    }

                    value.IsDirty = false; //reset IsDirty so that it is correct when SetPropertyValues is called 
                    values.Add(value);
                    continue;
                }

                // Not a "special" setting
                bool isUserSetting = IsUserSetting(setting); 

                if (isUserSetting && !ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
                    // We encountered a user setting, but the current configuration system does not support
                    // user settings.
                   throw new ConfigurationErrorsException(SR.GetString(SR.UserSettingsNotSupported));
                }

                IDictionary settings = isUserSetting ? userSettings : appSettings;
                
                if (settings.Contains(settingName)) {
                    StoredSetting ss = (StoredSetting) settings[settingName];
                    string valueString = ss.Value.InnerXml;

                    // We need to un-escape string serialized values
                    if (ss.SerializeAs == SettingsSerializeAs.String) {
                        valueString = Escaper.Unescape(valueString);
                    }

                    value.SerializedValue = valueString;
                }
                else if (setting.DefaultValue != null) {
                    value.SerializedValue = setting.DefaultValue;
                }
                else {
                    //No value found and no default specified 
                    value.PropertyValue = null;
                }

                value.IsDirty = false; //reset IsDirty so that it is correct when SetPropertyValues is called 
                values.Add(value);
            }

            return values;
        }

        /// <devdoc>
        ///     Abstract SettingsProvider method
        /// </devdoc>
        public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values) {
            string sectionName = GetSectionName(context);
            IDictionary roamingUserSettings = new Hashtable();
            IDictionary localUserSettings = new Hashtable();
            
            foreach (SettingsPropertyValue value in values) {
                SettingsProperty setting = value.Property;
                bool isUserSetting = IsUserSetting(setting);

                if (value.IsDirty) {
                    if (isUserSetting) {
                        bool isRoaming = IsRoamingSetting(setting);
                        StoredSetting ss = new StoredSetting(setting.SerializeAs, SerializeToXmlElement(setting, value));

                        if (isRoaming) {
                            roamingUserSettings[setting.Name] = ss;
                        }
                        else {
                            localUserSettings[setting.Name] = ss;
                        }
                        
                        value.IsDirty = false; //reset IsDirty
                    }
                    else {
                        // This is an app-scoped or connection string setting that has been written to. 
                        // We don't support saving these.
                    }
                }
            }
            
            // Semi-hack: If there are roamable settings, let's write them before local settings so if a handler 
            // declaration is necessary, it goes in the roaming config file in preference to the local config file.
            if (roamingUserSettings.Count > 0) {
                Store.WriteSettings(sectionName, true, roamingUserSettings);
            }

            if (localUserSettings.Count > 0) {
                Store.WriteSettings(sectionName, false, localUserSettings);
            }
        }

        /// <devdoc>
        ///     Implementation of IClientSettingsProvider.Reset. Resets user scoped settings to the values 
        ///     in app.exe.config, does nothing for app scoped settings.
        /// </devdoc>
        public void Reset(SettingsContext context) {
            string sectionName = GetSectionName(context);

            // First revert roaming, then local
            Store.RevertToParent(sectionName, true);
            Store.RevertToParent(sectionName, false);
        }

        /// <devdoc>
        ///    Implementation of IClientSettingsProvider.Upgrade.
        ///    Tries to locate a previous version of the user.config file. If found, it migrates matching settings.
        ///    If not, it does nothing.
        /// </devdoc>
        public void Upgrade(SettingsContext context, SettingsPropertyCollection properties) {
            // Separate the local and roaming settings and upgrade them separately.
            
            SettingsPropertyCollection local = new SettingsPropertyCollection();
            SettingsPropertyCollection roaming = new SettingsPropertyCollection();
            
            foreach (SettingsProperty sp in properties) {
                bool isRoaming = IsRoamingSetting(sp);

                if (isRoaming) {
                    roaming.Add(sp);
                }
                else {
                    local.Add(sp);
                }
            }

            if (roaming.Count > 0) {
                Upgrade(context, roaming, true);
            }

            if (local.Count > 0) {
                Upgrade(context, local, false);
            }
        }

        /// <devdoc>
        ///     Encapsulates the Version constructor so that we can return null when an exception is thrown.
        /// </devdoc>
        private Version CreateVersion(string name) {
            Version ver = null;

            try {
                ver = new Version(name);
            }
            catch (ArgumentException) { 
                ver = null;
            }
            catch (OverflowException) {
                ver = null;
            }
            catch (FormatException) {
                ver = null;
            }

            return ver;
        }

        /// <devdoc>
        ///    Implementation of IClientSettingsProvider.GetPreviousVersion.
        /// </devdoc>
        //  Security Note: Like Upgrade, GetPreviousVersion involves finding a previous version user.config file and 
        //  reading settings from it. To support this in partial trust, we need to assert file i/o here. We believe 
        //  this to be safe, since the user does not have a way to specify the file or control where we look for it. 
        //  So it is no different than reading from the default user.config file, which we already allow in partial trust.
        //  BTW, the Link/Inheritance demand pair here is just a copy of what's at the class level, and is needed since
        //  we are overriding security at method level.
        [
         FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read),
         PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"),
         PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")
        ]
        public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property) {
            bool isRoaming = IsRoamingSetting(property);
            string prevConfig = GetPreviousConfigFileName(isRoaming);

            if (!String.IsNullOrEmpty(prevConfig)) {
                SettingsPropertyCollection properties = new SettingsPropertyCollection();
                properties.Add(property);
                SettingsPropertyValueCollection values = GetSettingValuesFromFile(prevConfig, GetSectionName(context), true, properties);
                return values[property.Name];
            }
            else {
                SettingsPropertyValue value = new SettingsPropertyValue(property);
                value.PropertyValue = null;
                return value;
            }
        }

        /// <devdoc>
        ///     Locates the previous version of user.config, if present. The previous version is determined
        ///     by walking up one directory level in the *UserConfigPath and searching for the highest version
        ///     number less than the current version.
        ///     SECURITY NOTE: Config path information is privileged - do not directly pass this on to untrusted callers.
        ///     Note this is meant to be used at installation time to help migrate 
        ///     config settings from a previous version of the app.
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        private string GetPreviousConfigFileName(bool isRoaming) {
            if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) {
                throw new ConfigurationErrorsException(SR.GetString(SR.UserSettingsNotSupported));
            }

            string prevConfigFile = isRoaming ? _prevRoamingConfigFileName : _prevLocalConfigFileName;

            if (String.IsNullOrEmpty(prevConfigFile)) {
                string userConfigPath = isRoaming ? ConfigurationManagerInternalFactory.Instance.ExeRoamingConfigDirectory : ConfigurationManagerInternalFactory.Instance.ExeLocalConfigDirectory;
                Version curVer = CreateVersion(ConfigurationManagerInternalFactory.Instance.ExeProductVersion);
                Version prevVer = null;
                DirectoryInfo prevDir = null;
                string file = null;
    
                if (curVer == null) {
                    return null;
                }
    
                DirectoryInfo parentDir = Directory.GetParent(userConfigPath);
    
                if (parentDir.Exists) {
                    foreach (DirectoryInfo dir in parentDir.GetDirectories()) {
                        Version tempVer = CreateVersion(dir.Name);
        
                        if (tempVer != null && tempVer < curVer) {
                            if (prevVer == null) {
                                prevVer = tempVer;
                                prevDir = dir;
                            }
                            else if (tempVer > prevVer) {
                                prevVer = tempVer;
                                prevDir = dir;
                            }
                        }
                    }
        
                    if (prevDir != null) {
                        file = Path.Combine(prevDir.FullName, ConfigurationManagerInternalFactory.Instance.UserConfigFilename);
                    }
        
                    if (File.Exists(file)) {
                        prevConfigFile = file;
                    }
                }

                //Cache for future use.
                if (isRoaming) {
                    _prevRoamingConfigFileName = prevConfigFile;
                }
                else {
                    _prevLocalConfigFileName = prevConfigFile;
                }
            }

            return prevConfigFile;
        }

        /// <devdoc>
        ///     Gleans information from the SettingsContext and determines the name of the config section.
        /// </devdoc>
        private string GetSectionName(SettingsContext context) {
            string groupName = (string) context["GroupName"];
            string key = (string) context["SettingsKey"];
            
            Debug.Assert(groupName != null, "SettingsContext did not have a GroupName!");

            string sectionName = groupName;

            if (!String.IsNullOrEmpty(key)) {
                sectionName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", sectionName, key);
            }

            return XmlConvert.EncodeLocalName(sectionName);
        }

        /// <devdoc>
        ///     Retrieves the values of settings from the given config file (as opposed to using 
        ///     the configuration for the current context)
        /// </devdoc>
        private SettingsPropertyValueCollection GetSettingValuesFromFile(string configFileName, string sectionName, bool userScoped, SettingsPropertyCollection properties) {
            SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();
            IDictionary settings = ClientSettingsStore.ReadSettingsFromFile(configFileName, sectionName, userScoped);

            // Map each SettingProperty to the right StoredSetting and deserialize the value if found.
            foreach (SettingsProperty setting in properties) {
                string settingName = setting.Name;
                SettingsPropertyValue value = new SettingsPropertyValue(setting);
                
                if (settings.Contains(settingName)) {
                    StoredSetting ss = (StoredSetting) settings[settingName];
                    string valueString = ss.Value.InnerXml;

                    // We need to un-escape string serialized values
                    if (ss.SerializeAs == SettingsSerializeAs.String) {
                        valueString = Escaper.Unescape(valueString);
                    }

                    value.SerializedValue = valueString;
                    value.IsDirty = true;
                    values.Add(value);
                }
            }
            
            return values;
        }

        /// <devdoc>
        ///     Indicates whether a setting is roaming or not.
        /// </devdoc>
        private static bool IsRoamingSetting(SettingsProperty setting) {
            // Roaming is not supported in Clickonce deployed apps, since they don't have roaming config files.
            bool roamingSupported = !ApplicationSettingsBase.IsClickOnceDeployed(AppDomain.CurrentDomain);
            bool isRoaming = false;

            if (roamingSupported) {
                SettingsManageabilityAttribute manageAttr = setting.Attributes[typeof(SettingsManageabilityAttribute)] as SettingsManageabilityAttribute;
                isRoaming = manageAttr != null && ((manageAttr.Manageability & SettingsManageability.Roaming) == SettingsManageability.Roaming);
            }

            return isRoaming;
        }

        /// <devdoc>
        ///     This provider needs settings to be marked with either the UserScopedSettingAttribute or the
        ///     ApplicationScopedSettingAttribute. This method determines whether this setting is user-scoped
        ///     or not. It will throw if none or both of the attributes are present.
        /// </devdoc>
        private bool IsUserSetting(SettingsProperty setting) {
            bool isUser = setting.Attributes[typeof(UserScopedSettingAttribute)] is UserScopedSettingAttribute;
            bool isApp  = setting.Attributes[typeof(ApplicationScopedSettingAttribute)] is ApplicationScopedSettingAttribute;

            if (isUser && isApp) {
                throw new ConfigurationErrorsException(SR.GetString(SR.BothScopeAttributes));
            }
            else if (!(isUser || isApp)) {
                throw new ConfigurationErrorsException(SR.GetString(SR.NoScopeAttributes));
            }

            return isUser;
        }

        private XmlNode SerializeToXmlElement(SettingsProperty setting, SettingsPropertyValue value) {
            XmlDocument doc = new XmlDocument();
            XmlElement valueXml = doc.CreateElement("value");

            string serializedValue = value.SerializedValue as string;
            
            if (serializedValue == null && setting.SerializeAs == SettingsSerializeAs.Binary) {
                // SettingsPropertyValue returns a byte[] in the binary serialization case. We need to
                // encode this - we use base64 since SettingsPropertyValue understands it and we won't have
                // to special case while deserializing.
                byte[] buf = value.SerializedValue as byte[];
                if (buf != null) {
                    serializedValue = Convert.ToBase64String(buf);
                }
            }

            if (serializedValue == null) {
                serializedValue = String.Empty;
            }
            
            // We need to escape string serialized values
            if (setting.SerializeAs == SettingsSerializeAs.String) {
                serializedValue = Escaper.Escape(serializedValue);
            }

            valueXml.InnerXml = serializedValue; 
            
            // Hack to remove the XmlDeclaration that the XmlSerializer adds. 
            XmlNode unwanted = null;
            foreach (XmlNode child in valueXml.ChildNodes) {
                if (child.NodeType == XmlNodeType.XmlDeclaration) {
                    unwanted = child;
                    break;
                }
            }
            if (unwanted != null) {
                valueXml.RemoveChild(unwanted);
            }
            
            return valueXml;
        }

        /// <devdoc>
        ///    Private version of upgrade that uses isRoaming to determine which config file to use.
        /// </devdoc> 
        // Security Note: Upgrade involves finding a previous version user.config file and reading settings from it. To
        // support this in partial trust, we need to assert file i/o here. We believe this to be safe, since the user
        // does not have a way to specify the file or control where we look for it. As such, it is no different than
        // reading from the default user.config file, which we already allow in partial trust.
        // The following suppress is okay, since the Link/Inheritance demand pair at the class level are not needed for
        // this method, since it is private.
        [SuppressMessage("Microsoft.Security", "CA2114:MethodSecurityShouldBeASupersetOfType")]
        [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read)]
        private void Upgrade(SettingsContext context, SettingsPropertyCollection properties, bool isRoaming) {
            string prevConfig = GetPreviousConfigFileName(isRoaming); 
            
            if (!String.IsNullOrEmpty(prevConfig)) {
                //Filter the settings properties to exclude those that have a NoSettingsVersionUpgradeAttribute on them.
                SettingsPropertyCollection upgradeProperties = new SettingsPropertyCollection();
                foreach (SettingsProperty sp in properties) {
                    if (!(sp.Attributes[typeof(NoSettingsVersionUpgradeAttribute)] is NoSettingsVersionUpgradeAttribute)) {
                        upgradeProperties.Add(sp);
                    }
                }
                
                SettingsPropertyValueCollection values = GetSettingValuesFromFile(prevConfig, GetSectionName(context), true, upgradeProperties);
                SetPropertyValues(context, values);
            }
        }

        private class XmlEscaper {
            private XmlDocument doc;
            private XmlElement temp;
    
            internal XmlEscaper() {
                doc = new XmlDocument();
                temp = doc.CreateElement("temp");
            }
    
            internal string Escape(string xmlString) {
                if (String.IsNullOrEmpty(xmlString)) {
                    return xmlString;
                }
    
                temp.InnerText = xmlString;
                return temp.InnerXml;
            }
    
            internal string Unescape(string escapedString) {
                if (String.IsNullOrEmpty(escapedString)) {
                    return escapedString;
                }
    
                temp.InnerXml = escapedString;
                return temp.InnerText;
            }
        }
    }
}