1
0
mirror of https://github.com/chylex/Backup-Essentials.git synced 2025-08-04 15:59:07 +02:00

Added dictionary<->string conversion and a safe dict that returns null if key is not found

This commit is contained in:
chylex 2015-04-05 18:20:10 +02:00
parent 39974d0bac
commit 809c802429
3 changed files with 71 additions and 0 deletions

View File

@ -96,6 +96,8 @@
<Compile Include="TestingWindow.xaml.cs">
<DependentUpon>TestingWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Utils\SafeDictionary.cs" />
<Compile Include="Utils\StringDictionarySerializer.cs" />
<Compile Include="Utils\ProgramArgsParser.cs" />
<Compile Include="Utils\ScheduledUpdate.cs" />
<Compile Include="Utils\WindowsVersion.cs" />

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BackupEssentials.Utils{
class SafeDictionary<K,V> : Dictionary<K,V>{
public new V this[K key]{
get {
V value;
TryGetValue(key,out value);
return value;
}
set {
base[key] = value;
}
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BackupEssentials.Utils{
class StringDictionarySerializer{
public static string ToString(Dictionary<string,string> dict){
StringBuilder build = new StringBuilder();
foreach(KeyValuePair<string,string> kvp in dict){
build.Append(kvp.Key).Append((char)31).Append(kvp.Value).Append((char)31);
}
if (build.Length > 0)build.Remove(build.Length-1,1);
return build.ToString();
}
public static string ToString(IObjectToDictionary obj){
SafeDictionary<string,string> dict = new SafeDictionary<string,string>();
obj.ToDictionary(dict);
return ToString(dict);
}
public static SafeDictionary<string,string> FromString(string data){
SafeDictionary<string,string> dict = new SafeDictionary<string,string>();
string key = null;
foreach(string part in data.Split((char)31)){
if (key == null)key = part;
else{
dict.Add(key,part);
key = null;
}
}
return dict;
}
public static void FromString(IObjectToDictionary obj, string data){
obj.FromDictionary(FromString(data));
}
public interface IObjectToDictionary{
void ToDictionary(SafeDictionary<string,string> dict);
void FromDictionary(SafeDictionary<string,string> dict);
}
}
}