NullReferenceException on an object not null - asp.net-mvc

I'm passing an object to a view and am getting a null reference exception, but the object is not null.
In the Action I have this simple code:
return View(db.Users.First());
View code:
#model User
#using DG.WEB.Models
#{
ViewBag.SecondTitle = "Ver";
ViewBag.MostraEditarTab = "false";
ViewBag.MostraApagarTab = "false";
ViewBag.Tab = "tab2";
Layout = "~/Views/Conds/_Layout.cshtml";
}
<div class="container">
#if (Model != null)
{
<h5>#Model.Nome</h5>
<div id="container_atalhos">
<div class="btn-group">
<i class="icon-th-large"></i> Nova frac
<i class="icon-fire"></i> Nova OcorrĂȘncia
<i class="icon-shopping-cart"></i> Novo Fornecedor
<i class="icon-file"></i> Novo documento
<i class="icon-pencil"></i> Editar
<i class="icon-remove-circle icon-white"></i> Apagar
</div>
</div>
}else{
#:Not found
}
</div>
EDIT:
I just test a small code that prints the name of the first user in the view.
And it happens to me the same error!
The try / catch apparently works badly ... I do not understand.
Look at the picture
EDIT2:
I found the error. In the layout page there was an error and for some reason visual studio didnt detect it.
Thanks to all.

Usually such error are not directly related to the place where they blow up, but a consequence of IoC / Dependency Injection.
What basically happens is that in the background, the dependency injection is able to provide various objects as needed, but does this is a lazy fashion. So if something - like your layout page - isn't needed yet, it won't be created yet.
So then when you access something like your model, which can have internal requirements needing something like your layout, then the dependency injection kicks in, throwing an error at your model, even though the error is not model-related at all.
This is one of the really difficult aspects of dependency injection and will probably plague you again in the future :(.
There is also no best-practice I know of to avoid this. Your approach to gradually cornering the issue is the best way to go ahead AFAIK.

Related

What is the difference between bind:after and bind:set in Blazor 7?

Recently, in Blazor 7, a feature has been added to make it easier to bind and call the method based on changes in the bound expression.
In .NET 7, you can now easily run async logic after a binding event has completed using the new #bind:after modifier:
<input #bind="searchText" #bind:after="PerformSearch" />
#code {
string searchText = "";
async Task PerformSearch()
{
// Do something async with searchText
}
}
In this example, the PerformSearch async method runs automatically after any changes to the search text are detected.
Another method has been added too. The #bind:get and #bind:set modifiers are always used together. The #bind:get modifier specifies the value to bind to, and the #bind:set modifier specifies a callback that's called when the value changes.
The questions are:
What is the difference between #bind:after="PerformSearch" and #bind:set="PerformSearch"? Both of these seem to call the PerformSearch after the searchText is changed.
Where is the use of each?
What is the difference between #bind:after="PerformSearch" and #bind:set="PerformSearch"?
You should only use #bind:after="PerformSearch" with #bind="searchText",in which case the bind will set the value of searchText, so you shouldn't also try and set it in PerformSearch.
If you use #bind:set="PerformSearch" then you must set the value of searchText in PerformSearch, and use #bind:get="searchText".
Where is the use of each?
The MS Docs article I think gives a good guide. It all depends on your knowledge level on components.
It's important to understand two points:
This is Razor syntax, not C#.
It's just syntactic sugar: high level functionality, shorthand Razor directives to encapsulate existing functionality.
Also note:
There's been a lot of MS Blazor Team activity on this subject since 7.0 was released. See https://github.com/dotnet/aspnetcore/issues/44957 for details on problems with the way the Razor compiler treats the #bind directives.
There are some updates to the MS Docs on the subject - https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-7.0?view=aspnetcore-7.0#blazor-custom-elements.
Here's my demo page for this answer.
#page "/"
<PageTitle>Index</PageTitle>
<input class="form-control mb-3" type="text" #bind:get="this.Value" #bind:set="ValueSetter" #bind:event="oninput" />
<input class="form-control mb-3" type="text" #bind:get="this.Value" #bind:after="ValueSetter" />
<input class="form-control mb-3" type="text" #bind="this.Value" #bind:after="DoSearch" #bind:event="oninput"/>
<div class="alert alert-info m-2 p-2">
#Value
</div>
<div class="alert alert-primary m-2 p-2">
#message
</div>
#code {
private string? Value;
private string message = "Not Set";
private async Task DoSearch()
{
await Task.Delay(1000);
message= $"Set at {DateTime.Now.ToLongTimeString()}";
}
private void ValueSetter(string __value)
=> this.Value = __value;
private Task SearchSetter(string __value)
{
this.searchText = __value;
return DoSearch();
}
}
Let's look at the actual C# code the Razor compiler builds.
This is the code snippet when just using bind:set=this.ValueSetter:
__builder.AddAttribute(8, "oninput", EventCallback.Factory.CreateBinder(
this,
CompilerServices.RuntimeHelpers.CreateInferredBindSetter(
callback: this.ValueSetter,
value: this.Value
),
this.Value));
This simply calls the setter delegate assigned to set.
This is the code snippet when using :bind=this.Value and #bind:after=DoSearch:
__builder.AddAttribute(14, "oninput", EventCallback.Factory.CreateBinder(
this, CompilerServices.RuntimeHelpers.CreateInferredBindSetter(
callback: __value => {
this.Value = __value;
return RuntimeHelpers.InvokeAsynchronousDelegate(callback: DoSearch);
},
value: this.Value),
this.Value));
It's a little more complicated. The compiler builds the equivalent to this:
Task AnonymousMethod(string __value)
{
this.Value = __value;
return DoSearch()
}
A Note on Development Environment Errors
Depending on your development environment, you will get errors with certain combinations. Some of which at the moment appear to be misleading or totally wrong. They will be fixed shortly.
Quote from Dan Roth: Hi folks. The VS fix for this just missed the window for 17.4.4 but should be addressed in the next VS patch update in February. We apologize for the wait and thank you for your patience!
In Visual Studio.
This is a correct error:
<InputText class="form-control" #bind-Value:get="this.searchText" #bind-Value:set="this.SetSearchText" #bind-Value:after="DoSearch" />
Severity Code Description Project File Line Suppression State
Error (active) RZ10019 Attribute 'bind-Value:after' can not be used with 'bind-Value:set'. Invoke the code in 'bind-Value:after' inside 'bind-Value:set' instead.
While this is bull!
<input class="form-control mb-3" type="text" #bind:get="this.Value" #bind:set="ValueSetter" #bind:event="oninput" />
And while it gives this error compiles and runs!
Severity Code Description Project File Line Suppression State
Error (active) CS1503 Argument 3: cannot convert from 'Microsoft.AspNetCore.Components.EventCallback<string>' to 'System.Action<string?>'
And this line:
<input class="form-control mb-3" type="text" #bind:get="this.Value" #bind:after="ValueSetter" />
Compiles but is obviously also total bull.
__builder.AddMarkupContent(9, "\r\n\r\n<input class=\"form-control mb-3\" type=\"text\" #bind:get=\"this.Value\" #bind:after=\"ValueSetter\">\r\n\r\n");
Why is it #bind:get+#bind:set and not just #bind+#bind:set?
Because if you see <input #bind="#val" #bind:set="#MyMethod" /> often, it creates confusion:
It looks as if the #bind:set is what makes it a two-way binding, and that you could make it one-way by removing that. Whereas in fact that would be wrong (you'd still have a two-way binding, just one that behaves differently now).
It looks as if it would be equivalent to write <input value="#val" #bind:set="#MyMethod />, and it almost is, but not quite because the formatting logic would differ. Much better not to create the ambiguity and have one correct solution.
We can avoid the above problems by having a compiler rule that #bind:get and #bind:set must always be used as a pair - you can't just have one of them and not the other (nor can you have them with #bind). So none of the weird cases will arise.
Couldn't you use #bind:set to achieve (in effect) #bind:after, and hence we don't need #bind:after?
Theoretically yes. You could #bind:set to a method that writes to your field and then runs your async logic. However, this is far less obvious for newcomers, and is less convenient in common cases. And it invites mistakes: if you do something async before setting the field, the UI will temporarily revert and generally behave badly. So it's valuable to have #bind:after for convenience and to guide correct usage. We can regard #bind:get/#bind:set as a more advanced case mainly for people implementing bindable components, as it gives them a really clean and safe solution, and such developers are advanced enough to understand that they just shouldn't do async work before calling ValueChanged.
Can you use all three at once, e.g., <input #bind:get="#value" #bind:set="#MyMethod" #bind:after="#DoStuff" />?
Sure, why not? I think that the generated logic should await MyMethod before calling DoStuff, since "after" feels like it means "after all the work involved in calling set". It's an edge case but I can't think of any problems this will cause nor any major increase in implementation cost.
Do other #bind modifiers like #bind:event and #bind:format work with this?
Yes, and that's partly why it's a big improvement over manual value/onchange pairs.
you can refer this link get more idea https://github.com/dotnet/aspnetcore/issues/39837

Not able to get the title of Page using geb when it has multiple div elements and no ID

Below is my html, from where I am trying to get the text of header. I tried multiple ways to select it but not succeeded in it. Could you please help me to get the element so that I can get the text.
<div class="esuite-right">
<div class="angular-css ng-panel ng-panel-boxed">
<div class="ng-panel-hdr">
<h2 class="ng-binding">
Case-10006336-2015
<span class="sch-tek "> | </span>
Case details
</h2>
</div>
<!-- ngIf: zaak.vertrouwelijk -->
<div>
</div>
Title of the frame is "Case-10006336-2015" and tried to locate the element by using below various ways however not able to succeed in it.
labelSelectedCase { $("div", class: contains("angular-css ng-panel ng-panel-boxed")).$("div", class: contains("ng-panel-hdr")).$("h2",class: contains("ng-binding") ) }
labelSelectedCase { $("div.angular-css ng-panel ng-panel-boxed div.ng-panel-hdr").find("h2", class: contains("ng-binding")) }
and several others but not able to locate this element.
Could you please help me to get this element so that I can get the text and assert it.
Thanks in advance.
Either of these should work -
labelSelectedCase { $("h2.ng-binding")}
labelSelectedCase { $("span.sch-tek").parent()}
I'm not sure Content defined like you have in 1) is even valid so that could explain why $(x).$(y).$(z) doesn't work, and I'm pretty sure 2) goes astray at the second and third classes of the first div, maybe you have to chain the classes if you want to select on multiple classes like this -
labelSelectedCase { $("div.angular-css.ng-panel.ng-panel-boxed div.ng-panel-hdr").find("h2", class: contains("ng-binding")) }
Good luck,
Deon.

How can I make a conditional statement like "include?" method in Ruby on Angular ng-if

Sorry about the difficulty for me to make the title much clearer. I'll explain as much as I can.
I use Rails as the backend (API), and AngularJS as the frontend.
I got several article_ids that have been liked(thumb up) from articleCtrl, named $scope.article_has_liked (it's an array contains several article_ids, like [24,45,55] ), just like below, :
articleCtrl.js.coffee
$http.get(url).success((data)->
console.log(data)
$scope.articles = data.articles
$scope.topic = data.topic
$scope.article_has_liked = data.article_has_liked
)
And I pass these article_ids ($scope.article_has_liked) to the show.html, in order to use "ng-if" to conduct a judgement, just like below:
Show.html
<div ng-if="article_has_liked.include?(article.id)">
<button class="btn btn-link" ng-click="likeItOrNot(article.id, topic.id)">
<span class="glyphicon glyphicon-star"></span>
</button>
</div>
<div ng-if="article_has_liked.exclude?(article.id)">
<button class="btn btn-link" ng-click="likeItOrNot(article.id, topic.id)">
<span class="glyphicon glyphicon-star-empty"></span>
</button>
</div>
Here comes the problem !
I'd like to use .include? method in Ruby to determine if the article.id is included by the article_ids that have been liked. If it is liked, I'll give it a solid star. But I found that the Angular seems not to accept the usage, and it returned the error just like below:
Error: Syntax Error: Token 'undefined' expected : at column NaN of the expression [article_has_liked.include?(article.id)] starting at [article_has_liked.include?(article.id)].
throwError#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6672:1
ternary#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6827:9
_assignment#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6800:16
expression#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6796:12
_filterChain#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6762:16
statements#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6742:25
parser#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:6661:13
$ParseProvider/this.$get</<#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:7282:1
compileToFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:9215:16
$RootScopeProvider/this.$get</Scope.prototype.$watch#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:8547:19
ngIfDirective</<.compile/<#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:14677:9
nodeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4960:13
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4539:15
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4554:13
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4554:13
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4554:13
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4554:13
compositeLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4554:13
publicLinkFn#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:4456:30
ngRepeatAction#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:15463:15
$watchCollectionAction#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:8718:11
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:8812:21
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:9013:13
done#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:10266:34
completeRequest#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:10450:7
createHttpBackend/</xhr.onreadystatechange#http://localhost:3000/assets/angular.self-cdfe10db265380c82ec938d307fce2720dc9fb9d8cfa21c78928031af124e282.js?body=1:10405:1
<!-- ngIf: article_has_liked.include?(article.id) -->
So I want to ask if there is any conditional statement which has similar meaning to .include? that I can use in AngularJS "ng-if", or there is any better way for me to conduct this judgement?
Thanks everyone for helping me this confusing question!
That is a JavaScript relating question, not AngularJS. But may that answer your question:
Often you will need to check whether an array contains a certain item. You can do this by using the indexOf() method. If the code does not find the item in the list, it returns a -1.
var article_has_liked = [24,45,55];
if(article_has_liked.indexOf(99) == -1){
alert("data not found");
}
Not sure but you can try something:
<div ng-if="article_has_liked.indexOf(article.id) != -1">
Note: This above condition is to check for include. If it include your article.id in article_has_liked then only execute that block. If you want to check exclude then you can simply use == instead != I hope it works for you.
ng-if="article_has_liked.include?(article.id)"
update to this one:
ng-if="article_has_liked.include?(article.id):false value here"

Get children of an XHPChild

I am trying to move my website to Hack and XHP, of course. Below is a structure of what code structure I want to achieve:
<ui:backstageHeader>
<ui:backstageHeader-navItem href="/">stories</ui:backstageHeader-navItem>
<ui:backstageHeader-navItem href="/story/send">send a story</ui:backstageHeader-navItem>
<ui:backstageHeader-navItem href="/aboutus">support</ui:backstageHeader-navItem>
</ui:backstageHeader>
(Note: :ui:backstageHeader-navItem basically renders to <a href={$this->:href}>{$this->getCHildren}</a> so there is not need to attach its class here.)
Below is the code for :ui:backstageHeader:
final class :ui:backstageHeader extends :ui:base {
attribute :div;
children (:ui:backstageHeader-navItem)*;
protected function compose() {
$dom =
<section class="backstage-header">
<div class="container">
<div class="cell-logo">
<a href="/">
<span class="no23-logo-white"></span>
</a>
</div>
<div class="cell-navigation">
</div>
<div class="cell-account">
<div class="cell-login">
<div id="siteNav-login">Autentificare</div>
</div>
</div>
</div>
</section>;
$mainContainer = $dom->getChildren("div")[0];
$cellNavigation = $mainContainer->getChildren("div")[1];
$navItems = <ul class="main-navigation"></ul>;
foreach($this->getChildren() as $child) {
$navItems->appendChild(<li>{$child}</li>);
}
$dom->appendChild($navItems);
return $dom;
}
}
I used the Terminal to debug my code using hhvm -m d <file.php>, and everything was alright there; however, when I get to my browser, I get 500 error header. This is what the log says:
Catchable fatal error: Hack type error: Could not find method getChildren in an object of type XHPChild at /var/www/res/ui/backstage-header.php line 25
The error comes from
$cellNavigation = $mainContainer->getChildren("div")[1];
But, somehow, I need to append ul.main-navigation to div.cell-navigation from my section.backstage-header.
How can I do it?
Don't structure your code this way. Built it up from the inside out, so that you don't have to do a ton of unreadable getChildren calls looking for specific children. Those calls are super hard to read, and super inflexible when you change the structure of your XHP. You wouldn't do something like node.firstChild.lastChild.lastChild.firstChild in the JS DOM, would you? No, there's a better way in JS, to find things by class or ID; in XHP, you can just build it up the right way in the first place!
I'd give you an example of this, but it doesn't look like you actually use $mainContainer or $cellNavigation, so you can just remove those two problematic definitions.
As an aside, you really shouldn't be getting your type errors as catchable fatals from HHVM; this is a last resort sort of check. Try running the hh_client checker directly, maybe even showing its result in your IDE; it will give you a much faster iteration cycle, and much more information than HHVM provides.
From my experience, appendChild is very prone to human error. It's easier to do something like:
$items = (new Vector($this->getChildren()))->map($child ==> <li>{$child}</li>);
return <div id="container">{$items}</div>;
If you want to wrap the children in <li />.
Not sure if that will work but it will be close.
Pro tip: You can assign variables from within an XHP tree.
$root =
<div>
{$child = <span>
Text children
</span>}
</div>;
Now $child is already set to the <span> element.

Getting issue to generate Absolute Url's in MVC

Hi I have created a mvc website which is working fine with localhost if i am coding something like this:
<base href="http://localhost:5400/" />
<li><a class="home" href="/Home/Index/">Home</a></li>
<li class="wish"><a class="wishlist" href="/Products/Index/" id="wishlist-total">Products</a></li>
<li><a class="account" href="/Home/Contact/">Contact Us</a></li>
But now to run it on live if i am trying to changing this:
<base href="http://localhost:5400/" />
with this:
<base href="HttpContext.Current.Request.Url" />
then its actually taking full root url everytime.So whenever i am clicking on any menu and moves to next menu it regain previous menu path also.
For this issue i tried below code which is also not working.
<li>Home</li>
<li>Products</li>
<li> Contact</li>
According me this code will work,But if i am trying to pass "null" as third parameter then i gives error:
ERROR: 'null' is not declared. 'Null' constant is no longer supported; use 'System.DBNull' instead.
Can someone please suggest what i should need to change?
Thanks
Quick fix...
#Url.Action("Index", "Home")
There's no need to enter null as a parameter... if you want to indicate that a parameter can be null, then you need to define that in the route its self, and if the parameter is missing, then it will know that the value is null implicitly...
// http://yoursite/Example/{id}
[Route("~/Example/{id}"] // Can't be null
public ActionResult Example(string id){ return View(); }
// http://yoursite/ExampleTwo/
[Route("~/ExampleTwo/{id?} // Can be null
public ActionResult ExampleTwo(string id) { return View(); }
TLDR if you want more errors...
Your issue is actually indicating a much larger issue... it looks as if you're accepting a query from a URI directly into a SQL query... if you are doing that, you're opening yourself up to injection attacks and as much as a part of me feels that anyone who does that pretty much has it coming to them... I can't stand by and just say nothing... sanitize any data that you receive from the user, no matter where it's coming from, example
Remove all those magic strings... you shouldn't have any strings such as the one you just displayed...
// Bad...
<a class="home" href="/Home/Index/">
// Better...
<a class="home" href="#Url.Action("Index", "Home")">Home</a>
// Good
#Html.ActionLink("Home", "Index", "Home")

Resources