i have senario for change Active Status property use . IsActive .
i have problem with update entity in asp core and DomainDriven Desogn .
when i change the IsActive to True or False it create a new record inctance a update that recoed .
i put here my code :
Step One :
this is my controller , in this controller i call the Command :
public async Task<ApiReturn> ChangeUserActiveStatus(long id)
{
var result = await dispatchers.SendAsync(new UserActiveStateCommand { id = id });
if(result.Success)
{
return Ok();
}
return BadRequest(result.Exception);
}
step Two :
i send a request to the database and give The desired record :
public class UserActiveStateCommandHandler : ICommandHandler<UserActiveStateCommand, OperationResult<string>>, IScopedDepency
{
private readonly IDomainUnitOfWork unitOfWork;
private readonly IDispatchers dispatchers;
public UserActiveStateCommandHandler(IDomainUnitOfWork unitOfWork, IDispatchers dispatchers)
{
this.unitOfWork = unitOfWork;
this.dispatchers = dispatchers;
}
public async Task<OperationResult<string>> HandlerAsync(UserActiveStateCommand command)
{
var user = await dispatchers.QueryAsync(new GetUserByIdQuery { id = command.id });
if (user != null)
{
var u = new User();
var value = u.SetUser(user.Result.Id, user.Result.Email, user.Result.LastName, user.Result.Photo, user.Result.FirstName, user.Result.UserName, user.Result.PhoneNumber, !user.Result.IsActive);
await dispatchers.CallEvent(new UserActiveStateEvent { User = value });
return OperationResult<string>.BuildSuccessResult("success");
}
else
{
return OperationResult<string>.BuildFailure("fail");
}
}
}
}
this is that recoed and its correct :
"email": "kiadr9372#gmail.com",
"photo": null,
"lastName": "Dortaj",
"firstName": "Kianoush",
"userName": "kia9372",
"phoneNumber": "09159810616",
"securityStamp": "e7cd82a5-71f3-41a1-b239-4d705b6d5d35",
"isActive": false,
"phoneConfirm": false,
"emailConfirm": false,
"isLockOut": false,
"lockOutEnd": null,
"isFailurAccount": 0,
"userRoles": null,
"id": 1
step there :
i call Event for Update Record in database :
public class UserActiveStatusEventHandler : IEventHandler<UserActiveStateEvent> , IScopedDepency
{
private readonly IDomainUnitOfWork unitOfWork;
public UserActiveStatusEventHandler(IDomainUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public async Task HandelEventAsync(UserActiveStateEvent #event)
{
var state = await unitOfWork.UserRepository.UpdateUser(#event.User);
if (state.Success)
{
unitOfWork.Commit();
}
}
}
this is the update code in repository :
public async Task<OperationResult<bool>> UpdateUser(User user)
{
if (user != null)
{
try
{
context.Update(user);
return OperationResult<bool>.BuildSuccessResult(true);
}
catch (Exception ex)
{
return OperationResult<bool>.BuildFailure(ex);
}
}
return OperationResult<bool>.BuildFailure("user Cannot be null");
}
and this is the commit code :
public void Commit()
{
context.SaveChanges();
}
this is User Aggregate :
public class User : AggregrateRoot, IAggregate
{
#region Backing Field
private string _email;
private string _photo;
private string _userName;
private string _phoneNumber;
private string _firstName;
private string _lastName;
private Guid _securityStamp;
private bool _isActive;
private bool _phoneConfirm;
private bool _emailConfirm;
private bool _isLockOut;
private DateTimeOffset? _lockOutEnd;
private int _isFailurAccount;
#endregion
#region Properies
public string Email
{
get
{
return _email;
}
private set
{
_email = value;
SetNotification();
}
}
public string Photo
{
get
{
return _photo;
}
set
{
_photo = value;
SetNotification();
}
}
public string LastName
{
get
{
return _lastName;
}
private set
{
_lastName = value;
SetNotification();
}
}
public string FirstName
{
get
{
return _firstName;
}
private set
{
_firstName = value;
SetNotification();
}
}
public string UserName
{
get
{
return _userName;
}
private set
{
_userName = value;
SetNotification();
}
}
public string PhoneNumber
{
get
{
return _phoneNumber;
}
private set
{
_phoneNumber = value;
SetNotification();
}
}
public Guid SecurityStamp
{
get
{
return _securityStamp;
}
private set
{
_securityStamp = value;
SetNotification();
}
}
public bool IsActive
{
get
{
return _isActive;
}
private set
{
_isActive = value;
SetNotification();
}
}
public bool PhoneConfirm
{
get
{
return _phoneConfirm;
}
private set
{
_phoneConfirm = value;
SetNotification();
}
}
public bool EmailConfirm
{
get
{
return _emailConfirm;
}
private set
{
_emailConfirm = value;
SetNotification();
}
}
public bool IsLockOut
{
get
{
return _isLockOut;
}
private set
{
_isLockOut = value;
SetNotification();
}
}
public DateTimeOffset? LockOutEnd
{
get
{
return _lockOutEnd;
}
private set
{
_lockOutEnd = value;
SetNotification();
}
}
public int IsFailurAccount
{
get
{
return _isFailurAccount;
}
private set
{
_isFailurAccount = value;
SetNotification();
}
}
public ICollection<UserRole> UserRoles { get; set; }
#endregion
public User()
{
}
#region Private Constructor
private User(long id,string Email, string LastName, string photo, string FirstName, string UserName, string PhoneNumber, bool isActive)
{
this.Email = Email;
this.Photo = photo;
this.LastName = LastName;
this.FirstName = FirstName;
this.UserName = UserName;
this.PhoneNumber = PhoneNumber;
this.SecurityStamp = Guid.NewGuid();
this.IsActive = isActive;
this.PhoneConfirm = false;
this.EmailConfirm = false;
this.IsLockOut = false;
this.LockOutEnd = null;
this.IsFailurAccount = 0;
}
#endregion
#region Methonds
public User SetUser(string email, string lastName, string photo, string firstName, string userName, string phoneNumber, bool isActive = false)
{
var user = new User(email, lastName, firstName, photo, userName, phoneNumber, isActive);
return user;
}
public UserRole AddUserRole(long userId, long roleId)
{
return new UserRole().AddUserRole(userId, roleId);
}
#endregion
}
but problem is here : i create a new recoed in datebase but i need update that recoed . how can i solve this problem ???
I guess your problem occurs in UserActiveStateCommandHandler class.
You're fetching User from DB which should be tracked by EF by default.
Later you're creating new User object instance and provide changes on new object which is not recognized by EF as existing one.
You should update data directly on object returned from your query...
I am creating a help desk where one can create a new account. If the username is already in the database, you should get a message that tells you to take another username.
If the username is correct, the password must be provided with a hash before the data is entered in the database.
I have already searched for an answer via the internet but I don't find anything that works in my program.
//Declaratie private variabelen
private int _klantnummer;
private string _gebruikersnaam, _voornaam, _achternaam, _straatEnNummer, _postcode, _gemeente, _telefoonnummer, _email, _wachtwoord;
private bool _admin;
//Publieke eigenschappen
private int Klantnummer
{
get { return _klantnummer; }
set { _klantnummer = value; }
}
public string Gebruikersnaam
{
get { return _gebruikersnaam; }
set { _gebruikersnaam = value; }
}
public string Voornaam
{
get { return _voornaam; }
set { _voornaam = value; }
}
public string Achternaam
{
get { return _achternaam; }
set { _achternaam = value; }
}
public string StraatEnNummer
{
get { return _straatEnNummer; }
set { _straatEnNummer = value; }
}
public string Postcode
{
get { return _postcode; }
set { _postcode = value; }
}
public string Gemeente
{
get { return _gemeente; }
set { _gemeente = value; }
}
public string Telefoonnummer
{
get { return _telefoonnummer; }
set { _telefoonnummer = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string Wachtwoord
{
get { return _wachtwoord; }
set { _wachtwoord = value; }
}
public bool Admin
{
get { return _admin; }
set { _admin = value; }
}
//Default Constructor
public Klant()
{
Klantnummer = 0;
Gebruikersnaam = "";
Voornaam = "";
Achternaam = "";
StraatEnNummer = "";
Postcode = "";
Gemeente = "";
Telefoonnummer = "";
Email = "";
Wachtwoord = "";
Admin = false;
}
//Constructor met parameters
public Klant (string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
bool pAdmin)
{
this.Gebruikersnaam = pGebruikersnaam;
this.Voornaam = pVoornaam;
this.Achternaam = pAchternaam;
this.StraatEnNummer = pStraatEnNummer;
this.Postcode = pPostcode;
this.Gemeente = pGemeente;
this.Telefoonnummer = pTelefoonnummer;
this.Email = pEmail;
this.Wachtwoord = pWachtwoord;
this.Admin = pAdmin;
}
//Constructor met parameters met klantnummer
public Klant(int pKlantnummer, string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
bool pAdmin)
{
this.Klantnummer = pKlantnummer;
this.Gebruikersnaam = pGebruikersnaam;
this.Voornaam = pVoornaam;
this.Achternaam = pAchternaam;
this.StraatEnNummer = pStraatEnNummer;
this.Postcode = pPostcode;
this.Gemeente = pGemeente;
this.Telefoonnummer = pTelefoonnummer;
this.Email = pEmail;
this.Wachtwoord = pWachtwoord;
this.Admin = pAdmin;
}
What I usually do is make the username field unique in the database then use a try...catch on the call to the database. If it fails for a unique validation error I know the username was already used and respond to the user.
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.
This is the main class
[Table(Name = "scanResult")]
public class SniffResult
{
public SniffResult()
{
}
public SniffResult(Address address)
{
this.address = address;
}
private int _pk_SniffResult;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }
private int _fk_scan;
[Column(Storage = "_fk_scan", Name = "scan")]
public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }
private Scan _scan;
[Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
public Scan scan { get { return _scan; } set { this._scan = value; } }
private int _fk_address;
[Column(Storage = "_fk_address", Name = "address")]
public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }
private Address _address;
[Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
public Address address { get { return _address; } set { this._address = value; } }
private string _rawResult;
[Column(Storage = "_rawResult", Name = "raw")]
public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }
private int _code = -5;
[Column(Storage = "_code")]
public int code { get { return _code; } set { this._code = value; } }
private DateTime _scanDate = DateTime.Now;
[Column(Storage = "_scanDate")]
public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }
private int? _fk_proxy;
[Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }
private ProxyData _usedProxy;
[Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }
public string message { get; set; } = "";
public bool availability { get; set; }
public int planCode { get; set; }
public string planning { get; set; }
public override string ToString()
{
return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
}
}
This is one of the child classes
[Table(Name = "address")]
public class Address
{
private int _pk_address;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }
private string _provId;
[Column(Storage = "_provId")]
public string provId { get { return _provId; } set { this._provId = value; } }
private string _zipcode;
[Column(Storage = "_zipcode")]
public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }
private int _houseNumber;
[Column(Storage = "_houseNumber")]
public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }
private string _addressAddition;
[Column(Storage = "_addressAddition")]
public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }
public string ToAddresString()
{
return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
}
public override string ToString()
{
return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
}
}
I want to get SniffResult including the associated fields. But they are all null. This is the code I use:
SniffDAO dao = new SniffDAO();
var test = from sr in dao.SniffResults
where sr.fk_scan == 3
select sr;
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
one.address gives me a null, what am I doing wrong?
This is the Dao class
public class SniffDAO
{
private string currentDir;
private DataContext db;
public Table<Scan> Scans { get; set; }
public Table<SniffResult> SniffResults { get; set; }
public Table<Address> Addresses { get; set; }
public SniffDAO()
{
db = new DataContext(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");
db.ObjectTrackingEnabled = true;
Scans = db.GetTable<Scan>();
SniffResults = db.GetTable<SniffResult>();
Addresses = db.GetTable<Address>();
currentDir = Directory.GetCurrentDirectory();
}
public void save()
{
db.SubmitChanges();
}
}
You need to Include related entities like this:
SniffDAO dao = new SniffDAO();
var test = dao.SniffResults.Include(x=>x.address).Where(sr.fk_scan == 3);
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
I found the solution thanks to #Kris. I now use:
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<SniffResult>(sr => sr.address);
dlo.LoadWith<SniffResult>(sr => sr.usedProxy);
dlo.LoadWith<SniffResult>(sr => sr.scan);
db.LoadOptions = dlo; //db is the DataContext
See https://msdn.microsoft.com/en-us/library/bb548760(v=vs.110).aspx for more info
I'm pretty new to programming and have run into a problem with a basic application I am working on. I have a person class which resembles this...
Person
{
SqlConnection conn = new SqlConnection(#"Integrated Security=True; Data
Source=ME\MyPRESS;Initial Catalog=TEST5");
SqlCommand cmd = new SqlCommand("usp_employee", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#emp_id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
try
{
conn.Open();
{
department = dr["dept_name"].ToString();
fname = dr["emp_first_name"].ToString();
lname = dr["emp_last_name"].ToString();
email = dr["emp_email"].ToString();
phone = dr["emp_phone"].ToString();
position = dr["emp_position"].ToString();
address1 = dr["emp_address1"].ToString();
address2 = dr["emp_address2"].ToString();
city = dr["emp_city"].ToString();
state = dr["emp_state"].ToString();
postal_code = dr["emp_postal_code"].ToString();
// department = txtFirst_name.Text;
}
}
finally
{
// 3. close the reader
if (dr != null)
{
dr.Close();
}
// close the connection
if (conn != null)
{
conn.Close();
}
}
}
protected string department;
public string Department
{
get { return department; }
set { department = value; }
}
protected string fname;
public string Fname
{
get { return fname; }
set { fname = value;}
}
protected string lname;
public string Lname
{
get { return lname; }
set { lname = value; }
}
protected string email;
public string Email
{
get { return email; }
set { email = value; }
}
protected string position;
public string Position
{
get { return position; }
set { position = value; }
}
protected string address1;
public string Address1
{
get { return address1; }
set { address1 = value; }
}
protected string address2;
public string Address2
{
get { return address2; }
set { address2 = value; }
}
protected string phone;
public string Phone
{
get { return phone; }
set { phone = value; }
}
protected string city;
public string City
{
get { return city; }
set { city = value; }
}
protected string state;
public string State
{
get { return state; }
set { state = value; }
}
protected string postal_code;
public string Postal_Code
{
get { return postal_code; }
set { postal_code = value; }
}
}
I have a form and a db with a stored procedure to retrieve the data as you can see above....
Where I am lost is in wiring up my form to display the record from the stored procedure.
A simple way would be to define a constructor for your Person class:
public class Person
{
public Person(string Department, string fName /* etc */)
{
this.Department = Department;
this.fName = fName;
// and so on for all the fields
}
// the rest of the class definition goes here
}
Then when looping through the data, create a Person object using that constructor. Return the new Person object from your function.
That helps! I have it up and running now....
public Person(int id)
{
SqlConnection conn = new SqlConnection(#"Integrated Security=True; Data Source=JODIEPC\XPRESS;Initial Catalog=TEST5");
conn.Open();
SqlCommand cmd = new SqlCommand("usp_EmployeeSelect", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#emp_id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
department = dr["dept_name"].ToString();
fname = dr["emp_first_name"].ToString();
lname = dr["emp_last_name"].ToString();
email = dr["emp_email"].ToString();
phone = dr["emp_phone"].ToString();
position = dr["emp_position"].ToString();
address1 = dr["emp_address1"].ToString();
address2 = dr["emp_address2"].ToString();
city = dr["emp_city"].ToString();
state = dr["emp_state"].ToString();
postal_code = dr["emp_postal_code"].ToString();
}
}
protected int id;
protected string fname;
protected string lname;
protected string department;
protected string email;
protected string position;
protected string address1;
protected string address2;
protected string phone;
protected string city;
protected string state;
protected string postal_code;
public int Id
{
get { return id; }
set { id = value; }
}
public string Department
{
get { return department; }
set{ department = value; }
}
public string Fname
{
get { return fname; }
set { fname = value; }
}
public string Lname
{
get { return lname; }
set { lname = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public string Position
{
get { return position; }
set { position = value; }
}
public string Address1
{
get { return address1; }
set { address1 = value; }
}
public string Address2
{
get { return address2; }
set { address2 = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string Postal_Code
{
get { return postal_code; }
set { postal_code = value; }
}
}
---------winform---------------
private void btnSearch_Click(object sender, EventArgs e)
{
Person Emp = new Person(Int32.Parse(txtId.Text));
txtFirstName.Text = Emp.Fname;
txtLastName.Text = Emp.Lname;
txtEmail.Text = Emp.Fname;
txtPhone.Text = Emp.Phone;
txtDepartment.Text = Emp.Department;
txtPosition.Text = Emp.Position;
txtAddress1.Text = Emp.Address1;
txtAddress2.Text =Emp.Address2;
txtCity.Text = Emp.City;
txtState.Text = Emp.State;
txtPostalCode.Text = Emp.Postal_Code;
}
}
It's not the most creative way of going about it but it works....
Thanks alot guys....
I have this Business Layer/ Contactentry.ascx page which calls a stored prcoedure to insert data into sql database and then the page below calls this business layer method. the issue is this method
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString())
,Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone
,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry
,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
throws an error saying object refernece not set to an instance of an object although I have entered all values for the text fields.
using System;
using System.Data;
using System.Configuration;
using aspdotnet.DataAccessLayer;
namespace aspdotnet.BusinessLogicLayer
{
public class ContactEntry
{
private int _ContactID;
private string _Title;
private string _FirstName;
private string _MiddleName;
private string _LastName;
private string _JobTitle;
private string _Company;
private string _Website;
private string _OfficePhone;
private string _HomePhone;
private string _Mobile;
private string _Fax;
private string _OEmail;
private string _PEmail;
private string _OAStreet;
private string _OACity;
private string _OAState;
private string _OACountry;
private string _OAZipCode;
private string _PAStreet;
private string _PACity;
private string _PAState;
private string _PACountry;
private string _PAZipCode;
public int ContactID
{
get { return _ContactID; }
set { _ContactID = value; }
}
public string Title
{
get { return _Title; }
set { _Title = value; }
}
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string MiddleName
{
get { return _MiddleName; }
set { _MiddleName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public string JobTitle
{
get { return _JobTitle; }
set { _JobTitle = value; }
}
public string Company
{
get { return _Company; }
set { _Company = value; }
}
public string Website
{
get { return _Website; }
set { _Website = value; }
}
public string OfficePhone
{
get { return _OfficePhone; }
set { _OfficePhone = value; }
}
public string HomePhone
{
get { return _HomePhone; }
set { _HomePhone = value; }
}
public string Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
public string Fax
{
get { return _Fax; }
set { _Fax = value; }
}
public string OEmail
{
get { return _OEmail; }
set { _OEmail = value; }
}
public string PEmail
{
get { return _PEmail; }
set { _PEmail = value; }
}
public string OAStreet
{
get { return _OAStreet; }
set { _OAStreet = value; }
}
public string OACity
{
get { return _OACity; }
set { _OACity = value; }
}
public string OAState
{
get { return _OAState; }
set { _OAState = value; }
}
public string OACountry
{
get { return _OACountry; }
set { _OACountry = value; }
}
public string OAZipCode
{
get { return _OAZipCode; }
set { _OAZipCode = value; }
}
public string PAStreet
{
get { return _PAStreet; }
set { _PAStreet = value; }
}
public string PACity
{
get { return _PACity; }
set { _PACity = value; }
}
public string PAState
{
get { return _PAState; }
set { _PAState = value; }
}
public string PACountry
{
get { return _PACountry; }
set { _PACountry = value; }
}
public string PAZipCode
{
get { return _PAZipCode; }
set { _PAZipCode = value; }
}
public ContactEntry()
{
}
public ContactEntry(int ContactID, string Title, string FirstName, string MiddleName, string LastName, string JobTitle, string Company, string Website, string OfficePhone, string HomePhone, string Mobile, string Fax, string OEmail, string PEmail, string OAStreet, string OACity, string OAState, string OACountry, string OAZipCode, string PAStreet, string PACity, string PAState, string PACountry, string PAZipCode)
{
_ContactID=ContactID;
_Title=Title;
_FirstName = FirstName;
_MiddleName = MiddleName;
_LastName = LastName;
_JobTitle = JobTitle;
_Company = Company;
_Website = Website;
_OfficePhone = OfficePhone;
_HomePhone = HomePhone;
_Mobile = Mobile;
_Fax = Fax;
_OEmail=OEmail;
_PEmail=PEmail;
_OAStreet = OAStreet;
_OACity = OACity;
_OAState = OAState;
_OACountry =OACountry;
_OAZipCode = OAZipCode;
_PAStreet = PAStreet;
_PACity = PACity;
_PAState = PAState;
_PACountry = PACountry;
_PAZipCode = PAZipCode;
}
public bool Save()
{
if (_ContactID == 0)
return Insert();
else
return Update();
}
private bool Insert()
{
_ContactID = Convert.ToInt32(DBTask.ExecuteScalar(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Insert", _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode));
return (0 < _ContactID);
}
public static void Remove(int ContactID)
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Delete", ContactID);
}
private bool Update()
{
try
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Update", _ContactID, _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode);
return true;
}
catch
{
return false;
}
}
public void LoadContact(int ContactID)
{
DataSet ds = DBTask.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_GetContact", ContactID);
DataRow row = ds.Tables[0].Rows[0];
_ContactID=Convert.ToInt32(row["ContactID"].ToString());
_Title=row["Title"].ToString();
_FirstName = row["FirstName"].ToString();
_MiddleName = row["MiddleName"].ToString();
_LastName = row["LastName"].ToString();
_JobTitle = row["JobTitle"].ToString();
_Company = row["Company"].ToString();
_Website = row["Website"].ToString();
_OfficePhone = row["OfficePhone"].ToString();
_HomePhone = row["HomePhone"].ToString();
_Mobile = row["Mobile"].ToString();
_Fax = row["Fax"].ToString();
_OEmail=row["OfficialEmail"].ToString();
_PEmail=row["PersonalEmail"].ToString();
_OAStreet = row["OAStreet"].ToString();
_OACity = row["OACity"].ToString();
_OAState = row["OAState"].ToString();
_OACountry =row["OACountry"].ToString();
_OAZipCode = row["OAZip"].ToString();
_PAStreet = row["PAStreet"].ToString();
_PACity = row["PACity"].ToString();
_PAState = row["PAState"].ToString();
_PACountry = row["PACountry"].ToString();
_PAZipCode = row["PAZip"].ToString();
}
}
}
Insert form calling above function from Business Layer:
private void btnSave_Click(object sender, System.EventArgs e)
{
string Title = drplstTitle.SelectedItem.Text;
string FirstName = txtFirstName.Text;
string MiddleName = txtMiddleName.Text;
string LastName = txtLastName.Text;
string JobTitle = this.txtJobTitle.Text;
string Company = this.txtCompany.Text;
string Website = this.txtWebSite.Text;
string OfficePhone = this.txtOfficePhone.Text;
string HomePhone = this.txtHomePhone.Text;
string Mobile = this.txtMobile.Text;
string Fax = this.txtFax.Text;
string OEmail = this.txtOfficialEmail.Text;
string PEmail = this.txtPersonalEmail.Text;
string OAStreet = this.txtOAStreet.Text;
string OACity = this.txtOACity.Text ;
string OAState = this.txtOAState.Text;
string OACountry = this.txtOACountry.Text;
string OAZipCode = this.txtOAZipCode.Text;
string PAStreet = this.txtPAStreet.Text;
string PACity = this.txtPACity.Text;
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString()),Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
//AddEntry.Save();
}
I get object reference not set to an insance of object right after above method aspdotnet.BusinessLogicLayer.ContactEntry above. I see all values are being passed when I am debugging. I entered all values when entering values above but it still errors out. Not sure what I am missing. Please help , appreciate your time.
This line is suspicious:
Convert.ToInt32(Session["ContactID"].ToString())
Session["ContactID"] may return null and calling ToString() on null blows up. Convert.ToInt32(null) wouldn't throw an error - it would return 0, not NULL.
You to handle Session["ContactID"] for nulls and Empty before Converting it to Int32
Example :
ContactEntry cEntry = null;
if(Session["ContactID"] != null)
{
if(!String.IsNullOrEmpty(Session["ContactID"]))
{
cEntry = new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString());
}
}
Check your Session["ContactID"].
Consider changing your code to something like this...
//...
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
string contactIDstr = Session["ContactID"] as string;
int contactID = 0;
if(!String.IsNullOrEmpty(conactIDStr))
Int32.TryParse(contactIDStr, out contactID);
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry = new ContactEntry(
contentID,
Title,
FirstName,MiddleName,LastName,JobTitle,Company,
Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,
OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode
);