public override async Task <IDocument> ExecuteAsync( KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary dictionary = args.ToDictionary( "Key", "Value"); dictionary.RequireKeys("Key"); object keyValue = document.Get(dictionary.GetString("Key")); if (dictionary.ContainsKey("Value")) { return(TypeHelper.TryConvert(dictionary.Get("Value"), keyValue.GetType(), out object value) && (keyValue?.Equals(value) ?? (keyValue == null && value == null)) ? await document.CloneAsync(content) : null); } return(TypeHelper.TryConvert(keyValue, out bool result) && result ? await document.CloneAsync(content) : null); }
public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( Src, Style); var style = arguments.GetString(Style) ?? "container"; XElement container = new XElement( "div", new XAttribute("class", style)); XElement figure = new XElement( "figure"); // Image XElement image = arguments.XElement("img", Src, x => new[] { new XAttribute("src", context.GetLink(x)) }); if (image is object) { figure.Add(image); } // Caption if (content is object) { figure.Add(new XElement("figcaption", content)); } container.Add(figure); return(container.ToString()); }
public BlittableJsonReaderObject ToBlittable(object entity, IMetadataDictionary metadata, JsonOperationContext context, IJsonSerializer jsonSerializer) { using (var writer = new BlittableJsonWriter(context, new DocumentInfo { MetadataInstance = metadata })) return(ToBlittableInternal(entity, Conventions.Conventions, context, jsonSerializer, writer)); }
public PutCompareExchangeValueOperation(string key, T value, long index, IMetadataDictionary metadata = null) { _key = key; _value = value; _index = index; _metadata = metadata; }
/// <inheritdoc /> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary dictionary = args.ToDictionary( "Language", "Element", "HighlightJsFile"); HtmlParser parser = new HtmlParser(); using (IJavaScriptEnginePool enginePool = context.GetJavaScriptEnginePool(x => { if (dictionary.ContainsKey("HighlightJsFile")) { x.ExecuteFile(dictionary.GetString("HighlightJsFile")); } else { x.ExecuteResource("highlight-all.js", typeof(Statiq.Highlight.HighlightCode)); } })) { AngleSharp.Dom.IDocument htmlDocument = parser.Parse(string.Empty); AngleSharp.Dom.IElement element = htmlDocument.CreateElement(dictionary.GetString("Element", "code")); element.InnerHtml = content.Trim(); if (dictionary.ContainsKey("Language")) { element.SetAttribute("class", $"language-{dictionary.GetString("Language")}"); } Statiq.Highlight.HighlightCode.HighlightElement(enginePool, element); return(context.CreateDocument(await context.GetContentProviderAsync(element.OuterHtml))); } }
public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary(Owner, Repo, PathFileName, RegionName); arguments.RequireKeys(Owner, Repo, PathFileName); content = GetContent(arguments.GetString(Owner), arguments.GetString(Repo), arguments.GetString(PathFileName), arguments.GetString(RegionName)).Result; return(content); }
/// <inheritdoc /> public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary(Id, Username, File); arguments.RequireKeys(Id); return($"<script src=\"//gist.github.com/{arguments.GetString(Username, x => x + "/")}{arguments.GetString(Id)}.js" + $"{arguments.GetString(File, x => "?file=" + x)}\" type=\"text/javascript\"></script>"); }
public async Task StoreAsync(object entity, string id, IMetadataDictionary metadata = null) { VerifyValidId(id); if (_stream == null) { await WaitForId().ConfigureAwait(false); await EnsureStream().ConfigureAwait(false); } var docInfo = new DocumentInfo { Collection = _requestExecutor.Conventions.GetCollectionName(entity) }; JsonOperationContext tempContext; using (_requestExecutor.ContextPool.AllocateOperationContext(out tempContext)) { if (metadata != null) { docInfo.MetadataInstance = metadata; docInfo.Metadata = EntityToBlittable.ConvertEntityToBlittable(metadata, _requestExecutor.Conventions, tempContext); } using (var doc = EntityToBlittable.ConvertEntityToBlittable(entity, _requestExecutor.Conventions, tempContext, docInfo)) { if (_first == false) { _jsonWriter.WriteComma(); } _first = false; var cmd = new DynamicJsonValue { [nameof(PutCommandDataWithBlittableJson.Type)] = "PUT", [nameof(PutCommandDataWithBlittableJson.Id)] = id, [nameof(PutCommandDataWithBlittableJson.Document)] = doc }; try { tempContext.Write(_jsonWriter, cmd); } catch (Exception e) { var error = await GetExceptionFromOperation().ConfigureAwait(false); if (error != null) { throw error; } await ThrowOnUnavailableStream(id, e).ConfigureAwait(false); } } } }
private static DateTime?GetExpiry(IMetadataDictionary metadata) { if (metadata.ContainsKey(Constants.Documents.Metadata.Expires)) { return(DateTime.Parse(metadata[Constants.Documents.Metadata.Expires].ToString()).ToUniversalTime()); } else { return(null); } }
public async Task <string> StoreAsync(object entity, IMetadataDictionary metadata = null) { if (metadata == null || metadata.TryGetValue(Constants.Documents.Metadata.Id, out var id) == false) { id = GetId(entity); } await StoreAsync(entity, id, metadata).ConfigureAwait(false); return(id); }
public void WriteMetadata(IMetadataDictionary metadata) { _manualBlittableJsonDocumentBuilder.StartWriteObject(); foreach (var kvp in metadata) { _manualBlittableJsonDocumentBuilder.WritePropertyName(kvp.Key); WritePropertyValue(kvp.Key, kvp.Value); } _manualBlittableJsonDocumentBuilder.WriteObjectEnd(); }
public GetMetadata() { using (var store = new DocumentStore()) { using (var session = store.OpenSession()) { #region get_metadata_2 Employee employee = session.Load <Employee>("employees/1-A"); IMetadataDictionary metadata = session.Advanced.GetMetadataFor(employee); #endregion } } }
/// <inheritdoc /> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( "Id", "Username", "File"); arguments.RequireKeys("Id"); return(context.CreateDocument( await context.GetContentProviderAsync( $"<script src=\"//gist.github.com/{arguments.GetString("Username", x => x + "/")}{arguments.GetString("Id")}.js" + $"{arguments.GetString("File", x => "?file=" + x)}\" type=\"text/javascript\"></script>"))); }
/// <summary> /// Shortcodes for specific oEmbed services should override this method and call one of the other execute helper methods. /// </summary> public virtual async Task <ShortcodeResult> ExecuteAsync(KeyValuePair <string, string>[] args, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary(Endpoint, Url, Format); arguments.RequireKeys(Endpoint, Url); return(await GetEmbedResultAsync( arguments.GetString(Endpoint), arguments.GetString(Url), arguments.ContainsKey(Format) ?new string[] { $"format={arguments.GetString(Format)}" } : null, context)); }
/// <inheritdoc /> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( "Src", "Link", "Target", "Rel", "Alt", "Class", "Height", "Width"); XElement figure = new XElement( "figure", arguments.XAttribute("class")); // Image link XElement imageLink = arguments.XElement("a", "link", x => new[] { new XAttribute("href", context.GetLink(x)), arguments.XAttribute("target"), arguments.XAttribute("rel") }); // Image XElement image = arguments.XElement("img", "src", x => new[] { new XAttribute("src", context.GetLink(x)), arguments.XAttribute("alt"), arguments.XAttribute("height"), arguments.XAttribute("width") }); if (imageLink != null && image != null) { imageLink.Add(image); figure.Add(imageLink); } else if (image != null) { figure.Add(image); } // Caption if (content != null) { figure.Add(new XElement("figcaption", content)); } return(context.CreateDocument(await context.GetContentProviderAsync(figure.ToString()))); }
/// <inheritdoc /> public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( Path, IncludeHost, Host, Root, Scheme, UseHttps, HideIndexPages, HideExtensions, Lowercase); arguments.RequireKeys(Path); string path = arguments.GetString(Path); if (LinkGenerator.TryGetAbsoluteHttpUri(path, out string absoluteUri)) { return(absoluteUri); } NormalizedPath filePath = new NormalizedPath(path); // Use "Host" if it's provided, otherwise use Host setting if "IncludeHost" is true string host = arguments.GetString(Host, arguments.GetBool(IncludeHost) ? context.Settings.GetString(Keys.Host) : null); // Use "Root" if it's provided, otherwise LinkRoot setting NormalizedPath root = arguments.GetPath(Root, context.Settings.GetPath(Keys.LinkRoot)); // Use "Scheme" if it's provided, otherwise if "UseHttps" is true use "https" or use LinksUseHttps setting string scheme = arguments.GetString(Scheme, arguments.ContainsKey(UseHttps) ? (arguments.GetBool(UseHttps) ? "https" : null) : (context.Settings.GetBool(Keys.LinksUseHttps) ? "https" : null)); // If "HideIndexPages" is provided and true use default hide pages, otherwise use default hide pages if LinkHideIndexPages is true string[] hidePages = arguments.ContainsKey(HideIndexPages) ? (arguments.GetBool(HideIndexPages) ? LinkGenerator.DefaultHidePages : null) : (context.Settings.GetBool(Keys.LinkHideIndexPages) ? LinkGenerator.DefaultHidePages : null); // If "HideExtensions" is provided and true use default hide extensions, otherwise use default hide extensions if LinkHideExtensions is true string[] hideExtensions = arguments.ContainsKey(HideExtensions) ? (arguments.GetBool(HideExtensions) ? LinkGenerator.DefaultHideExtensions : null) : (context.Settings.GetBool(Keys.LinkHideExtensions) ? LinkGenerator.DefaultHideExtensions : null); // If "Lowercase" is provided use that, otherwise use LinkLowercase setting bool lowercase = arguments.ContainsKey(Lowercase) ? arguments.GetBool(Lowercase) : context.Settings.GetBool(Keys.LinkLowercase); return(LinkGenerator.GetLink(filePath, host, root, scheme, hidePages, hideExtensions, lowercase)); }
/// <inheritdoc /> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( "Path", "IncludeHost", "Host", "Root", "Scheme", "UseHttps", "HideIndexPages", "HideExtensions", "Lowercase"); arguments.RequireKeys("Path"); string path = arguments.GetString("Path"); if (LinkGenerator.TryGetAbsoluteHttpUri(path, out string absoluteUri)) { return(context.CreateDocument(await context.GetContentProviderAsync(absoluteUri))); } FilePath filePath = new FilePath(path); // Use "Host" if it's provided, otherwise use Host setting if "IncludeHost" is true string host = arguments.GetString("Host", arguments.GetBool("IncludeHost") ? context.Settings.GetString(Keys.Host) : null); // Use "Root" if it's provided, otherwise LinkRoot setting DirectoryPath root = arguments.GetDirectoryPath("Root", context.Settings.GetDirectoryPath(Keys.LinkRoot)); // Use "Scheme" if it's provided, otherwise if "UseHttps" is true use "https" or use LinksUseHttps setting string scheme = arguments.GetString("Scheme", arguments.ContainsKey("UseHttps") ? (arguments.GetBool("UseHttps") ? "https" : null) : (context.Settings.GetBool(Keys.LinksUseHttps) ? "https" : null)); // If "HideIndexPages" is provided and true use default hide pages, otherwise use default hide pages if LinkHideIndexPages is true string[] hidePages = arguments.ContainsKey("HideIndexPages") ? (arguments.GetBool("HideIndexPages") ? LinkGenerator.DefaultHidePages : null) : (context.Settings.GetBool(Keys.LinkHideIndexPages) ? LinkGenerator.DefaultHidePages : null); // If "HideExtensions" is provided and true use default hide extensions, otherwise use default hide extensions if LinkHideExtensions is true string[] hideExtensions = arguments.ContainsKey("HideExtensions") ? (arguments.GetBool("HideExtensions") ? LinkGenerator.DefaultHideExtensions : null) : (context.Settings.GetBool(Keys.LinkHideExtensions) ? LinkGenerator.DefaultHideExtensions : null); // If "Lowercase" is provided use that, otherwise use LinkLowercase setting bool lowercase = arguments.ContainsKey("Lowercase") ? arguments.GetBool("Lowercase") : context.Settings.GetBool(Keys.LinkLowercase); return(context.CreateDocument(await context.GetContentProviderAsync(LinkGenerator.GetLink(filePath, host, root, scheme, hidePages, hideExtensions, lowercase)))); }
public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( Src, Link, Target, Rel, Alt, Class, Height, Width); XElement figure = new XElement( "figure", arguments.XAttribute(Class)); // Image link XElement imageLink = arguments.XElement("a", Link, x => new[] { new XAttribute("href", context.GetLink(x)), arguments.XAttribute(Target), arguments.XAttribute(Rel) }); // Image XElement image = arguments.XElement("img", Src, x => new[] { new XAttribute("src", context.GetLink(x)), arguments.XAttribute(Alt), arguments.XAttribute(Height), arguments.XAttribute(Width) }); if (imageLink != null && image != null) { imageLink.Add(image); figure.Add(imageLink); } else if (image != null) { figure.Add(image); } // Caption if (content != null) { figure.Add(new XElement("figcaption", content)); } return(figure.ToString()); }
public static TocItem Create(IMetadataDictionary data) { var tocItem = new TocItem() { Title = data.Get <string>("title"), Link = data.Get <string>("link"), }; if (data.ContainsKey("children")) { tocItem.Children = Create(data.GetList <IMetadataDictionary>("children")); } return(tocItem); }
/// <summary> /// Shortcodes for specific oEmbed services should override this method and call one of the other execute helper methods. /// </summary> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( "Endpoint", "Url", "Format"); arguments.RequireKeys("Endpoint", "Url"); return(await ExecuteAsync( arguments.GetString("Endpoint"), arguments.GetString("Url"), arguments.ContainsKey("Format") ?new string[] { $"format={arguments.GetString("Format")}" } : null, context)); }
public override async Task <IEnumerable <IDocument> > ExecuteAsync( KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary dictionary = args.ToDictionary( "Key", "ValueKey", "IndexKey"); dictionary.RequireKeys("Key", "ValueKey"); string valueKey = dictionary.GetString("ValueKey"); if (string.IsNullOrEmpty(valueKey)) { throw new ShortcodeArgumentException("Invalid ValueKey"); } string indexKey = dictionary.GetString("IndexKey"); IReadOnlyList <object> items = document.GetList <object>(dictionary.GetString("Key")); if (items != null) { List <IDocument> results = new List <IDocument>(); int index = 0; foreach (object item in items) { MetadataItems metadata = new MetadataItems() { { valueKey, item } }; if (!string.IsNullOrEmpty(indexKey)) { metadata.Add(indexKey, index); } results.Add(await document.CloneAsync(metadata, content)); index++; } return(results); } return(null); }
public PutCompareExchangeValueCommand(string key, T value, long index, IMetadataDictionary metadata = null, DocumentConventions conventions = null) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key), "The key argument must have value"); } if (index < 0) { throw new InvalidDataException("Index must be a non-negative number"); } _key = key; _value = value; _index = index; _metadata = metadata; _conventions = conventions ?? DocumentConventions.Default; }
internal static void OnPageSave(string key, IPage currentPage, IMetadataDictionary metadata) { using (IDocumentSession session = DocumentStore.OpenSession()) { var trie = session.Load <Trie>(TrieId); if (trie.RootNode == null) { trie.RootNode = new TrieNode { PageId = key }; } else { TrieNode[] nodes = trie.RootNode.Flatten(n => n.Children).ToArray(); TrieNode parent = currentPage.Parent != null ? nodes.SingleOrDefault( n => String.Equals(n.PageId, currentPage.Parent.Id, StringComparison.CurrentCultureIgnoreCase)) : null; if (parent != null) { currentPage.Metadata.Slug = Slug.CreateSlug(currentPage); currentPage.Metadata.Url = currentPage.Metadata.Slug.Insert(0, VirtualPathUtility.AppendTrailingSlash(parent.Url ?? "")); if (parent.Children.All(n => n.PageId != key.Replace("/draft", ""))) { parent.Children.Add(new TrieNode { PageId = key.Replace("/draft", ""), ParentId = parent.PageId, Url = currentPage.Metadata.Url }); } } } session.SaveChanges(); } }
public override IEnumerable <ShortcodeResult> Execute( KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary dictionary = args.ToDictionary(Key, ValueKey, IndexKey); dictionary.RequireKeys(Key, ValueKey); string valueKey = dictionary.GetString(ValueKey); if (string.IsNullOrEmpty(valueKey)) { throw new ShortcodeArgumentException(ValueKey); } string indexKey = dictionary.GetString(IndexKey); IReadOnlyList <object> items = document.GetList <object>(dictionary.GetString(Key)); if (items != null) { List <ShortcodeResult> results = new List <ShortcodeResult>(); int index = 0; foreach (object item in items) { MetadataItems metadata = new MetadataItems() { { valueKey, item } }; if (!string.IsNullOrEmpty(indexKey)) { metadata.Add(indexKey, index); } results.Add(new ShortcodeResult(content, metadata)); index++; } return(results); } return(null); }
/// <summary> /// Invoked before the delete request is sent to the server. /// </summary> /// <param name="key">The key.</param> /// <param name="entityInstance">The entity instance.</param> /// <param name="metadata">The metadata.</param> public void BeforeDelete(string key, object entityInstance, IMetadataDictionary metadata) { var entity = entityInstance as IPage; if (entity == null) { return; } if (DocumentListenerContext.IsInDocumentListenerContext) { return; } using (DocumentListenerContext.Enter()) { this.onDocumentDelete(key, entity, metadata); } }
/// <summary> /// Invoked before the store request is sent to the server. /// </summary> /// <param name="key">The key.</param> /// <param name="entityInstance">The entity instance.</param> /// <param name="metadata">The metadata.</param> /// <param name="original">The original document that was loaded from the server</param> /// <returns> /// Whatever the entity instance was modified and requires us re-serialize it. /// Returning true would force re-serialization of the entity, returning false would /// mean that any changes to the entityInstance would be ignored in the current SaveChanges call. /// </returns> public bool BeforeStore(string key, object entityInstance, IMetadataDictionary metadata, IMetadataDictionary original) { var entity = entityInstance as IPage; if (entity == null) { return(false); } if (DocumentListenerContext.IsInDocumentListenerContext) { return(false); } var action = HttpContext.Current.Items["storeAction"] as StoreAction?; using (DocumentListenerContext.Enter()) { switch (action) { case StoreAction.None: return(false); case StoreAction.Save: //_onPageSave(key, entity, metadata); this.onPagePublish(key, entity, metadata); break; case StoreAction.Publish: this.onPagePublish(key, entity, metadata); break; case StoreAction.UnPublish: //_onPageUnpublish(key, entity, metadata); return(false); default: return(false); } return(true); } }
/// <summary> /// Called when [document delete]. /// </summary> /// <param name="key">The key.</param> /// <param name="page">The currentPage.</param> /// <param name="metadata">The metadata.</param> internal void OnDocumentDelete(string key, IPage page, IMetadataDictionary metadata) { using (IDocumentSession session = DocumentStore.OpenSession()) { var trie = session.Load <Trie>(TrieId); TrieNode node = trie.Get(key); if (node != null) { trie.Delete(node); } // Clean up any existing draft for this page if (session.Advanced.Exists(key + "/draft")) { var draft = session.Load <IPage>(key + "/draft"); session.Delete(draft); } session.SaveChanges(); } }
public void MatchesPositionalAndNamedArguments() { // Given KeyValuePair <string, string>[] args = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(null, "1"), new KeyValuePair <string, string>("C", "3"), new KeyValuePair <string, string>("B", "2") }; // When IMetadataDictionary dictionary = args.ToDictionary("A", "B", "C"); // Then dictionary.ShouldBe( new KeyValuePair <string, object>[] { new KeyValuePair <string, object>("A", "1"), new KeyValuePair <string, object>("B", "2"), new KeyValuePair <string, object>("C", "3") }, true); }
public async Task <string> StoreAsync(object entity, IMetadataDictionary metadata = null) { if (Interlocked.CompareExchange(ref _concurrentCheck, 1, 0) == 1) { throw new ConcurrencyException("Store/StoreAsync in bulkInsert concurrently is forbidden"); } string id; try { if (metadata == null || metadata.TryGetValue(Constants.Documents.Metadata.Id, out id) == false) { id = GetId(entity); } await StoreAsync(entity, id, metadata).ConfigureAwait(false); } finally { Interlocked.CompareExchange(ref _concurrentCheck, 0, 1); } return(id); }
/// <inheritdoc /> public override async Task <IDocument> ExecuteAsync(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context) { IMetadataDictionary arguments = args.ToDictionary( "Id", "HideMedia", "HideThread", "Theme", "OmitScript"); arguments.RequireKeys("Id"); // Create the url List <string> query = new List <string>(); if (arguments.GetBool("HideMedia")) { query.Add("hide_media=true"); } if (arguments.GetBool("HideThread")) { query.Add("hide_thread=true"); } if (arguments.ContainsKey("Theme")) { query.Add($"theme={arguments.GetString("theme")}"); } if (_omitScript || arguments.GetBool("OmitScript")) { query.Add("omit_script=true"); } // Omit the script on the next Twitter embed _omitScript = true; return(await ExecuteAsync("https://publish.twitter.com/oembed", $"https://twitter.com/username/status/{arguments.GetString("Id")}", query, context)); }