Umbraco count active content pages - umbraco

I would like to get a count of pages in nodes in an Umbraco site with output something like this:
Root (9 subnodes)
First Folder (4 subnodes)
document 1
document 2
document 3
document 4
Second Folder (3 subnodes)
document 1
document 2
document 3
Basically I am trying to see how much active content there is in a given site and come up with a way to divide the work. Is there a reasonable way to get this information?

This worked for me:
Descendants.cs in App_Code folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.presentation;
using umbraco.presentation.nodeFactory;
public static class ExtensionMethods
{
public static IEnumerable<Node> AllDescendants(this Node node)
{
foreach (Node child in node.Children)
{
yield return child;
foreach (Node grandChild in child.AllDescendants())
yield return grandChild;
}
}
}
Razor View
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using umbraco.presentation.nodeFactory;
#{
Layout = "";
}
#functions{
public string CreateSitemap()
{
var temp = "<ul class='collapsibleList'>" + sitemap(-1) + "</ul>" + Environment.NewLine;
return temp;
}
public string sitemap(int nodeID)
{
var rootNode = new umbraco.presentation.nodeFactory.Node(nodeID);
var sitemapstring = "<li>" + rootNode.Name + " (" + rootNode.AllDescendants().Count() + ") <span style='font-size:9px'>" + rootNode.NodeTypeAlias + "</span></li>" + Environment.NewLine;
if (rootNode.Children.Count > 0)
{
sitemapstring += "<ul>" + Environment.NewLine;
sitemapstring = rootNode.Children.Cast<Node>().Aggregate(sitemapstring, (current, node) => current + sitemap(node.Id));
sitemapstring += "</ul>" + Environment.NewLine;
}
return sitemapstring;
}
}
<body>
#Html.Raw(CreateSitemap())
</body>

Related

How to get Page<RegisteredClient> in Spring Authorization Server?

I want to add or update RegisteredClient use my custom controller,so first need to show the RegisteredClient's list.
so I want to get Page use RegisteredClientRepository.findAll(Pageable pageable),but RegisteredClientRepositor have no findAll method ,just have findById,findByClientId
How can I get The RegisteredClient's list?
finally I use jdbcTemplate to query
#Component
public class CustomRegisteredClientRepo {
#Autowired
private JdbcTemplate jdbcTemplate;
public Page<CustomClient> findAll(Pageable page) {
Order order = !page.getSort().isEmpty() ? page.getSort().toList().get(0) : Order.by("id");
SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT * FROM oauth2_registered_client ORDER BY "
+ order.getProperty() + " " + order.getDirection().name() + " LIMIT " + page.getPageSize()
+ " OFFSET " + page.getOffset());
long count =
jdbcTemplate.queryForObject("select count(*) from oauth2_registered_client", long.class);
List<CustomClient> list = new ArrayList<CustomClient>();
while (rs.next()) {
CustomClient client = new CustomClient();
client.setId(rs.getString("id"));
client.setClientId(rs.getString("client_id"));
list.add(client);
}
return new PageImpl<CustomClient>(list, page, count);
}
}

Trying to pass a json string into ActionResult view from ActionAsPdf using rotativa

So I have a controller that builds a pdf using several views, each view builds a specific section of the pdf.
I am passing pdfdata which is a json string that contains all the data the views need into ActionAsPdf like this
private byte[] CreateCertificatePart(CertificatePart part, string pdfdata)
{
var customSwitches = string.Format(
"--print-media-type " +
"--margin-top 10mm " +
"--margin-bottom 10mm " +
"--margin-left 10mm " +
"--margin-right 10mm " +
"--encoding utf-8 " +
"--minimum-font-size 11 " +
"--zoom 1.0 " +
"--disable-smart-shrinking"
);
var viewname = part.ToString();
var pdfResult = new ActionAsPdf(viewname,pdfdata) { CustomSwitches = customSwitches };
var pdfBytes = pdfResult.BuildFile(ControllerContext);
return pdfBytes;
}
Then the Action result calls the razor view which gets converted to pdf bytes by the ActionAsPdf.
public ActionResult CertificateBody(string pdfdata)
{
var data = new PdfData();
try
{
data = JsonConvert.DeserializeObject<PdfData>(pdfdata);
return View(data.PdfBodyName, data.CertModel);
}
catch (Exception ex)
{
AppInsightLog.LogError(ex, $"NewCertificateBody{data.CertModel.Schedule.QuoteReference}");
return new HttpStatusCodeResult(400, "NewCertificateBody");
}
}
The problem is pdfData is always null! this was a very long json string in CreateCertificatePart. I tried passing a model originally but that was also null, which is why I am trying to pass a string instead thinking that would be ok.
Its ok if I pass a very simple string like "hello" or an integer, so I could pass an ID but I do not want to make a database call in the action result method.. because then I will make the same call several times.
CreateCertificatePart is recursive but all the different views need the same model which is PdfData.
Thanks

Alternative to Deltaspike Multi-Window Handling in Seam 3 Applikation

I have problems with the Multi-Window Handling in my appliacation.
I currently using Conversation Scope to enable multi window / tab handling but in case the user opens a link (button) in a new tab the conversation is shared between the old and new tab.
Apache Deltaspike has a solution for that (http://deltaspike.apache.org/documentation/#_module_overview) but I already using Seam 3 (and JSF 2.1) and don't want to migrate to Deltaspike.
So I'm searching for an alternative solution without Deltaspike or is it possible to use Deltaspike AND Seam 3?
I build a solution with p:remoteCommand and this answer: In javascript, how can I uniquely identify one browser window from another which are under the same cookiedbased sessionId
I added this JS to my template which creates a unique id for each browswer tab an stores it in the window.name. Then it calls a p:remoteCommand to check the guid:
$(window).load(function() {
// ----------------------
var GUID = function() {
// ------------------
var S4 = function() {
return (Math.floor(Math.random() * 0x10000 /* 65536 */
).toString(16));
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
if (!window.name.match(/^GUID-/)) {
window.name = "GUID-" + GUID();
}
if ($('#guid_form\\:server_guid').text().length == 0 ||
$('#guid_form\\:server_guid').text() != window.name) {
checkGuid([{name:'guid', value:window.name}]);
}
})
Added a Primefaces remoteCommand to my template which is called by the script above.
<h:form id="guid_form">
<h:outputText value="#{checkTabAction.guid}" id="server_guid"/>
<p:remoteCommand name="checkGuid" actionListener="#{checkTabAction.checkGuid}" process="#this" partialSubmit="true" />
</h:form>
And added a check action which validateds the current browser tab / window by comparing the guid's:
#ConversationScoped
#Named(value = "checkTabAction")
public class CheckTabAction implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private Logger log;
private String guid = null;
public void checkGuid() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String guid = params.get("guid").toString();
if (this.guid == null) {
this.guid = guid;
}
if (!StringUtils.equals(this.guid, guid)) {
log.info("New tab detected!");
throw new NonexistentConversationException("New tab detected!");
}
}
public String getGuid() {
return guid;
}
}

Rerender/update a JSF 2.0 custom component using a primefaces command button does not work

Thanks in advance for your attention.
I've created a JSF 2.0 custom component to render Google GeoCharts. So, the renderer just writes some javascript and a div at the end.
The component works fine doing that. But my requirement is that the GeoChart should change its values using an ajax request. To do that, i'm using a primefaces command button putting in its attribute "update" the id of the geoChart.
The problem is that the GeoChart is not being updated when the comand button is clicked.
I'm using a maven archetype (myfaces-archetype-jsfcomponents20) allowing the automatic generation of some configuration files. So, I just need to write to classes and annotations. Those classes are the UIComponent and the Renderer.
I'm running this code in GlassFish 3.1 and Mojarra 2.1.6
The code of those classes:
UIComponent:
#JSFComponent(
name = "processum:geochart",
clazz = "org.processum.component.gchart.GoogleChart",
tagClass = "org.processum.component.gchart.GoogleChartTag")
abstract class AbstractGoogleChart extends UIComponentBase {
public static final String COMPONENT_TYPE = "org.processum.GoogleChart";
public static final String DEFAULT_RENDERER_TYPE = "org.processum.GoogleChartRenderer";
public static final String COMPONENT_FAMILY = "javax.faces.Output";
/**
*
* GoogleChartModel
*/
#JSFProperty
public abstract GoogleGeoChartModel getModel();
}
Renderer:
#JSFRenderer(
renderKitId = "HTML_BASIC",
family = "javax.faces.Output",
type = "org.processum.GoogleChartRenderer")
public class GoogleChartRenderer extends Renderer {
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
GoogleChart chart = (GoogleChart) component;
String divId = (String) component.getClientId() + "chartDiv";
GoogleGeoChartModel model = chart.getModel();
ResponseWriter writer = context.getResponseWriter();
writer.write("<script type='text/javascript'>"
+ "google.load('visualization', '1', {'packages': ['geochart']});"
+ "google.setOnLoadCallback(initGeoMap);"
+ "function initGeoMap() {"
+ "var data = google.visualization.arrayToDataTable(["
+ "[");
StringBuilder data = new StringBuilder();
for (String header : model.getHeaders()) {
data.append("\'").append(header).append("\'").append(",");
}
data.deleteCharAt(data.length() - 1).append("],");
for (String[] value : model.getValues()) {
data.append("[");
for (int i = 0; i < value.length; i++) {
if (i == 0) {
data.append("\'").append(value[i]).append("\'");
} else {
data.append(value[i]);
}
data.append(",");
}
data.deleteCharAt(data.length() - 1).append("],");
}
data.deleteCharAt(data.length() - 1);
writer.write(data.toString());
writer.write("]);");
writer.write("var options = {"
+ "region: 'CO',"
+ "displayMode: 'markers'"
+ "};"
+ "var chart = new google.visualization.GeoChart(document.getElementById(\'" + divId + "\'));"
+ "chart.draw(data, options);"
+ "};"
+ "</script>"
+ "<div id=\"" + divId + "\"/>");
}
}
XHTML:
<h:form>
<div id="anotherContent" style="width: 900px; height: 500px;">
<h:panelGroup id="chartCont" layout="block">
<processum:geochart id="chart" model="#{chartBackBean.model}"/>
</h:panelGroup>
</div>
<p:commandButton id="change" value="Cambio" actionListener="#{chartBackBean.change}" update="chart"/>
</h:form>
Some debugging:
The ajax request is triggered adequately. The managed bean updates the GoogleGeoChartModel with new values.
Next, the control flow goes to the Renderer which "encodes" the new values of the chart (that means that the encondeEnd is called again). But, this new "enconding" is not painted in the browser.
The html has two JSF components. My custom component and a h:panelGroup. If in the "update" attribute on primefaces button I put the id of the chart's div and then I trigger the ajax request, the chart does not change. But instead I put the id of the h:panelGroup, the div of the chart disappears.

Create User by profession - How to Populate/Submit/Validate form?

I am trying to create user by registration form which contains dropdown for profession in ASP.NET MVC
Eg. Individual, professional, manager etc.
some fields are common like name & Last Name...
some fields are unique by profession...
how do i program it with ajax.
Thanks
I do this sort of thing by creating a SelectList in a controller and passing it to the view as part of a view model. Then in the view, I have the option of doing something when the SelectedValue changes, or simply returning the value of the dropdown when something else triggers a call to a controller.
Controller code:
int count = 0;
List<string> YearList = new List<string>();
for (int i = 2000; i < (DateTime.Now.Year + 6); i += 4)
{
YearList.Add(i.ToString());
if (i < iyear)
count++;
}
var q = from c in doc.Descendants("candidate")
select new can_sw_model
{
name = c.Attribute("name").Value,
office = c.Parent.Attribute("name").Value.ToUpper(),
party = c.Attribute("party").Value,
};
can_sw_view model = new can_sw_view()
{
YearList = new SelectList(YearList),
value = YearList[count],
model = q,
};
return View(model);
View code:
<script type="text/javascript">
$(document).ready(function() {
$('#YearList').val('<%= Model.value %>');
$('#YearList').change(function(event) {
window.location.replace('<%= ResolveUrl("~/Candidate/sw_candidates") %>' + "?year=" + $('#YearList').val());
});
});
function pdfclick() {
var grid = $("#grid1").data("tGrid");
window.location.replace('<%= ResolveUrl("~/Candidate/pdf") %>' + "?year=" + $('#YearList').val() + "&tab=statewide" +
"&page=" + grid.currentPage + "&orderBy=" + grid.orderBy + "&groupBy=" + grid.groupBy + "&filterBy=" + grid.filterBy);
}
</script>
I hope this helps!
Bob

Resources