private static void magix_web_get_file(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.web", "Magix.web.hyperlisp.inspect.hl", "[magix.web.get-file-dox].value"); AppendCodeFromResource( ip, "Magix.web", "Magix.web.hyperlisp.inspect.hl", "[magix.web.get-file-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("file")) { throw new ArgumentException("you need to supply a [file] parameter"); } if (!ip["file"].ContainsValue("url")) { throw new ArgumentException("you need to supply which file to load as the [url] parameter"); } string filepath = Expressions.GetExpressionValue <string>(ip["file"]["url"].Get <string>(), dp, ip, false); if (string.IsNullOrEmpty(filepath)) { throw new ArgumentException("you need to define which file to load, as [url]"); } DownloadFile(ip, filepath); }
private static void p5_crypto_get_public_key(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new ArgsRemover(e.Args)) { // Getting key ID to look for string keyID = e.Args.GetExValue <string> (context, null); if (string.IsNullOrEmpty(keyID)) { throw new LambdaException("No ID given to use for looking up key", e.Args, context); } // Creating new GnuPG context using (var ctx = new GnuPrivacyContext()) { // Looping through each public key in GnuPG database foreach (PgpPublicKeyRing idxRing in ctx.PublicKeyRingBundle.GetKeyRings()) { // Looping through each key in keyring foreach (PgpPublicKey idxPublicKey in idxRing.GetPublicKeys()) { // Checking if this is the requested key if (idxPublicKey.KeyId.ToString("X") == keyID) { // This is the key we're looking for using (var memStream = new MemoryStream()) { using (var armored = new ArmoredOutputStream(memStream)) { idxPublicKey.Encode(armored); armored.Flush(); } memStream.Flush(); memStream.Position = 0; var sr = new StreamReader(memStream); e.Args.Value = sr.ReadToEnd(); } return; } } } } } }
public void p5_web_widgets_find_ancestor(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(e.Args, true)) { // Sanity check. if (e.Args.Children.Count(ix => ix.Name != "") == 0) { throw new LambdaException("No criteria submitted to [" + e.Name + "]", e.Args, context); } if (e.Args.Value == null) { throw new LambdaException("No starting widget submitted to [" + e.Name + "]", e.Args, context); } // Setting up a result node, to avoid modifying our args before all iteration is finished // Notice, if we hadn't done this, then each match would create a new (bogus) criteria, meaning there could never be more than one match. var retVal = new Node(); // Iterating start widget(s) to start searching for criteria amongst ancestor widgets. foreach (var idxStartWidgetId in XUtil.Iterate <string> (context, e.Args)) { // Retrieving start widget from where to start searching for widgets matching criteria. var startControl = FindControl <Widget> (idxStartWidgetId, Manager.AjaxPage); // Retrieving all widgets having properties matching whatever criteria are supplied. foreach (var idxWidget in FindWidgetsMatchingCriteria(e.Args, startControl, context, e.Name.Contains("-like"), true)) { // Adding type of widget as name, and ID of widget as value. retVal.FindOrInsert(idxStartWidgetId).Add(GetTypeName(idxWidget), idxWidget.ID); // Checking if caller only wants one result for each starting widget. if (e.Name.Contains("-first")) { break; } } } e.Args.AddRange(retVal.Children); } }
public static void p5_csv_lambda2csv(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution. using (new Utilities.ArgsRemover(e.Args)) { // Loops through all documents we're supposed to transform, and stuffing into temporary StringBuilder. var builder = new StringBuilder(); bool first = true; foreach (var idxLambda in XUtil.Iterate <Node> (context, e.Args)) { var content = ""; if (first) { // Adding headers. foreach (var idxInnerHeader in idxLambda.Children) { content += idxInnerHeader.Name + ","; } builder.Append(content.Substring(0, content.Length - 1) + "\r\n"); first = false; } // Adding values. content = ""; foreach (var idxInner in idxLambda.Children) { var value = idxInner.Get <string> (context); if (value.Contains(",")) { content += "\"" + value.Replace("\"", "\"\"") + "\","; } else { content += value + ","; } } builder.Append(content.Substring(0, content.Length - 1) + "\r\n"); } e.Args.Value = builder.ToString(); } }
static void p5_hyperlisp_get_object_value_date(ApplicationContext context, ActiveEventArgs e) { if (e.Args.Value is DateTime) { return; } var strValue = e.Args.Get <string> (context); if (strValue != null) { switch (strValue.Length) { case 10: e.Args.Value = DateTime.ParseExact(strValue, "yyyy-MM-dd", CultureInfo.InvariantCulture); break; case 16: e.Args.Value = DateTime.ParseExact(strValue, "yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture); break; case 19: e.Args.Value = DateTime.ParseExact(strValue, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture); break; case 23: e.Args.Value = DateTime.ParseExact(strValue, "yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); break; default: throw new ArgumentException("date; '" + strValue + "' is not recognized as a valid date"); } } else { throw new LambdaException( "Don't know how to convert that to a date", e.Args, context); } }
public static void magix_execute_open(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.open-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.open-sample]"); return; } if (!ip.ContainsValue("name")) { throw new ArgumentException("[open] needs a [name] parameter"); } Node dp = Dp(e.Params); string activeEvent = Expressions.GetExpressionValue <string>(ip["name"].Get <string>(), dp, ip, false); if (!ip.Contains("persist") || ip["persist"].Get <bool>()) { DataBaseRemoval.Remove(activeEvent, "magix.execute.open", e.Params); Node saveNode = new Node("magix.data.save"); saveNode["id"].Value = Guid.NewGuid(); saveNode["value"]["event"].Value = activeEvent; saveNode["value"]["type"].Value = "magix.execute.open"; BypassExecuteActiveEvent(saveNode, e.Params); } ActiveEvents.Instance.MakeRemotable(activeEvent); }
public static void magix_execute_else_if(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params, true); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.else-if-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.else-if-sample]"); return; } // checking syntax VerifySyntaxElseIf(ip); // making sure previous [if] or [else-if] didn't execute before we run comparison to see if we should execute body of [else-if] if (!CheckState(e.Params)) { IfElseIfImplementation( e.Params, "magix.execute.else-if"); } else { // checking to see if next keyword is [else] or [else-if], and if not, we remove signaling state ("_state_if") from state Node next = ip.Next(); if (next == null || (next.Name != "else-if" && next.Name != "magix.execute.else-if" && next.Name != "else" && next.Name != "magix.execute.else")) { PopState(e.Params, ip); } } }
private static void p5_crypto_delete_public_key(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new Utilities.ArgsRemover(e.Args, true)) { // Creating new GnuPG context using (var ctx = new GnuPrivacyContext()) { // Signaler boolean bool somethingWasRemoved = false; var bundle = ctx.PublicKeyRingBundle; // Looping through each ID given by caller foreach (var idxId in XUtil.Iterate <string> (context, e.Args, true)) { // Looping through each public key ring in GnuPG database until we find given ID foreach (PgpPublicKeyRing idxPublicKeyRing in bundle.GetKeyRings()) { // Looping through each key in keyring foreach (PgpPublicKey idxPublicKey in idxPublicKeyRing.GetPublicKeys()) { if (idxId == idxPublicKey.KeyId.ToString("X")) { // Removing entire keyring, and signaling to save keyring bundle somethingWasRemoved = true; bundle = PgpPublicKeyRingBundle.RemovePublicKeyRing(bundle, idxPublicKeyRing); // Breaking inner most foreach break; } } } } // Checking to see if something was removed, and if so, saving GnuPG context if (somethingWasRemoved) { ctx.SavePublicKeyRingBundle(bundle); } } } }
/* * Raise the Active Event with the specified name, with the given args (if any), within the given application context. */ internal Node RaiseEvent(ApplicationContext context, Node args, string activeEventName) { try { // Constructing EventArgs to pass into event handler. // If no Node is null, we create a new Node, such that event handlers are never given null node, and can return // values, even though caller did not pass in a Node into handler. var e = new ActiveEventArgs(activeEventName, args ?? new Node()); // Checking if we have any Active Event handlers for the given name. if (_events.ContainsKey(activeEventName)) { // Looping through all Active Events handlers for the given Active Event name, invoking all methods handling event. // Notice, we must iterate the events using "ToList", since an Active Event, theoretically, might create a new Active Event, // invalidating the enumerator for our foreach loop. foreach (var idxMethod in _events[activeEventName].ToList()) { idxMethod.Item1.Invoke(idxMethod.Item2, new object [] { context, e }); } } // Then iterating through all "null Active Event handlers" afterwards, and invoking these handlers. if (_events.ContainsKey("")) { // Active Event was not protected, and we have a "null event handler". foreach (var idxMethod in _events[""].ToList()) { idxMethod.Item1.Invoke(idxMethod.Item2, new object [] { context, e }); } } // Returning results of invocation of event to caller. return(e.Args); } catch (TargetInvocationException err) { // Making sure we transform reflection exceptions into actual exceptions thrown. ExceptionDispatchInfo.Capture(err.InnerException).Throw(); // Never reached, but needed for compiler to not choke, since it doesn't realize the above invocation to Capture will always throw ...!! throw; } }
static void p5_crypto_pgp_keys_public_get(ApplicationContext context, ActiveEventArgs e) { // Using common helper to iterate all public keyrings matching filter. PGPKeyIterator.Find(context, e.Args, delegate(OpenPgpContext ctx, PgpPublicKeyRing keyring) { // Retrieving fingerprint of currently iterated key, and returning to caller. var key = keyring.GetPublicKey(); var fingerprint = Fingerprint.FingerprintString(key.GetFingerprint()); var node = e.Args.Add(fingerprint).LastChild; // Returning public key as armored ASCII. using (var memStream = new MemoryStream()) { using (var armored = new ArmoredOutputStream(memStream)) { key.Encode(armored); armored.Flush(); } memStream.Flush(); memStream.Position = 0; var sr = new StreamReader(memStream); node.Value = sr.ReadToEnd(); } }, false); }
public static void p5_mongo_insert(ApplicationContext context, ActiveEventArgs e) { // Looping through each document to insert foreach (var idx in XUtil.Iterate <Node> (context, e.Args, false, false, true)) { // Finding table name to insert document into var tableName = idx.Name; // Populating document var document = CreateDocument(context, idx); // Checking if we've got an explicit ID if (idx.Value != null) { document.Add("_id", BsonValue.Create(idx.Value)); } // Inserting document into database instance var collection = Database.Instance.MongoDatabase.GetCollection <BsonDocument>(tableName); collection.InsertOne(document); } }
public static void p5_types_get_typename(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution using (new ArgsRemover(e.Args)) { // Syntax checking invocation if (!(e.Args.Value is Expression)) { throw new ArgumentException("[p5.types.get-typename] needs an expression as its value"); } // Getting value of expression. var val = e.Args.GetExValue <object> (context); if (val == null) { e.Args.Value = "unknown"; } else { e.Args.Value = context.RaiseEvent(".p5.hyperlambda.get-type-name." + val.GetType().FullName).Value ?? "string"; } } }
public static void p5_data_update(ApplicationContext context, ActiveEventArgs e) { // Retrieving expression and doing some basic sanity checks. if (!(e.Args.Value is Expression)) { throw new LambdaException("[p5.data.update] requires an expression leading to whatever you want to be updated in your database", e.Args, context); } // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(e.Args)) { // Acquiring write lock on database. using (new Common.Lock(true)) { // Storing affected nodes, and number of affected items. var changed = new List <Node> (); int affectedItems = 0; // Retrieving source, and iterating through each destination, updating with source value. // Notice, we don't provide transaction support here, but we do make sure at least any changes // that actually occurs, are serialized to disc! var source = XUtil.Source(context, e.Args); try { foreach (var idxDestination in e.Args.Get <Expression> (context).Evaluate(context, Common.Database, e.Args)) { // Updates the destination with the source, making sure we can keep track of files that are changed, and that we throw if update is unsuccessful. if (!UpdateDestination(context, source, idxDestination)) { throw new LambdaException("[p5.data.update] requires your new node needs to have a unique ID, or use its old ID by not providing one", e.Args, context); } Common.AddNodeToChanges(idxDestination.Node, changed); affectedItems += 1; } } finally { Common.SaveAffectedFiles(context, changed); e.Args.Value = affectedItems; } } } }
public static void magix_execute_stop(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params, true); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.stop-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.stop-sample]"); return; } // throws stop exception to signal upwards in stack that we're supposed to end the current execution scope throw new HyperlispStopException(); }
public static void hyper2lambda(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution using (new ArgsRemover(e.Args, true)) { // Concatenating all Hyperlambda submitted, injecting CR/LF between each component var builder = new StringBuilder(); foreach (var idxHyperlisp in XUtil.Iterate <string> (context, e.Args)) { // Making sure we put in a carriage return between each Hyperlambda entity if (builder.Length > 0) { builder.Append("\r\n"); } // Appending currently iterated Hyperlambda into StringBuilder builder.Append(idxHyperlisp); } // Utilizing NodeBuilder to create our p5 lambda return value e.Args.AddRange(new NodeBuilder(context, builder.ToString()).Nodes); } }
public static void p5_io_folder_list_files(ApplicationContext context, ActiveEventArgs e) { // Getting root folder var rootFolder = Common.GetRootFolder(context); // Checking if we've got a filter string filter = e.Args.GetExChildValue("filter", context, "") ?? ""; // Looping through each argument. ObjectIterator.Iterate(context, e.Args, true, "read-folder", delegate(string foldername, string fullpath) { foreach (var idxFile in Directory.GetFiles(fullpath)) { if (filter == "" || MatchFilter(idxFile, filter)) { // Making foldername "canonical". var fileName = idxFile.Replace("\\", "/"); fileName = fileName.Replace(rootFolder, ""); e.Args.Add(fileName); } } }); }
static void p5_crypto_pgp_keys_get_details(ApplicationContext context, ActiveEventArgs e) { /* * Using common helper to iterate all public keys, assuming that if caller * has supplied a fingerprint or key-id to a private key, the public key * will also exist in PGP context. */ PGPKeyIterator.Find(context, e.Args, delegate(OpenPgpContext ctx, PgpPublicKeyRing keyring) { // This key is matching specified filter criteria. var key = keyring.GetPublicKey(); var fingerprint = Fingerprint.FingerprintString(key.GetFingerprint()); var node = e.Args.Add(fingerprint).LastChild; node.Add("id", ((int)key.KeyId).ToString("X")); node.Add("algorithm", key.Algorithm.ToString()); node.Add("strength", key.BitStrength); node.Add("creation-time", key.CreationTime); node.Add("is-encryption-key", key.IsEncryptionKey); node.Add("is-master-key", key.IsMasterKey); node.Add("is-revoked", key.IsRevoked()); node.Add("version", key.Version); DateTime expires = key.CreationTime.AddSeconds(key.GetValidSeconds()); node.Add("expires", expires); // Returning all user IDs that are strings to caller. foreach (var idxUserId in key.GetUserIds()) { if (idxUserId is string) { node.FindOrInsert("user-ids").Add("", idxUserId); } } // Adding key IDs of all keys that have signed this key. foreach (PgpSignature signature in key.GetSignatures()) { node.FindOrInsert("signed-by").Add(((int)signature.KeyId).ToString("X"), signature.CreationTime); } }, false); }
public static void unzip(ApplicationContext context, ActiveEventArgs e) { // Retrieving password, if there is one, and untying it, // to make sure it never leaves method, in case of an exception, etc. string password = e.Args.GetExChildValue <string> ("password", context, null); e.Args.FindOrInsert("password").UnTie(); // Making sure password never leaved method, in case of exceptions, etc ... // Basic syntax checking. if (e.Args.Value == null) { throw new LambdaException( "[unzip] needs at least one source zip file as its value", e.Args, context); } // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(e.Args, true)) { // Getting root folder. var rootFolder = Helpers.GetBaseFolder(context); // Getting destination folder. var destFolder = GetDestinationFolder(context, e); // Looping through each source zip file given. foreach (var idxZipFilePath in XUtil.Iterate <string> (context, e.Args).ToList()) { // Unzips currently iterated file. UnzipFile( context, e.Args, rootFolder, Helpers.GetSystemPath(context, Utilities.Convert <string> (context, idxZipFilePath)), destFolder, password); } } }
public static void p5_string_split(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution. using (new Utilities.ArgsRemover(e.Args, true)) { // Figuring out source value of [p5.string.split], and returning early if there is none. string source = XUtil.Single <string> (context, e.Args); if (source == null) { return; } // Checking if we should explicitly keep empty items. StringSplitOptions options = e.Args.GetExChildValue("keep-empty", context, false) ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries; // Checking if each item should be trimmed before returned. var trim = e.Args.GetExChildValue("trim", context, false); // Retrieving separator objects, which might be multiple integers, multiple strings, or a single regular expression. var sepObjects = e.Args.Children .Where(ix => ix.Name == "=") .Select(ix => ix.GetExValue <object> (context)) .ToList(); // Checking if there were any separators. if (sepObjects.Count > 0) { // We have separators, meaning we should actually perform a split operation. RunSplit(context, e.Args, source, options, trim, sepObjects); } else { // Special case, no separators, splitting entire string into characters. // Which is actually the only way we can iterate over each character in a string in P5. e.Args.AddRange(source.Select(ix => new Node(ix.ToString()))); } } }
public static void p5_mysql_connect(ApplicationContext context, ActiveEventArgs e) { // Creating connection, opening it, and evaluating lambda for [p5.mysql.connect]. using (var connection = new MySqlConnection(ConnectionString(context, e.Args))) { // Opening connection. connection.Open(); // Storing connection in current context, making sure it's on top of "stack of connections". var connections = Connections(context); connections.Add(connection); // Evaluating lambda for current connection, making sure we are able to remove connection, even if an exception occurs. try { // Evaluating lambda for [p5.mysql.connect]. context.RaiseEvent("eval-mutable", e.Args); } finally { // Cleaning up ... connections.Remove(connection); connection.Close(); } } }
public static void p5_events_get(ApplicationContext context, ActiveEventArgs e) { // Acquire write lock, since we're consuming object shared amongst more than one thread (_events). _lock.EnterReadLock(); try { // Checking if event exists. var list = new List <Node> (); foreach (var idx in XUtil.Iterate <string> (context, e.Args)) { if (_events.ContainsKey(idx)) { list.Add(_events [idx]); } } e.Args.Value = null; e.Args.Clear(); e.Args.AddRange(list.Select(ix => ix.Clone())); } finally { // Making sure we release lock in a finally, such that we can never exit method, without releasing our lock. _lock.ExitReadLock(); } }
public void p5_web_widgets_ajax_events_raise(ApplicationContext context, ActiveEventArgs e) { // Sanity check. if (e.Args.Value == null || e.Args.Count == 0) { throw new LambdaException( string.Format("[{0}] needs both a value being widget(s) to iterate, and children arguments being events to retrieve", e.Args.Name), e.Args, context); } // Iterating through all widget(s) supplied by caller. foreach (var idxWidget in FindWidgets <Widget> (context, e.Args)) { // Iterating through all Ajax event(s) requested by caller. foreach (var idxEventNameNode in e.Args.Children.Where(ix => ix.Name != "")) { // Raising currently iterated Ajax event for currently iterated widget, letting p5.ajax do the heavy lifting. idxWidget.InvokeEventHandler(idxEventNameNode.Name); } } }
public static void p5_imaging_get_size(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution. using (new Utilities.ArgsRemover(e.Args, true)) { // Looping through each image caller requests the size for. foreach (var idxPath in XUtil.Iterate <string> (context, e.Args)) { // Unrolling path, and verifying user is authorized to reading file. var source = context.Raise(".p5.io.unroll-path", new Node("", idxPath)).Get <string> (context); context.Raise(".p5.io.authorize.read-file", new Node("", source).Add("args", e.Args)); // Getting root folder, and opening file. var rootFolder = Helpers.GetBaseFolder(context); using (var src = Image.FromFile(rootFolder + source)) { // Returning width and height to caller. var resultNode = e.Args.Add(source).LastChild; resultNode.Add("width", src.Width); resultNode.Add("height", src.Height); } } } }
protected void magix_viewport_pin_container(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.viewports", "Magix.viewports.hyperlisp.inspect.hl", "[magix.viewports.pin-container-dox].value"); AppendCodeFromResource( ip, "Magix.viewports", "Magix.viewports.hyperlisp.inspect.hl", "[magix.viewports.pin-container-sample]"); return; } Node dp = Dp(e.Params); if (!ip.ContainsValue("container")) { throw new ArgumentException("no [container] given to [magix.viewport.pin-container]"); } string container = Expressions.GetExpressionValue <string>(ip["container"].Get <string>(), dp, ip, false); if (ViewState["magix.viewport.pin-container"] == null) { ViewState["magix.viewport.pin-container"] = new Node(); } Node viewStateNode = ViewState["magix.viewport.pin-container"] as Node; if (!viewStateNode.Contains(container)) { viewStateNode.Add(new Node(container)); } }
public static void magix_package_pack(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.tiedown", "Magix.tiedown.hyperlisp.inspect.hl", "[magix.package.pack-dox].value"); AppendCodeFromResource( ip, "Magix.tiedown", "Magix.tiedown.hyperlisp.inspect.hl", "[magix.package.pack-sample]"); return; } Node dp = Dp(e.Params); if (!ip.Contains("files")) { throw new ArgumentException("no [files] given to [magix.package.pack]"); } string zipFile = Expressions.GetFormattedExpression("zip", e.Params, ""); string zipAbsolutePath = HttpContext.Current.Server.MapPath(zipFile); using (ZipFile zip = new ZipFile()) { foreach (Node idxZipFile in ip["files"]) { zip.AddItem(HttpContext.Current.Server.MapPath(idxZipFile.Get <string>()), idxZipFile.Name ?? ""); } zip.Save(zipAbsolutePath); } }
public void magix_execute_debug(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params, true); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.debug-dox].value"); AppendCodeFromResource( ip, "Magix.execute", "Magix.execute.hyperlisp.inspect.hl", "[magix.execute.debug-sample]"); return; } Node stack = ip.RootNode(); if (!string.IsNullOrEmpty(ip.Get <string>())) { stack = Expressions.GetExpressionValue <Node>(ip.Get <string>(), Dp(e.Params), ip, false); if (stack == null) { throw new HyperlispExecutionErrorException("tried to debug a non-existing node tree in [debug], expression was; '" + ip.Get <string>() + "'"); } } Node confirmNode = new Node(); confirmNode["code"].AddRange(stack.Clone()); confirmNode["message"].Value = "stackdump of tree from debug instruction"; confirmNode["closable-only"].Value = true; RaiseActiveEvent( "magix.viewport.confirm", confirmNode); }
private static void p5_crypto_list_public_keys(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new ArgsRemover(e.Args, true)) { // Checking if user provided a filter string filter = e.Args.GetExValue <string> (context, null); // Creating new GnuPG context using (var ctx = new GnuPrivacyContext()) { // Looping through each public key in GnuPG database foreach (PgpPublicKeyRing idxRing in ctx.PublicKeyRingBundle.GetKeyRings()) { // Looping through each key in keyring foreach (PgpPublicKey idxPublicKey in idxRing.GetPublicKeys()) { // Finding identity of key foreach (var idxUserID in idxPublicKey.GetUserIds()) { // Converting to a string, before checking for a match, but only if object is a string if (idxUserID is string) { var userID = idxUserID.ToString(); // Checking if filter is not null, and if so, making sure identity of currently iterated key matches filter if (string.IsNullOrEmpty(filter) || userID.Contains(filter)) { // Returning identity and key ID to caller e.Args.Add(userID, idxPublicKey.KeyId.ToString("X")); // We'll risk adding the same key twice unless we break here! break; } } } } } } } }
protected void magix_ide_add_control(object sender, ActiveEventArgs e) { Node ip = Ip(e.Params); if (ShouldInspect(ip)) { AppendInspectFromResource( ip["inspect"], "Magix.ide", "Magix.ide.hyperlisp.inspect.hl", "[magix.ide.add-control-dox].value"); AppendCodeFromResource( ip, "Magix.ide", "Magix.ide.hyperlisp.inspect.hl", "[magix.ide.add-control-sample]"); return; } if (!SurfaceEnabled) { throw new ArgumentException("wysiwyg surface is not enabled"); } if (!ip.Contains("control")) { throw new ArgumentException("no [control] given to [magix.ide.add-control]"); } if (ip["control"].Count != 1) { throw new ArgumentException("you must supply exactly one control to [magix.ide.add-control]"); } AddControlToSurface( ip, ip["control"][0].Clone()); }
public static void p5_mysql_select(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up after ourselves. using (new ArgsRemover(e.Args, true)) { // Getting connection, and doing some basic sanity check. var connection = Connection.Active(context, e.Args); if (connection == null) { throw new LambdaException("No connection has been opened, use [p5.mysql.connect] before trying to invoke this event", e.Args, context); } // Retrieving SQL and running query, returning result to caller. Making sure we run basic sanity check. var sql = e.Args.GetExValue <string> (context); if (string.IsNullOrEmpty(sql)) { throw new LambdaException("No SQL or query given to [p5.mysql.select]", e.Args, context); } // Creating command object. using (var cmd = new MySqlCommand(sql, connection)) { // Creating reader, and iterating as long as we have resulting rows. using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // Adding row. var current = e.Args.Add("row").LastChild; // Looping through all columns in current result row, returning to caller. for (int ix = 0; ix < reader.FieldCount; ix++) { // Adding currently iterated cell for row. current.Add(reader.GetName(ix), reader [ix]); } } } } } }
public static void p5_data_update(ApplicationContext context, ActiveEventArgs e) { // Retrieving expression and doing some basic sanity checks. if (!(e.Args.Value is Expression)) { throw new LambdaException("[p5.data.update] requires an expression leading to whatever you want to be updated in your database", e.Args, context); } // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(e.Args)) { // Acquiring write lock on database, and making sure we keep track of which files are changed, and how many items were affected. var changed = new List <Node> (); int affectedItems = 0; Common.Locker.EnterWriteLock(); try { // Retrieving source, and iterating through each destination, updating with source value. var source = XUtil.Source(context, e.Args); foreach (var idxDestination in e.Args.Get <Expression> (context).Evaluate(context, Common.Database, e.Args)) { // Updates the destination with the source, making sure we can keep track of files that are changed, and that we throw is update is unsuccessful. if (!UpdateDestination(context, source, idxDestination)) { throw new LambdaException("[p5.data.update] requires your new node needs to have a unique ID, or use its old ID by not providing one", e.Args, context); } Common.AddNodeToChanges(idxDestination.Node, changed); affectedItems += 1; } } finally { // Saving all affected files. // Notice, we do this even though an exception has occurred, since exception is thrown before nodes are updated with any "bad data". // This means that if you update several nodes, some might become updated though, while others are not updated. // Hence, [p5.data.update] does not feature any sorts of "transactional update support" at the moment. Common.SaveAffectedFiles(context, changed); e.Args.Value = affectedItems; Common.Locker.ExitWriteLock(); } } }