umbracoNaviHide not working in Where statement - asp.net-mvc-3

Trying to get children of a given document type, with umbracoNavihide not set to false:
The following produces correct output.
#foreach (var child in root.Children.Where("ContentTypeAlias == \"DocumentTypehere\""))
{
if (child.umbracoNaviHide == "False")
{
continue;
}
<li>#child.Name</li>
}
This does not:
#foreach (var child in root.Children.Where("umbracoNaviHide == #0 && ContentTypeAlias == \"DocumentTypehere\"","False"))
{
<li>#child.Name</li>
}

umbracoNaviHide is not supported in Umbraco 5 as per the words of Niels Hartvig:
While these special aliases does [sic] [recte: do] a great job and are super easy to use
(albeit totally impossible to discover if you don't stumble across
docs that mention their usage), the problem with these are that
they're 'magic' strings which really is a mess (read: They're hacks
inside the core).
So they won't come back in v5 in the form we know from v4.
So, besides the Linq imitations being somewhat broken anyway, the short answer is that this (either form) shouldn't work (nor should Athul's answer).
The long answer is that you could use this property (and others like it) only if you explicitly support it as part of your Document Type. There is a feature request, though, asking for the 'built-in' umbraco... properties here should you care to follow and support it.
I would personally ask that you don't, however; as using these properties and relying on them are problematic (not least for the point mentioned by Neils himself). Make your own, dedicated properties that are aptly aliased for their task.

you can simply do it like
#foreach (var child in root.Children.Where("umbracoNaviHide != true && NodeTypeAlias == \"DocumentTypehere\" ")
{
<li>#child.Name</li>
}

You can just write for your check on umbracoNaviHide:
if (!child.umbracoNaviHide)
{
continue;
}
<li>#child.Name</li>

Just to add another approach - a few of the existing answers did not work for me - you can try this. Works for me in Umbraco 4.11
#foreach (var child in root.Children.Where(child => child.GetPropertyValue("umbracoNaviHide") == "0"))
{
..
}

Related

How can I sort child nodes by property value in Scala.js?

The problem is to sort all child divs of a root node according to their top CSS property.
Here is my code:
val elements = global.document.getElementById("root").childNodes.asInstanceOf[dom.NodeList]
val clones = (for (i <- (0 to (elements.length - 1)) if (elements(i).isInstanceOf[dom.raw.HTMLDivElement])) yield {
val clone = elements(i).cloneNode(true)
val style = clone.attributes.getNamedItem("style").value
val parts = style.split("top: ")
val parts2 = parts(1).split("px")
val px = parts2(0).toDouble
Tuple2[dom.Node, Double](clone, px)
}).toList
val sorted = clones.sortWith((a, b) => a._2 > b._2)
global.document.getElementById("root").innerHTML = ""
for (e <- sorted) {
global.document.getElementById("root").appendChild(e._1)
}
I'm new to Scala.js and it took quite an effort to come up with this solution. It compiles and seems to work, however I'm not sure how legitimate it is.
For example I can only get the top property of the node in a very complicated way. Also I suspect that for deleting all child nodes global.document.getElementById("root").innerHTML = "" is a backdoor way. I'm not sure if this sorting can be done in place without creating clones. I welcome any suggestions for improvement and I hope that some beginner out there may find even this code useful.
Various suggestions, some pertaining to Scala and some to the underlying browser environment:
First, jQuery (actual JavaScript library) (Scala.js facade) is your friend. Trying to do anything with the raw DOM is a pain in the ass, and I don't recommend it for anything but the simplest toy applications. (This has nothing to do with Scala.js, mind -- that's just the reality of working in the browser, and is all true of JavaScript as well.)
Using jQuery, getting the elements is just:
val elements = $("root").children
Second, essentially nobody loops using indexes in Scala like that -- it's legal, but extremely rare. Instead, you get each element directly in the for. And you can stick the value assignments right into the for itself, keeping the yield clause clean.
jQuery lets you get at CSS properties directly. (Although I think you still have to parse out the "px".) Again, everything is much harder if you try to use the raw DOM functions.
And it's very rare to spell out Tuple2 -- you just use parens for a tuple. Putting it all together, it would look something like this:
for {
element <- elements
if (element.isInstanceOf[dom.raw.HTMLDivElement])
clone = element.clone()
top = clone.css("top")
px = top.dropRight(2).toDouble
}
yield (clone, px)
Mind, I haven't actually tried out the above code -- there are probably some bugs -- but that's more like what idiomatic Scala.js + jQuery code would look like, and is worth considering as a starting point.

How to match a enum value with some enum values using linq

I want to know what could be the shortest linq query instead of following if statement.
public enum ErrorMessage { Error1=1, Error2=2, Error3=3, Error4=4 }
ErrorMessage error = ErrorMessage.Error4;
if (error == ErrorMessage.Error1 || error == ErrorMessage.Error2)
{
//do something
}
Linq will make this code complicated,
code you provide is readable, fast and maintainable more than Linq will be
You could use
if (new [] {ErrorMessage.Error1, ErrorMessage.Error2}.Contains(error))
{
//do something
}
or
var bad_errors = new [] {ErrorMessage.Error1, ErrorMessage.Error2};
if (bad_errors.Contains(error))
{
//do something
}
if a single call to an extension method is LINQ enough for you.
I guess to most C# developers such a pattern seems strange (and it totally is), but if you're already working on a dynamically created list of errors you want to check against...
Otherwise, stick with if.
It actually works nicer in languages with less boilerplate, e.g. Python, where this pattern is commonly used and looks a lot nicer:
if error in (Error1, Error2):
# do something

Code style = when to use comparision value first in 'if' statement

I have seen a few examples lately where if statements are written as follows:
if ( false === $testValue) {
//do something
}
as opposed to the more general:
if ($testValue === false) {
//do something
}
Clearly it is a style issue and it has no bearing on the result, but my question is can anyone say why anyone would use this style and where it comes from.
The code examples I have seen with this style have been from seriously good programmers so I dont think its a necessarily a bad style.
It's so that if you accidentally type = (assignment) instead of == (comparison), the compiler complains that the constant cannot be assigned to.
Compare:
if (false = $testValue) {
// does not compile, cannot assign to constant
}
to:
if ($testValue = false) {
// assigns false to $testValue, never evaluates to true
}
The former doesn't compile, the latter does and has a bug.
I used to see checks like this in C and C++:
if (null == x)
The reason for it was that mistyping = for == would make no sense to the compiler, because assignment to null or a constant would be an error.
In something like C++ (I'm not sure what language you're using there with the ===) if you have
if(x == 2), and you write it if(x=2) (so the value is assigned an not checked for equality) this doesn't cause a compiler error (most compilers today will warn you about it), but if you write if (2=x) instead of if(2==x) that will defintely produce an error.
It's to prevent assignment when comparison was intended.
I don't like this style myself but I see it a lot from our Indian developers so maybe it's being taught over there.
It's completely unnecessary if a '0 warnings, 0 errors' build policy was adhered to, and anyone who uses this style is not likely to provide clean building code.

Sorting CouchDB Views By Value

I'm testing out CouchDB to see how it could handle logging some search results. What I'd like to do is produce a view where I can produce the top queries from the results. At the moment I have something like this:
Example document portion
{
"query": "+dangerous +dogs",
"hits": "123"
}
Map function
(Not exactly what I need/want but it's good enough for testing)
function(doc) {
if (doc.query) {
var split = doc.query.split(" ");
for (var i in split) {
emit(split[i], 1);
}
}
}
Reduce Function
function (key, values, rereduce) {
return sum(values);
}
Now this will get me results in a format where a query term is the key and the count for that term on the right, which is great. But I'd like it ordered by the value, not the key. From the sounds of it, this is not yet possible with CouchDB.
So does anyone have any ideas of how I can get a view where I have an ordered version of the query terms & their related counts? I'm very new to CouchDB and I just can't think of how I'd write the functions needed.
It is true that there is no dead-simple answer. There are several patterns however.
http://wiki.apache.org/couchdb/View_Snippets#Retrieve_the_top_N_tags. I do not personally like this because they acknowledge that it is a brittle solution, and the code is not relaxing-looking.
Avi's answer, which is to sort in-memory in your application.
couchdb-lucene which it seems everybody finds themselves needing eventually!
What I like is what Chris said in Avi's quote. Relax. In CouchDB, databases are lightweight and excel at giving you a unique perspective of your data. These days, the buzz is all about filtered replication which is all about slicing out subsets of your data to put in a separate DB.
Anyway, the basics are simple. You take your .rows from the view output and you insert it into a separate DB which simply emits keyed on the count. An additional trick is to write a very simple _list function. Lists "render" the raw couch output into different formats. Your _list function should output
{ "docs":
[ {..view row1...},
{..view row2...},
{..etc...}
]
}
What that will do is format the view output exactly the way the _bulk_docs API requires it. Now you can pipe curl directly into another curl:
curl host:5984/db/_design/myapp/_list/bulkdocs_formatter/query_popularity \
| curl -X POST host:5984/popularity_sorter/_design/myapp/_view/by_count
In fact, if your list function can handle all the docs, you may just have it sort them itself and return them to the client sorted.
This came up on the CouchDB-user mailing list, and Chris Anderson, one of the primary developers, wrote:
This is a common request, but not supported directly by CouchDB's
views -- to do this you'll need to copy the group-reduce query to
another database, and build a view to sort by value.
This is a tradeoff we make in favor of dynamic range queries and
incremental indexes.
I needed to do this recently as well, and I ended up doing it in my app tier. This is easy to do in JavaScript:
db.view('mydesigndoc', 'myview', {'group':true}, function(err, data) {
if (err) throw new Error(JSON.stringify(err));
data.rows.sort(function(a, b) {
return a.value - b.value;
});
data.rows.reverse(); // optional, depending on your needs
// do something with the data…
});
This example runs in Node.js and uses node-couchdb, but it could easily be adapted to run in a browser or another JavaScript environment. And of course the concept is portable to any programming language/environment.
HTH!
This is an old question but I feel it still deserves a decent answer (I spent at least 20 minutes on searching for the correct answer...)
I disapprove of the other suggestions in the answers here and feel that they are unsatisfactory. Especially I don't like the suggestion to sort the rows in the applicative layer, as it doesn't scale well and doesn't deal with a case where you need to limit the result set in the DB.
The better approach that I came across is suggested in this thread and it posits that if you need to sort the values in the query you should add them into the key set and then query the key using a range - specifying a desired key and loosening the value range. For example if your key is composed of country, state and city:
emit([doc.address.country,doc.address.state, doc.address.city], doc);
Then you query just the country and get free sorting on the rest of the key components:
startkey=["US"]&endkey=["US",{}]
In case you also need to reverse the order - note that simple defining descending: true will not suffice. You actually need to reverse the start and end key order, i.e.:
startkey=["US",{}]&endkey=["US"]
See more reference at this great source.
I'm unsure about the 1 you have as your returned result, but I'm positive this should do the trick:
emit([doc.hits, split[i]], 1);
The rules of sorting are defined in the docs.
Based on Avi's answer, I came up with this Couchdb list function that worked for my needs, which is simply a report of most-popular events (key=event name, value=attendees).
ddoc.lists.eventPopularity = function(req, res) {
start({ headers : { "Content-type" : "text/plain" } });
var data = []
while(row = getRow()) {
data.push(row);
}
data.sort(function(a, b){
return a.value - b.value;
}).reverse();
for(i in data) {
send(data[i].value + ': ' + data[i].key + "\n");
}
}
For reference, here's the corresponding view function:
ddoc.views.eventPopularity = {
map : function(doc) {
if(doc.type == 'user') {
for(i in doc.events) {
emit(doc.events[i].event_name, 1);
}
}
},
reduce : '_count'
}
And the output of the list function (snipped):
165: Design-Driven Innovation: How Designers Facilitate the Dialog
165: Are Your Customers a Crowd or a Community?
164: Social Media Mythbusters
163: Don't Be Afraid Of Creativity! Anything Can Happen
159: Do Agencies Need to Think Like Software Companies?
158: Customer Experience: Future Trends & Insights
156: The Accidental Writer: Great Web Copy for Everyone
155: Why Everything is Amazing But Nobody is Happy
Every solution above will break couchdb performance I think. I am very new to this database. As I know couchdb views prepare results before it's being queried. It seems we need to prepare results manually. For example each search term will reside in database with hit counts. And when somebody searches, its search terms will be looked up and increments hit count. When we want to see search term popularity, it will emit (hitcount, searchterm) pair.
The Link Retrieve_the_top_N_tags seems to be broken, but I found another solution here.
Quoting the dev who wrote that solution:
rather than returning the results keyed by the tag in the map step, I would emit every occurrence of every tag instead. Then in the reduce step, I would calculate the aggregation values grouped by tag using a hash, transform it into an array, sort it, and choose the top 3.
As stated in the comments, the only problem would be in case of a long tail:
Problem is that you have to be careful with the number of tags you obtain; if the result is bigger than 500 bytes, you'll have couchdb complaining about it, since "reduce has to effectively reduce". 3 or 6 or even 20 tags shouldn't be a problem, though.
It worked perfectly for me, check the link to see the code !

How much information hiding is necessary when doing code refactoring?

How much information hiding is necessary? I have boilerplate code before I delete a record, it looks like this:
public override void OrderProcessing_Delete(Dictionary<string, object> pkColumns)
{
var c = Connect();
using (var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM orders WHERE order_id = :_order_id", c)
{ Parameters = { {"_order_id", pkColumns["order_id"]} } } )
{
var count = (long)cmd.ExecuteScalar();
// deletion's boilerplate code...
if (count == 0) throw new RecordNotFoundException();
else if (count > 1) throw new DatabaseStructureChangedException();
// ...boiler plate code
}
// deleting of table(s) goes here...
}
NOTE: boilerplate code is code-generated, including the "using (var cmd = new NpgsqlCommand( ... )"
But I'm seriously thinking to refactor the boiler plate code, I wanted a more succint code. This is how I envision to refactor the code (made nicer with extension method (not the sole reason ;))
using (var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM orders WHERE order_id = :_order_id", c)
{ Parameters = { {"_order_id", pkColumns["order_id"]} } } )
{
cmd.VerifyDeletion(); // [EDIT: was ExecuteWithVerification before]
}
I wanted the executescalar and the boilerplate code to goes inside the extension method.
For my code above, does it warrants code refactoring / information hiding? Is my refactored operation looks too opaque?
I would say that your refactor is extremely good, if your new single line of code replaces a handful of lines of code in many places in your program. Especially since the functionality is going to be the same in all of those places.
The programmer coming after you and looking at your code will simply look at the definition of the extension method to find out what it does, and now he knows that this code is defined in one place, so there is no possibility of it differing from place to place.
Try it if you must, but my feeling is it's not about succinctness but whether or not you want to enforce the behavior every time or most of the time. And by extension, if the verify-condition changes that it would likely change across the board.
Basically, reducing a small chunk of boiler-plate code doesn't necessarily make things more succinct; it's just one more bit of abstractness the developer has to wade through and understand.
As a developer, I'd have no idea what "ExecuteWithVerify" means. What exactly are we verifying? I'd have to look it up and remember it. But with the boiler-plate code, I can look at the code and understand exactly what's going on.
And by NOT reducing it to a separate method I can also tune the boiler-plate code for cases where exceptions need to be thrown for differing conditions.
It's not information-hiding when you extract or refactor your code. It's only information-hiding when you start restricting access to your extension definition after refactoring.
"new" operator within a Class (except for the Constructor) should be Avoided at all costs. This is what you need to refactor here.

Resources