I just bought a book on ASP.NET MVC With Razor View Engine. There is a subsection called Usage of # Operator and this subsection title makes me ... well, uncomfortable.
Is # inside the razor view engine called operator?
UPDATE
I guess my question is not so clear. I want to know if # is an operator inside the razor view engine. For example, < > = != >= => these are called as operator inside C# language. Is it same for # inside Razor view engine?
I think the reason for you discomfort is that the # token (when talking about it from a parsing perspective, though the word character should also do) is overloaded to indicate a number of different situations. Let's examine what those are:
Write a value to the output:
#this.Value
Indicate a code block transition:
#{
var foo = 1;
foo += 1;
}
Indicate a code statement transition:
<div>
#if(foo) {
// code
}
</div>
Indicate an escape to markup till the end of the line
#if(foo) {
foo = false;
#: value printed to output
}
Indicate directive statements:
#inherits MyCustomBaseType
Indicate special code blocks:
#section Foo {
<div />
}
#helper Bar(int param) {
param += 1;
}
Delimit comment blocks:
#*
This is a comment
*#
Escape the # character:
Email me at myemail##example.com
In my opinion only the first usage can be considered as an operator. The operand (i.e. everything else that follows the # up to but excluding the first markup-significant whitespace character) is passed as the parameter to the Write() method. All other usages don't have any clearly identifiable operands or require additional tokens (the * in the comment block, etc) to be indentified.
According to the official pages on Razor, you can find one example here, it does not seem that this is called an operator.
From the linked page:
You add code to a page using the # character
(my emphasis)
I also found numerous other pages on that same site, all referring it to just the "# character", so in that sense it isn't considered an operator.
<opinion>
However, if you read on Wikipedia on the topic of operators, then:
Syntactically operators usually contrast to functions. In most languages, functions may be seen as a special form of prefix operator with fixed precedence level and associativity, often with compulsory parentheses e.g. Func(a) (or (Func a) in LISP). Most languages support programmer-defined functions, but cannot really claim to support programmer-defined operators, unless they have more than prefix notation and more than a single precedence level. Semantically operators can be seen as special form of function with different calling notation and a limited number of parameters (usually 1 or 2).
(again, my emphasis)
Then I would argue that # is in fact an operator. It is a symbol with a specific meaning, and you could argue that you're "escaping out of the surrounding context to do something else", sort of like a function call.
In other words, while the word operator does not appear in the website articles I've seen so far, I would consider it to be an operator nonetheless.
</opinion>
Hmm, are you referring to the Fonts and Colors section of the Tools > Options dialog in Visual Studio? If so, no it isn't an Operator, it's "HTML Server-Side Script". The "functions", "section" and other razor-specific keywords are also this color.
Otherwise, yes it is an operator from a technical description. I'm not entirely sure what other distinction you are looking for.
No, the # character is not used as an operator. It's only the choise of that author to call it so.
For example, in the blog post introducing Razor it's not described as an operator anywhere.
There doesn't seem to be an official or de-facto term for it yet. Personally I would call it a tag, as it's used in the markup code along with other tags, and it's used as a replacement for the <% %> script tag.
I guess that it's not really incorrect to call it an operator, but it's not commonly used. As the razor tag contains C# or VB code which also can contain operators, it can get confusing.
The # character starts inline expressions, single statement blocks, and multi-statement blocks.
On Scott Gu's blog, he doesn't refer to it as an operator but there are lots of other developers who do. Personally, I don't see this as an operator but more of an identifier.
As far as I know are symbols like >, != and && called equality, relational or conditional operators. The # symbol does not seem to fit in any of those groups so I must say, no, it cannot be called an operator. On the other hand however, it does indicate that 'some operation' is performed which makes it rather likely to be called an operator.
The # symbol is not an operator, it is an indicator which indicates that a razor statement begins.
It is comparable with <?php ?> in php. This indicates to the compiler/interpreter where your code is
e.g.
#Html.ActionLink(...)
a #(...) gives you the oportunitie to do some coding int there
e.g
#(
int a = 0;
int b = 4;
int c = a + b;
)
I hope this helps you on the way
Related
I am using Handlebars templates. If I want to insert a variable in an hbs file, I add it as {{var_name}}.
The issue is, I have a large object with its keys taking formats similar to:
{
"stats.name":"John",
"stats.performance.day":123,
"stats.performance.month":4567,
"company":"My LLC"
}
If I try to add these to the Handlebars file as {{company}}, {{stats.name}}, {{stats.performance.day}}, {{stats.performance.month}} then only the {{company}} will be displayed. All other values come out blank, I assume because "." is a special character in Handlebars.
My question is, is there a way to override this, or do I actually need to iterate through this object and change every "." to a "_" or something before passing it to Handlebars to make it work?
I would recommend renaming your properties. Dot Notation is one of the two ways to access object properties in JavaScript. Typical code would look like: obj.prop. If your object's keys are not valid identifiers, then you must use Bracket Notation: obj['my-prop']. Since a dot is a property accessor, it is very unusual to see one in a property name. If I were to come across code written as obj['stats.performance.date'], I would assume it was a mistake and that obj.stats.performance.date was intended.
With that said, Handlebars does support referencing properties that are not valid identifiers. This is called "segment-literal-notation", and it is as simple as wrapping square brackets around your identifier:
{{[stats.performance.day]}}
The documentation also states that:
JavaScript-style strings, " and ', may also be used vs. [ pairs.
So the following alternatives are valid:
{{"stats.performance.day"}}
{{'stats.performance.day'}}
CSS3 added the <column-token> operator as follow:
<column-token>: ||
It also says:
<column-token> has been added, to keep Selectors parsing in single-token lookahead.
So, is that just an artifact of the lexer, or is that an actual operator used for something I do not know about yet?
CSS level 4 does in fact have a column operator (used to select table cells of a column).
No idea if that's related and the token was added to CSS3 to be forward-compatile - it would be strange, but then the naming does not sound coincidental. The argument for the new token was indeed parsing convenience:
I just added a COLUMN token to the Syntax draft, matching "||". It's
needed for Selectors, so it can maintain LL(1). (Otherwise, seeing
"*" followed by "|" is ambiguous until you look at the next token.)
Which I admit I don't quite understand. What else could *| be interpreted as, even in CSS4? There is no other valid use of | in a selector (except inside an attribute matcher, but there there is no valid use for ||). CSS4 Values uses both *, | and || but that's not the spec the email was referring to.
This is not strictly a CSS3 feature, column-token is just one of many tokens used to parse currently interpreted CSS stylesheet by CSS parser. So it has no use for you unless you're implementing a CSS parser.
We have a simple search interface which calls the search:search($query-text) function. Is there a syntax to include control for wildcarding, stemming and case sensitivity within the single text string that the function accepts? I haven't been able to find anything in the MarkLogic docs.
See the $options parameter and the <term> and <term-option> constraint at https://docs.marklogic.com/search:search . There is a guide at http://developer.marklogic.com/learn/2009-07-search-api-walkthrough
and some details http://developer.marklogic.com/learn/2009-07-search-api-walkthrough#ndbba3437f320a4a4
I don't know of any existing syntax for those options, aside from the built-in behavior of turning on wildcards when a term contains '*' or '?' and turning on case-sensitivity when the term contains capital letters.
You could develop a syntax. Implementing it might involve a custom parser along the lines of https://github.com/mblakele/xqysp then feeding the resulting cts:query into search:resolve.
Piggybacking on Eric Bloch's answer... you can always dynamically construct your node based on input in the user interface.
For example, I often do this in order to separate the facet selection portion of the query from the text search portion and put the facet selection query in the additional-query element in the options node.
I have different cases:
No spaces allowed at all
No spaces allowed at the beginning or the end of the string only
..A little question, is it good to check (to validate) the input for spaces through the RegEx of the RegularExpressionValidator ?
The \S escape sequence matches anything that isn't a whitespace character.
Thus the regexes that you need follow:
^\S+$
^\S.*\S$
In your previous question, you mentioned you wanted from 0 to 50 characters. If that's still the case, here's what you want:
/^\S{0,50}$/
/^(?!\s).{0,50}(?<!\s)$/
As of right now, I think these are the only regexes posted that allow for less than one letter with the first pattern, and less than two letters with the second pattern.
Regexes are not a "bad" thing, they're just a specialized tool that isn't suited for every task. If you're trying to validate input in ASP.NET, I would definitely use a RegularExpressionValidator for this particular pattern, because otherwise you'll have to waste your time writing a CustomValidator for a pretty meager performance boost. See my answer to this other question for a little guidance on when and when not to use regex.
In this case, the reason I'd use a regex validator has less to do with the pattern itself and more to do with ASP.NET. A RegularExpressionValidator can just be dragged and dropped into your ASPX code, and all you'd have to write would be 10-21 characters of regex. With a CustomValidator, you'd have to write custom validation functions, both in the codebehind and the JavaScript. You might squeeze a little more performance out of it, but think about when validation comes into play: only once per postback. The performance difference is going to be less than a millisecond. It's simply not worth your time as a developer -- to you or your employer. Remember: Hardware is cheap, programmers are expensive, and premature optimization is the root of all evil.
You know the saying about regex's (now you have two problems) - this is doable without regex and should be more performant and easier to read.
string checkString = /* whatever */
if(checkString.IndexOf(" ") > -1)
// Failed Condition 1
if(checkString.Trim() != checkString)
// Failed Condition 2
No spaces allowed at all:
^\S+$
No spaces allowed at the beginning or end:
^\S+.*\S+$
The System.String class contains everything you need:
No spaces allowed at all
This will handle the case of spaces only:
bool valid = !str.Contains(" ");
If you need to check for tabs as well:
char[] naughty = " \t".ToCharArray();
bool fail = (str.IndexOfAny(naughty) == -1);
There are other whitespace characters you could check for, see Character Escapes for more details.
No spaces allowed at the beginning or the end of the string only
A bit simpler, since Trim() will remove any kind of whitespace, including newlines:
bool valid = str.Length == str.Trim().Length;
Can I with ASP.NET Resources/Localization translate strings to depend on one or other (the English grammar) in a easy way, like I pass number 1 in my translate, it return "You have one car" or with 0, 2 and higher, "You have %n cars"?
Or I'm forced to have logic in my view to see if it's singular or plural?
JasonTrue wrote:
To the best of my knowledge, there isn't a language that requires something more complicated than singular/plural
Such languages do exist. In my native Polish, for example, there are three forms: for 1, for 2-4 and for zero and numbers greater than 4. Then after you reach 20, the forms for 21, 22-24 and 25+ are again different (same grammatical forms as for numerals 0-9). And yes, "you have 0 things" sounds awkward, because you're not likely to see that used in real life.
As a localization specialist, here's what I would recommend:
If possible, use forms which put the numeral at the end:
a: Number of cars: %d
This means the form of the noun "car" does not depend on the numeral, and 0 is as natural as any other number.
If the above is not acceptable, at least always make a complete sentence a translatable resource. That is, do use
b: You have 1 car.
c: You have %d cars.
But never split such units into smaller fragments such as
d: You have
e: car(s)
(Then somewhere else you have a non-localizable resource such as %s %d %s)
The difference is that while I cannot translate (c) directly, since the form of the noun will change, I can see the problem and I can change the sentence to form (a) in translation.
On the other hand, when I am faced with (d) and (e) fragments, there is no way to make sure the resulting sentence will be grammatical. Again: using fragments guarantees that in some languages the translation will be anything from grammatically awkward to completely broken.
This applies across the board, not just to numerals. For example, a fragment such as %s was deleted is also untranslatable, since the form of the verb will depend on the gender of the noun, which is unavailable here. The best I can do for Polish is the equivalent of Deleted: %s, but I can only do it as long as the %s placeholder is included in the translatable resource. If all I have is "was deleted" with no clue to the referent noun, I can only startle my dog by cursing aloud and in the end I still have to produce garbage grammar.
I've been working on a library to assist with internationalization of an application. It's called SmartFormat and is open-source on GitHub.
It contains "grammatical number" rules for many languages that determine the correct singular/plural form based on the locale. When translating a phrase that has words that depend on a quantity, you specify the multiple forms and the formatter chooses the correct form based on these rules.
For example:
var message = "There {0:is:are} {0} {0:item:items} remaining.";
var output = Smart.Format(culture, message, items.Count);
It has a very similar syntax to String.Format(...), but has tons of great features that make it easy to create natural and grammatically-correct messages.
It also deals with possible gender-specific formatting, lists, and much more.
moodforaday wrote:
This applies across the board, not just to numerals. For example, a fragment such as "%s was deleted" is also untranslatable, since the form of the verb will depend on the gender of the noun, which is unavailable here. The best I can do for Polish is the equivalent of "Deleted: %s", but I can only do it as long as the %s placeholder is included in the translatable resource. If all I have is "was deleted" with no clue to the referent noun, I can only startle my dog by cursing aloud and in the end I still have to produce garbage grammar.
The point I would like to make here, is never include a noun as a parameter. Many European languages modify the noun based on its gender, and in the case of German, whether it is the subject, object, or indirect object. Just use separate messages.
Instead of, "%s was deleted.", use a separate translation string for each type:
"The transaction was deleted."
"The user was deleted." etc.
This way, each string can be translated properly.
The solution to handle plural forms in different languages can be found here:
http://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html
While you can't use the above software in a commercial application (it's covered under GPL), you can use the same concepts. Their plural form expressions fit perfectly with lambda expressions in .NET. There are a limited number of plural form expressions that cover a large number of languages. You can map a particular language to a lambda expression that calculates which plural form to use based on the language. Then, look up the appropriate plural form in a .NET resx file.
There is nothing built in, we ended up coding something like this:
Another solution can be:
use place holders like {CAR} in the resource file strings
Maintain separate resource entries for singular and plural words for "car" :
CAR_SINGULAR car
CAR_PLURAL cars
Develop a class with this logic:
class MyResource
{
private List<string> literals = new List<string>();
public MyResource() { literals.Add("{CAR}") }
public static string GetLocalizedString(string key,bool isPlural)
{
string val = rm.GetString(key);
if(isPlural)
{
val = ReplaceLiteralWithPlural(val);
}
else
{
val = ReplaceLiteralWithSingular(val);
}
}
}
string ReplaceLiteralWithPlural(string val)
{
StringBuilder text = new StringBuilder(val)
foreach(string literal in literals)
{
text = text.Replace(literal,GetPluralKey(literal));
}
}
string GetPluralKey(string literal)
{
return literal + "_PLURAL";
}
This is still not possible in .NET natively. But it is a well known problem and already solved by gettext. It have native support for many technologies, even includes C# support. But looks like there is modern reimplementation now in .NET: https://github.com/VitaliiTsilnyk/NGettext
Orchard CMS uses GNU Gettext's PO files for localization and plural forms.
Here is their code where you can grab the idea:
https://github.com/OrchardCMS/OrchardCore/tree/main/src/OrchardCore/OrchardCore.Localization.Core
https://github.com/OrchardCMS/OrchardCore/tree/main/src/OrchardCore/OrchardCore.Localization.Abstractions
The logic needn't be in your view, but it's certainly not in the resource model the DotNet framework. Yours is a simple enough case that you can probably get away with creating a simple format string for singular, and one for plural. "You have 1 car."/"You have {0} cars." You then need to write a method that discriminates between the plural and singular case.
There are also a number of languages where there's no distinction between singular and plural, but this just requires a little duplication in the resource strings. (edit to add: gender and sometimes endings change depending on number of units in many languages, but this should be fine as long as you distinguish between singular and plural sentences, rather than just words).
Microsoft mostly gave up on semantically clever localization because it's hard to generalize even something like pluralization to 30+ languages. This is why you see such boring presentation of numeric quantities in most applications that are translated to many languages, along the lines of "Cars: {0}". That sounds lame, but surprisingly, the last time I checked, usability studies didn't actually favor the verbose natural language presentation in most cases.