public static void p5_events_list(ApplicationContext context, ActiveEventArgs e) { // Retrieving filter, if any. var filter = new List <string> (XUtil.Iterate <string> (context, e.Args)); // Acquire read lock, since we're consuming object shared amongst more than one thread (_events). _lock.EnterReadLock(); try { // Getting all dynamic Active Events, making sure we clean up after ourselves. using (new ArgsRemover(e.Args, true)) { ListActiveEvents(_events.Keys, e.Args, filter, "dynamic", context); } } finally { // Making sure we release lock in a finally, such that we can never exit method, without releasing our lock. _lock.ExitReadLock(); } // Getting all core Active Events. ListActiveEvents(context.ActiveEvents, e.Args, filter, "static", context); // Checking if there exists a whitelist, and if so, removing everything not in our whitelist. if (context.Ticket.Whitelist != null) { e.Args.RemoveAll(ix => context.Ticket.Whitelist [ix.Get <string> (context)] == null); } // Sorting such that static events comes first, and then having keywords coming. e.Args.Sort(delegate(Node lhs, Node rhs) { if (lhs.Name == "static" && rhs.Name == "dynamic") { return(-1); } if (lhs.Name == "dynamic" && rhs.Name == "static") { return(1); } if (!lhs.Get <string> (context).Contains(".") && rhs.Get <string> (context).Contains(".")) { return(-1); } if (lhs.Get <string> (context).Contains(".") && !rhs.Get <string> (context).Contains(".")) { return(1); } return(lhs.Get <string> (context).CompareTo(rhs.Value)); }); }
private static void p5_crypto_delete_public_key(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new 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)) { // 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()) { // Checking for a match, making sure we do not match UserIDs. if (ObjectIterator.IsMatch(idxPublicKey, idxId, false)) { // Removing entire keyring, and signaling to save keyring bundle somethingWasRemoved = true; bundle = PgpPublicKeyRingBundle.RemovePublicKeyRing(bundle, idxPublicKeyRing); // Breaking inner most foreach break; } } // Checking if currently iterated filter was found in currently iterated secret keyring. if (somethingWasRemoved) { break; } } } // Checking to see if something was removed, and if so, saving GnuPG context if (somethingWasRemoved) { ctx.SavePublicKeyRingBundle(bundle); } } } }
public ScriptMetadata[] LoadScriptMetadata() { var list = new List <ScriptMetadata>(); var scripts = XUtil.GetScriptMap(); using (var reader = OpenFile("properties", "scriptMetadata.txt")) using (var txt = new StreamReader(reader)) { string line; while ((line = txt.ReadLine()) != null) { if (!line.HasValue() || line[0] == '#') { continue; } string[] fields = line.Split(';'); string code = fields[0]?.Trim(); if (!code.HasValue()) { continue; } if (!scripts.TryGetValue(code, out WritingScript script)) { throw new FormatException("Id " + code); } var cur = new ScriptMetadata(); cur.Script = script; list.Add(cur); code = fields[1].Trim(); if (int.TryParse(code, out int rank)) { cur.Rank = rank; } code = fields[3].Trim(); if (code.HasValue()) { cur.Territory = GetTerritory(code); } code = fields[4].Trim(); if (int.TryParse(code, out rank)) { cur.Density = rank; } } } return(list.ToArray()); }
public static void lambda_sort(ApplicationContext context, ActiveEventArgs e) { // House cleaning. using (new ArgsRemover(e.Args, true)) { // Creating copy of node list to insert as result of [sort] after sorting nodes. var nodeList = XUtil.Iterate <Node> (context, e.Args).Where(ix => ix.Name != "").Select(ix => ix.Clone()).ToList(); // Special case for empty [sort] node, at which case we use "default sorting", sorting by value if (e.Args.Children.Count(ix => ix.Name != "") == 0) { // Defaulting to sorting nodes by "value" casted to IComparable nodeList.Sort(delegate(Node lhs, Node rhs) { if (e.Name == "sort") { return(string.Compare(lhs.Name, rhs.Name, System.StringComparison.InvariantCulture)); } return(string.Compare(rhs.Name, lhs.Name, System.StringComparison.InvariantCulture)); }); } else { // We have a lambda delegate here nodeList.Sort(delegate(Node lhs, Node rhs) { // Cloning [sort] node, using clone for [eval] for each node in result var exeNode = e.Args.Clone(); // Making sure exeNode has name of [eval], and forcing children evaluation exeNode.Name = "eval"; exeNode.Value = null; // Injecting [_lhs] and [_rhs] to sort callback exeNode.Insert(0, new Node("_lhs", lhs)); exeNode.Insert(1, new Node("_rhs", rhs)); // Invoking [sort] callback context.RaiseEvent("eval", exeNode); // Retrieving value of [sort] callback, defaulting to "equals" return(exeNode.Get(context, 0)); }); } // Returning sorted list to caller e.Args.AddRange(nodeList); } }
/* * Iterates all public keys in all keyrings in GnuPrivacyContext, and invokes given delegate for every key matching filter condition. */ internal static void MatchingPublicKeys(ApplicationContext context, Node args, MatchingPublicKeysDelegate functor, bool write) { // House cleaning. using (new ArgsRemover(args, true)) { // Storing all filter given by caller in list, to avoid destroying enumeration iterator, due to modifying collection in caller's callback. var filters = XUtil.Iterate <string> (context, args).Where(ix => ix != null).ToList(); // Creating new GnuPG context. using (var ctx = new GnuPrivacyContext(write)) { // Iterating all secret keyrings. foreach (PgpPublicKeyRing idxRing in ctx.PublicKeyRingBundle.GetKeyRings()) { // Iterating all keys in currently iterated secret keyring. foreach (PgpPublicKey idxPublicKey in idxRing.GetPublicKeys()) { // Verifying that this is a normal plain public key. // Notice, we only return keys with at least one User ID. if (!idxPublicKey.GetUserIds().GetEnumerator().MoveNext()) { continue; // Probably just a signature for another key, or something. } // Checking if caller provided filters, and if not, yielding "everything". if (filters.Count == 0) { // No filters provided, matching everything. functor(idxPublicKey); } else { // Iterating all filters given by caller. foreach (var idxFilter in filters) { // Checking if current filter is a match. if (IsMatch(idxPublicKey, idxFilter)) { // Invoking callback supplied by caller, and breaking current filter enumeration, to avoid adding key twice. functor(idxPublicKey); break; } } } } } } } }
public static void p5_web_css_minify(ApplicationContext context, ActiveEventArgs e) { // House cleaning. using (new ArgsRemover(e.Args, true)) { // Iterating through each CSS content supplied, and minifying it, returning the results to caller. foreach (var idxCss in XUtil.Iterate <string> (context, e.Args)) { // Minifying CSS content. var minifier = new Microsoft.Ajax.Utilities.Minifier(); var options = new Microsoft.Ajax.Utilities.CssSettings(); options.CommentMode = Microsoft.Ajax.Utilities.CssComment.None; // Returning minified content to caller. e.Args.Add("result", minifier.MinifyStyleSheet(idxCss, options)); } } }
public void p5_web_widgets_lambda_events_vocabulary(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up arguments after invocation. using (new ArgsRemover(e.Args, true)) { // Retrieving filter, if any. var filter = new List <string> (XUtil.Iterate <string> (context, e.Args)); // Retrieving all lambda events, matching any optional filters supplied. ListActiveEvents(Manager.WidgetLambdaEventStorage.Keys, e.Args, filter, context); // Checking if there exists a whitelist, and if so, removing everything not in it. if (context.Ticket.Whitelist != null) { e.Args.RemoveAll(ix => context.Ticket.Whitelist [ix.Get <string> (context)] == null); } } }
public static void p5_mime_parse(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up after ourselves using (new ArgsRemover(e.Args, true)) { // Looping through each MIME message supplied foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args)) { // Sanity check if (string.IsNullOrEmpty(idxMimeMessage)) { throw new LambdaException( "No MIME message provided to [p5.mime.parse]", e.Args, context); } // Loading MIME entity from stream using (var writer = new StreamWriter(new MemoryStream())) { // Writing MIME content to StreamWriter, flushing the stream, and setting reader head back to beginning writer.Write(idxMimeMessage); writer.Flush(); writer.BaseStream.Position = 0; // Loading MimeEntity from MemoryStream MimeEntity entity = null; if (e.Args ["Content-Type"] != null) { entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].Get <string> (context)), writer.BaseStream); } else { entity = MimeEntity.Load(writer.BaseStream); } var parser = new helpers.MimeParser( context, e.Args, entity, e.Args.GetExChildValue <string> ("attachment-folder", context), e.Args.GetExChildValue <bool> ("attachment-folder-no-prefix", context, true)); // Parses the MimeEntity and stuffs results into e.Args node parser.Process(); } } } }
public static void p5_html_html2lambda(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(e.Args, true)) { // Loops through all documents we're supposed to transform. foreach (var idxHtmlDoc in XUtil.Iterate <string> (context, e.Args)) { // Converting currently iterated document/fragment, making sure it yielded a value. if (!string.IsNullOrEmpty(idxHtmlDoc)) { var doc = new HtmlDocument(); doc.LoadHtml(idxHtmlDoc); ParseHtmlDocument(e.Args, doc.DocumentNode); } } } }
/* * Common helper for iterating files/folders for move/copy/rename operation. */ internal static void CopyMoveFileObject( ApplicationContext context, Node args, string sourceAuthorizeEvent, string destinationAuthorizeEvent, MoveCopyDelegate functorMoveObject, ObjectExistDelegate functorObjectExist) { // Sanity check. if (args.Value == null) { throw new LambdaException( string.Format("[{0}] requires a value being the source file(s) to operate upon", args.Name), args, context); } // Making sure we clean up and remove all arguments passed in after execution. using (new ArgsRemover(args)) { // Retrieving destination file or folder, and root folder for app, making sure we get a [dest] node for destination. var dest = Common.GetSystemPath(context, Utilities.Convert <string> (context, XUtil.Source(context, args, "src"))); var rootFolder = Common.GetRootFolder(context); // Iterating through each source. foreach (var idxSource in XUtil.Iterate <string> (context, args)) { // Figuring out destination file, which might be "relative" to currently iterated source file. var destinationFile = dest.EndsWithEx("/") ? dest + idxSource.Substring(idxSource.LastIndexOfEx("/") + 1) : dest; // Making sure user is authorized to do operation on both source file and destination file. Common.RaiseAuthorizeEvent(context, args, sourceAuthorizeEvent, idxSource); Common.RaiseAuthorizeEvent(context, args, destinationAuthorizeEvent, destinationFile); // Making sure destination file does not already exist. if (functorObjectExist(rootFolder + destinationFile)) { throw new LambdaException(string.Format("The file '{0}' already exist from before", destinationFile), args, context); } functorMoveObject( rootFolder, Common.GetSystemPath(context, Utilities.Convert <string> (context, idxSource)), destinationFile); } } }
public static void p5_mime_load(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up after ourselves using (new ArgsRemover(e.Args, true)) { // Looping through each MIME message supplied foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args)) { // Sanity check if (string.IsNullOrEmpty(idxMimeMessage)) { throw new LambdaException( "No MIME message provided to [p5.mime.parse]", e.Args, context); } // Retrieving output filename, and doing some basic sanity checking. var filePath = idxMimeMessage; filePath = context.RaiseEvent(".p5.io.unroll-path", new Node("", filePath)).Get <string> (context); context.RaiseEvent(".p5.io.authorize.read-file", new Node("", filePath).Add("args", e.Args)); // Loading MIME entity from currentl iterated file. using (var reader = File.OpenRead(Common.GetRootFolder(context) + filePath)) { // Loading MimeEntity from MemoryStream MimeEntity entity = null; if (e.Args ["Content-Type"] != null) { entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].Get <string> (context)), reader); } else { entity = MimeEntity.Load(reader); } var parser = new helpers.MimeParser( context, e.Args, entity, e.Args.GetExChildValue <string> ("attachment-folder", context), e.Args.GetExChildValue <bool> ("attachment-folder-no-prefix", context, true)); // Parses the MimeEntity and stuffs results into e.Args node parser.Process(); } } } }
/* * Returns all access objects for system. */ public static void AddAccess(ApplicationContext context, Node args) { // Locking access to password file as we create new access object. AuthFile.ModifyAuthFile( context, delegate(Node authFile) { // Verifying access rights exists. if (authFile ["access"] == null) { authFile.Add("access"); } // Iterating all access objects passed in by caller, and adding them to root access node. var access = authFile ["access"]; var newAccessRights = XUtil.Iterate <Node> (context, args).ToList(); foreach (var idxAccess in newAccessRights) { // Sanity checking. var val = idxAccess.GetExValue(context, ""); if (string.IsNullOrEmpty(val)) { // Creating a new random GUID as the ID of our access object. val = Guid.NewGuid().ToString(); idxAccess.Value = val; } else { // Verifying access ID is unique. if (access.Children.Any(ix => ix.Get(context, "") == val)) { throw new LambdaException("Each access right must have a unique name/value combination, and there's already another access right with the same name/value combination in your access list", idxAccess, context); } } // Sanity checking access object. if (idxAccess.Count == 0) { throw new LambdaException("There's no actual content in your access object", idxAccess, context); } // Adding currently iterated access object. access.Add(idxAccess.Clone()); } }); }
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 LEAVES METHOD!! // Basic syntax checking if (e.Args.Value == null) { throw new LambdaException( "[unzip] needs both a destination as its value", e.Args, context); } // Making sure we clean up and remove all arguments passed in after execution using (new Utilities.ArgsRemover(e.Args)) { // Getting root folder var rootFolder = Helpers.GetBaseFolder(context); // Getting destination folder var destFolder = GetDestinationFolder(context, e); // Getting source files var source = XUtil.Source(context, e.Args, e.Args, "src", new string[] { "password" }.ToList()); // Looping through each source zip file given foreach (var idxZipFilePath in source) { // Unzips currently iterated file UnzipFile( context, e.Args, rootFolder, Helpers.GetSystemPath(context, Utilities.Convert <string> (context, idxZipFilePath)), destFolder, password); } // Returning folder path of where files where unzipped to caller e.Args.Value = destFolder; } }
public static void p5_html_html_decode(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution using (new Utilities.ArgsRemover(e.Args)) { // Used as return value StringBuilder builder = new StringBuilder(); // Loops through all documents/fragments we're supposed to transform foreach (var idx in XUtil.Iterate <string> (context, e.Args)) { // Changing to 'safe HTML' builder.Append(HttpUtility.HtmlDecode(idx)); } // Returning decoded HTML to caller e.Args.Value = builder.ToString(); } }
/* * Common insertion method for both of the above Active Events. */ private static void InsertNodes(ApplicationContext context, Node args, bool after) { // Finding source nodes, and returning early if no source is given. var src = XUtil.Sources(context, args); if (src.Count == 0) { return; } // Looping through each destination, and inserting all source node at specified position, in order of appearance. foreach (var idxDestination in XUtil.DestinationMatch(context, args, true)) { // Figuring out insertion point before we insert nodes. var index = idxDestination.Node.Parent.IndexOf(idxDestination.Node) + (after ? 1 : 0); idxDestination.Node.Parent.InsertRange(index, src.Select(ix => ix.Clone())); } }
public void p5_web_set_location(ApplicationContext context, ActiveEventArgs e) { // Checking if this is ajax callback, which means we'll have to redirect using JavaScript if (AjaxPage.IsAjaxRequest) { // Redirecting using JavaScript. AjaxPage.SendJavaScript(string.Format("window.location='{0}';", XUtil.Single <string> (context, e.Args).Replace("'", "\\'"))); } else { // Redirecting using Response object. try { AjaxPage.Response.Redirect(XUtil.Single <string> (context, e.Args)); } catch (System.Threading.ThreadAbortException) { ; // Silently catching, no reasons to allow it to penetrate ... } } }
public static void p5_html_url_encode(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution using (new ArgsRemover(e.Args)) { // Used as return value var builder = new StringBuilder(); // Loops through all documents/fragments we're supposed to encode and eppending into StringBuilder foreach (var idxHtmlFragment in XUtil.Iterate <string> (context, e.Args)) { // Changing to 'safe HTML' builder.Append(HttpUtility.UrlEncode(idxHtmlFragment)); } // Returning "encoded HTML" back to caller e.Args.Value = builder.ToString(); } }
public static void eval_mutable(ApplicationContext context, ActiveEventArgs e) { // Checking if we should foce execution of children nodes, and not evaluate expression/object in main node. if (e.Args.Value == null || e.Args.Name != e.Name) { // Evaluating current scope. ExecuteAll(e.Args, context); } else { // Evaluating a value object or an expression. foreach (var idxLambda in XUtil.Iterate <Node> (context, e.Args)) { // Evaluating currently iterated lambda. ExecuteAll(idxLambda, context); } } }
public static void lambda_src_dest(ApplicationContext context, ActiveEventArgs e) { // Figuring out type of source. var x = e.Args.Value as Expression; if (x != null) { // Source is an expression, evaluating it, and returning results back to caller. var match = x.Evaluate(context, e.Args, e.Args); if (match.TypeOfMatch == Match.MatchType.count) { // Simple count expression. e.Args.Value = match.Count; } else if (match.TypeOfMatch == Match.MatchType.node) { // Node values, single or multiple is irrelevant, still need to clone them. e.Args.AddRange(match.Select(ix => ix.Node.Clone())); e.Args.Value = null; } else if (match.Count == 1) { // Single value, name or value type of value is irrelevant, adding to value anyways. e.Args.Value = match [0].Value; } else if (match.TypeOfMatch == Match.MatchType.name) { // Multiple name values. e.Args.AddRange(match.Select(ix => new Node(ix.Node.Name))); e.Args.Value = null; } else { // Multiple value values. e.Args.AddRange(match.Select(ix => new Node("", ix.Value))); e.Args.Value = null; } } else if (e.Args.Value != null) { // Returning formatted value. e.Args.Value = XUtil.FormatNode(context, e.Args); } // else, returning children nodes as is }
public bool saveFile(string fileName) { try { string result = save(); XUtil.assureDirectory(fileName); FileStream fs = File.Open(fileName, FileMode.Create); byte[] data = new UTF8Encoding().GetBytes(result); fs.Write(data, 0, data.Length); fs.Close(); } catch (Exception e) { XDebug.LogError(e.Message); return(false); } return(true); }
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 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)) { if (first) { // Adding headers. foreach (var idxInnerHeader in idxLambda.Children) { if (builder.Length > 0) { builder.Append(","); } builder.Append(idxInnerHeader.Name); } builder.Append("\r\n"); first = false; } // Adding values. var content = ""; foreach (var idxInner in idxLambda.Children) { var val = idxInner.Get <string> (context); if (val != null && (val.Contains(",") || val.Contains("\n"))) { content += "\"" + val.Replace("\"", "\"\"") + "\","; } else { content += val + ","; } } builder.Append(content.Substring(0, content.Length - 1) + "\r\n"); } e.Args.Value = builder.ToString(); } }
private static void p5_crypto_preview_public_pgp_key(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new ArgsRemover(e.Args, true)) { // Looping through each public key (in ascii armored format) and importing into GnuPG database foreach (var idxKey in XUtil.Iterate <string> (context, e.Args)) { // Creating armored input stream to wrap key using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) { using (var armored = new ArmoredInputStream(memStream)) { var keys = new PgpPublicKeyRing(armored); // Now returning key details to caller. foreach (PgpPublicKey key in keys.GetPublicKeys()) { var node = e.Args.Add(BitConverter.ToString(key.GetFingerprint()).Replace("-", "")).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); foreach (var idxUserId in key.GetUserIds()) { if (idxUserId is string) { node.FindOrInsert("user-ids").Add("", idxUserId); } } foreach (PgpSignature signature in key.GetSignatures()) { node.FindOrInsert("signed-by").Add(((int)signature.KeyId).ToString("X"), signature.CreationTime); } } } } } } }
/// <summary> /// Helper to retrieve all [fork] objects within scope /// </summary> /// <returns>The fork objects</returns> /// <param name="context">Application Context</param> /// <param name="args">Active Event arguments</param> public static IEnumerable <Node> GetForkObjects(ApplicationContext context, Node args) { // Checking if we have an argument in value, at which point argument is evaluated and // gives basis for lambda object to evaluate on different thread if (args.Value == null) { // Executing current scope only yield return(args); } else { // Iterating each result from expression or value foreach (var idxResult in XUtil.Iterate <Node> (context, args)) { // Returning each iterated result yield return(idxResult); } } }
public static void p5_web_cookie_set(ApplicationContext context, ActiveEventArgs e) { XUtil.Set(context, e.Args, delegate(string key, object value) { if (value == null) { // Removal var httpCookie = HttpContext.Current.Response.Cookies[key]; if (httpCookie != null) { httpCookie.Expires = DateTime.Now.Date.AddDays(-1); } } else { // Setting or updating HttpContext.Current.Response.Cookies.Add(CreateCookieFromNode(e.Args, context, key, value)); } }, "duration", "http-only"); }
public string[] GetDays(LocaleFieldSize width, LocaleFieldType compose = LocaleFieldType.Default) { var path = new[] { new NodePathEntry("days"), new NodePathEntry("dayContext", compose.ToCode()) }; var ctx = this.Select(path); LdmlNode found = null; if (ctx != null) { foreach (int i in XUtil.GetClosest((int)width, (int)LocaleFieldSize.Wide)) { found = ctx.Select("dayWidth", ((LocaleFieldSize)i).ToCode(), LdmlAttribute.Type); if (found != null) { break; } } } if (found == null && compose == LocaleFieldType.StandAlone) { path[1].Attributes[0].Value = LocaleFieldType.Default.ToCode(); ctx = this.Select(path); if (ctx != null) { foreach (int i in XUtil.GetClosest((int)width, (int)LocaleFieldSize.Wide)) { found = ctx.Select("dayWidth", ((LocaleFieldSize)i).ToCode(), LdmlAttribute.Type); if (found != null) { break; } } } } if (found == null) { return(null); } return(found.GetList("day", GetDayIndex)); }
public static void p5_mime_save_file(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up after ourselves using (new Utilities.ArgsRemover(e.Args, true)) { // Keeping base folder to application around string baseFolder = Common.GetRootFolder(context); // Retrieving filename supplied by caller to serialize MimeEntity to var filename = XUtil.Single <string> (context, e.Args, true); // Verifying user is authorized to saving to the specified file context.Raise(".p5.io.authorize.modify-file", new Node("", filename).Add("args", e.Args)); // Retrieving root MIME entity from args var mimeNode = e.Args [0]; // Making sure we keep track of, closes, and disposes all streams created during process List <Stream> streams = new List <Stream> (); try { // Creating and returning MIME message to caller as string MimeCreator creator = new MimeCreator( context, mimeNode, streams); var mimeEntity = creator.Create(); // Creating file to store MIME entity into using (var stream = File.Create(baseFolder + filename)) { // Writing MimeEntity to file stream mimeEntity.WriteTo(stream); } } finally { // Disposing all streams created during process foreach (var idxStream in streams) { // Closing and disposing currently iterated stream idxStream.Close(); idxStream.Dispose(); } } } }
public static void p5_net_http_rest(ApplicationContext context, ActiveEventArgs e) { // Making sure we clean up and remove all arguments passed in after execution using (new ArgsRemover(e.Args, true)) { // Figuring out which HTTP method to use string method = e.Args.Name.Split('.').Last().ToUpper(); if (method.Contains("-")) { method = method.Substring(0, method.IndexOfEx("-")); } try { // Iterating through each request URL given foreach (var idxUrl in XUtil.Iterate <string> (context, e.Args)) { // Creating request var request = WebRequest.Create(idxUrl) as HttpWebRequest; // Setting HTTP method request.Method = method; // Writing content to request, if any RenderRequest(context, request, e.Args, method); // Returning response to caller RenderResponse(context, request, e.Args); } } catch (Exception err) { // Trying to avoid throwing a new exception, unless we have to if (err is LambdaException) { throw; } // Making sure we re-throw as LambdaException, to get more detailed information about what went wrong ... throw new LambdaException( string.Format("Something went wrong with request, error message was; '{0}'", err.Message), e.Args, context, err); } } }
/* * Renders HTTP post/put file request */ static void RenderFileRequest( ApplicationContext context, HttpWebRequest request, Node args, string method) { // Verifying caller supplied [file] node if (args["filename"] == null) { throw new LambdaException( "No [filename] node given", args, context); } // Getting file to post or put, verifying expression does not lead into oblivion var filename = context.RaiseEvent(".p5.io.unroll-path", new Node("", XUtil.Single <string> (context, args["filename"]))).Get <string> (context); // Making sure user is authorized to read the file request should send context.RaiseEvent(".p5.io.authorize.read-file", new Node("", filename).Add("args", args)); // Opening request stream, and render file as content of request using (Stream stream = request.GetRequestStream()) { // Setting Content-Type to "application/octet-stream", unless file ends with ".hl", or Content-Type is explicitly supplied request.ContentType = args.GetExChildValue( "Content-Type", context, filename.EndsWithEx(".hl") ? "application/x-hyperlambda" : "application/octet-stream"); // Setting other HTTP request headers SetRequestHeaders(context, request, args); // Retrieving root node of web application var rootFolder = context.RaiseEvent(".p5.core.application-folder").Get <string> (context); // Copying FileStream to RequestStream using (Stream fileStream = File.OpenRead(rootFolder + filename)) { // Sending file to server end-point fileStream.CopyTo(stream); } } }
static void _p5_core_null_active_event(ApplicationContext context, ActiveEventArgs e) { // Acquire read lock, since we're consuming object shared amongst more than one thread (_events). // This lock must be released before event is invoked, and is only here since we're consuming Node lambda = null; _lock.EnterReadLock(); try { // Checking if there's an event with given name in dynamically created events. // To avoid creating a lock on every single event invocation in system, we create a "double check" // here, first checking for existance of key, then to create lock, for then to re-check again, which // should significantly improve performance of event invocations in the system if (_events.ContainsKey(e.Name)) { // Keep a reference to all lambda objects in current event, such that we can later delete them lambda = _events [e.Name].Clone(); } } finally { // Making sure we release lock in a finally, such that we can never exit method, without releasing our lock. _lock.ExitReadLock(); } // Raising Active Event, if it exists. if (lambda != null) { // Making sure we do not pass in whitelist to event invocation, if it is specified. if (context.Ticket.Whitelist == null) { XUtil.EvaluateLambda(context, lambda, e.Args); } else { var whitelist = context.Ticket.Whitelist; context.Ticket.Whitelist = null; try { XUtil.EvaluateLambda(context, lambda, e.Args); } finally { context.Ticket.Whitelist = whitelist; } } } }
private static void p5_crypto_import_public_pgp_key(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new ArgsRemover(e.Args, true)) { // Creating new GnuPG context using (var ctx = new GnuPrivacyContext()) { // Looping through each public key (in ascii armored format) and importing into GnuPG database foreach (var idxKey in XUtil.Iterate <string> (context, e.Args)) { // Creating armored input stream to wrap key using (var memStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(idxKey))) { using (var armored = new ArmoredInputStream(memStream)) { var key = new PgpPublicKeyRing(armored); ctx.Import(key); } } } } } }