"Object reference not set to an instance of an object" Error - c#

Im Having Problems Figuring Out Why I am Receiving an "Object reference not set to an instance of an object" Error in the Presentation Layer with this line:
TempAccountManager.Accounts.Add(tempAccount);
I Have Walked Through the Code With Visual Studios Debugger and the Account Gets Created. I Believe I Have an Issue With an Access Modifer, Not Sure.
Presentation Layer
using myBudget.BusinessObject;
using myBudget.BusinessLogic;
namespace myBudget
{
public partial class NewBudgetWizard : Form
{
public int CurrentStep { get; set; }
public Account TempAccount = new Account();
public AccountManager TempAccountManager = new AccountManager();
public NewBudgetWizard()
{
private void createAccountList(ListView lvAccounts)
{
foreach (ListViewItem lvi in lvAccounts.Items)
{
int tempAccNumber = Int32.Parse(lvi.SubItems[0].Text);
string tempAccName = lvi.SubItems[1].Text;
string tempAccType = lvi.SubItems[2].Text;
decimal tempAccBalance = decimal.Parse(lvi.SubItems[3].Text, System.Globalization.NumberStyles.Currency);
Account tempAccount = new Account(tempAccNumber, tempAccName, tempAccType, tempAccBalance, DateTime.Now);
TempAccount = new Account(tempAccNumber, tempAccName, tempAccType, tempAccBalance, DateTime.Now);
TempAccountManager.Accounts.Add(tempAccount);
}
}
}
}
Business Logic Layer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using myBudget.BusinessObject;
namespace myBudget.BusinessLogic
{
public class AccountManager : Account
{
public List<Account> Accounts { get; set; }
}
}
Business Object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myBudget.BusinessObject
{
public class Account
{
public int AccountID { get; set; }
public int UserID { get; set; }
public int Number { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public decimal Balance { get; set; }
public DateTime ReconcileTimeStamp { get; set; }
public Account()
{
}
public Account(int number, string name, string type, decimal balance, DateTime reconcileTimeStamp)
{
Number = number;
Name = name;
Type = type;
Balance = balance;
ReconcileTimeStamp = reconcileTimeStamp;
}
}
}

The AccountManager Class Never Initializes The Accounts Property. Therefore TempAccountManager.Accounts Is Null.
Adding A Constructor Like This Will Fix It.
public class AccountManager : Account
{
public AccountManager()
{
Accounts = new List<Account>();
}
public List<Account> Accounts { get; set; }
}

Do you create Accounts in your AccountManager?
You should do somewhere:
Accounts = new List<Account>();
EDIT
You've got public set accessor. You may do:
TempAccountManager.Accounts = new List<Account>();
Or add a constructor to the class, as Joel Mueller suggested. But think over, if you need the public set. It gives an opportunity to completely replace your collection out of the object.

Not sure, but where do you initialize Accounts?
public List<Account> Accounts { get; set; }
Your get, set interface provides access, but doesn't define the value.

Related

ASP.NET Boilerplate - Entity Task Requires Primary Key [duplicate]

I'm training following aspnetboilerplate.com tutorials about developing using their frameworks. I'm stuck at the very first coding point where I have to create a basic table "Task" as stated in the code below.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(string title, string description = null)
: this()
{
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
I added the following code in my WebApp DBContext, too.
public class WebAppDbContext : AbpDbContext
{
public DbSet<Task> Tasks { get; set; } //<- This line
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
The tutorial does not mention any error regarding this code, but every time I make the command
Add-migration "Initial"
in the package manager console, I get this error.
The entity type "Task" requires a primary key to be defined.
I surfed the web for similar errors and each solution I've found does not work for me...
Update #1: I edited the code to this, but the error still remains.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Key]
public int Id { get; set; }
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(int id, string title, string description = null)
: this()
{
Id = id;
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
Tutorial link: https://aspnetboilerplate.com/Pages/Documents/Articles/Introduction-With-AspNet-Core-And-Entity-Framework-Core-Part-1/index.html
Update #2: This is the code of WebAppDbContext.cs
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
I've tried to reproduce your codes on my end and I noticed that the problem that you're dealing with is due to the wrong namespaces in the context WebAppDbContext.
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
//using System.Threading.Tasks;//<------------ this line causes the error
using WebApp.Tasks; //<----------- You need to add this namespace.
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
The problem is due to a conflict in the naming convention. I would recommend changing the name of the entity to something else to prevent further conflicts in the future.

How to get Department Name, Manager, Role title using System.DirectoryServices in Windows Form

Am newbie to C# script development, am trying to fetch Department Name, Manager Name & Role Title in windows form labels thru adding reference system.directoryservices. Can anyone support me, how to get the details in form labels.
I do not know how the manager is stored, but you can debug below method and look on the results and figure out what you are looking for.
The below example, demonstrate how to access user info:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
//from nuget you need this 2
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GetUserAD();
}
public void GetUserAD()
{
var userDto = new UserDto();
using PrincipalContext pc = new PrincipalContext(ContextType.Domain);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, Environment.UserName);
userDto.FirstName = up.GivenName;
userDto.LastName = up.Surname;
userDto.UserEmail = up.EmailAddress;
userDto.LastLogon = up.LastLogon;
userDto.FixPhone = up.VoiceTelephoneNumber;
userDto.UserDisplayName = up.DisplayName;
userDto.JobTitle = up.Description;
DirectoryEntry directoryEntry = up.GetUnderlyingObject() as DirectoryEntry;
userDto.Department = directoryEntry.Properties["department"]?.Value as string;
userDto.MobilePhone = directoryEntry.Properties["mobile"]?.Value as string;
userDto.MemberOf = directoryEntry.Properties["memberof"]?.OfType<string>()?.ToList();
}
}
public class UserDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserEmail { get; set; }
public string LastLogon { get; set; }
public string FixPhone { get; set; }
public string UserDisplayName { get; set; }
public string JobTitle { get; set; }
public string Department { get; set; }
public string MobilePhone { get; set; }
public List<string> MemberOf { get; set; }
}
}

Crash in runtime in Razor while using ViewModel

I'm trying to show multiple lists thru ViewModel. Currently started with one, but I'm getting the following runtime error:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'object' does not contain a definition for 'allLocationBasedPromotions
using System.Text;
using System.Threading.Tasks;
namespace FreeRolla.BaseObjects
{
class LocationBasedPromotion
{
public string Country { get; set; }
public string City { get; set; }
public string FlagIcon { get; set; }
public int HotelCount { get; set; }
public int StartingPrice { get; set; }
public string WeatherIcon { get; set; }
public string WeatherTemperature { get; set; }
public string CityImage { get; set; }
public List<LocationBasedPromotion> Promotions { get; set; }
}
}
using FreeRolla.BaseObjects;
namespace FreeRolla.BL
{
class HPLocationBasedPromotionProvider
{
public List<LocationBasedPromotion> GetAllPromotions()
{
return new List<LocationBasedPromotion>{
new LocationBasedPromotion{Country="UK", City="London", FlagIcon="", HotelCount=135, StartingPrice=350, CityImage="London.jpg", WeatherIcon="cloudy", WeatherTemperature="+18" },
new LocationBasedPromotion{Country="Spain", City="Barcelona", FlagIcon="", HotelCount=215, StartingPrice=230, CityImage="Barcelona.jpg", WeatherIcon="sunny", WeatherTemperature="+28" },
new LocationBasedPromotion{Country="Israel", City="Tel-Aviv", FlagIcon="", HotelCount=75, StartingPrice=280, CityImage="Tel-Aviv.jpg", WeatherIcon="sunny", WeatherTemperature="+32" }
};
}
}
}
using FreeRolla.BaseObjects;
using System.Web;
using System.Web.Mvc;
namespace FreeRolla.Models.ViewModels
{
class HomeView
{
public List<LocationBasedPromotion> allLocationBasedPromotions { get; set; }
}
}
using FreeRolla.BL;
using FreeRolla.Models.ViewModels;
namespace FreeRolla.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//return View();
HPLocationBasedPromotionProvider _BigPromotions = new HPLocationBasedPromotionProvider();
HomeView hv = new HomeView();
hv.allLocationBasedPromotions = _BigPromotions.GetAllPromotions();
return View(hv);
}
}
}
From the view - here the crash is occures:
#foreach (var item in Model.allLocationBasedPromotions)
{
Might be too obvious, but looks like your view file is missing this
#model FreeRolla.Models.ViewModels.HomeView
EDIT:
Your view class should have the following declaration:
namespace FreeRolla.Models.ViewModels
{
public class HomeView
{
public List<LocationBasedPromotion> allLocationBasedPromotions { get; set; }
}
}
The class LocationBasedPromotion should also be made public. Basically, as a tip, make every class public in your project, unless you have a good reason not too. As you gain more experience, you will encounter situations where you'll know when not to make a class public. But in your case, just make them public.

How can I use a viewmodel in ASP.NET MVC to show a calculated field?

I want to show a calculated field in a view, so I tried to create a viewmodel like this:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Facturacion.Models
{
public class Test
{
public int testId { get; set; }
[Required]
public decimal price { get; set; }
}
public class TestViewModel
{
[Key]
public int testId { get; set; }
public Test test { get; set; }
public decimal price { get; set; }
public decimal calculated { get; set; }
public TestViewModel(Test test)
{
Test = test;
calculated = Test.price * 2;
}
}
}
It gave me an error so I changed the constructor:
public TestViewModel(Test test)
{
var foo = test;
calculated = foo.price * 2;
}
But now when I build the project, it creates a table called "TestViewModels", so I can not reach the data in the Tests table.
I think a viewmodel shouldn't have an id, but if it does not the scaffolder won't generate the controllers.
What is the correct way to use a viewmodel to show a calculated field in a view?
I could solve it without using the viewmodel
namespace Facturacion.Models
{
public class Test
{
public int testId { get; set; }
[Required]
public decimal price { get; set; }
public decimal calculated
{
get
{
return (decimal)(price*2);
}
}
}
}
Notice the calculated field does not have a set method.

Razor View Engine in Console App with Complex Bass Class

I'm using the Razor view engine to render some HTML which will then live within an XML document. the base class I'm using has a number of properties, along with a static method which will return a list of that object (using Dapper to populate the list). I'm having trouble executing the method since it needs to return the base class, which is an abstract class. Some sample code is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
using System.IO;
namespace LocalBranchesPOC
{
public abstract class PersonData : TemplateBase
{
#region Properties
public string RecordId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Variable1 { get; set; }
public string Variable2 { get; set; }
public string Variable3 { get; set; }
#endregion
public static List<PersonData> GetPeople()
{
const string QUERY = "SELECT [RecordId], [Name], [Address], [City], [County], [State], [Country], [Zip], [Phone], [Variable1], [Variable2], [Variable3] FROM Data.Person";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BranchLocator"].ConnectionString))
{
return getPeople(QUERY, conn);
}
}
private static List<PersonData> getPeople(string QUERY, SqlConnection conn)
{
conn.Open();
var result = conn.Query<PersonData>(QUERY).ToList();
conn.Close();
return result;
}
}
public abstract class TemplateBase
{
[Browsable(false)]
public StringBuilder Buffer { get; set; }
[Browsable(false)]
public StringWriter Writer { get; set; }
public TemplateBase()
{
Buffer = new StringBuilder();
Writer = new StringWriter(Buffer);
}
public abstract void Execute();
// Writes the results of expressions like: "#foo.Bar"
public virtual void Write(object value)
{
// Don't need to do anything special
// Razor for ASP.Net does HTML encoding here.
WriteLiteral(value);
}
// Writes literals like markup: "<p>Foo</p>"
public virtual void WriteLiteral(object value)
{
Buffer.Append(value);
}
}
}
Basically my call to PersonData.GetPeople() is failing because the PersonData class is abstract. Any thoughts would be appreciated. I'm using the example from here as my guide.
You're trying to merge the model and the view.
Don't do that; it cannot possibly work.
Instead, pass the model to the view as a separate property, perhaps loading it in the TemplateBase constructor.

Categories