A bunch of classes imported to Core from XmlApiClient (webdrive)

main
Inga 🏳‍🌈 14 years ago
parent a673704c8b
commit faadde7444
  1. 13
      Core/Core.csproj
  2. 59
      Core/DataObject.cs
  3. 26
      Core/IDataObject.cs
  4. 50
      Core/Registry.cs
  5. 28
      Core/Switch.cs
  6. 117
      Core/Util.cs
  7. 8
      Core/delegates/Lazy.cs
  8. 10
      Core/delegates/Predicate.cs
  9. 14
      Core/exceptions/CriticalException.cs
  10. 28
      Core/exceptions/FLocalException.cs
  11. 16
      Core/exceptions/ObjectDoesntHaveAnIdException.cs
  12. 47
      Core/extensions/Delegate.cs
  13. 222
      Core/extensions/Extensions.cs
  14. 53
      Core/extensions/String.cs

@ -45,7 +45,20 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DataObject.cs" />
<Compile Include="delegates\Lazy.cs" />
<Compile Include="delegates\Predicate.cs" />
<Compile Include="exceptions\CriticalException.cs" />
<Compile Include="exceptions\FLocalException.cs" />
<Compile Include="exceptions\ObjectDoesntHaveAnIdException.cs" />
<Compile Include="extensions\Delegate.cs" />
<Compile Include="extensions\Extensions.cs" />
<Compile Include="extensions\String.cs" />
<Compile Include="IDataObject.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Registry.cs" />
<Compile Include="Switch.cs" />
<Compile Include="Util.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace FLocal.Core {
abstract class DataObject<TKey, T> : IDataObject<TKey, T>
where T : DataObject<TKey, T>, new()
where TKey : struct {
private TKey? _id;
public TKey id {
get {
if(this.isNewObject) {
throw new ObjectDoesntHaveAnIdException();
}
return this._id.Value;
}
}
public bool isNewObject {
get {
return !this._id.HasValue;
}
}
private bool isJustCreated;
public DataObject() {
Debug.Assert(this is T);
this.isJustCreated = true;
this._id = null;
}
public static T LoadById(TKey id) {
return registry.Get(id);
}
protected virtual void AfterCreate() { }
public void CreateByIdFromRegistry(TKey id) {
if(!this.isJustCreated) throw new CriticalException("Object already has an id");
this._id = id;
this.isJustCreated = false;
this.AfterCreate();
}
public static Registry<TKey, T> registry {
get {
return Registry<TKey, T>.instance;
}
}
}
}

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
interface IDataObject<TKey, TData> /*: IDataObject<TKey>*/
where TData : IDataObject<TKey, TData>, new()
where TKey : struct {
//static TData LoadById(TKey id);
//static TData CreateByIdFromRegistry(TKey id);
void CreateByIdFromRegistry(TKey id);
//TKey GetId();
TKey id {
get;
}
}
}

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
class Registry<TKey, TData>
where TData : IDataObject<TKey, TData>, new()
where TKey : struct {
public static readonly Registry<TKey, TData> instance = new Registry<TKey,TData>();
private Dictionary<TKey, TData> storage;
private HashSet<TKey> locks;
protected Registry() {
this.storage = new Dictionary<TKey,TData>();
this.locks = new HashSet<TKey>();
}
public TData Get(TKey id) {
if(this.locks.Contains(id)) throw new CriticalException("Locked");
if(!this.storage.ContainsKey(id)) {
try {
this.locks.Add(id);
//this.storage[id] = IDataObject<TKey, TData>.CreateByIdFromRegistry(id);
//this.storage[id] = TData.CreateByIdFromRegistry(id);
TData obj = new TData();
obj.CreateByIdFromRegistry(id);
this.storage[id] = obj;
this.locks.Remove(id);
} catch(FLocalException e) {
this.locks.Remove(id);
throw e;
}
}
return this.storage[id];
}
public bool IsCached(TKey id) {
if(this.locks.Contains(id)) throw new CriticalException("locked");
return this.storage.ContainsKey(id);
}
}
}

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
class Switch<TResult> : List<KeyValuePair<Predicate, Func<TResult>>> {
public void Add(Predicate checker, Func<TResult> calculator) {
this.Add(new KeyValuePair<Predicate,Func<TResult>>(checker, calculator));
}
public void Add(bool checkResult, Func<TResult> calculator) {
this.Add(() => checkResult, calculator);
}
public TResult Value {
get {
return this.Single(kvp => kvp.Key(), () => {
throw new FLocalException("Not found");
}).Value();
}
}
}
}

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
class Util {
private static bool? _isRunningOnMono;
public static bool isRunningOnMono {
get {
if(!_isRunningOnMono.HasValue) {
_isRunningOnMono = (Type.GetType("Mono.Runtime") != null);
}
return _isRunningOnMono.Value;
}
}
public static bool string2bool(string _val) {
switch(_val.ToLower()) {
case "y":
case "yes":
case "true":
case "enabled":
case "on":
case "1":
return true;
case "n":
case "no":
case "false":
case "disabled":
case "off":
case "0":
return false;
default:
throw new FLocalException("Cannot parse string '" + _val + "'; try to use 'n' or 'y'");
}
}
public static T string2enum<T>(string value) {
return (T)System.Enum.Parse(typeof(T), value);
}
public static void CheckEmail(string email) {
if(!email.Contains('@') || !email.Contains('.')) throw new FLocalException("Wrong email '" + email + "'");
}
public static Predicate<string> PhoneValidator {
get {
return phone => {
return true;
};
}
}
public static T EnumParse<T>(string name) {
return (T)Enum.Parse(typeof(T), name, true);
}
public static IEnumerable<int> Range(int start, int count, int step) {
if(step == 0) {
throw new FLocalException("Step could not be equal to zero");
}
for(int i=0; i<count; i++) {
yield return start + (i*count);
}
}
public static IEnumerable<int> Range(int start, int count) {
return Range(start, count, 1);
}
public static IEnumerable<T> CreateList<T>(int length, Func<int, T> creator) {
return from i in Range(0, length) select creator(i);
}
public static IEnumerable<T> CreateList<T>(int length, Func<T> creator) {
return CreateList<T>(length, num => creator());
}
private static readonly Random RandomGenerator = new Random();
public static int RandomInt(int gethan, int lessthan) {
return RandomGenerator.Next(gethan, lessthan);
}
public enum RandomSource {
LETTERS,
LETTERS_DIGITS,
CYRILLIC,
}
private static Dictionary<RandomSource, string> randoms = new Dictionary<RandomSource,string> {
{ RandomSource.LETTERS, "abcdefghijklmnopqrstuvwxyz" },
{ RandomSource.LETTERS_DIGITS, "abcdefghijklmnopqrstuvwxyz0123456789" },
{ RandomSource.CYRILLIC, "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" },
};
public static string RandomString(int length, RandomSource source) {
return new String(
CreateList(length, (
(Func<string, char>)(str => str[RandomInt(0, str.Length)])
).Curry(
randoms[source]
)).ToArray()
);
}
public static string RandomString(int length) {
return RandomString(length, RandomSource.LETTERS);
}
}
}

@ -0,0 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
delegate T Lazy<T>();
}

@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
delegate bool Predicate();
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
partial class CriticalException : FLocalException {
public CriticalException(string Message) : base(Message) { }
}
}

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
partial class FLocalException : ApplicationException {
public readonly string FullStackTrace;
public FLocalException(string Message) : base(Message) {
this.FullStackTrace = Environment.StackTrace;
}
public string getMessage() {
return this.Message;
}
public override string StackTrace {
get {
return FullStackTrace;
}
}
}
}

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
partial class ObjectDoesntHaveAnIdException : FLocalException {
public ObjectDoesntHaveAnIdException()
: base("Object doesn't have an id") {
}
}
}

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
static class DelegateExtension {
public static Func<T, bool> ToFunc<T>(this Predicate<T> p) {
return arg => p(arg);
}
public static Func<TResult> Curry<T1, TResult>(this Func<T1, TResult> func, T1 arg1) {
return () => func(arg1);
}
public static Action Curry<T1>(this Action<T1> action, T1 arg1) {
return () => action(arg1);
}
public static Func<TResult> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func, T1 arg1, T2 arg2) {
return () => func(arg1, arg2);
}
public static Action Curry<T1, T2>(this Action<T1, T2> action, T1 arg1, T2 arg2) {
return () => action(arg1, arg2);
}
public static Func<T2, TResult> LCurry<T1, T2, TResult>(this Func<T1, T2, TResult> func, T1 arg1) {
return arg2 => func(arg1, arg2);
}
public static Action<T2> LCurry<T1, T2>(this Action<T1, T2> action, T1 arg1) {
return arg2 => action(arg1, arg2);
}
public static Func<T1, TResult> RCurry<T1, T2, TResult>(this Func<T1, T2, TResult> func, T2 arg2) {
return arg1 => func(arg1, arg2);
}
public static Action<T1> RCurry<T1, T2>(this Action<T1, T2> action, T2 arg2) {
return arg1 => action(arg1, arg2);
}
}
}

@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
static class ExtensionMethods {
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> kvps) {
Dictionary<TKey, TValue> res = new Dictionary<TKey,TValue>();
foreach(KeyValuePair<TKey, TValue> kvp in kvps) {
res[kvp.Key] = kvp.Value;
}
return res;
}
public static TDestinationDictionary
Convert<TSourceDictionary, TDestinationDictionary, TKey, TSource, TDestination>
(this TSourceDictionary dict, Func<TSource, TDestination> converter)
where TSourceDictionary : IDictionary<TKey, TSource>
where TDestinationDictionary : IDictionary<TKey, TDestination>, new()
{
TDestinationDictionary res = new TDestinationDictionary();
foreach(KeyValuePair<TKey, TSource> kvp in dict) {
res[kvp.Key] = converter(kvp.Value);
}
return res;
}
public delegate TResult RefFunc<T, TResult>(ref T arg);
public static RefFunc<T, T> getProperty<T>(this object obj, Func<T> creator) {
return (ref T arg) => {
if(arg == null) {
arg = creator();
}
return arg;
};
}
public static T getProperty<T>(this object obj, ref T arg, Func<T> creator) {
return obj.getProperty<T>(creator)(ref arg);
}
public static string ToPrintableString(this bool val) {
return val ? "Enabled" : "Disabled";
}
public static string ToXmlApiRequestString(this bool val) {
return val ? "1" : "0";
}
public static T Safe<T>(this T obj, T defaultValue) {
if(obj == null) {
return defaultValue;
} else {
return obj;
}
}
public static HashSet<T> Clone<T>(this HashSet<T> obj) {
return new HashSet<T>(obj);
}
/// <summary>
/// Note that actions from todoArr can be executed in any order!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="todoArr"></param>
/// <returns></returns>
public static T Tee<T>(this T obj, params Action<T>[] todoArr) {
foreach(Action<T> todo in todoArr) todo(obj);
return obj;
}
public static T Tee<T>(this T obj, Action todo) {
todo();
return obj;
}
private static List<TAttribute> GetAttributeArray<TAttribute>(this System.Reflection.PropertyInfo property) where TAttribute : Attribute {
return new List<TAttribute>(from attribute in property.GetCustomAttributes(true) where /*Tie(attribute, obj => Console.WriteLine(obj.GetType().FullName))*/ attribute is TAttribute select (TAttribute)attribute);
}
public static TAttribute GetAttribute<TAttribute>(this System.Reflection.PropertyInfo property) where TAttribute : Attribute {
return property.GetAttributeArray<TAttribute>().Single();
}
public static bool HasAttribute<TAttribute>(this System.Reflection.PropertyInfo property) where TAttribute : Attribute {
return property.GetAttributeArray<TAttribute>().Count > 0;
}
public static TResult Invoke<TResult>(this System.Reflection.MethodBase method, object obj, params object[] args) {
return (TResult)method.Invoke(obj, args);
}
public static void Invoke(this System.Reflection.MethodBase method, object obj, params object[] args) {
method.Invoke(obj, args);
}
public static Dictionary<TKey, TResult> Replace<TKey, TValue, TResult>(this IDictionary<TKey, TValue> dict, Func<TValue, TResult> Replacer) {
return new List<KeyValuePair<TKey, TResult>>(
from kvp in dict
select new KeyValuePair<TKey, TResult>(kvp.Key, Replacer(kvp.Value))
).ToDictionary();
}
public static Dictionary<TKey, TValue> Replace<TKey, TValue>(this IDictionary<TKey, TValue> dict, Func<TValue, TValue> Replacer) {
return dict.Replace<TKey, TValue, TValue>(Replacer);
}
public static T Single<T>(this IEnumerable<T> list, Predicate<T> checker, Func<T> onNotFound) {
try {
return list.Single(checker.ToFunc());
} catch(InvalidOperationException) {
return onNotFound();
}
}
public static IEnumerable<string> Enquote(this IEnumerable<string> strings) {
return from str in strings select str.Enquote();
}
public static TResult Check<TSource, TResult>(this TSource obj, Predicate<TSource> checker, Func<TSource, TResult> returnOnFail, TResult returnOnSuccess) {
if(!checker(obj)) {
return returnOnFail(obj);
} else {
return returnOnSuccess;
}
}
public static TResult Check<TSource, TResult>(this TSource obj, Predicate<TSource> checker, Func<TSource, Exception> onFail, Func<TSource, TResult> returnOnSuccess) {
if(!checker(obj)) {
throw onFail(obj);
} else {
return returnOnSuccess(obj);
}
}
public static void Check<T>(this T obj, Predicate<T> checker, Func<T, Exception> onFail) {
if(!checker(obj)) {
throw onFail(obj);
}
}
public static bool Empty<T>(this IEnumerable<T> list) {
return list.Count() == 0;
}
/// <summary>
/// Checks arg given against the predicate given; in case of type mismatch returns false
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arg"></param>
/// <param name="checker"></param>
/// <returns></returns>
public static bool TypedLoosePredicate<T>(this object arg, Predicate<T> checker) {
return (arg is T) && checker((T)arg);
}
public static Func<object, string> SafeToStringConvertor() {
return obj => obj == null ? "" : obj.ToString();
}
public static T Recurse<T>(this T obj, Func<T, T> step, Predicate<T> checker) {
//Debugger.Debug("recurse(" + typeof(T).FullName + ")");
int i=0;
while(checker(obj)) {
//Debugger.Debug("Iteration " + i.ToString());
obj = step(obj);
i++;
}
//Debugger.Debug("endrecurse(" + typeof(T).Name + ")");
return obj;
}
public static T[] Slice<T>(this T[] obj, int offset, int length) {
if(offset<0) throw new IndexOutOfRangeException();
if(offset+length > obj.Length) throw new IndexOutOfRangeException();
T[] res = new T[length];
Array.Copy(obj, offset, res, 0, length);
return res;
}
public static T[] Slice<T>(this T[] arr, int offset) {
return arr.Slice(offset, arr.Length-offset);
}
public static T TryValues<T>(this T obj, params Func<T>[] trials) {
//Debugger.Debug("TryValues(" + typeof(T).FullName + ")");
return new KeyValuePair<T, Func<T>[]>(obj, trials).Recurse(
kvp => new KeyValuePair<T, Func<T>[]>(kvp.Value[0](), kvp.Value.Slice(1)),
kvp => !kvp.Value.Empty() && kvp.Key == null
).Key;
}
public static IEnumerable<T> Replace<T>(this IEnumerable<T> list, Func<T, T> replacer) {
return from elem in list select replacer(elem);
}
public static string ToStringOnFail(this bool test, Lazy<string> onFail) {
return test ? "" : onFail();
}
public static string Join(this IEnumerable<string> strings, string separator) {
return String.Join(separator, strings.ToArray());
}
public static IEnumerable<T> GetSorted<T>(this IEnumerable<T> list) {
return from elem in list orderby elem select elem;
}
public static Int64 ToInt64(this decimal number) {
return decimal.ToInt64(number);
}
}
}

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FLocal.Core {
static class StringExtension {
public static string PHPSubstring(this string str, int start, int length) {
if(start > str.Length) {
return "";
} else if(start + length > str.Length) {
return str.Substring(start);
} else {
return str.Substring(start, length);
}
}
public static string PHPSubstring(this string str, int start) {
if(start > str.Length) {
return "";
} else {
return str.Substring(start);
}
}
public static string Enquote(this string str, string quotationMark) {
return quotationMark + str + quotationMark;
}
public static string Enquote(this string str) {
return str.Enquote("'");
}
public static string Replace(this string src, IEnumerable<KeyValuePair<string, string>> replacePairs) {
string dest = src;
foreach(KeyValuePair<string, string> kvp in replacePairs) {
dest = dest.Replace(kvp.Key, kvp.Value);
}
return dest;
}
public static bool Contains(this string str, IEnumerable<string> needles) {
return (from needle in needles select str.Contains(needle)).Contains(true);
}
public static bool IContains(this string str, IEnumerable<string> needles) {
return str.ToLower().Contains(from needle in needles select needle.ToLower());
}
}
}
Loading…
Cancel
Save