Object reference not set while SQL manager says it is - asp.net

Lately I have run in a strange NullReferenceException. It pops up only occasionally why it is so hard to debug it for me. Today it happened again and I want to fix it now I have the error.
I have the following setup:
An asp.net view with relevant code:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WerkStageNu.Profiles>" %>
<%# Import Namespace="WerkStageNu.Helpers" %>
<div class="listing">
<div class="content">
<h3><%=Html.ActionLink(Model.Persons.UserName, "Details", new { id = Model.ID } )%></h3>
And when running this it tells me that Model.Persons is null giving the following error, while the Model itself is loaded with the data from the (SQL) Database. I am using ADO.net entities. Retrieving the profile instead of using the model resulted in the same error.
<%=Html.ActionLink(WerkStageNu.Models.Repository.Instance.GetProfileByID(Model.ID)
.Persons.UserName, "Details", new { id = Model.ID } )%>
Did not do any good.
Some error images:
debug mode http://www.bastijn.nl/zooi/model_persons.png
stack trace http://www.bastijn.nl/zooi/stacktrace.png
So far it seems a normal error, but when I checked my DB behind the request I found that this field is filled in and that the link is correct. SQL manager screens to show this information:
Profiles table:
profiles DB http://www.bastijn.nl/zooi/profiles_sql.png
Persons table:
persons DB http://www.bastijn.nl/zooi/persons_sql.png
As one can see all the PersonIDs are set so normally all the links should be loaded? Sometimes this is the case, but sometimes however this nullreference pops up from out of nowhere. Am I forgetting something? Should I manually load something?
//edit
I notice
<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %>
Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?

It could be related to lazy loading the Persons collection.

I notice
<% Model.PersonsReference.Load(); Model.EmploymentsReference.Load(); %>
Fixes this problem, the question is why I need it here and not throughout the rest of my views using the same approach?

Related

ASP 4.0 get values from session

im trying to find the contents of the session in a webpage im working on.
But since im not a programmer i have to revert to copy paste code i find online...
I dont know what variables are set in the session, thats why i want to know how many and what variables there are.
Now i found the following
<font face=arial size=1>
Session Variables - <% =Session.Contents.Count %> Found<br><br>
This works like a charm. It finds 7 to 12 values in the session. But when i try to follow up WHATS inside the session...
<%
Dim item, itemloop
For Each item in Session.Contents
If IsArray(Session(item)) then
For itemloop = LBound(Session(item)) to UBound(Session(item))
%>
<% =item %> <% =itemloop %> <font color=blue><% =Session(item)(itemloop) %></font><BR>
<%
Next
Else
%>
<% =item %> <font color=blue><% =Session.Contents(item) %></font><BR>
<%
End If
Next
%>
my page crashes with: CS1044 (and the dutch translation)
Since part 1 worked of the code i assumed that part 2 would work too.
Could anyone please help?
Seems that i needed to use Visual Studio 2015 (community edition) to find my answer for at least part of the question.
Hightlighting the string with what seemd to be a session variable (user.firstname) took me to user.cs (using F12) where i could find the other variables.
Hope this helps someone...

rails 4.1 undefined method for nil class

Hi I am trying to show the current users friend list / or the friends that might be pending, but i got an error like this one
NoMethodError in UserFriendships#index
undefined method `each' for nil:NilClass
this is what is was showing to give out the error
<% #user_friendships.each do |friendship| %>
This is my code in the controller
before_filter :authenticate_user!
def index
#user_friendship = current_user.user_friendships.all
end
this is my code in the index
<% #user_friendships.each do |friendship| %>
<% friend = friendship.friend %>
<div id="<%= dom_id(friendship) %>" class="friend now">
<div class="span1">
<%= link_to image_tag(friend.gravatar_url), profile_path(friend) %>
</div>
</div>
</div>
<% end %>
I have already defined the #user_friendship in my controller but it seems that its not working properly I am a bit new here and getting things together, but this error keeps me from going forward, if anybody can help me that would be great!
Rails cannot see your defined method user_friendships on current_user, hence #user_friendship is nill.
For your use, you would need to only call id directly on current_user, like
#user_id = current_user.id
Then, you can search the database for the User with this particular id
#current_user = User.find(#user_id)
So, you can get any method this new #current_user, in your case;
def index
#user_friendship = #current_user.user_friendships.all
end
And proceed with the list
<% #user_friendships.each do |friendship| %>
Rails is an MVC framework, meaning Models, Views, and Controllers. The Models primarily, enables communication between the database (like MYSql) and the controllers. Views are basically what the users see (like HTML, CSS), they communicate and grasp needed data through the Controller. And the Controller does the most work. The Controller takes in requests from the user, points the request through a model to the database, and returns the result to the view. All these are done by the Controller with the help of the server. For further explanations on Rails MVC framework and MVC generally, please checkout these links
How are Model, View and Controller connected?
What is MVC in Ruby on Rails?
http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
http://www.codelearn.org/ruby-on-rails-tutorial/mvc-in-rails
http://blog.codinghorror.com/understanding-model-view-controller/

Displaying name after login asp.net webmatrix

I built a site using the starter site template in Webmatrix that uses a log in. After a user logs in, it displays near the top "Hello, (email address)!"
Looking at the html code, I see
Hello, <a id="logname" class="email" href="~/Account/Manage" title="Manage">#WebSecurity.CurrentUserName</a>!
I'm just a beginner with asp.net but can work things out following logic, so what I have done is added a 'Name' field to the database where the email and password is stored and edited the registration page so users can enter their name as well, it writes to the database no problems.
Now I assumed it's just a matter of finding where #WebSecurity.CurrentUserName is referring to the user's email address and make it point to the Name field instead. However I've searched high and low and can not seem to find it anywhere.
So my next approach was to use code from a Bakery database tutorial that fetches data from a field and modify it to grab the name and display it where I want, the code I tried to use here:
#foreach(var row in db.Query(selectQueryString))
This appeared to work at first, It displayed "Hello, Ben!" but then if I made any more accounts it started to display them too, so after a while I was getting "Hello, Ben, Steve, Grace, etc..."
Even though I'm a beginner I do realize that this code isn't quite what I need, but something similar that takes that single Name field but only from the currently logged in user... I've googled and searched and seen many people wanting the same thing, except it's using PHP or VB or something that isn't Webmatrix.
If it's a quick answer I'd appreciate the code I need, or otherwise pointed in the right direction, any help would be greatly appreciated. Thanks in advance..
OK ironically I find the solution moments after posting the question, so here goes..
This is the code needed to be put at the very top of the file _SiteLayout.chtml
#{
var authenticatedUser = "";
if (WebSecurity.IsAuthenticated) {
authenticatedUser = WebSecurity.CurrentUserName;
var db = Database.Open("StarterSite");
var UserData = db.QuerySingle("SELECT Name FROM UserProfile WHERE LOWER(Email) = LOWER(#0)", authenticatedUser);
authenticatedUser = UserData.Name;
}
}
StarterSite is the name of the database, and UserProfile is the name of the Table, and I labeled the name field Name (explained for the purpose of beginners like me who might be reading this)
Then in the html markup I changed #WebSecurity.CurrentUserName to #authenticatedUser so now it reads:
Hello, <a id="logname" class="email" href="~/Account/Manage" title="Manage">#authenticatedUser</a>!
resulting in the desired outcome of it now displaying the user's name instead of their email address.

Error handling for ASP based sites and forms

I'm working on a asp based (not .net) site, which spans about 400 odd pages... Now, throughout the site there're ASP and VBScript errors, such as:
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'Cdate'
/MySite/page.asp, line 71
(The above happened when I put in characters into a 'date' field. I know its VBScript in this case, but I get plenty all over.)
Now, I know I can avoid this scenario with client side validation (jQuery for example), but when such things do happen, how do I code up a default 'error' page? You hit the error, and instead of showing you the above, you get redirected to a generic 'error' page?
I've looked up some of this, and found the ASP 'On Error Resume Next' thing, but I haven't found any viable examples. Each one is tailored to a specific error (like dividing 5 by 0), and I really don't want to code up like 400+ potential error messages.
You could create custom error pages, via IIS. I'm not sure what version you're running, etc - but this should give you a good jumping off point. http://support.microsoft.com/kb/224070
You add following code in top in your page.
<% on error resume next%>
.
..
....
(Other code is above instead of point(.))
Then you add
<% if err then
response.redirect("err.page?code="&err.code)
end if%>
And you define error message in your generic error page according to error number.
if you ask same question for client side. You can try and catch code block for possible code clock that will can throw.
For examle
<script language="text/javascript">
try
{
//Code that will can throw error is here.
}
catch(err)
{
document.href.location="genericerrorpage.asp?err=" + err.code;
}
}
</script>

"Failed to enable constraints" Error keeps cropping up (seemingly randomly) in my ASP.Net project

I have a weird problem where the "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." error sometimes pops up when I am trying to build my project.
The line in question throwing the error was auto-generated code in the designer file for the dataset. To find out the offending table, I used the following code:
Try
Me.Adapter.Fill(dataTable) <--Breakpoint here on the offending line
Catch ex As Exception
For Each TRow As DataRow In dataTable.Rows
If TRow.HasErrors Then
Trace.Write(TRow.RowError)
End If
Next
End Try
Funnily enough, as soon as I run the project after putting in the above code and breakpoint, the error disappears. I assume this has something to do with the code being regenerated. All data is presented successfully, and the project compiles without errors.
However, this has happened often enough for me to frustrate me. Anybody know what might be causing the error and how I can isolate it?
What unique constraint are you placing on the datatable and have you verified that the data your passing in doesn't have any duplicates? If this is coming from a shared database perhaps someone else is modifying the data which could be causing the randomness.
Edit
If that code is exactly as what you have (And forgive me my vb.net is not as strong as my C#). Wouldn't it swallow the exception? In C# we need to rethrow the error.
Add a Trace.Write() right before you go into your for loop.
You are probably working with a typed dataset, or have some code configuration on it. Also you might be reading from one table, and then adding data from another.
In any of those cases, you really want to look into any inconsistencies between the schema. If it is a typed dataset / or configured in code, check its definition, and look for anything different from the sql table. If you are reading from 2 different tables, check the definition of both tables.
Figured it out finally!
The reason the breakpoint wasn't being hit was because the code in question was auto-generated, and had the attribute "DebuggerNonUserCodeAttribute". In addition, in my VS settings, I had set the debugger to "Just my code".
When I ran the code again, and the breakpoint wasn't hit, I noticed the breakpoint icon had changed to a warning. Hovering showed this:
"The breakpoint will currently not be hit. Breakpoints cannot be set in a method or class with the 'DebuggerNonUserCode' attribute when the debugger option 'Just My Code' is enabled."
Ouch!
Once I had removed the "Just My Code" debugging option, the breakpoint was hit, and I discovered that one of the rows had a NULL value in one of the columns which had a non-null constraint. Stupid ole' me!
You should use this code before you fill DataTable :
var dt = new System.DataTable.DataTable();
dt.Clear();
dt.Rows.Clear();
dt.Columns.Clear();

Resources