powered by simpleCommunicator - 2.0.53     © 2025 Programmizd 02
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Сохранение пользовательской конфигурации.
25 сообщений из 127, страница 5 из 6
Сохранение пользовательской конфигурации.
    #39213305
Фотография Cat2
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
ИзопропилCat2,

а репликацию с локальным хранилищем - организовал?
Локальные хранилища - зло
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213375
Фотография Изопропил
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Cat2ИзопропилCat2,

а репликацию с локальным хранилищем - организовал?
Локальные хранилища - зло
а работа в оффлайне?
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213379
Фотография Cat2
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
ИзопропилCat2пропущено...

Локальные хранилища - зло
а работа в оффлайне?
Тюрьма?Там что, тюремного сервера нет?
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213384
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Конкурс обьявляется открытым.

По тесту возражения/предложения будут?


Код: c#
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.
[TestClass]
    public class TestMRUStore
    {
        const int REPEAT_TEST = 1000;

        [TestMethod]
        public void TestFillMRUStore()
        {
            var store = new MRUStore("TestMru", 40);
            var stopwatch = new Stopwatch();
            var random = new Random();
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\хранилища\\";

            store.Reload();
            stopwatch.Start();
            for (int i = REPEAT_TEST; --i >= 0;)
            {
                string pickItem;
                if (random.NextDouble() <= 0.4 && store.Count > 0)
                {
                    pickItem = store[random.Next(store.Count)];
                }
                else
                {
                    pickItem = string.Concat(basePath, random.Next(), ".txt");
                }
                store.Add(pickItem);
                store.Save();
            }
            stopwatch.Stop();
            Debug.Write("Test completed in " + stopwatch.Elapsed.ToString());
        }

        [TestMethod]
        public void TestLoadMRUStore()
        {
            var store = new MRUStore("TestMru");
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = REPEAT_TEST; --i >= 0;)
            {
                store.Reload();
            }
            stopwatch.Stop();
            Debug.Write("Test completed in " + stopwatch.Elapsed.ToString());
        }
    }


...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213387
Фотография skyANA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Cat2skyANAпропущено...


А скажите мне где та БД, где Visual Studio хранит то, о чём пишет автор? На каком сервере?
Я - молодой динамичный компаний и я иду впереди Микрософта! Он только-только начинает хранить настройки в облаке!
Пользовательские настройки в базе хранили ещё 15 лет назад :) Но у ТСа не тот случай.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213389
Фотография skyANA
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А насчёт "молодой динамичный компаний"... Ну хорошо, не Microsoft... Покажи на каком сервере продукты от JetBrains хранят то, о чём пишет ТС? :)
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213412
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Cat2При замене компа у пользователя все реестры и прочие локальные хранилища идут лесомИ пофиг. Не настолько там ценная информация.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213416
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Axeleron,
давай уже сделан что нибудь полезное для повышения энтропии.

Вот мой результат.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213419
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikronКонкурс обьявляется открытым.Сделай стандартно: модель + репозитарий, сохраняющий модель в реестре, БД, XML (нужное подчеркнуть). Не понравится - перепишешь репозитарий под хранение в другом месте за 5 минут.

Конкурс объявляется закрытым.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213431
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Алексей КСделай стандартно: модель + репозитарий, сохраняющий модель в реестре, БД, XML (нужное подчеркнуть). Не понравится - перепишешь репозитарий под хранение в другом месте за 5 минут.

"Сделать стандартно" это гениальная мысль. Потрать 5 минут и покажи как сделать стандартно на XML?
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213444
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikronАлексей КСделай стандартно: модель + репозитарий, сохраняющий модель в реестре, БД, XML (нужное подчеркнуть). Не понравится - перепишешь репозитарий под хранение в другом месте за 5 минут.

"Сделать стандартно" это гениальная мысль. Потрать 5 минут и покажи как сделать стандартно на XML? Практическое руководство. Запись данных объекта в XML-файл

Ссылка на практическое руководство по чтению XML-файлов нужна? :-)
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213452
Фотография Изопропил
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Cat2Изопропилпропущено...

а работа в оффлайне?
Тюрьма?Там что, тюремного сервера нет?
localhost есть
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213456
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Алексей Кmikronпропущено...

"Сделать стандартно" это гениальная мысль. Потрать 5 минут и покажи как сделать стандартно на XML? Практическое руководство. Запись данных объекта в XML-файл

Ссылка на практическое руководство по чтению XML-файлов нужна? :-)
И это всё что может? бездарность, геть от седа, шелкать семки и в носу ковырять. Так и просрёш всё жизнь на пустословие.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213458
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Сейчас отсеется семена от плевел.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213462
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Если кто нибудь напишет для XML выставлю свой код для всех.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213465
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikronЕсли кто нибудь напишет для XML выставлю свой код для всех.Попробуй денег предложить. :-)
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213477
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikronЕсли кто нибудь напишет для XML выставлю свой код для всех.Впрочем, почему бы и нет. :-)

Идеальный код
Код: c#
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.
using System;
using System.Collections.Generic;
 
namespace SspMain
{
    public class SettingsModel
    {
        public SettingsSection RootSection { get; set; }
 
        public SettingsModel()
        {
            RootSection = new SettingsSection();
        }
    }
 
    public class SettingsSection
    {
        public SettingsValueDictionary Values { get; set; }
        public SettingsSectionDictionary Sections { get; set; }
 
        public SettingsSection()
        {
            Values = new SettingsValueDictionary();
            Sections = new SettingsSectionDictionary();
        }
    }
 
    public partial class SettingsSectionDictionary : Dictionary<string, SettingsSection>
    {
        public SettingsSectionDictionary()
            : base(StringComparer.InvariantCultureIgnoreCase)
        { }
    }
 
    public partial class SettingsValueDictionary : Dictionary<string, object>
    {
        public SettingsValueDictionary()
            : base(StringComparer.InvariantCultureIgnoreCase)
        { }
    }
}

//----------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
 
namespace SspMain
{
    public class SettingsStorage
    {
        #region Default Storage
 
        public static SettingsStorage I
        {
            get
            {
                return Singleton<SettingsStorage>.GetInstance(
                    () => new SettingsStorage
                    {
                        FilePath = Path.Combine(ApplicationInfo.ApplicationDataFolder, "settings.xml")
                    }
                );
            }
        }
 
        #endregion
 
        #region Model Management
 
        public string FilePath { get; set; }
 
        object LockObj = new object();
 
        SettingsXmlSerializer Serializer = new SettingsXmlSerializer();        
 
        bool IsModelChanged;
 
        SettingsModel Model
        {
            get
            {
                if (_model == null)
                    Load();
 
                return _model;
            }
        }
 
        SettingsModel _model;
 
        public void Load()
        {
            lock (LockObj)
            {
                if (File.Exists(FilePath))
                    Log.ExecuteWithLog(() => _model = Serializer.Deserialize(FilePath));
 
                if (_model == null)
                    _model = new SettingsModel();
 
                IsModelChanged = false;
            }
        }
 
        public void Save()
        {
            lock (LockObj)
                if (IsModelChanged)
                {
                    Serializer.Serialize(FilePath, Model);
                    IsModelChanged = false;
                }
        }
 
        #endregion
 
        #region Section Management
 
        SettingsSection GetOrCreateSectionByPath(string[] sectionPath)
        {
            var result = Model.RootSection;
            foreach (var sectionName in sectionPath)
                result = GetOrCreateChildSection(result, sectionName);
            return result;
        }
 
        SettingsSection GetOrCreateChildSection(SettingsSection parentSection, string sectionName)
        {
            SettingsSection result;
            if (parentSection.Sections.TryGetValue(sectionName, out result) == false)
            {
                result = new SettingsSection();
                parentSection.Sections.Add(sectionName, result);
            }
            return result;
        }
 
        SettingsSection GetSectionByPath(string[] sectionPath)
        {
            var result = Model.RootSection;
            foreach (var sectionName in sectionPath)
            {
                result = result.Sections.GetValueOrDefault(sectionName);
                if (result == null)
                    return null;
            }
            return result;
        }
 
        #endregion
 
        #region Value Management
 
        public bool RemoveValue(SettingsStorageKey key)
        {
            lock (LockObj)
            {
                var section = GetSectionByPath(key.SectionPath);
                if (section == null)
                    return false;
 
                bool result = section.Values.Remove(key.ValueName);
                if (result)
                    IsModelChanged = true;
 
                return result;
            }
        }
 
        public void SetValue(SettingsStorageKey key, object value)
        {
            lock (LockObj)
            {
                var storageValue = CloneHelper.XmlCloneIfRefType(value);
                GetOrCreateSectionByPath(key.SectionPath).Values[key.ValueName] = storageValue;
                IsModelChanged = true;
            }
        }
 
        public bool TryGetValue(SettingsStorageKey key, Type valueType, out object result)
        {
            lock (LockObj)
            {
                result = null;
 
                var section = GetSectionByPath(key.SectionPath);
 
                if (section == null)
                    return false;
 
                object value;
                if (section.Values.TryGetValue(key.ValueName, out value) == false)
                    return false;
 
                if (CheckValueType(valueType, value))
                {
                    result = CloneHelper.XmlCloneIfRefType(value);
                    return true;
                }
 
                return false;
            }
        }
 
        bool CheckValueType(Type valueType, object value)
        {
            if (value != null)
                return valueType.IsAssignableFrom(value.GetType());
 
            return valueType.CanBeNull();
        }
 
        #endregion
 
        #region Value Management Extension
 
        public bool TryGetValue<T>(SettingsStorageKey key, out T result)
        {
            object value;
 
            if (TryGetValue(key, typeof(T), out value))
            {
                result = (T)value;
                return true;
            }
 
            result = default(T);
            return false;
        }
 
        public T GetValueOrDefault<T>(SettingsStorageKey key, T defaultValue = default(T))
        {
            object result;
 
            if (TryGetValue(key, typeof(T), out result))
                return (T)result;
 
            return defaultValue;
        }
 
        #endregion
    }
}

//----------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SspMain
{
    public class SettingsStorageKey
    {
        public string[] SectionPath { get; private set; }
 
        public string ValueName { get; private set; }
 
        public SettingsStorageKey(string[] sectionPath, string valueName)
        {
            if (sectionPath == null)
                throw new ArgumentNullException("sectionPath");
 
            if (sectionPath.Length == 0)
                throw new ArgumentException("sectionPath.Length == 0");
 
            if (sectionPath.Any(v => string.IsNullOrWhiteSpace(v)))
                throw new ArgumentException("sectionPath.Any(v => string.IsNullOrWhiteSpace(v))");
 
            if (string.IsNullOrWhiteSpace(valueName))
                throw new ArgumentException("string.IsNullOrWhiteSpace(valueName)");
 
            SectionPath = sectionPath;
            ValueName = valueName;
        }
    }
}

//----------------------------------------------

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
 
namespace SspMain
{
    class SettingsXmlSerializer
    {
        XmlSerializer Serializer = new XmlSerializer(typeof(SettingsModel));
 
        public void Serialize(string filePath, SettingsModel model)
        {
            var dir = Path.GetDirectoryName(filePath);
 
            if (string.IsNullOrEmpty(dir) == false && Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);
 
            var tempFilePath = filePath + ".temp.xml";
 
            if (File.Exists(tempFilePath))
                File.Delete(tempFilePath);
 
            using (var xw = new XmlTextWriter(tempFilePath, Encoding.GetEncoding(1251)))
            {
                xw.Formatting = Formatting.Indented;
                Serializer.Serialize(xw, model);
            }
 
            if (File.Exists(filePath))
                File.Delete(filePath);
 
            File.Move(tempFilePath, filePath);
        }
 
        public SettingsModel Deserialize(string filePath)
        {
            try
            {
                using (var xr = new XmlTextReader(filePath))
                    return (SettingsModel)Serializer.Deserialize(xr);
            }
            catch (Exception e)
            {
                throw new InfoException("Ошибка при чтении файла хранилища настроек.", e);
            }
        }
    }
 
    public partial class SettingsSectionDictionary : IXmlSerializable
    {
        #region IXmlSerializable Members
 
        const string E_Item = "Item";
        const string A_Key = "Key";
 
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }
 
            var vs = GetValueSerializer();
 
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    reader.ReadEndElement();
                    break;
                }
 
                if (reader.NodeType == XmlNodeType.Element && reader.Name == E_Item)
                {
                    string key = reader[A_Key];
 
                    reader.Read();
                    var value = (SettingsSection)vs.Deserialize(reader);
                    reader.ReadEndElement();
 
                    Add(key, value);
                }
            }
        }
 
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            var vs = GetValueSerializer();
 
            foreach (var item in this)
            {
                writer.WriteStartElement(E_Item);
                writer.WriteAttributeString(A_Key, item.Key);
                vs.Serialize(writer, item.Value);
                writer.WriteEndElement();
            }
        }
 
        XmlSerializer GetValueSerializer()
        {
            return new XmlSerializer(typeof(SettingsSection));
        }
 
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }
 
        #endregion
    }
 
    public partial class SettingsValueDictionary : IXmlSerializable
    {
        #region IXmlSerializable Members
 
        const string E_Item = "Item";
        const string A_Key = "Key";
        const string A_ValueType = "ValueType";
 
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }
 
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    reader.ReadEndElement();
                    break;
                }
 
                if (reader.NodeType == XmlNodeType.Element && reader.Name == E_Item)
                {
                    string key = reader[A_Key];
                    string valueType = reader[A_ValueType];
 
                    object value = null;
                    bool hasValue = true;
 
                    if (valueType != null)
                        hasValue = TryDeserializeValue(valueType, reader.ReadInnerXml(), out value);
 
                    if (hasValue)
                        Add(key, value);
                }
            }
        }
 
        bool TryDeserializeValue(string type, string data, out object value)
        {
            try
            {
                var vs = new XmlSerializer(Type.GetType(type));
 
                var doc = new XmlDocument();
                doc.LoadXml(data);
                doc.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
 
                using (var xr = new XmlNodeReader(doc))
                    value = vs.Deserialize(xr);
 
                return true;
            }
            catch
            {
                value = null;
                return false;
            }
        }
 
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            foreach (var item in this)
            {
                writer.WriteStartElement(E_Item);
                writer.WriteAttributeString(A_Key, item.Key);
 
                if (item.Value != null)
                {
                    var valueType = item.Value.GetType();
                    writer.WriteAttributeString(A_ValueType, GetTypeName(valueType));
                    var vs = new XmlSerializer(valueType);
                    vs.Serialize(writer, item.Value);
                }
 
                writer.WriteEndElement();
            }
        }
 
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }
 
        string GetTypeName(Type type)
        {
            var fullName = type.AssemblyQualifiedName;
            var simpleName = type.FullName + ", " + type.Assembly.GetName().Name;
 
            try
            {
                if (Type.GetType(simpleName) == null)
                    return fullName;
            }
            catch
            {
                return fullName;
            }
 
            return simpleName;
        }
 
        #endregion
    }
}

...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213497
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikron
И это всё что может? бездарность, геть от седа, шелкать семки и в носу ковырять. Так и просрёш всё жизнь на пустословие.

Беру свои слова обратно. Как этим пользоваться? Поправь пожалуйста тест для этих классов.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213520
Фотография Cat2
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Модератор форума
skyANAА насчёт "молодой динамичный компаний"... Ну хорошо, не Microsoft... Покажи на каком сервере продукты от JetBrains хранят то, о чём пишет ТС? :)
Они - старый не динамичный. У них унаследованного кода миллион строк!
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213525
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Алексей К,

Пока не компилируется:

Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 175 Active
Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 198 Active
Error CS1061 'Type' does not contain a definition for 'CanBeNull' and no extension method 'CanBeNull' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?) BssEditor.Test SST.cs 211 Active

Внесённые изменения
Код: c#
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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace SspMain
{
    public class SettingsModel
    {
        public SettingsSection RootSection { get; set; }

        public SettingsModel()
        {
            RootSection = new SettingsSection();
        }
    }

    public class SettingsSection
    {
        public SettingsValueDictionary Values { get; set; }
        public SettingsSectionDictionary Sections { get; set; }

        public SettingsSection()
        {
            Values = new SettingsValueDictionary();
            Sections = new SettingsSectionDictionary();
        }
    }

    public partial class SettingsSectionDictionary : Dictionary<string, SettingsSection>
    {
        public SettingsSectionDictionary()
            : base(StringComparer.InvariantCultureIgnoreCase)
        { }

        // CHANGED:
        internal SettingsSection GetValueOrDefault(string sectionName)
        {
            SettingsSection result;
            return TryGetValue(sectionName ,out result) ? result : null;
        }
    }

    public partial class SettingsValueDictionary : Dictionary<string, object>
    {
        public SettingsValueDictionary()
            : base(StringComparer.InvariantCultureIgnoreCase)
        { }
    }

    public class SettingsStorage
    {
        #region Default Storage

        //CHANGED:
        public static Lazy<SettingsStorage> I = new Lazy<SettingsStorage>(() => new SettingsStorage
        {
            FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "settings.xml")
        });

        #endregion

        #region Model Management

        public string FilePath { get; set; }

        object LockObj = new object();

        SettingsXmlSerializer Serializer = new SettingsXmlSerializer();

        bool IsModelChanged;

        SettingsModel Model
        {
            get
            {
                if (_model == null)
                    Load();

                return _model;
            }
        }

        SettingsModel _model;

        public void Load()
        {
            lock (LockObj)
            {
                if (File.Exists(FilePath))
                    //CHANGED: Log.ExecuteWithLog(() => _model = Serializer.Deserialize(FilePath));
                    _model = Serializer.Deserialize(FilePath);

                if (_model == null)
                    _model = new SettingsModel();

                IsModelChanged = false;
            }
        }

        public void Save()
        {
            lock (LockObj)
                if (IsModelChanged)
                {
                    Serializer.Serialize(FilePath, Model);
                    IsModelChanged = false;
                }
        }

        #endregion

        #region Section Management

        SettingsSection GetOrCreateSectionByPath(string[] sectionPath)
        {
            var result = Model.RootSection;
            foreach (var sectionName in sectionPath)
                result = GetOrCreateChildSection(result, sectionName);
            return result;
        }

        SettingsSection GetOrCreateChildSection(SettingsSection parentSection, string sectionName)
        {
            SettingsSection result;
            if (parentSection.Sections.TryGetValue(sectionName, out result) == false)
            {
                result = new SettingsSection();
                parentSection.Sections.Add(sectionName, result);
            }
            return result;
        }

        SettingsSection GetSectionByPath(string[] sectionPath)
        {
            var result = Model.RootSection;
            foreach (var sectionName in sectionPath)
            {
                result = result.Sections.GetValueOrDefault(sectionName);
                if (result == null)
                    return null;
            }
            return result;
        }

        #endregion

        #region Value Management

        public bool RemoveValue(SettingsStorageKey key)
        {
            lock (LockObj)
            {
                var section = GetSectionByPath(key.SectionPath);
                if (section == null)
                    return false;

                bool result = section.Values.Remove(key.ValueName);
                if (result)
                    IsModelChanged = true;

                return result;
            }
        }

        public void SetValue(SettingsStorageKey key, object value)
        {
            lock (LockObj)
            {
                var storageValue = CloneHelper.XmlCloneIfRefType(value);
                GetOrCreateSectionByPath(key.SectionPath).Values[key.ValueName] = storageValue;
                IsModelChanged = true;
            }
        }

        public bool TryGetValue(SettingsStorageKey key, Type valueType, out object result)
        {
            lock (LockObj)
            {
                result = null;

                var section = GetSectionByPath(key.SectionPath);

                if (section == null)
                    return false;

                object value;
                if (section.Values.TryGetValue(key.ValueName, out value) == false)
                    return false;

                if (CheckValueType(valueType, value))
                {
                    result = CloneHelper.XmlCloneIfRefType(value);
                    return true;
                }

                return false;
            }
        }

        bool CheckValueType(Type valueType, object value)
        {
            if (value != null)
                return valueType.IsAssignableFrom(value.GetType());

            return valueType.CanBeNull();
        }

        #endregion

        #region Value Management Extension

        public bool TryGetValue<T>(SettingsStorageKey key, out T result)
        {
            object value;

            if (TryGetValue(key, typeof(T), out value))
            {
                result = (T) value;
                return true;
            }

            result = default(T);
            return false;
        }

        public T GetValueOrDefault<T>(SettingsStorageKey key, T defaultValue = default(T))
        {
            object result;

            if (TryGetValue(key, typeof(T), out result))
                return (T) result;

            return defaultValue;
        }

        #endregion
    }
    public class SettingsStorageKey
    {
        public string[] SectionPath { get; private set; }

        public string ValueName { get; private set; }

        public SettingsStorageKey(string[] sectionPath, string valueName)
        {
            if (sectionPath == null)
                throw new ArgumentNullException("sectionPath");

            if (sectionPath.Length == 0)
                throw new ArgumentException("sectionPath.Length == 0");

            if (sectionPath.Any(v => string.IsNullOrWhiteSpace(v)))
                throw new ArgumentException("sectionPath.Any(v => string.IsNullOrWhiteSpace(v))");

            if (string.IsNullOrWhiteSpace(valueName))
                throw new ArgumentException("string.IsNullOrWhiteSpace(valueName)");

            SectionPath = sectionPath;
            ValueName = valueName;
        }
    }
    class SettingsXmlSerializer
    {
        XmlSerializer Serializer = new XmlSerializer(typeof(SettingsModel));

        public void Serialize(string filePath, SettingsModel model)
        {
            var dir = Path.GetDirectoryName(filePath);

            if (string.IsNullOrEmpty(dir) == false && Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);

            var tempFilePath = filePath + ".temp.xml";

            if (File.Exists(tempFilePath))
                File.Delete(tempFilePath);

            using (var xw = new XmlTextWriter(tempFilePath, Encoding.GetEncoding(1251)))
            {
                xw.Formatting = Formatting.Indented;
                Serializer.Serialize(xw, model);
            }

            if (File.Exists(filePath))
                File.Delete(filePath);

            File.Move(tempFilePath, filePath);
        }

        public SettingsModel Deserialize(string filePath)
        {
            try
            {
                using (var xr = new XmlTextReader(filePath))
                    return (SettingsModel) Serializer.Deserialize(xr);
            }
            catch (Exception e)
            {
                throw new Exception("Ошибка при чтении файла хранилища настроек.", e);
            }
        }
    }

    public partial class SettingsSectionDictionary : IXmlSerializable
    {
        #region IXmlSerializable Members

        const string E_Item = "Item";
        const string A_Key = "Key";

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }

            var vs = GetValueSerializer();

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    reader.ReadEndElement();
                    break;
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == E_Item)
                {
                    string key = reader[A_Key];

                    reader.Read();
                    var value = (SettingsSection) vs.Deserialize(reader);
                    reader.ReadEndElement();

                    Add(key, value);
                }
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            var vs = GetValueSerializer();

            foreach (var item in this)
            {
                writer.WriteStartElement(E_Item);
                writer.WriteAttributeString(A_Key, item.Key);
                vs.Serialize(writer, item.Value);
                writer.WriteEndElement();
            }
        }

        XmlSerializer GetValueSerializer()
        {
            return new XmlSerializer(typeof(SettingsSection));
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        #endregion
    }

    public partial class SettingsValueDictionary : IXmlSerializable
    {
        #region IXmlSerializable Members

        const string E_Item = "Item";
        const string A_Key = "Key";
        const string A_ValueType = "ValueType";

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    reader.ReadEndElement();
                    break;
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == E_Item)
                {
                    string key = reader[A_Key];
                    string valueType = reader[A_ValueType];

                    object value = null;
                    bool hasValue = true;

                    if (valueType != null)
                        hasValue = TryDeserializeValue(valueType, reader.ReadInnerXml(), out value);

                    if (hasValue)
                        Add(key, value);
                }
            }
        }

        bool TryDeserializeValue(string type, string data, out object value)
        {
            try
            {
                var vs = new XmlSerializer(Type.GetType(type));

                var doc = new XmlDocument();
                doc.LoadXml(data);
                doc.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");

                using (var xr = new XmlNodeReader(doc))
                    value = vs.Deserialize(xr);

                return true;
            }
            catch
            {
                value = null;
                return false;
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            foreach (var item in this)
            {
                writer.WriteStartElement(E_Item);
                writer.WriteAttributeString(A_Key, item.Key);

                if (item.Value != null)
                {
                    var valueType = item.Value.GetType();
                    writer.WriteAttributeString(A_ValueType, GetTypeName(valueType));
                    var vs = new XmlSerializer(valueType);
                    vs.Serialize(writer, item.Value);
                }

                writer.WriteEndElement();
            }
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        string GetTypeName(Type type)
        {
            var fullName = type.AssemblyQualifiedName;
            var simpleName = type.FullName + ", " + type.Assembly.GetName().Name;

            try
            {
                if (Type.GetType(simpleName) == null)
                    return fullName;
            }
            catch
            {
                return fullName;
            }

            return simpleName;
        }

        #endregion
    }
}

...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213542
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Хранилище для Registry


Код: c#
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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Security.AccessControl;
using BSS.Common;
using Microsoft.Win32;

namespace BSS.Editor
{
    public class MRUStore : IReadOnlyList<string>, ICollection<string>
    {
        private const string MRU_KEY_PREFIX = "MRU";

        private static string _regkeyBasePath;

        private string _name;

        private int _usedEntries;
        private int _maxEntries;
        private int _updateEntries;
        private int _lastUpdateNo;
        private STuple<int, int, string>[] _mru;              // Update number, key number, value

        public MRUStore(string name)
            : this(name, 0)
        { }

        public MRUStore(string name, int maxEntries)
        {
            if (_regkeyBasePath == null)
            {
                string companyName = null;
                string productName = null;
                var runAssembly = Assembly.GetEntryAssembly();
                if (runAssembly != null)
                {
                    var namespaceParts = runAssembly.EntryPoint.DeclaringType.Namespace.Split('.');
                    var companyAttr = runAssembly.GetCustomAttribute<AssemblyCompanyAttribute>();
                    if (companyAttr != null && !string.IsNullOrWhiteSpace(companyAttr.Company))
                    {
                        companyName = companyAttr.Company;

                    }
                    else if (namespaceParts.Length > 0)
                    {
                        companyName = namespaceParts[0];
                    }
                    var productAttr = runAssembly.GetCustomAttribute < AssemblyProductAttribute>();
                    if (productAttr != null && !string.IsNullOrWhiteSpace(productAttr.Product))
                    {
                        productName = productAttr.Product;
                    }
                    else if (namespaceParts.Length > 1)
                    {
                        productName = namespaceParts[1];
                    }
                }
                _regkeyBasePath = string.Concat("Software\\", 
                    companyName ?? "unknown", "\\", 
                    productName ?? AppDomain.CurrentDomain.FriendlyName, "\\");
                _regkeyBasePath = string.Concat("Software\\",
                    companyName ?? "BSS", "\\",
                    productName ?? "BssEdit", "\\");
            }
            _name = name;
            _maxEntries = maxEntries;
        }

        public void Reload()
        {
            var mruList = new List<STuple<int, int, string>>();
            using (var mruRootKey = Registry.CurrentUser.OpenSubKey(_regkeyBasePath + _name, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey))
            {
                if (mruRootKey != null)
                {
                    int itemNo;
                    int updateNo;
                    foreach (var keyName in mruRootKey.GetValueNames())
                    {
                        if (!keyName.StartsWith(MRU_KEY_PREFIX)
                        || !int.TryParse(keyName.Substring(MRU_KEY_PREFIX.Length), NumberStyles.None, CultureInfo.InvariantCulture, out itemNo)
                        || mruRootKey.GetValueKind(keyName) != RegistryValueKind.String)
                            continue;

                        var keyValue = mruRootKey.GetValue(keyName) as string;
                        if (keyValue == null)
                            continue;
                        var d = keyValue.IndexOf(':');
                        if (d <= 0 || !int.TryParse(keyValue.Substring(0, d), NumberStyles.None, CultureInfo.InvariantCulture, out updateNo))
                            continue;
                        mruList.Add(STuple.New(updateNo, itemNo, keyValue.Substring(d + 1)));
                        _lastUpdateNo = Math.Max(_lastUpdateNo, updateNo);
                    }
                }
            }
            _usedEntries = mruList.Count;
            if(_maxEntries <= 0)
                _maxEntries = _usedEntries;
            _mru = new STuple<int, int, string>[Math.Max(_maxEntries, _usedEntries)];
            mruList.Sort();
            mruList.CopyTo(_mru);
            _updateEntries = 0;
        }

        public void Save()
        {
            using (var mruRootKey = Registry.CurrentUser.CreateSubKey(_regkeyBasePath + _name, RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                // delete removed keys
                if (_usedEntries < _mru.Length)
                {
                    for (int i = _usedEntries; i < _mru.Length; ++i)
                    {
                        var t = _mru[i];
                        if (t.Item2 == 0)
                            break;
                        mruRootKey.DeleteValue(string.Concat(MRU_KEY_PREFIX, _mru[i].Item2.ToString(CultureInfo.InvariantCulture)));
                        _mru[i] = STuple.New(0, 0, (string) null);
                    }
                }
                // shrink used keys
                if (_maxEntries < _usedEntries)
                {
                    for (int i = _usedEntries - _maxEntries; --i >= 0;)
                    {
                        mruRootKey.DeleteValue(string.Concat(MRU_KEY_PREFIX, _mru[i].Item2.ToString(CultureInfo.InvariantCulture)));
                    }
                    Array.Copy(_mru, _usedEntries - _maxEntries, _mru, 0, _maxEntries);
                    _usedEntries = _maxEntries;
                    _updateEntries = Math.Min(_updateEntries, _maxEntries);
                }
                if (_maxEntries < _mru.Length)
                {
                    Array.Resize(ref _mru, _maxEntries);
                }
                // Update entries
                for (int i = _usedEntries - _updateEntries; i < _usedEntries; ++i)
                {
                    var t = _mru[i];
                    mruRootKey.SetValue(
                        string.Concat(MRU_KEY_PREFIX, t.Item2.ToString(CultureInfo.InvariantCulture)),
                        string.Concat(t.Item1.ToString(CultureInfo.InvariantCulture), ":", t.Item3),
                        RegistryValueKind.String);
                }
                _updateEntries = 0;
            }
        }

        public int Count
        {
            get
            {
                return _usedEntries;
            }
        }

        public string this[int index]
        {
            get
            {
                return _mru[_usedEntries - index - 1].Item3;
            }
        }

        public IEnumerator<string> GetEnumerator()
        {
            for (int i = _usedEntries; --i >= 0;)
                yield return _mru[i].Item3;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        private int IndexOf(string value)
        {
            for (int i = _usedEntries; --i >= 0;)
                if (value == _mru[i].Item3)
                    return i;
            return -1;
        }

        public bool Contains(string item)
        {
            return this.IndexOf(item) >= 0;
        }

        public void Add(string item)
        {
            int itemNo;
            if (_lastUpdateNo > 99999)
            {
                for (int i = _usedEntries; --i >= 0;)
                {
                    _mru[i].Item1 = i;
                }
                _lastUpdateNo = _usedEntries;
                _updateEntries = _usedEntries;
            }
            var pos = this.IndexOf(item);
            if (pos < 0 && _usedEntries < _maxEntries)
            {
                itemNo = _mru[_usedEntries].Item2;
                if(itemNo == 0)
                {
                    do { ++itemNo; } while (Array.FindIndex(_mru, 0, _usedEntries, t => t.Item2 == itemNo) >= 0);
                }
                _mru[_usedEntries++] = STuple.New(++_lastUpdateNo, itemNo, item);
                ++_updateEntries;
                return;
            }
            if(pos < 0)
            {
                pos = 0;
            }
            if (pos + _updateEntries < _usedEntries)
            {
                ++_updateEntries;
            }
            itemNo = _mru[pos].Item2;
            if (pos < _usedEntries - 1)
            {
                Array.Copy(_mru, pos + 1, _mru, pos, _usedEntries - 1 - pos);
            }
            _mru[_usedEntries - 1] = STuple.New(++_lastUpdateNo, itemNo, item);
        }

        public bool Remove(string item)
        {
            var pos = this.IndexOf(item);
            if (pos < 0)
                return false;
            if (pos + _updateEntries > --_usedEntries)
            {
                --_updateEntries;
            }
            if (pos == _usedEntries)
            {
                _mru[_usedEntries].Item3 = null;
            }
            else
            {
                var t = _mru[pos];
                Array.Copy(_mru, pos + 1, _mru, pos, _usedEntries - pos);
                _mru[_usedEntries] = STuple.New(t.Item1, t.Item2, (string) null);
            }
            return true;
        }

        public void Clear()
        {
            for (int i = _usedEntries; --i >= 0;)
                _mru[i].Item3 = null;
            _usedEntries = _updateEntries = 0;
        }

        public void CopyTo(string[] array, int arrayIndex)
        {
            for (int i = _usedEntries; --i >= 0;)
                array[arrayIndex++] = _mru[i].Item3;
        }
    }
}

...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213589
Фотография Алексей К
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikronАлексей К,

Пока не компилируется:

Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 175 Active
Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 198 Active
Error CS1061 'Type' does not contain a definition for 'CanBeNull' and no extension method 'CanBeNull' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?) BssEditor.Test SST.cs 211 Active
Недостающее
Код: c#
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SspMain
{
    public static class CloneHelper
    {
        public static T XmlClone<T>(T src)
            where T : class
        {
            if (src == null)
                return null;

            var serializer = new XmlSerializer(src.GetType());
            var doc = new XmlDocument();

            using (var xw = doc.CreateNavigator().AppendChild())
                serializer.Serialize(xw, src);

            using (var xr = new XmlNodeReader(doc))
                return (T)serializer.Deserialize(xr);
        }

        public static object XmlCloneIfRefType(object value)
        {
            if
            (
                value != null &&
                value.GetType().IsValueType == false &&
                (value is string) == false
            )
                return XmlClone(value);

            return value;
        }
    }
}


Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace SspMain
{
    public static class TypeHelper
    {
        public static Type GetGenericTypeDefinitionEx(this Type type)
        {
            return type.IsGenericType ? type.GetGenericTypeDefinition() : null;
        }

        public static bool CanBeNull(this Type type)
        {
            return
                type.IsValueType == false ||
                type.GetGenericTypeDefinitionEx() == typeof(Nullable<>);
        }
    }
}


...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213681
mikron
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Алексей КmikronАлексей К,

Пока не компилируется:

Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 175 Active
Error CS0103 The name 'CloneHelper' does not exist in the current context BssEditor.Test SST.cs 198 Active
Error CS1061 'Type' does not contain a definition for 'CanBeNull' and no extension method 'CanBeNull' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?) BssEditor.Test SST.cs 211 Active


позитивные момент - Компиулируется.
Код не МРУ список вообще и не решает задачи. Потому результаты тоже не надёжны.

Изменённый тест:


Код: c#
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.
    [TestClass]
    public class TestXMLStore
    {
        const int REPEAT_TEST = 1000;
        static string[] PATH = new [] { "TestMru" };

        [TestMethod]
        public void TestFillMRUStore()
        {
            var store = SettingsStorage.I.Value;
            var stopwatch = new Stopwatch();
            var random = new Random();
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\хранилища\\";

            store.Load();
            stopwatch.Start();
            for (int i = REPEAT_TEST; --i >= 0;)
            {
                string pickItem = null;
                var key = new SettingsStorageKey(PATH, random.Next(40).ToString());
                if (random.NextDouble() <= 0.4)
                {
                    store.TryGetValue<string>(key, out pickItem);
                }
                if(pickItem == null)
                {
                    pickItem = string.Concat(basePath, random.Next(), ".txt");
                }
                store.SetValue(key, pickItem);
                store.Save();
            }
            stopwatch.Stop();
            Debug.Write("Test completed in " + stopwatch.Elapsed.ToString());
        }

        [TestMethod]
        public void TestLoadMRUStore()
        {
            var store = SettingsStorage.I.Value;
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = REPEAT_TEST; --i >= 0;)
            {
                store.Load();
            }
            stopwatch.Stop();
            Debug.Write("Test completed in " + stopwatch.Elapsed.ToString());
        }
    }



Результат:
TestFillMRUStore - 3 sec.
TestLoadMRUStore - 1 sec.
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213751
ViPRos
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mikron,

все что касается пользователя без роуминга в реестре, с роумингом в конфиг файле, общее для всех в БД
Структура в реестре
ВИПРОС
--Конфигурация
----БД
------Задача
----------Юзер
---------------Роль в конфиге
----------------------Задача
--------------------------Форма или еще что
-----------------------------Элементы <->
---------------------------------Настройки
...
Рейтинг: 0 / 0
Сохранение пользовательской конфигурации.
    #39213754
ViPRos
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
это все работает пулей, никаких проблем (проблемы при их применении, потому там много чего делается Lazy)
...
Рейтинг: 0 / 0
25 сообщений из 127, страница 5 из 6
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Сохранение пользовательской конфигурации.
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]