How to split string in View in MVC? - asp.net-mvc

In my View I have this condition:
#if (User.Identity.Name == "abc")
{
... do this!
}
How can I split this string "User.Identity.Name" in View (in MVC) so I can create new condition, something like this:
string last = User.Identity.Name.Substring(User.Identity.Name.LastIndexOf('.') + 1);
if (last == "this")
{
... do this!
}
thanks.

you can do it like this:
#{
var temp= User.Identity.Name.Split('.');
if (temp[temp.Count() - 1] == "this")
{
}
}
or if "." will be only one time in that string then you can hardcode like this:
#{
var temp= User.Identity.Name.Split('.');
if (temp[1] == "this")
{
}
}

see below example , which finds last word of a string after last dot in it.
String str = "abc.def.xyz";
String last = str.substring(str.lastIndexOf('.')+1);
System.out.println(last);
if(last.equals("something")){
//do this
}
else{
//do this
}
here last comes as xyz

Related

How to make sure a string of pure whitespace is invalid with a succinct code in Swift

I am making a section with TextFields and Button("Continue") and then use .disable(isValidAddress) modifier to a whole section to disable the button. The code works well, but I am seeking any solution to make it more succinct with no need to write .hasPrefix() or .hasSuffix() to all parameters one by one.
var isValidAddress: Bool {
if name.hasPrefix(" ") || street.hasPrefix(" ") || city.hasPrefix(" ") || country.hasPrefix(" ") {
return false
} else if name.hasSuffix(" ") || street.hasSuffix(" ") || city.hasSuffix(" ") || country.hasSuffix(" ") {
return false
}
return true
}
var isValidAddress: Bool {
[street, name, city, etc..].reduce(true, { result, text in
if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return false
} else {
return result
}
})
}
You can add them to an array and trim white space and check if empty in a loop
func isValidAddress() -> Bool {
for field in [name, street, city, country] {
if field.trimmingCharacters(in: .whitespaces).isEmpty { return false }
}
return true
}
I used a function here but a computed property works just as well.
If you don't mind moving some complexity into extensions, you can tidy up the call site. This makes it more readable, and less error prone - you can easily add in another field without mistakes for example.
extension String {
func hasPrefixOrSuffix(_ s: String) -> Bool {
hasPrefix(s) || hasSuffix(s)
}
var noSpacesAtEnds: Bool {
!hasPrefixOrSuffix(" ")
}
}
let isValid = [name, street, city, country]
.allSatisfy(\.noSpacesAtEnds)
If you do mean none of them are "all whitespace strings" then:
extension String {
var isNotAllWhitespace: Bool {
!trimmingCharacters(in: .whitespaces).isEmpty
}
}
let isValid = [name, street, city, country]
.allSatisfy(\.isNotAllWhitespace)
One benefit of having named functions for these things is you can test the pieces, so you can write a test to ensure that isNotAllWhitespace works the way you expect. You couldn't if the logic like name.hasPrefix(" ") || street.hasPrefix(" ") is mixed in with your isValidAddress function.

xtext Format comment with AbstractFormatter2,

I am using AbstractFormatter2 with xtext 2.9.2
I want to put the comment in a specific column
My syntax looks something like this
terminal SL_COMMENT : '*' !('\n'|'\r')* ('\r'? '\n')?;
So far, I tried to put multiple spaces before my comment, but this doesn't work either
def dispatch void format(Model model, extension IFormattableDocument document) {
SL_COMMENTRule.prepend[space " "]
model.getEnte.format;
model.getMapset.format;
}
can anyone guide my how to format comments in general then how to put them in a specific column
comment formatting is done by commentreplacers
thus something like the following should work
override createCommentReplacer(IComment comment) {
val EObject grammarElement = comment.getGrammarElement();
if (grammarElement instanceof AbstractRule) {
val String ruleName = grammarElement.getName();
if (ruleName.startsWith("SL")) {
if (comment.getLineRegions().get(0).getIndentation().getLength() > 0) {
return new SinglelineDocCommentReplacer(comment, "//") {
override configureWhitespace(WhitespaceReplacer leading, WhitespaceReplacer trailing) {
leading.getFormatting().space = " ";
}
};
} else {
return new SinglelineCodeCommentReplacer(comment, "//") {
override configureWhitespace(WhitespaceReplacer leading, WhitespaceReplacer trailing) {
leading.getFormatting().space = " ";
}
}
}
}
}
super.createCommentReplacer(comment)
}

How to append to the URL Path Grails

I'm using Grails 1.3.7 and I'm trying to figure out how to append a state (region) abbreviation (NM, AZ, UT) in the path of my URL. So it looks like this:
localhost/NM/action/
or
localhost/UT/action2/3/
This has to be done for all urls on the site. I also don't want to change the URLMappings.groovy file, would a filter help with this?
I created this filter definition:
def filters = {
...
regionAppender(uri:'/**') {
before = {
if (request.region) {
if (!request.forwardURI.contains(request.region)) {
String[] split = s.split("/");
String redirectUri = split[0] + "/" + request.region
if (split.length > 1) {
for (int i = 1; i < split.length; i++){
redirectUri = redirectUri + "/" + split[i]
}
}
redirect(uri: redirectUri)
return false
}
return true
}
return true
}
}
}
But it doesn't seem to be working. Is there a way to do this, or do I have change all my URLMappings?
I haven't test this but maybe it is to do with your declaration of request... try params.region instead
Take a look here
def filters = {
....
before = {
if(params?.id) {

Razor Escaping my html even if I use Html.Raw

I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
#{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage) I've even tried to manually create an HTMLString with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
#Html.Raw(TrialMessage)
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
#{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
#if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:#trialColor;">#trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended #Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.

Human readable key names for characters

I want to trigger some code if the 'A' key is pressed:
document.on.keyDown.add((event) {
if (event.keyIdentifier == 'U+0041') {
...
}
});
Using the unicode code (U+0041) of the character is not very readable. Is there any method I can use to convert the code to a character or vice versa? I would like to do something like this:
document.on.keyDown.add((event) {
if (event.keyIdentifier == unicodeCode('A')) {
...
}
});
I hope this will help:
document.on.keyPress.add((KeyboardEvent event) {
final String char = new String.fromCharCodes([event.charCode]);
print('Key: $char');
if (event.keyIdentifier == 'U+0041') {
print('$char pressed.');
}
if (char == 'a') {
print('Lowercase "a" has been pressed.');
}
});
Currently the keyDown event doesn't provide the appropriate charCodes.

Resources