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
using System;
using System.Collections.Specialized;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;

namespace PortableSettings
{
public class Provider : ProviderBase
{
public static string SettingsFileName { get; set; } = "Settings.config";

public override string Name => "PortableSettingsProvider";

public static void Apply(params ApplicationSettingsBase[] settingsList) => Apply(new Provider(), settingsList);

private string ApplicationSettingsFile => Path.Combine(SettingsDirectory, SettingsFileName);

public override void Reset(SettingsContext context)
{
if (File.Exists(ApplicationSettingsFile))
File.Delete(ApplicationSettingsFile);
}

private XDocument GetXmlDoc()
{
XDocument xmlDoc = null;
bool initnew = false;
if (File.Exists(ApplicationSettingsFile))
{
try
{
xmlDoc = XDocument.Load(ApplicationSettingsFile);
}
catch
{
initnew = true;
}
}
else
{
initnew = true;
}
if (initnew)
{
xmlDoc = new XDocument(new XElement("configuration", new XElement("userSettings", new XElement("Roaming"))));
}
return xmlDoc;
}

public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
{
XDocument xmlDoc = GetXmlDoc();
SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();
foreach (SettingsProperty setting in collection)
{
SettingsPropertyValue value = new SettingsPropertyValue(setting)
{
IsDirty = false,
SerializedValue = getXmlValue(xmlDoc, XmlConvert.EncodeLocalName((string)context["GroupName"]), setting)
};
values.Add(value);
}
return values;
}

public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
{
XDocument xmlDoc = GetXmlDoc();
foreach (SettingsPropertyValue value in collection)
{
setXmlValue(xmlDoc, XmlConvert.EncodeLocalName((string)context["GroupName"]), value);
}
try
{
using (var writer = XmlWriter.Create(ApplicationSettingsFile, new XmlWriterSettings() { NewLineHandling = NewLineHandling.Entitize, Indent = true }))
{
xmlDoc.Save(writer);
}
}
catch { }
}

private object getXmlValue(XDocument xmlDoc, string scope, SettingsProperty prop)
{
object result = null;
if (!IsUserScoped(prop))
return result;
XElement xmlSettings = xmlDoc.Element("configuration").Element("userSettings");
if (IsRoaming(prop))
xmlSettings = xmlSettings.Element("Roaming");
else
xmlSettings = xmlSettings.Element("PC_" + Environment.MachineName);
if (xmlSettings != null && xmlSettings.Element(scope) != null && xmlSettings.Element(scope).Element(prop.Name) != null)
{
using (var reader = xmlSettings.Element(scope).Element(prop.Name).CreateReader())
{
reader.MoveToContent();
switch (prop.SerializeAs)
{
case SettingsSerializeAs.Xml:
result = reader.ReadInnerXml();
break;
case SettingsSerializeAs.Binary:
result = reader.ReadInnerXml();
result = Convert.FromBase64String(result as string);
break;
default:
result = reader.ReadElementContentAsString();
break;
}
}
}
else
{
result = prop.DefaultValue;
}
return result;
}

private void setXmlValue(XDocument xmlDoc, string scope, SettingsPropertyValue value)
{
if (!IsUserScoped(value.Property)) return;
XElement xmlSettings = xmlDoc.Element("configuration").Element("userSettings");
XElement xmlSettingsLoc;
if (IsRoaming(value.Property))
xmlSettingsLoc = xmlSettings.Element("Roaming");
else
xmlSettingsLoc = xmlSettings.Element("PC_" + Environment.MachineName);
XNode serialized;
if (value.SerializedValue == null || value.SerializedValue is string s && String.IsNullOrWhiteSpace(s))
serialized = new XText("");
else if (value.Property.SerializeAs == SettingsSerializeAs.Xml)
serialized = XElement.Parse((string)value.SerializedValue);
else if (value.Property.SerializeAs == SettingsSerializeAs.Binary)
serialized = new XText(Convert.ToBase64String((byte[])value.SerializedValue));
else
serialized = new XText((string)value.SerializedValue);
if (xmlSettingsLoc == null)
{
if (IsRoaming(value.Property))
xmlSettingsLoc = new XElement("Roaming");
else
xmlSettingsLoc = new XElement("PC_" + Environment.MachineName);
xmlSettingsLoc.Add(new XElement(scope, new XElement(value.Name, serialized)));
xmlSettings.Add(xmlSettingsLoc);
}
else
{
XElement xmlScope = xmlSettingsLoc.Element(scope);
if (xmlScope != null)
{
XElement xmlElem = xmlScope.Element(value.Name);
if (xmlElem == null)
xmlScope.Add(new XElement(value.Name, serialized));
else
xmlElem.ReplaceAll(serialized);
}
else
{
xmlSettingsLoc.Add(new XElement(scope, new XElement(value.Name, serialized)));
}
}
}
}

public abstract class ProviderBase : SettingsProvider, IApplicationSettingsProvider
{
public static bool AllRoaming { get; set; } = false;

public static string SettingsDirectory { get; set; } = AppDomain.CurrentDomain.BaseDirectory;

public override string ApplicationName { get { return Assembly.GetExecutingAssembly().GetName().Name; } set { } }

protected static void Apply(ProviderBase provider, params ApplicationSettingsBase[] settingsList)
{
foreach (var settings in settingsList)
{
settings.Providers.Clear();
settings.Providers.Add(provider);
foreach (SettingsProperty prop in settings.Properties)
prop.Provider = provider;
settings.Reload();
}
}

public override void Initialize(string name, NameValueCollection config)
{
if (string.IsNullOrEmpty(name)) name = Name;
base.Initialize(name, config);
}

public virtual SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property)
{
throw new NotImplementedException();
}

public abstract void Reset(SettingsContext context);

public virtual void Upgrade(SettingsContext context, SettingsPropertyCollection properties) { }

protected bool IsUserScoped(SettingsProperty prop)
{
foreach (DictionaryEntry d in prop.Attributes)
{
Attribute a = (Attribute)d.Value;
if (a.GetType() == typeof(UserScopedSettingAttribute))
return true;
}
return false;
}

protected bool IsRoaming(SettingsProperty prop)
{
if (AllRoaming)
return true;
foreach (DictionaryEntry d in prop.Attributes)
{
Attribute a = (Attribute)d.Value;
if (a.GetType() == typeof(SettingsManageabilityAttribute))
return true;
}
return false;
}
}
}