0

EDIT(2) -- Why this IS a duplicate: Going through the code I saw that the partial view that I'm loading as the right side pane. I declared each new variable with new Class(). This fixed the problem.

I've been working on this Solution for a while now and I just tested the "Register" process that was autogenerated when I created the project. Now that I create a new user when I login I get the following error:

Error

I check if the variable I'm using has anything in it and it does:

CompanyId

Current User Data

Database data

As you can see in the first screenshot that the GUID {cb2ddf79-6c36-4459-96df-5496f5416d21} does exist in the database with the last screenshot the "OrgId" is there too.

The question is why is the error showing if there's nothing null?

When I remove the code from the razor page I still get the error:

Razor Page Error

But there's data in the variables: FirstName LastName

I keep doing this and it seems that the ApplicationUser has a problem... Here's my code:

Razor Page:

@using Microsoft.AspNet.Identity
@using Microsoft.AspNet.Identity.EntityFramework
@using CrossingsCloud.Models

<nav class="navbar-default navbar-static-side" role="navigation" style="position:fixed;">
    <div class="sidebar-collapse">
        <ul class="nav" id="side-menu">
            <li class="nav-header" style="padding-bottom:5px;background:none;">
                @{
                    CrossingsCloudDBContext db = new CrossingsCloudDBContext();
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new CrossingsCloudDBContext()));
                    var currentUser = manager.FindById(User.Identity.GetUserId());
                    var FullName = currentUser.FirstName + " " + currentUser.LastName;
                    Organization userOrg = (from o in db.Organizations
                                            where o.OrgId == currentUser.CompanyId
                                            select o).Single();
                }
                <div class="dropdown profile-element" style="margin-bottom:20px; text-align:center;">
                    <span>
                        <a href="@Url.Action("DashboardUserProjects", "Dashboards")"><img class="image" width="150" height="75" src="~/Content/images/logos/cc-logo-sidenav.png" style="margin-bottom:20px;" /></a>
                            <img alt="image" class="img-circle" height="48" width="48" src="~/Content/@currentUser.ProfilePic.FileLocation/@currentUser.ProfilePic.SystemFileName@currentUser.ProfilePic.FileExt" />
                    </span>
                    <a data-toggle="dropdown" class="dropdown-toggle" href="#">
                        <span class="clear">
                            <span class="block m-t-xs">
                                <strong class="font-bold">@FullName</strong><br />
                                <span class="font-noraml">@userOrg.OrgName</span>
                            </span>
                            <span class="text-muted text-xs block">
                                @{
                                    if (User.IsInRole("Admin"))
                                    {
                                        @: Administrator
                                    }
                                    else
                                    {
                                        @: SuperAdmin
                                    }

                                }
                            </span>
                        </span>
                    </a>
                </div>
                ... and so on  ...

Model:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid CompanyId { get; set; }
    public virtual Guid? ProfileId { get; set; }

    // Foreign Keys
    [ForeignKey("CompanyId")]
    public Organization Company { get; set; }

    [ForeignKey("ProfileId")]
    public virtual File ProfilePic { get; set; }
}

public class File
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual Guid FileId { get; set; }

    public string FileName { get; set; }

    public string FileExt { get; set; }

    public string FileLocation { get; set; }

    [Column(TypeName = "DateTime2")]
    public DateTime DateCreated { get; set; }

    [Column(TypeName = "DateTime2")]
    public DateTime DateModified { get; set; }

    public Guid CreatedUserId { get; set; }

    public Guid ModifiedUserId { get; set; }

    public bool DeleteFlag { get; set; }

    public string SystemFileName { get; set; }
}

public class Organization
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public virtual Guid OrgId { get; set; }

    public virtual Guid? ClientId { get; set; }

    public virtual string OrgName { get; set; }

    public virtual string OrgEmail { get; set; }

    public virtual Guid? OrgTypeId { get; set; }

    public virtual Guid? OrgLogoFileId { get; set; }

    public virtual string OrgAddress1 { get; set; }

    public virtual string OrgAddress2 { get; set; }

    public virtual string PostalCode { get; set; }

    public virtual Guid? CityId { get; set; }

    public virtual Guid? ProvinceId { get; set; }

    public virtual Guid? CountryId { get; set; }

    public virtual string PhoneNumber { get; set; }

    [ForeignKey("ClientId")]
    public virtual Client Client { get; set; }

    [ForeignKey("OrgTypeId")]
    public virtual OrgType OrgType { get; set; }

    [ForeignKey("OrgLogoFileId")]
    public virtual File File { get; set; }

    [ForeignKey("CityId")]
    public virtual City City { get; set; }

    [ForeignKey("ProvinceId")]
    public virtual Province Province { get; set; }

    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Controller:

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, string CompanyAC)
{
    int companychk = (from o in db.Organizations
                      where (o.OrgName.Contains(CompanyAC))
                      orderby o.OrgName
                      select o.OrgName).Count();
    Organization orgInfo = (from o in db.Organizations
                            where o.OrgId == model.Company
                            select o).Single();
    if (companychk != 0)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() 
            { 
                //Id = Guid.NewGuid().ToString(), 
                UserName = model.UserName, 
                FirstName = model.FirstName, 
                LastName = model.LastName, 
                CompanyId = model.Company,
                LockoutEnabled = true, 
                EmailConfirmed = false, 
                Email = model.UserName 
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // await SignInAsync(user, isPersistent: false);
                // return RedirectToAction("Index", "Home");
                UserManager.AddToRoles(user.Id.ToString(), "Admin");
                TempData["Company"] = CompanyAC;
                TempData["FirstName"] = model.FirstName;
                TempData["LastName"] = model.LastName;
                TempData["Email"] = model.UserName;
                return Redirect("/Account/Register#modal-newuser");
            }
            else
            {
                AddErrors(result);
            }
        }
    }
    else
    {
        if (!CompanyAC.Equals(""))
        {
            var client = new Client() { ClientId = Guid.NewGuid(), Clientname = CompanyAC };
            db.Clients.Add(client);
            db.SaveChanges();
            var org = new Organization { ClientId = client.ClientId, OrgName = CompanyAC };
            db.Organizations.Add(org);
            db.SaveChanges();
            var user = new ApplicationUser() { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, LockoutEnabled = true, EmailConfirmed = false, Email = model.UserName, CompanyId = org.OrgId };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                UserManager.AddToRoles(user.Id.ToString(), "Admin");
                TempData["NewCompany"] = CompanyAC;
                TempData["FirstName"] = model.FirstName;
                TempData["LastName"] = model.LastName;
                TempData["Email"] = model.UserName;
                return Redirect("/Account/Register#modal-newcompany");
            }
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}
Og Ramos
  • 46
  • 1
  • 9
  • Probably `.Single()` called on the result of your LINQ statement iterating over organizations is causing the exception. Instead of calling `.Single()` on the statement, store the result in a variable first and see if that variable is `null`. – ebyrob Feb 25 '16 at 17:06
  • or use FirstorDefault() – Viru Feb 25 '16 at 17:10
  • SingleOrDefault() --> http://prntscr.com/a7tv5p Still get the error. FirstOrDefault() --> http://prntscr.com/a7tvry Still get the error. – Og Ramos Feb 25 '16 at 17:11
  • `currentUser` is non-null? – Lasse V. Karlsen Feb 25 '16 at 17:18
  • @LasseV.Karlsen no... this is so odd! I'm going through the page you marked for duplicate and trying what can help. but still is null. I think it might be how I'm registering the new user and how Company is null on the user but CompanyId isn't --EDIT-- I tried checking manager variable and it's not null either: http://prntscr.com/a7u30a – Og Ramos Feb 25 '16 at 17:23
  • @LasseV.Karlsen current user is not null but do you see how "Company" is? http://prntscr.com/a7u49c – Og Ramos Feb 25 '16 at 17:28
  • **Answer** `@{ CrossingsCloudDBContext db = new CrossingsCloudDBContext(); **Organization userOrg = new Organization();** userOrg = (from o in db.Organizations where o.OrgId == currentUser.CompanyId select o).Single(); }` – Og Ramos Feb 25 '16 at 18:34
  • @LasseV.Karlsen Thank you for your help! – Og Ramos Feb 25 '16 at 18:36

0 Answers0