I'm attempting to pull out the Created UTC value from my Orchard project but I keep getting "object is null"
Here is my code
IUser loggedOnUser = _orchardServices.WorkContext.CurrentUser;
var userCreatedDate = loggedOnUser.As<CommonPart>().CreatedUtc;
When it hits the second line it throws the exception of "Object reference not set to an instance of an object".
Looking at this link my code should work fine.
User content item contains only a UserPart. If you need to access created/modified dates, you need to attach a CommonPart to it via data migrations, like this:
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("User", cfg => cfg.WithPart("CommonPart));
return 1;
}
Just keep in mind that it won't affect existing users automatically - you would have to go through them one by one and hit "Save" for the part to be created.
Related
I have a Request class containing a property CreatedBy of the type ApplicationUser.
I then need to do some authorization to see if the request is accessible by the current user, like so:
public bool HasAccessToRequest(Request req)
{
var user = GetCurrentUser();
if (req == null)
{
return false;
}
if (req.CreatedBy.Department.Managers.Any(x => x.Id == user.Id))
{
return true;
}
return false;
}
Where GetCurrentUser() just get's the currently logged in user as an object.
The issue is, when I do this I get an error:
“Object reference not set to an instance of an object”
This is verifiable by stepping through this block of code and I notice that when breakpointing, CreatedBy is indeed not loaded. Then I look to my db table and there is a valid value there, so I try again but this time waiting for about 5 seconds and then it magically appears in the req parameter upon hovering over.
I'm not using any sort of async methods and I have this same method in a different controller which is working totally fine. Any pointers on what it could be? As far as I know there is no other code that is running before hand that I need to wait for, I can just see that this is taking a while to load and without setting a breakpoint and waiting I get the above error.
First this happens:
Then after waiting for 2-4 seconds this happens:
Looks like I had lazy loading disabled for CreatedBy so making it:
public virtual ApplicationUser CreatedBy { get; set; }
Seemed to fix the issue. This is a little bit confusing because I'm more than half way through the development of this project and this field never needed to be virtualised before and worked completely fine, and I'm not sure if it could cause potential problems later on.
I have an MVC5, which uses ASP.NET Identity for users. I have a class named Business which inherits from ApplicationUser, then I populate the database with the entries in my CSV files, but then in the database they don't have a SecurityStamp and I cannot seem to be able to log in. I tried something like this in my Configuration.cs file, but it doesn't seem to work:
var userManager = new UserManager<Business>(new UserStore<Business>(context));
foreach (Business b in context.Businesses)
{
userManager.UpdateSecurityStampAsync(b.Id);
}
context.SaveChanges();
Please note that initially their SecurityStamp is null in the database. Any idea, how to add the security stamps from Configuration.cs?
You should always use the non-async versions of methods that are not intended to be awaited.
userManager.UpdateSecurityStamp(b.Id);
Change context.Businesses to context.Businesses.ToList()
The error you were getting There is already an open DataReader associated with this Connection which must be closed first. is probably because you are iterating a set which is streaming objects from your DB and at the same time trying to issue additional commands through UpdateSecurityStamp
I am trying to create a command line quick program to do a once-off import of users from an old system (non-DNN) to a new system. However, a NullReferenceException gets thrown at the following line of code:
var user = new UserInfo();
user.PortalID = portalId;
user.FirstName = firstName;
On that last line is where the exception occurs. I know this code works when run in a module, as it's part of a library I'm using. I imagine that this is erroring because the UserInfo class is relying on information that's usually setup in a web environment.
Is there any way I can do this? I really don't want to have this as a module running on a production site.
You need to configure the necessary providers in order to use the UserController and UserInfo classes. The most straightforward way to do this is to use the website's working configuration and implement the app as a DNN module.
But you can also try to copy the required DLL's and configuration sections from the DNN site to the console application, and use the DNN source to debug problems.
In this case, the source tells that setting the UserInfo object's FirstName property fails because the FirstName property is backed by the profile provider, which uses the caching provider and data provider for data access.
By default, profile is implemented by the DNNProfileProvider that uses the FileBasedCachingProvider and SqlDataProvider to get the profile properties and data. Profile property definitions are retrieved also for a new UserInfo object when ProfileController.GetUserProfile is called. That is why the NullReferenceException gets thrown.
The corresponding properties in DNN 5.6.3 are:
UserInfo.vb
<SortOrder(1), MaxLength(50), Required(True)> _
Public Property FirstName() As String
Get
Return Profile.FirstName
End Get
Set(ByVal Value As String)
Profile.FirstName = Value
End Set
End Property
<Browsable(False)> _
Public Property Profile() As UserProfile
Get
'implemented progressive hydration
'this object will be hydrated on demand
If _Profile Is Nothing Then
_Profile = New UserProfile
ProfileController.GetUserProfile(Me)
End If
Return _Profile
End Get
Set(ByVal Value As UserProfile)
_Profile = Value
End Set
End Property
I'm writing an ASP.NET C# web site that needs to access data from a database and show it to the user for viewing and editing. The specific data it accesses is based on the user who logs in, and I need for multiple users to be able to use the site simultaneously, viewing and editing different data as they do so. I stumbled upon the concept of Session States, and after a lot of reading and not as much understanding. I've come across a problem.
In my default page, I do this to create a Session variable:
Session.Add("UserData",userdata);
I have also tried this:
Session["UserData"] = userdata;
Then in a later page, I do this to try to call it:
object myobject = Session["UserData"];
This gives me an error, saying that Session["UserData"] is not set to an instance of an object. This is the method everyone seems to be using, is there something I'm missing?
My site is configured on IIS to have the Session State Mode set to "In Process", but most people seem to set this manually using their web.config file. However, when I try to do this in my web.config file I am always greeted with "unrecognized configuration section". My compiler doesn't know what this is:
<sessionstate mode="inproc"/>
EDIT, more detailed code:
MyClass userdata = new MyClass();
userdata.name = "myname";
userdata.number = 5;
Session["UserData"] = userdata;
later...
MyClass mydata = (MyClass)(Session["UserData"]);
This returns the error that Session["UserData"] is null.
The fact that you can't set the session mode in the web.config is a red flag to me of something weird and smelly going on. So ...
Check that the session mode is under the system.web element of the web.config otherwise it won't be valid.
Check that enableSessionState hasn't been set to false in either the web.config or the page directive
Try to rule out IIS. If possible convert your website to a web app and run through visual studio so it starts with it's own built in web server. What happens then? Is the Session state back?
It should n't make a difference but if you are not doing the test in Page_Load then just try it there - just in case you are doing these tests somewhere unusual.
Whatever the answer is to this when we know it will be headachingly obvious. I'm geninuely looking forward to finding out what it is. Good luck
Session variables are good to manage multiple users on your website, but to initialize them you should use the Global.asax file in your web application. This file has two methods specifically for Session variables, Session_Start and Session_End. To initialize your Session variable you would use code liked the following in Global.asax:
void Session_Start(object sender, EventArgs e)
{
// initialize session variable
Session["MySessionVar"] = 1;
}
Also you may have to cast the value of your session variable if you are doing operations on it like +, for example if you have a session variable holding an integer value, you may have to do like the following:
Session["MySessionVar"] = ((int) Session["MySessionVar]) + 1;
Also, if you try to use your session variable outside of a method like Page_Load or other method, like trying to use it as a property of the System.Web.UI.Page class in your C# code behind file, that may not work, you can only use your session variables within a method.
I would search for any calls to Session.Clear or Session.Abandon to see if your session is being purged in between those two actions.
You could also hook up to the Session_End event and see if that gets hit sometime in between the two calls.
Where you have
Session.Add("UserData",userdata);
you want to check the value you need to cast the object with (string) like this
string userdata= (string)(Session["UserData"]);
you could then run a check to see
if(string.IsNullOrEmpty(userdata))
but not sure how you are initializing and assigning a a value to userdata
Does it complain the your myobject is null or that Session is null? When you try to retrieve the value you are doing this from the method of what class?
Yet another question - by any chance are you trying to access it in a parallel thread?
I have a User table, with a many-to-many relationship to an Alerts table. After creating a Membership user, I am adding some extra info into the database.
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
if (createStatus == MembershipCreateStatus.Success) {
User user = new MidTier.Models.User();
user.FullName = model.FullName;
if (Alerts.Count() > 0)
{
var userAlerts = SetAlert(Alerts); // creates an IEnumerable of Alerts (from a list of int )
foreach (var alert in userAlerts)
{
user.Alerts.Add(alert); //add each alert to the user
}
}
userRepository.Add(user); //throwing error
userRepository.Save();
}
I get an error (' An entity object cannot be referenced by multiple instances of IEntityChangeTracker.') on calling the Add method. there are lots of references about this error on the net even here on SO, but after reading all those comments and suggestions, I a havent found a solution or the reason I am getting this error.
there are lots of references about
this error on the net even here on SO,
but after reading all those comments
and suggestions, I a havent found a
solution or the reason I am getting
this error.
If you really searched you should already know that error says you that some entity in object graph is already attached to other context. Because of that your code sample is mostly not related. The real important code is wrapped in your methods - probably SetAlerts and userRepository.Add. If these two methods use internally context and they don't use the same instance it is the reason for your exception.