public static JsonValue GenerateGraph() { var nodes = Ut.NewArray(1 << _numSwitches, ix => new Node { SwitchStates = ix }); var edges = new List <Edge>(); foreach (var node in nodes) { foreach (var node2 in nodes) { if (node2 != node && isPowerOf2(node.SwitchStates ^ node2.SwitchStates)) { for (int c = 0; c < _numColors; c++) { edges.Add(new Edge(node, node2, c)); } } } } // Remove as many edges as possible without compromising reachability edges.Shuffle(); var reducedEdges = Ut.ReduceRequiredSet(edges, skipConsistencyTest: true, test: state => allNodesReachable(nodes, state.SetToTest)); return(ClassifyJson.Serialize(reducedEdges.ToList())); }
private static TranslationInfo makeDefault() { var ti = new TranslationInfo(); ti.Json = ClassifyJson.Serialize(ti).ToString(); return(ti); }
private void saveCore() { _file.HexagonySource = _file.Grid.ToString(); File.WriteAllText(_currentFilePath, ClassifyJson.Serialize(_file).ToStringIndented()); File.WriteAllText(sourceFilePath(), _file.HexagonySource); // _lastFileTime = File.GetLastWriteTimeUtc(_currentFilePath); _anyChanges = false; }
private void ensureModuleInfoCache() { if (_moduleInfoCache == null) { lock (this) if (_moduleInfoCache == null) { const int cols = 20; // number of icons per row const int w = 32; // width of an icon in pixels const int h = 32; // height of an icon in pixels var iconFiles = new DirectoryInfo(_config.ModIconDir).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray(); var rows = (iconFiles.Length + cols - 1) / cols; var coords = new Dictionary <string, (int x, int y)>(); using (var bmp = new Bitmap(w * cols, h * rows)) { using (var g = Graphics.FromImage(bmp)) { for (int i = 0; i < iconFiles.Length; i++) { using (var icon = new Bitmap(iconFiles[i].FullName)) g.DrawImage(icon, w * (i % cols), h * (i / cols)); coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols)); } } using (var mem = new MemoryStream()) { bmp.Save(mem, ImageFormat.Png); _moduleInfoCache = new ModuleInfoCache { IconSpritePng = mem.ToArray() }; _moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(_moduleInfoCache.IconSpritePng).ToHex(); var modules = new DirectoryInfo(_config.ModJsonDir) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(4, file => { try { var origFile = File.ReadAllText(file.FullName); var modJson = JsonDict.Parse(origFile); var mod = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson); #if DEBUG var newJson = (JsonDict)ClassifyJson.Serialize(mod); var newJsonStr = newJson.ToStringIndented(); if (newJsonStr != origFile) { File.WriteAllText(file.FullName, newJsonStr); } modJson = newJson; #endif return((modJson, mod, file.LastWriteTimeUtc).Nullable()); }
public override IMessage Invoke(IMessage rawMsg) { var msg = (IMethodCallMessage)rawMsg; var method = msg.MethodBase as MethodInfo; var args = msg.Args; if (method == null || args == null) { throw new InternalErrorException("The transparent proxy received an invalid message."); } var parameters = method.GetParameters(); var hArgs = new List <HArg> { new HArg("Method", mangledMethodName(method)), new HArg("Arguments", new JsonList(args.Select((arg, i) => parameters[i].IsOut ? null : arg is Delegate ? new JsonDict { { ":delegate", true } } : ClassifyJson.Serialize(parameters[i].ParameterType, arg)))) }; if (_objectId != -1) { hArgs.Add(new HArg("ObjectID", _objectId)); } var responseRaw = _client.Post(_url, hArgs.ToArray()); var response = ClassifyJson.Deserialize <CommunicatorResult>(responseRaw.DataJson); var responseRet = response as CommunicatorResultReturn; if (responseRet != null) { var refOut = Enumerable.Range(0, parameters.Length) .Where(i => parameters[i].ParameterType.IsByRef) .Select(i => translate(parameters[i].ParameterType.GetElementType(), responseRet.RefOutArguments[i])) .ToArray(); return(new ReturnMessage( translate(method.ReturnType, responseRet.ReturnValue), refOut, refOut.Length, msg.LogicalCallContext, msg)); } throw new NotImplementedException(); }
// This method is called in Init() (when the server is initialized) and in pull() (when the repo is updated due to a new git commit). private void generateTranslationCache() { var path = Path.Combine(_config.BaseDir, "Translations"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } #if DEBUG ClassifyJson.SerializeToFile(TranslationInfo.Default, Path.Combine(path, "en.json")); #endif _translationCache = new DirectoryInfo(path) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(Environment.ProcessorCount, file => { try { var translationJson = File.ReadAllText(file.FullName); var translation = ClassifyJson.Deserialize <TranslationInfo>(JsonDict.Parse(translationJson)); translation.langCode = file.Name.Remove(file.Name.Length - 5); var newJson = ClassifyJson.Serialize(translation); translation.Json = newJson.ToString(); #if DEBUG var newJsonIndented = newJson.ToStringIndented(); if (translationJson != newJsonIndented) { File.WriteAllText(file.FullName, newJsonIndented); } #endif return(translation); } catch (Exception e) { #if DEBUG Console.WriteLine(e.Message); Console.WriteLine(e.GetType().FullName); Console.WriteLine(e.StackTrace); #endif Log.Exception(e); return(null); } }).ToDictionary(t => t.langCode, t => t); }
/// <summary> /// Constructs a new instance of <see cref="AjaxHandler{TApi}"/>.</summary> /// <param name="options"> /// Specifies <see cref="AjaxHandler{TApi}"/>’s exception behaviour.</param> public AjaxHandler(AjaxHandlerOptions options = AjaxHandlerOptions.ReturnExceptionsWithoutMessages) { _apiFunctions = new Dictionary <string, Func <HttpRequest, TApi, JsonValue> >(); _options = options; var typeContainingAjaxMethods = typeof(TApi); foreach (var method in typeContainingAjaxMethods.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => m.IsDefined <AjaxMethodAttribute>())) { var parameters = method.GetParameters(); var returnType = method.ReturnType; _apiFunctions.Add(method.Name, (req, api) => { JsonDict json; var rawJson = req.Post["data"].Value; try { json = JsonDict.Parse(rawJson); } catch (Exception e) { throw new AjaxInvalidParameterDataException(rawJson, e); } var arr = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { var paramName = parameters[i].Name; if (parameters[i].IsOptional && !json.ContainsKey(paramName)) { arr[i] = parameters[i].DefaultValue; } else { try { arr[i] = ClassifyJson.Deserialize(parameters[i].ParameterType, json[paramName]); } catch (Exception e) { throw new AjaxInvalidParameterException(paramName, e); } } } object result; try { result = method.Invoke(api, arr); } catch (Exception e) { throw new AjaxException("Error invoking the AJAX method.", e); } if (result is JsonValue) { return((JsonValue)result); } try { return(ClassifyJson.Serialize(returnType, result)); } catch (Exception e) { throw new AjaxInvalidReturnValueException(result, returnType, e); } }); } }
private ModuleInfoCache getModuleInfoCache() { ModuleInfoCache mic = null; do { if (_moduleInfoCache == null) { lock (this) if (_moduleInfoCache == null) { const int cols = 20; // number of icons per row const int w = 32; // width of an icon in pixels const int h = 32; // height of an icon in pixels var iconFiles = new DirectoryInfo(Path.Combine(_config.BaseDir, "Icons")).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray(); var rows = (iconFiles.Length + cols - 1) / cols; var coords = new Dictionary <string, (int x, int y)>(); using var bmp = new Bitmap(w * cols, h * rows); using (var g = Graphics.FromImage(bmp)) { for (int i = 0; i < iconFiles.Length; i++) { using (var icon = new Bitmap(iconFiles[i].FullName)) g.DrawImage(icon, w * (i % cols), h * (i / cols)); coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols)); } } using var mem = new MemoryStream(); bmp.Save(mem, ImageFormat.Png); // This needs to be a separate variable (don’t use _moduleInfoCache itself) because that field needs to stay null until it is fully initialized var moduleInfoCache = new ModuleInfoCache { IconSpritePng = mem.ToArray() }; moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(moduleInfoCache.IconSpritePng).ToHex(); // Load TP data from the spreadsheet JsonList entries; try { entries = new HClient().Get("https://spreadsheets.google.com/feeds/list/1G6hZW0RibjW7n72AkXZgDTHZ-LKj0usRkbAwxSPhcqA/1/public/values?alt=json").DataJson["feed"]["entry"].GetList(); } catch (Exception e) { Log.Exception(e); entries = new JsonList(); } var moduleLoadExceptions = new JsonList(); var modules = new DirectoryInfo(Path.Combine(_config.BaseDir, "JSON")) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(Environment.ProcessorCount, file => { try { var origFile = File.ReadAllText(file.FullName); var modJson = JsonDict.Parse(origFile); var mod = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson); #if DEBUG var newJson = (JsonDict)ClassifyJson.Serialize(mod); var newJsonStr = newJson.ToStringIndented(); if (newJsonStr != origFile) { File.WriteAllText(file.FullName, newJsonStr); } modJson = newJson;
private HttpResponse generateJson(HttpRequest req) { if (req.Method != HttpMethod.Post) { return(HttpResponse.PlainText("Only POST requests allowed.", HttpStatusCode._405_MethodNotAllowed)); } void populateObject(object obj, Type type) { foreach (var f in type.GetFields()) { var attr = f.GetCustomAttribute <EditableFieldAttribute>(); if (attr == null) { continue; } var fType = f.FieldType; if (f.FieldType.TryGetGenericParameters(typeof(Nullable <>), out var fTypes)) { fType = fTypes[0]; } var val = req.Post[f.Name].Value; try { if (f.GetCustomAttribute <EditableNestedAttribute>() != null) { if (val != "on") { f.SetValue(obj, null); } else { var nestedObj = Activator.CreateInstance(f.FieldType); populateObject(nestedObj, f.FieldType); f.SetValue(obj, nestedObj); } continue; } if (fType == typeof(string)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? null : val.Trim()); } else if (fType.IsEnum) { var enumVal = val == null ? null : Enum.Parse(fType, val); if (enumVal != null) { f.SetValue(obj, enumVal); } } else if (fType == typeof(DateTime)) { f.SetValue(obj, DateTime.ParseExact(val, "yyyy-MM-dd", null)); } else if (fType == typeof(string[])) { f.SetValue(obj, val.Split(';').Select(str => str.Trim()).ToArray()); } else if (fType == typeof(int)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? 0 : int.Parse(val)); } else if (fType == typeof(decimal)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? 0m : decimal.Parse(val)); } else if (fType == typeof(bool)) { f.SetValue(obj, val == "on"); } else { throw new InvalidOperationException($"Unrecognized field type: {fType.FullName}"); } } catch (Exception e) { _logger.Warn($"Generate JSON: unrecognized value. Field: {f.Name}, Type: {fType}, Value: “{val ?? "<null>"}”, Exception: {e.Message} ({e.GetType().FullName})"); } } } var m = new KtaneModuleInfo(); populateObject(m, typeof(KtaneModuleInfo)); var json = ClassifyJson.Serialize(m); // Now deserialize and then re-serialize this to force KtaneModuleInfo to perform some sanity things var m2 = ClassifyJson.Deserialize <KtaneModuleInfo>(json); return(HttpResponse.PlainText(ClassifyJson.Serialize(m2).ToStringIndented())); }
private string serializeConfig() { return(ClassifyJson.Serialize(_config, new ClassifyOptions { SerializationEqualityComparer = new CustomEqualityComparer <object>(customComparison) }).ToStringIndented()); }
private void ensureModuleInfoCache() { if (_moduleInfoCache == null) { lock (this) if (_moduleInfoCache == null) { const int cols = 20; // number of icons per row const int w = 32; // width of an icon in pixels const int h = 32; // height of an icon in pixels var iconFiles = new DirectoryInfo(_config.ModIconDir).EnumerateFiles("*.png", SearchOption.TopDirectoryOnly).OrderBy(file => file.Name != "blank.png").ToArray(); var rows = (iconFiles.Length + cols - 1) / cols; var coords = new Dictionary <string, (int x, int y)>(); using var bmp = new Bitmap(w * cols, h * rows); using (var g = Graphics.FromImage(bmp)) { for (int i = 0; i < iconFiles.Length; i++) { using (var icon = new Bitmap(iconFiles[i].FullName)) g.DrawImage(icon, w * (i % cols), h * (i / cols)); coords.Add(Path.GetFileNameWithoutExtension(iconFiles[i].Name), (i % cols, i / cols)); } } using var mem = new MemoryStream(); bmp.Save(mem, ImageFormat.Png); _moduleInfoCache = new ModuleInfoCache { IconSpritePng = mem.ToArray() }; _moduleInfoCache.IconSpriteMd5 = MD5.Create().ComputeHash(_moduleInfoCache.IconSpritePng).ToHex(); // Load TP data from the spreadsheet JsonList entries; try { entries = new HClient().Get("https://spreadsheets.google.com/feeds/list/1WEzVOKxOO5CDGoqAHjJKrC-c-ZGgsTPRLXBCs8RrAwU/1/public/values?alt=json").DataJson["feed"]["entry"].GetList(); } catch (Exception e) { _logger.Exception(e); entries = new JsonList(); } var modules = new DirectoryInfo(_config.ModJsonDir) .EnumerateFiles("*.json", SearchOption.TopDirectoryOnly) .ParallelSelect(4, file => { try { var origFile = File.ReadAllText(file.FullName); var modJson = JsonDict.Parse(origFile); var mod = ClassifyJson.Deserialize <KtaneModuleInfo>(modJson); #if DEBUG var newJson = (JsonDict)ClassifyJson.Serialize(mod); var newJsonStr = newJson.ToStringIndented(); if (newJsonStr != origFile) { File.WriteAllText(file.FullName, newJsonStr); } modJson = newJson;
void IPropellerModule.Init(LoggerBase log, JsonValue settings, ISettingsSaver saver) { _log = log; _saver = saver; _settings = ClassifyJson.Deserialize <Settings>(settings) ?? new Settings(); var validPaths = new List <string>(); foreach (var path in _settings.Paths) { if (!Directory.Exists(path)) { _log.Warn(@"DocGen: Warning: The folder ""{0}"" specified in the settings does not exist. Ignoring path.".Fmt(path)); } else { validPaths.Add(path); } } _settings.Paths = validPaths.ToArray(); saver.SaveSettings(ClassifyJson.Serialize(_settings)); string copyToPath = null; if (_settings.DllTempPath != null) { // Try to clean up old folders we've created before var tempPath = _settings.DllTempPath; Directory.CreateDirectory(tempPath); foreach (var path in Directory.GetDirectories(tempPath, "docgen-tmp-*")) { try { Directory.Delete(path, true); } catch { } } // Find a new folder to put the DLL files into int j = 1; copyToPath = Path.Combine(tempPath, "docgen-tmp-" + j); while (Directory.Exists(copyToPath)) { j++; copyToPath = Path.Combine(tempPath, "docgen-tmp-" + j); } Directory.CreateDirectory(copyToPath); } _docGen = new DocumentationGenerator(_settings.Paths, _settings.RequireAuthentication ? _settings.UsernamePasswordFile ?? "" : null, copyToPath); lock (_log) { _log.Info("DocGen initialised with {0} assemblies: {1}".Fmt(_docGen.AssembliesLoaded.Count, _docGen.AssembliesLoaded.JoinString(", "))); if (_docGen.AssemblyLoadErrors.Count > 0) { _log.Warn("{0} assembly load errors:".Fmt(_docGen.AssemblyLoadErrors.Count)); foreach (var tuple in _docGen.AssemblyLoadErrors) { _log.Warn("{0} error: {1}".Fmt(tuple.Item1, tuple.Item2)); } } } }
private HttpResponse generateJson(HttpRequest req) { if (req.Method != HttpMethod.Post) { return(HttpResponse.PlainText("Only POST requests allowed.", HttpStatusCode._405_MethodNotAllowed)); } void populateObject(object obj, Type type) { foreach (var f in type.GetFields()) { var attr = f.GetCustomAttribute <EditableFieldAttribute>(); if (attr == null || attr.ReadableName == null) { continue; } var fType = f.FieldType; if (f.FieldType.TryGetGenericParameters(typeof(Nullable <>), out var fTypes)) { fType = fTypes[0]; } var val = req.Post[f.Name].Value; try { if (f.GetCustomAttribute <EditableNestedAttribute>() != null) { if (val != "on") { f.SetValue(obj, null); } else { var nestedObj = Activator.CreateInstance(f.FieldType); populateObject(nestedObj, f.FieldType); f.SetValue(obj, nestedObj); } continue; } if (fType == typeof(string)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? null : val.Trim()); } else if (fType.IsEnum && fType.GetCustomAttribute <FlagsAttribute>() != null) { var intVal = 0; foreach (var value in Enum.GetValues(fType)) { if (req.Post[$"{f.Name}-{value}"].Value != null) { intVal |= (int)value; } } f.SetValue(obj, intVal); } else if (fType.IsEnum) { var enumVal = val == null ? null : Enum.Parse(fType, val); if (enumVal != null) { f.SetValue(obj, enumVal); } } else if (fType == typeof(DateTime)) { f.SetValue(obj, DateTime.ParseExact(val, "yyyy-MM-dd", null)); } else if (fType == typeof(string[])) { f.SetValue(obj, val.Split(attr.AllowedSeparators).Select(str => str.Trim()).ToArray().Apply(list => list.Length == 0 || (list.Length == 1 && string.IsNullOrWhiteSpace(list[0])) ? null : list)); } else if (fType == typeof(Dictionary <string, string>)) { if (val.Trim() == "") { continue; } else if (!attr.AllowedDictSeparators.Any(sep => val.Contains(sep))) { f.SetValue(obj, new Dictionary <string, string>() { { attr.DefaultKey, string.IsNullOrWhiteSpace(val) ? null : val.Trim() } }); } else { f.SetValue(obj, val.Split(attr.AllowedSeparators).Select(str => str.Split(attr.AllowedDictSeparators)).ToDictionary(x => x[0].Trim(), x => x[1].Trim())); } } else if (fType == typeof(int)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? 0 : int.Parse(val)); } else if (fType == typeof(decimal)) { f.SetValue(obj, string.IsNullOrWhiteSpace(val) ? 0m : decimal.Parse(val)); } else if (fType == typeof(bool)) { f.SetValue(obj, val == "on"); } else if (fType == typeof(TutorialVideoInfo[])) { f.SetValue(obj, ClassifyJson.Deserialize <TutorialVideoInfo[]>(val)); } else { throw new InvalidOperationException($"Unrecognized field type: {fType.FullName}"); } } catch (Exception e) { Log.Warn($"Generate JSON: unrecognized value. Field: {f.Name}, Type: {fType}, Value: “{val ?? "<null>"}”, Exception: {e.Message} ({e.GetType().FullName})"); } } } var m = new KtaneModuleInfo(); populateObject(m, typeof(KtaneModuleInfo)); if (string.IsNullOrWhiteSpace(m.Name)) { return(HttpResponse.PlainText("You did not specify a module name.")); } var json = ClassifyJson.Serialize(m); // Now deserialize and then re-serialize this to force KtaneModuleInfo to perform some sanity things var m2 = ClassifyJson.Deserialize <KtaneModuleInfo>(json); return(HttpResponse.PlainText(ClassifyJson.Serialize(m2).ToStringIndented())); }
/// <summary>Saves the settings stored in <see cref="Settings"/>.</summary> protected void SaveSettings() { SettingsSaver.SaveSettings(ClassifyJson.Serialize(Settings)); }
/// <summary> /// Creates an HTTP request handler that responds to requests from clients to execute methods on the specified factory /// object as well as any remote objects generated from it.</summary> /// <typeparam name="T"> /// The type containing the factory methods. If the client is going to access the factory methods via an interface, /// this should be that interface type rather than the concrete type of <paramref /// name="factoryInstance"/>.</typeparam> /// <param name="factoryInstance"> /// An instance that implements or derives from <typeparamref name="T"/> which provides the factory functionality to /// be accessed by clients.</param> /// <returns> /// An HTTP handler that can be used in <see cref="HttpServer"/> or <see cref="UrlResolver"/>.</returns> public static Func <HttpRequest, HttpResponse> CreateHandlerFromFactory <T>(T factoryInstance) { var thisType = typeof(T); var methods = new Dictionary <Type, Dictionary <string, MethodInfo> > { { thisType, getMethodDictionary(typeof(T)) } }; return(req => { if (req.Method != HttpMethod.Post) { throw new HttpException(HttpStatusCode._400_BadRequest, userMessage: "POST request expected."); } var objectId = req.Post["ObjectID"].Value.NullOr(Convert.ToInt32); var instance = objectId == null ? factoryInstance : _activeObjects[objectId.Value]; var type = objectId == null ? thisType : instance.GetType(); Dictionary <string, MethodInfo> methodDict; if (!methods.TryGetValue(type, out methodDict)) { methods[type] = methodDict = getMethodDictionary(type); } MethodInfo method; if (!methodDict.TryGetValue(req.Post["Method"].Value, out method)) { throw new HttpException(HttpStatusCode._400_BadRequest, userMessage: "The method does not exist."); } var parameters = method.GetParameters(); object[] arguments = new object[parameters.Length]; var argumentsRaw = JsonList.Parse(req.Post["Arguments"].Value); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].IsOut) { continue; } var remoteId = argumentsRaw[i].Safe[":remoteid"].GetIntSafe(); if (remoteId != null) { lock (_activeObjects) arguments[i] = _activeObjects[remoteId.Value]; } else { // TODO: Delegates arguments[i] = ClassifyJson.Deserialize(parameters[i].ParameterType.IsByRef ? parameters[i].ParameterType.GetElementType() : parameters[i].ParameterType, argumentsRaw[i]); } } var returnValue = method.Invoke(instance, arguments); var process = Ut.Lambda((ParameterInfo param, object value) => { if (!param.IsDefined <RemoteAttribute>()) { return ClassifyJson.Serialize(param.ParameterType, value); } lock (_activeObjects) { var remoteId = _activeObjects.IndexOf(value); if (remoteId == -1) { remoteId = _activeObjects.Count; _activeObjects.Add(value); } return new JsonDict { { ":remoteid", remoteId } }; } }); var returnValueRaw = process(method.ReturnParameter, returnValue); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { argumentsRaw[i] = process(parameters[i], arguments[i]); } else { argumentsRaw[i] = null; } } return HttpResponse.Json(ClassifyJson.Serialize <CommunicatorResult>(new CommunicatorResultReturn(returnValueRaw, argumentsRaw))); }); }
private void saveCore() { File.WriteAllText(_currentFilePath, ClassifyJson.Serialize(_file).ToStringIndented()); _lastFileTime = File.GetLastWriteTimeUtc(_currentFilePath); _anyChanges = false; }