Related
I have a dashboard app, that displays certain applications to the user, loaded from the database..
The tiles are draggable (Jquery).. But im struggling to understand how to move a tile, and then keep the state, so that a user can come back the next day, and still have his preferences.
I have tried to follow Telerik demo, but unfortunately, i am a student, i can't afford the license.. Has anybody done something similar, to keep a users preferences?
Here is the Telerik demo, im struggling with what would be in the models.
Local storage for state
using Microsoft.JSInterop;
using System.Text.Json;
using System.Threading.Tasks;
namespace TelerikBlazorDemos.Services
{
public class LocalStorage
{
protected IJSRuntime JSRuntimeInstance { get; set; }
public LocalStorage(IJSRuntime jsRuntime)
{
JSRuntimeInstance = jsRuntime;
}
public ValueTask SetItem(string key, object data)
{
return JSRuntimeInstance.InvokeVoidAsync(
"localStorage.setItem",
new object[] {
key,
JsonSerializer.Serialize(data)
});
}
public async Task<T> GetItem<T>(string key)
{
var data = await JSRuntimeInstance.InvokeAsync<string>("localStorage.getItem", key);
if (!string.IsNullOrEmpty(data))
{
return JsonSerializer.Deserialize<T>(data);
}
return default;
}
public ValueTask RemoveItem(string key)
{
return JSRuntimeInstance.InvokeVoidAsync("localStorage.removeItem", key);
}
}
}
This is the part im struggling with.. #Code{ }
#page "/tilelayout/persist-state"
#inject LocalStorage LocalStorage
#inject IJSRuntime JsInterop
#using TelerikBlazorDemos.Shared.DemoConfigurator
<DemoConfigurator>
<DemoConfiguratorColumn>
<TelerikButton OnClick="#SaveState" Icon="save" Class="mr-xs">Save State</TelerikButton>
<TelerikButton OnClick="#ReloadPage" Icon="reload" Class="mr-xs">Reload the page</TelerikButton>
<TelerikButton OnClick="#LoadState" Icon="download" Class="mr-xs">Load last State</TelerikButton>
<TelerikButton OnClick="#SetExplicitState" Icon="gear" Class="mr-xs">Configure State</TelerikButton>
</DemoConfiguratorColumn>
</DemoConfigurator>
<div class="demo-alert demo-alert-info" role="alert">
<strong>Change the Tile Layout</strong> (resize and reorder some tiles, remember their order) and
<strong>Save</strong> the TileLayout state, then <strong>Reload</strong> the page to see the state persisted.
<strong>Change</strong> the layout some more and <strong>Load</strong> the state to see the last one preserved.
You can manage the TileLayout state with your own code to put it in a specific configuration through the <strong>Configure</strong> button.
This demo will remember your last layout until your clear your browser storage or click the Configure button to put it in its initial state.
</div>
<div style="display: inline-block;">
<TelerikTileLayout #ref="#TileLayoutInstance"
Columns="3"
ColumnWidth="285px"
RowHeight="285px"
Resizable="true"
Reorderable="true">
<TileLayoutItems>
<TileLayoutItem HeaderText="San Francisco">
<Content>
<img class="k-card-image" draggable="false" src="images/cards/sanfran.jpg" />
</Content>
</TileLayoutItem>
<TileLayoutItem HeaderText="South Africa">
<Content>
<img class="k-card-image" draggable="false" src="images/cards/south-africa.jpg" />
</Content>
</TileLayoutItem>
<TileLayoutItem HeaderText="Sofia" RowSpan="2">
<Content>
<img class="k-card-image" draggable="false" src="images/cards/sofia.jpg" />
<div class="text-center">
<div class="k-card-body">
<p>Sofia is the largest city and capital of Bulgaria. Sofia City Province has an area of 1344 km<sup>2</sup> while the surrounding and much bigger Sofia Province is 7,059 km<sup>2</sup>. The city is situated in the western part of the country at the northern foot of the Vitosha mountain, in the Sofia Valley that is surrounded by the Balkan mountains to the north. The valley has an average altitude of 550 metres (1,800 ft). Unlike most European capitals, Sofia does not straddle any large river, but is surrounded by comparatively high mountains on all sides.</p>
<br />
<em>* The data used in this demo is taken from <em>wikipedia.com</em></em>
</div>
</div>
</Content>
</TileLayoutItem>
<TileLayoutItem HeaderText="Rome" ColSpan="2" RowSpan="2">
<Content>
<img class="k-card-image image-center" draggable="false" src="images/cards/rome.jpg" />
<div class="text-center">
<div class="k-card-body">
<p>
</p>
<p>
<em>* The data used in this demo is taken from <em>wikipedia.com</em></em>
</p>
</div>
</div>
</Content>
</TileLayoutItem>
<TileLayoutItem HeaderText="Barcelona">
<Content>
<img class="k-card-image" draggable="false" src="images/cards/barcelona.jpg" />
</Content>
</TileLayoutItem>
</TileLayoutItems>
</TelerikTileLayout>
</div>
#code { TelerikTileLayout TileLayoutInstance { get; set; }
TileLayoutState SavedState { get; set; }
string stateStorageKey = "TelerikBlazorTileLayoutStateDemoKey";
async Task SaveState()
{
var state = TileLayoutInstance.GetState();
await LocalStorage.SetItem(stateStorageKey, state);
}
async Task LoadState()
{
TileLayoutState storedState = await LocalStorage.GetItem<TileLayoutState>(stateStorageKey);
if (storedState != null)
{
TileLayoutInstance.SetState(storedState);
}
}
void ReloadPage()
{
JsInterop.InvokeVoidAsync("window.location.reload");
}
async void SetExplicitState()
{
TileLayoutState desiredState = GetDefaultDemoState();
TileLayoutInstance.SetState(desiredState);
await SaveState();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var state = await LocalStorage.GetItem<TileLayoutState>(stateStorageKey);
if (state != null && TileLayoutInstance != null)
{
TileLayoutInstance.SetState(state);
}
}
TileLayoutState GetDefaultDemoState()
{
TileLayoutState defaultDemoState = new TileLayoutState()
{
ItemStates = new List<TileLayoutItemState>()
{
new TileLayoutItemState { Order = 1, ColSpan = 1, RowSpan = 1 },
new TileLayoutItemState { Order = 2, ColSpan = 1, RowSpan = 1 },
new TileLayoutItemState { Order = 3, ColSpan = 1, RowSpan = 2 },
new TileLayoutItemState { Order = 4, ColSpan = 2, RowSpan = 2 },
new TileLayoutItemState { Order = 5, ColSpan = 1, RowSpan = 1 },
}
};
return defaultDemoState;
} }
<style>
.k-card-image {
width: 285px;
height: 189px;
}
.k-card-body {
overflow: auto;
}
.image-center {
display: block;
margin: auto;
}
</style>
For instance TileLayoutInstance.SetState(storedState); I don't know how this is set up behind the bonnet.
p.s im using .netCore5 and visual studio 2019. Any help is much appreciated.
I am confused by your question. Are you using Telerik or are you trying to determine how their example works? If you are coding this from scratch then consider the dashboard as a set of rows and columns or a 2 dimensional array. When the user moves tiles they are switching the location of the tiles within the array. You need to store and maintain the state of the array. A solution can become more complicated depending on if the dashboard is a variable or fixed size. You can store an X and Y coordinate in the model and the tile at the location along with the overall size of the dashboard.
I have to assume that TileLayoutInstance.SetState expects an instance of TileLayoutState which contains a List of TileLayoutItemState objects. By the look of your example each TileLayoutItemState has an Order property, which determines the order of the object in the TelerikTileLayout component?
When the user moves a tile, you need to save its new position, which presumably your already doing somewhere?
You then save the current order to localStorage and read it back in when the user clicks the Load button.
From the look of it, (and apologies if I misunderstand what your trying to do or I misunderstand how this telerik component works), you then need to re-render the component using the order stored in localStorage. But your rendering code is hardcoded? It adds each TileLayoutItem in a fixed order. I see there is a ReOrderable property which presumably allows this order to be changed, but when the page reloads, I'm pretty sure that it will always render it back in the order you have provided in the HTML.
I think you will need to store the header text, P content and the image name into a list, as well as the order and then use a #ForEach loop around this List (using the correct order which you can control by using LINQ against the order property) to add each TileLayoutItem dynamically, providing the values for the src, headerText properties etc from the iterated object and render it in the persisted order.
Might be easier and more manageable to use a class and save it to a database to be honest.
Also, you can use Blazored.LocalStorage.ILocalStorageService to read/write local storage without having to write extra JS.
I'm writing an ASP.NET web app (university task for exam). I have a database which has columns like Id, Name, Age, SumNote. First of all I had to make a partial view with top 5 students in database:
This method to get top 5 students
public class HomeController : Controller
{
StudentContext db = new StudentContext();
public ActionResult ShowTopFive ()
{
var allStudents = db.Students.OrderByDescending(s => s.SumNote).Take(5);
return PartialView(allStudents);
}
}
This is the patrial View:
#model IEnumerable<Univercity.Models.Student>
<div id="results">
<h4>Best 5 students</h4>
<ul>
#foreach (var item in Model)
{
<li>#item.Name, Summ of notes: #item.SumNote</li>
}
</ul>
</div>
and with this one I got the list of students in my webpage
<div>
<h5>Show top 5 students</h5>
</div>
<div>
#using (Ajax.BeginForm("ShowTopFive", new AjaxOptions { UpdateTargetId = "results" }))
{
<input type="submit" value="Show"/>
}
<div id="results"></div>
</div>
the output result looks like this:
Ivanov Mikhail, Summ of notes: 16
Kozlov Pete, Summ of notes: 12
Mary Ann, Summ of notes: 11
I also need to save it as text file. Can't figure out how? May be there is a way to change something in Ajax code?
Thanks in advance. Hope someone know how to do it. Google didn't help
You could create a controller action method which uses FileStreamResult by iterating the list created from ToList() and write necessary property values into a stream, then use Controller.File() overload which accepts stream to let user download text file:
public ActionResult GetTextFile()
{
var topFiveStudents = db.Students.OrderByDescending(s => s.SumNote).Take(5).ToList();
if (topFiveStudents != null && topFiveStudents.Count > 0)
{
string fileName = "something.txt";
// create a stream
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (var students in topFiveStudents)
{
// iterate the list and write to stream
sw.WriteLine(string.Format("{0}, Sum of notes: {1}", students.Name, students.SumNote));
}
sw.Flush();
ms.Position = 0;
// return text file from stream
return File(ms, "text/plain", fileName);
}
else
{
// do something else
}
}
Afterwards, create an anchor link pointed to that action method mentioned above inside partial view:
#Html.ActionLink("Export to TXT", "GetTextFile", "ControllerName")
I'm learning asp.net core razor pages with ef. I want to implement pagination with my table, I have check this tutorial
https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-2.1
but it only support pre and next, I have researched for a long time, all of the solution are related to asp.net core mvc, but I'm using razor pages, there's no controller in my project, any ideas to implement?
This is the effect what I want to implement
<form method="get" asp-page="./Index">
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
#{
var totalPages = Model.Products.Count % 2 == 0 ? Model.Products.Count / 2 : Model.Products.Count / 2 + 1;
}
#for (int i = 1; i <= totalPages; i++)
{
<li><a asp-page="./Index" asp-route-id="#i">#i</a></li>
}
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</form>
cshtml.cs
public async Task OnGetAsync(string sortOrder, string searchString, string shopString, string statusString, int page)
{}
Pagination is relatively simple. There's libraries available to do it for you, but I've started to find them more trouble than they're worth.
You need three pieces of information from the request (or set to default values):
Page number (default to 1)
Page size (typically defaults to 10, but whatever you want)
Sort (not strictly necessary, but you should at least order by something to keep the results consistent across pages)
The page number and size give you your "skip" and "take" values:
var skip = (page - 1) * size;
var take = size;
You can then fetch the results via:
var pageOfResults = await query.Skip(skip).Take(take).ToListAsync();
Where query is an IQueryable - either your DbSet directly or the DbSet with a Where clause, OrderBy, etc. applied.
Then, you just need to the total number of items to figure the pages:
var count = await query.CountAsync();
Pro Tip, you can parallelize the two queries (results and total count) by doing:
var resultsTask = query.Skip(skip).Take(take).ToListAsync();
var countTask = query.CountAsync();
var results = await resultsTask;
var count = await countTask;
Tasks return hot, or already started. The await keyword simply holds the continuation of the rest of the code until the task completes. As a result, if you await each line, they'll complete in serial, but if you start both, first, and then await each, they'll process in parallel.
Anyways, once you have the count:
var totalPages = (int)Math.Ceil(Decimal.Divide(count, size));
var firstPage = 1;
var lastPage = totalPages;
var prevPage = Math.Max(page - 1, firstPage);
var nextPage = Math.Min(page + 1, lastPage);
Note: you can determine whether to show first/previous and last/next buttons based on whether they equal firstPage or lastPage, respectively.
Then, just build yourself a model with this information, and you can send that to the view to render the results and generate the paging HTML.
I have created a paging taghelper for .net Core Razor Pages, it can be configured within html tags or appsettings.json to show/ hide prev-next, first-last buttons, number of max displayed pages and more customization settings are available,
Install the nuget package:
Install-Package LazZiya.TagHelpers
Add the taghelper to _ViewImports.cshtml
#addTagHelper *, LazZiya.TagHelpers
Finally add the paging control to the view:
<paging
total-records="Model.TotalRecords"
page-no="Model.PageNo"
query-string-value="#(Request.QueryString.Value)">
</paging>
[Update]
Starting from v3.1.0 query-string-value is not necessary to be passed, additonally all options is turned on by default.
<paging
total-records="Model.TotalRecords"
page-no="Model.PageNo">
</paging>
Using appsettings.json for paging configurations will help to have more clean html code and it gives the ability to change paging settings on all or some paging taghelpers by once in the application.
See live demo for all settings: http://demo.ziyad.info/en/paging
Related article:
http://ziyad.info/en/articles/21-Paging_TagHelper_for_ASP_NET_Core
I made this implementation mixing together a few answers on the subject, I hope it helps someone.
Add a PagedResultBase class (that you can extend adding other properties you need):
public abstract class PagedResultBase
{
public int CurrentPage { get; set; }
public int PageCount { get; set; }
public int PageSize { get; set; }
public int RowCount { get; set; }
}
Add a PagedResult class:
public class PagedResult<T> : PagedResultBase where T : class
{
public ICollection<T> Results { get; set; }
public PagedResult()
{
Results = new List<T>();
}
}
Add a IQueryableExtensions with a GetPagedResult extension:
public static class IQueryableExtensions
{
public async static Task<PagedResult<T>> GetPagedResultAsync<T>(this IQueryable<T> query, int currentPage, int pageSize) where T : class
{
var skip = (currentPage - 1) * pageSize;
var take = pageSize;
var rowCount = await query.CountAsync();
var results = await query.Skip(skip).Take(take).ToListAsync();
var pagedResult = new PagedResult<T> {
CurrentPage = currentPage,
PageCount = (int)Math.Ceiling(decimal.Divide(rowCount, pageSize)),
PageSize = pageSize,
RowCount = rowCount,
Results = results
};
return pagedResult;
}
}
You are done:
var pagedResult = await MyContext.Posts.Where(p => p.Featured == true).GetPagedResultAsync(1, 10);
You can use the JW.Pager NuGet package (https://www.nuget.org/packages/JW.Pager/)
Here's an example razor pages page model that paginates a list of 150 items:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.RazorPages;
using JW;
namespace RazorPagesPagination.Pages
{
public class IndexModel : PageModel
{
public IEnumerable<string> Items { get; set; }
public Pager Pager { get; set; }
public void OnGet(int p = 1)
{
// generate list of sample items to be paged
var dummyItems = Enumerable.Range(1, 150).Select(x => "Item " + x);
// get pagination info for the current page
Pager = new Pager(dummyItems.Count(), p);
// assign the current page of items to the Items property
Items = dummyItems.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize);
}
}
}
And here's the razor pages page containing the html for the paged list and pager controls:
#page
#model RazorPagesPagination.Pages.IndexModel
<!-- items being paged -->
<table class="table table-sm table-striped table-bordered">
#foreach (var item in Model.Items)
{
<tr>
<td>#item</td>
</tr>
}
</table>
<!-- pager -->
#if (Model.Pager.Pages.Any())
{
<nav class="table-responsive">
<ul class="pagination justify-content-center d-flex flex-wrap">
#if (Model.Pager.CurrentPage > 1)
{
<li class="page-item">
<a class="page-link" href="/">First</a>
</li>
<li class="page-item">
<a class="page-link" href="/?p=#(Model.Pager.CurrentPage - 1)">Previous</a>
</li>
}
#foreach (var p in Model.Pager.Pages)
{
<li class="page-item #(p == Model.Pager.CurrentPage ? "active" : "")">
<a class="page-link" href="/?p=#p">#p</a>
</li>
}
#if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
{
<li class="page-item">
<a class="page-link" href="/?p=#(Model.Pager.CurrentPage + 1)">Next</a>
</li>
<li class="page-item">
<a class="page-link" href="/?p=#(Model.Pager.TotalPages)">Last</a>
</li>
}
</ul>
</nav>
}
For more details I posted a full tutorial with example project at http://jasonwatmore.com/post/2018/10/15/aspnet-core-razor-pages-pagination-example
I have a Tempada to show a list of error in a msg error,i create a List and in my foreach, each error find it, i add a error in my List and later i show this list in TempData
public IActionResult Demo()
{
List<string> LogErros = new List<string>();
try
{
foreach (var item in somethings)
{
// if have some error add to list
LogErros.add();
}
if (LogErros.Count > 0)
{
TempData["error-message"] = LogErros;
}
}
return View();
}
I try this:
#if (TempData["error-message"] != null)
{
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
#TempData["error-message"]
</div>
}
but get error
enter image description here
TempData["error-message"] stores a list of strings as an Object. So you need to get that first, cast it to a list of strings, loop through each one of them and render it.
Razor basically calls the ToString on the expression (in your case, object) and hence you are seeing your current results
This should work
#if (TempData["error-message"] != null)
{
var errors = TempData["error-message"] as List<string>;
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" >x</button>
#foreach(var errorMessage in errors)
{
<p>#errorMessage</p>
}
</div>
}
While this works, I recommend not putting a lot of C# code in the view. If it is an asp.net core project, I would recommend creating a tag helper for this. Here is a very simple one.
[HtmlTargetElement("div", Attributes = "messages")]
public class AlertMessagesTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
StringBuilder str = new StringBuilder();
var messages = ViewContext.TempData["error-message"] as List<string>;
if (messages != null && messages.Any())
{
str.Append("<div class='alert alert-danger alert-dismissable'>");
foreach (var message in messages)
{
str.AppendFormat("<div>{0}</div>", message);
}
str.Append("</div>");
}
output.Content.AppendHtml(str.ToString());
}
}
Now in your _ViewImports.cshtml file, use the addTagHelper method to include all the tag helpers from your project
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, YourAssemblyName
Now in your view or layout, you can call this tag helper by using a div element with the messages attribute
<div messages></div>
Feel free to update the tag helper code to render the HTML markup you want for the messages.
For Non-Asp.Net core projects, you can create an html helper method which does the same thing.
The problem is you are displaying #TempData["error-message"] in your view, but TempData is essentially a Dictionary<string, object> which means when you access the value at that key, the value is an object.
Even if you cast to its actual value (List<string>) it will implicitly call .ToString(), which wont automatically display the contents of the list if you just use the # symbol to render on the page.
First thing you need to do is cast your object to a List<string>:
var errorMessageList = TempData["error-message"] as List<string>;
Then you can iterate over the values in the list:
var errorMessageList = TempData["error-message"] as List<string>;
#if (errorMessageList != null)
{
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
#foreach(var message in errorMessageList)
{
#message
}
</div>
}
Of course you will have to format this how you want, maybe it should be comma separated? Maybe it should be in their own <span>... That is up to you.
I've created a custom section in Umbraco 7 that references external urls, but have a requirement to extend it to use exactly the same functionality as the media picker from the 'Content' rich text editor. I don't need any other rich text functionality other than to load the media picker overlay from an icon, and select either an internal or external url.
I've tried to distil the umbraco source code, as well as trying various adaptations of online tutorials, but as yet I can't get the media picker to load.
I know that fundamentally I need:
Another angular controller to return the data from the content
'getall' method
An html section that contains the media picker overlay
A reference in the edit.html in my custom section to launch the overlay.
However, as yet I haven't been able to wire it all together, so any help much appreciated.
So, this is how I came up with the solution.....
The first win was that I discovered 2 excellent tutorial blog posts, upon the shoulders of which this solution stands, so much respect to the following code cats:
Tim Geyssons - Nibble postings:
http://www.nibble.be/?p=440
Markus Johansson - Enkelmedia
http://www.enkelmedia.se/blogg/2013/11/22/creating-custom-sections-in-umbraco-7-part-1.aspx
Create a model object to represent a keyphrase, which will be associated to a new, simple, ORM table.
The ToString() method allows a friendly name to be output on the front-end.
[TableName("Keyphrase")]
public class Keyphrase
{
[PrimaryKeyColumn(AutoIncrement = true)]
public int Id { get; set; }
public string Name { get; set; }
public string Phrase { get; set; }
public string Link { get; set; }
public override string ToString()
{
return Name;
}
}
Create an Umbraco 'application' that will register the new custom section by implementing the IApplication interface. I've called mine 'Utilities' and associated it to the utilities icon.
[Application("Utilities", "Utilities", "icon-utilities", 8)]
public class UtilitiesApplication : IApplication { }
The decorator allows us to supply a name, alias, icon and sort-order of the new custom section.
Create an Umbraco tree web controller that will allow us to create the desired menu behaviour for our keyphrases, and display the keyphrase collection from our database keyphrase table.
[PluginController("Utilities")]
[Umbraco.Web.Trees.Tree("Utilities", "KeyphraseTree", "Keyphrase", iconClosed: "icon-doc", sortOrder: 1)]
public class KeyphraseTreeController : TreeController
{
private KeyphraseApiController _keyphraseApiController;
public KeyphraseTreeController()
{
_keyphraseApiController = new KeyphraseApiController();
}
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
var nodes = new TreeNodeCollection();
var keyphrases = _keyphraseApiController.GetAll();
if (id == Constants.System.Root.ToInvariantString())
{
foreach (var keyphrase in keyphrases)
{
var node = CreateTreeNode(
keyphrase.Id.ToString(),
"-1",
queryStrings,
keyphrase.ToString(),
"icon-book-alt",
false);
nodes.Add(node);
}
}
return nodes;
}
protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
var menu = new MenuItemCollection();
if (id == Constants.System.Root.ToInvariantString())
{
// root actions
menu.Items.Add<CreateChildEntity, ActionNew>(ui.Text("actions", ActionNew.Instance.Alias));
menu.Items.Add<RefreshNode, ActionRefresh>(ui.Text("actions", ActionRefresh.Instance.Alias), true);
return menu;
}
else
{
menu.Items.Add<ActionDelete>(ui.Text("actions", ActionDelete.Instance.Alias));
}
return menu;
}
}
The class decorators and TreeController extension allow us to declare the web controller for our keyphrase tree, associate it to our Utilities custom section, as well as choose an icon and sort order.
We also declare an api controller (we'll get to that!), which will allow us access to our Keyphrase data object.
The GetTreeNodes method allows us to iterate the keyphrase data collection and return the resultant nodes to the view.
The GetMenuNode method allows us to create the menu options we require for our custom section.
We state that if the node is the root (Utilities), then allow us to add child nodes and refresh the node collection.
However, if we are lower in the node tree (Keyphrase) then we only want users to be able to delete the node (ie the user shouldn't be allowed to create another level of nodes deeper than Keyphrase)
Create an api controller for our Keyphrase CRUD requests
public class KeyphraseApiController : UmbracoAuthorizedJsonController
{
public IEnumerable<Keyphrase> GetAll()
{
var query = new Sql().Select("*").From("keyphrase");
return DatabaseContext.Database.Fetch<Keyphrase>(query);
}
public Keyphrase GetById(int id)
{
var query = new Sql().Select("*").From("keyphrase").Where<Keyphrase>(x => x.Id == id);
return DatabaseContext.Database.Fetch<Keyphrase>(query).FirstOrDefault();
}
public Keyphrase PostSave(Keyphrase keyphrase)
{
if (keyphrase.Id > 0)
DatabaseContext.Database.Update(keyphrase);
else
DatabaseContext.Database.Save(keyphrase);
return keyphrase;
}
public int DeleteById(int id)
{
return DatabaseContext.Database.Delete<Keyphrase>(id);
}
}
Create the custom section views with angular controllers, which is the current architectual style in Umbraco 7.
It should be noted that Umbraco expects that your custom section components are put into the following structure App_Plugins//BackOffice/
We need a view to display and edit our keyphrase name, target phrase and url
<form name="keyphraseForm"
ng-controller="Keyphrase.KeyphraseEditController"
ng-show="loaded"
ng-submit="save(keyphrase)"
val-form-manager>
<umb-panel>
<umb-header>
<div class="span7">
<umb-content-name placeholder=""
ng-model="keyphrase.Name" />
</div>
<div class="span5">
<div class="btn-toolbar pull-right umb-btn-toolbar">
<umb-options-menu ng-show="currentNode"
current-node="currentNode"
current-section="{{currentSection}}">
</umb-options-menu>
</div>
</div>
</umb-header>
<div class="umb-panel-body umb-scrollable row-fluid">
<div class="tab-content form-horizontal" style="padding-bottom: 90px">
<div class="umb-pane">
<umb-control-group label="Target keyphrase" description="Keyphrase to be linked'">
<input type="text" class="umb-editor umb-textstring" ng-model="keyphrase.Phrase" required />
</umb-control-group>
<umb-control-group label="Keyphrase link" description="Internal or external url">
<p>{{keyphrase.Link}}</p>
<umb-link-picker ng-model="keyphrase.Link" required/>
</umb-control-group>
<div class="umb-tab-buttons" detect-fold>
<div class="btn-group">
<button type="submit" data-hotkey="ctrl+s" class="btn btn-success">
<localize key="buttons_save">Save</localize>
</button>
</div>
</div>
</div>
</div>
</div>
</umb-panel>
</form>
This utilises umbraco and angular markup to display data input fields dynamically and associate our view to an angular controller that interacts with our data layer
angular.module("umbraco").controller("Keyphrase.KeyphraseEditController",
function ($scope, $routeParams, keyphraseResource, notificationsService, navigationService) {
$scope.loaded = false;
if ($routeParams.id == -1) {
$scope.keyphrase = {};
$scope.loaded = true;
}
else {
//get a keyphrase id -> service
keyphraseResource.getById($routeParams.id).then(function (response) {
$scope.keyphrase = response.data;
$scope.loaded = true;
});
}
$scope.save = function (keyphrase) {
keyphraseResource.save(keyphrase).then(function (response) {
$scope.keyphrase = response.data;
$scope.keyphraseForm.$dirty = false;
navigationService.syncTree({ tree: 'KeyphraseTree', path: [-1, -1], forceReload: true });
notificationsService.success("Success", keyphrase.Name + " has been saved");
});
};
});
Then we need html and corresponding angular controller for the keyphrase delete behaviour
<div class="umb-pane" ng-controller="Keyphrase.KeyphraseDeleteController">
<p>
Are you sure you want to delete {{currentNode.name}} ?
</p>
<div>
<div class="umb-pane btn-toolbar umb-btn-toolbar">
<div class="control-group umb-control-group">
<a href="" class="btn btn-link" ng-click="cancelDelete()"
<localize key="general_cancel">Cancel</localize>
</a>
<a href="" class="btn btn-primary" ng-click="delete(currentNode.id)">
<localize key="general_ok">OK</localize>
</a>
</div>
</div>
</div>
</div>
Utilise Umbraco's linkpicker to allow a user to select an internal or external url.
We need html markup to launch the LinkPicker
<div>
<ul class="unstyled list-icons">
<li>
<i class="icon icon-add blue"></i>
<a href ng-click="openLinkPicker()" prevent-default>Select</a>
</li>
</ul>
</div>
And an associated directive js file that launches the link picker and posts the selected url back to the html view
angular.module("umbraco.directives")
.directive('umbLinkPicker', function (dialogService, entityResource) {
return {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/Utilities/umb-link-picker.html',
require: "ngModel",
link: function (scope, element, attr, ctrl) {
ctrl.$render = function () {
var val = parseInt(ctrl.$viewValue);
if (!isNaN(val) && angular.isNumber(val) && val > 0) {
entityResource.getById(val, "Content").then(function (item) {
scope.node = item;
});
}
};
scope.openLinkPicker = function () {
dialogService.linkPicker({ callback: populateLink });
}
scope.removeLink = function () {
scope.node = undefined;
updateModel(0);
}
function populateLink(item) {
scope.node = item;
updateModel(item.url);
}
function updateModel(id) {
ctrl.$setViewValue(id);
}
}
};
});
There is one final js file that allows us to send data across the wire, with everyone's favourite http verbs GET, POST(handles put too here too) and DELETE
angular.module("umbraco.resources")
.factory("keyphraseResource", function ($http) {
return {
getById: function (id) {
return $http.get("BackOffice/Api/KeyphraseApi/GetById?id=" + id);
},
save: function (keyphrase) {
return $http.post("BackOffice/Api/KeyphraseApi/PostSave", angular.toJson(keyphrase));
},
deleteById: function (id) {
return $http.delete("BackOffice/Api/KeyphraseApi/DeleteById?id=" + id);
}
};
});
In addition, we will need a package manifest to register our javascript behaviour
{
javascript: [
'~/App_Plugins/Utilities/BackOffice/KeyphraseTree/edit.controller.js',
'~/App_Plugins/Utilities/BackOffice/KeyphraseTree/delete.controller.js',
'~/App_Plugins/Utilities/keyphrase.resource.js',
'~/App_Plugins/Utilities/umbLinkPicker.directive.js'
]
}
Implement tweaks to allow the CMS portion of the solution to work correctly.
At this point we've almost got our custom section singing, but we just need to jump a couple more Umbraco hoops, namely
a) add a keyphrase event class that creates our keyphrase db table if it doesn't exist (see point 8)
b) fire up Umbraco and associate the new custom section to the target user (from the User menu)
c) alter the placeholder text for the custom section by searching for it in umbraco-->config-->en.xml and swapping out the placeholder text for 'Utilities'
Intercept target content fields of target datatypes when content is saved or published
The requirement I was given was to intercept the body content of a news article, so you'll need to create a document type in Umbraco that has, for example, a title field of type 'Textstring', and bodyContent field of type 'Richtext editor'.
You'll also want a, or many, keyphrase(s) to target, which should now be in a new Umbraco custom section, 'Utilities'
Here I've targeted the keyphrase 'technology news' to link to the bbc technology news site so that any time I write the phrase 'technology news' the href link will be inserted automatically.
This is obviously quite a simple example, but would be quite powerful if a user needed to link to certain repetitive legal documents, for example tax, property, due dilligence, for example, which could be hosted either externally or within the CMS itself. The href link will open an external resource in a new tab, and internal resource in the same window (we'll get to that in Point 9)
So, the principle of what we're trying to achieve is to intercept the Umbraco save event for a document and manipulate our rich text to insert our link. This is done as follows:
a) Establish a method (ContentServiceOnSaving) that will fire when a user clicks 'save', or 'publish and save'.
b) Target our desired content field to find our keyphrases.
c) Parse the target content html against our keyphrase collection to create our internal/external links.
NB: If you just want to get the custom section up and running, you only need the ApplicationStarted method to create the KeyPhrase table.
public class KeyphraseEvents : ApplicationEventHandler
{
private KeyphraseApiController _keyphraseApiController;
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
_keyphraseApiController = new KeyphraseApiController();
ContentService.Saving += ContentServiceOnSaving;
var db = applicationContext.DatabaseContext.Database;
if (!db.TableExist("keyphrase"))
{
db.CreateTable<Keyphrase>(false);
}
}
private void ContentServiceOnSaving(IContentService sender, SaveEventArgs<IContent> saveEventArgs)
{
var keyphrases = _keyphraseApiController.GetAll();
var keyphraseContentParser = new KeyphraseContentParser();
foreach (IContent content in saveEventArgs.SavedEntities)
{
if (content.ContentType.Alias.Equals("NewsArticle"))
{
var blogContent = content.GetValue<string>("bodyContent");
var parsedBodyText = keyphraseContentParser.ReplaceKeyphrasesWithLinks(blogContent, keyphrases);
content.SetValue("bodyContent", parsedBodyText);
}
}
}
}
The ContentServiceOnSaving method allows us to intercept any save event in Umbraco. Afterwhich we check our incoming content to see if it's of the type we're expecting - in this example 'NewsArticle' - and if it is, then target the 'bodyContent' section, parse this with our 'KeyphraseContentParser', and swap the current 'bodyContent' with the parsed 'bodyContent'.
Create a Keyphrase parser to swap keyphrases for internal/external links
public class KeyphraseContentParser
{
public string ReplaceKeyphrasesWithLinks(string htmlContent, IEnumerable<Keyphrase> keyphrases)
{
var parsedHtmlStringBuilder = new StringBuilder(htmlContent);
foreach (var keyphrase in keyphrases)
{
if (htmlContent.CaseContains(keyphrase.Phrase, StringComparison.OrdinalIgnoreCase))
{
var index = 0;
do
{
index = parsedHtmlStringBuilder.ToString()
.IndexOf(keyphrase.Phrase, index, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
var keyphraseSuffix = parsedHtmlStringBuilder.ToString(index, keyphrase.Phrase.Length + 4);
var keyPhraseFromContent = parsedHtmlStringBuilder.ToString(index, keyphrase.Phrase.Length);
var keyphraseTarget = "_blank";
if (keyphrase.Link.StartsWith("/"))
{
keyphraseTarget = "_self";
}
var keyphraseLinkReplacement = String.Format("<a href='{0}' target='{1}'>{2}</a>",
keyphrase.Link, keyphraseTarget, keyPhraseFromContent);
if (!keyphraseSuffix.Equals(String.Format("{0}</a>", keyPhraseFromContent)))
{
parsedHtmlStringBuilder.Remove(index, keyPhraseFromContent.Length);
parsedHtmlStringBuilder.Insert(index, keyphraseLinkReplacement);
index += keyphraseLinkReplacement.Length;
}
else
{
var previousStartBracket = parsedHtmlStringBuilder.ToString().LastIndexOf("<a", index);
var nextEndBracket = parsedHtmlStringBuilder.ToString().IndexOf("a>", index);
parsedHtmlStringBuilder.Remove(previousStartBracket, (nextEndBracket - (previousStartBracket - 2)));
parsedHtmlStringBuilder.Insert(previousStartBracket, keyphraseLinkReplacement);
index = previousStartBracket + keyphraseLinkReplacement.Length;
}
}
} while (index != -1);
}
}
return parsedHtmlStringBuilder.ToString();
}
}
It's probably easiest to step through the above code, but fundamentally the parser has to:
a) find and wrap all keyphrases, ignoring case, with a link to an internal CMS, or external web resource.
b) handle an already parsed html string to both leave links in place and not create nested links.
c) allow CMS keyphrase changes to be updated in the parsed html string.
The blog of this, as well as the github code can be found from the links in the previous post.
Ok, so after finding some excellent helper posts and digging around I came up with the solution, which I've written about here:
http://frazzledcircuits.blogspot.co.uk/2015/03/umbraco-7-automatic-keyphrase.html
And the source code is here:
https://github.com/AdTarling/UmbracoSandbox