Object loses data when PutParcable - c#

I created a user class and I initialize it like so:
User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
I then populated the object with the user data and to pass it to another activity I do it like so:
Intent intent = new Intent(this, typeof(MyActivity));
Bundle bundlee = new Bundle();
bundlee.PutParcelable("MyUser", MyUser); // Persist user class to next activity
intent.PutExtra("TheBundle", bundlee);
StartActivity(intent);
I then retrieve the user data in the other activity like so:
// I initialize a variable again
User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
MyUser = bundlee.GetParcelable("MyUser") as User;
I get all the data EXCEPT Address, City, and State. Weird ... I put breakpoints in the code and its all there when I put it in the bundle, but when I take it out those three fields are null strings. My user class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Object = Java.Lang.Object;
namespace MyAndroid
{
class User : Object, IParcelable
{
private string mUsername = "";
private string mPassword = "";
private string mFirstname = "";
private string mMiddleInitial = "";
private string mLastname = "";
private string mSuffix = "";
private string mAddress = "";
private string mCity = "";
private string mState = "";
private string mZip = "";
private string mZip4 = "";
private string mHomephone = "";
private string mCellphone = "";
private string mWorkphone = "";
private string mNationalOrgn = "";
private string mCountry = "";
private string mCompany = "";
private string mDepartment = "";
private string mSection = "";
private string mProgram = "";
private string mUsertype = "";
private string mEmailaddress = "";
[ExportField("CREATOR")]
public static UserCreator InitializeCreator()
{
return new UserCreator();
}
// properties
public string Username
{
get
{
return mUsername;
}
set
{
mUsername = value;
}
}
public string Password
{
get
{
return mPassword;
}
set
{
mPassword = value;
}
}
public string Firstname
{
get
{
return mFirstname;
}
set
{
mFirstname = value;
}
}
public string MiddleInitial
{
get
{
return mMiddleInitial;
}
set
{
mMiddleInitial = value;
}
}
public string Lastname
{
get
{
return mLastname;
}
set
{
mLastname = value;
}
}
public string Suffix
{
get
{
return mSuffix;
}
set
{
mSuffix = value;
}
}
public string Address
{
get
{
return mAddress;
}
set
{
mAddress = value;
}
}
public string City
{
get
{
return mCity;
}
set
{
mCity = value;
}
}
public string State
{
get
{
return mState;
}
set
{
mState = value;
}
}
public string Zip
{
get
{
return mZip;
}
set
{
mZip = value;
}
}
public string Zip4
{
get
{
return mZip4;
}
set
{
mZip4 = value;
}
}
public string Homephone
{
get
{
return mHomephone;
}
set
{
mHomephone = value;
}
}
public string Cellphone
{
get
{
return mCellphone;
}
set
{
mCellphone = value;
}
}
public string Workphone
{
get
{
return mWorkphone;
}
set
{
mWorkphone = value;
}
}
public string NationalOrgn
{
get
{
return mNationalOrgn;
}
set
{
mNationalOrgn = value;
}
}
public string Country
{
get
{
return mCountry;
}
set
{
mCountry = value;
}
}
public string Company
{
get
{
return mCompany;
}
set
{
mACompany = value;
}
}
public string Department
{
get
{
return mDepartment;
}
set
{
mDepartment = value;
}
}
public string Section
{
get
{
return mSection;
}
set
{
mSection = value;
}
}
public string Program
{
get
{
return mProgram;
}
set
{
mProgram = value;
}
}
public string Usertype
{
get
{
return mUsertype;
}
set
{
mUsertype = value;
}
}
public string Emailaddress
{
get
{
return mEmailaddress;
}
set
{
mEmailaddress = value;
}
}
public int DescribeContents()
{
return 0;
}
public User(string Username, string Password, string Firstname, string MiddleInitial, string Lastname, string Suffix,
string address, string city, string state, string Zip, string Zip4, string Homephone, string Cellphone, string Workphone,
string NationalOrgn, string Country, string Company, string Section, string Department, string Usertype,
string Emailaddress)
{
this.mUsername = Username;
this.mPassword = Password;
this.mFirstname = Firstname;
this.mMiddleInitial = MiddleInitial;
this.mLastname = Lastname;
this.mSuffix = Suffix;
this.mAddress = Address;
this.mCity = City;
this.mState = State;
this.mZip = Zip;
this.mZip4 = Zip4;
this.mHomephone = Homephone;
this.mCellphone = Cellphone;
this.mWorkphone = Workphone;
this.mNationalOrgn = NationalOrgn;
this.mCountry = Country;
this.mCompany = Company;
this.mSection = Section;
this.mDepartment = Department;
this.mUsertype = Usertype;
this.mEmailaddress = Emailaddress;
}
public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
dest.WriteString(this.Username);
dest.WriteString(this.Password);
dest.WriteString(this.Firstname);
dest.WriteString(this.MiddleInitial);
dest.WriteString(this.Lastname);
dest.WriteString(this.Suffix);
dest.WriteString(this.Address);
dest.WriteString(this.City);
dest.WriteString(this.State);
dest.WriteString(this.Zip);
dest.WriteString(this.Zip4);
dest.WriteString(this.Homephone);
dest.WriteString(this.Cellphone);
dest.WriteString(this.Workphone);
dest.WriteString(this.NationalOrgn);
dest.WriteString(this.Country);
dest.WriteString(this.Company);
dest.WriteString(this.Section);
dest.WriteString(this.Department);
dest.WriteString(this.Usertype);
dest.WriteString(this.Emailaddress);
}
}
class UserCreator : Object, IParcelableCreator
{
public Object CreateFromParcel(Parcel source)
{
return new User(source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(),
source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(),
source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(),
source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(), source.ReadString(),
source.ReadString(), source.ReadString());
}
public Object[] NewArray(int size)
{
return new Object[size];
}
}
}
I must be missing something ....

I think you got a bit of a naming issue here. Look at this part
public User(string Username, string Password, string Firstname, string MiddleInitial, string Lastname, string Suffix,
string address, string city, string state, string Zip, string Zip4, string Homephone, string Cellphone, string Workphone,
string NationalOrgn, string Country, string Company, string Section, string Department, string Usertype,
string Emailaddress)
{
this.mUsername = Username;
this.mPassword = Password;
this.mFirstname = Firstname;
this.mMiddleInitial = MiddleInitial;
this.mLastname = Lastname;
this.mSuffix = Suffix;
this.mAddress = Address;
this.mCity = City;
this.mState = State;
this.mZip = Zip;
this.mZip4 = Zip4;
this.mHomephone = Homephone;
this.mCellphone = Cellphone;
this.mWorkphone = Workphone;
this.mNationalOrgn = NationalOrgn;
this.mCountry = Country;
this.mCompany = Company;
this.mSection = Section;
this.mDepartment = Department;
this.mUsertype = Usertype;
this.mEmailaddress = Emailaddress;
}
Especially this:
this.mAddress = Address;
this.mCity = City;
this.mState = State;
The correct way would be:
this.mAddress = address;
this.mCity = city;
this.mState = state;
You are infact not using your parameters (these three at least)! This "error" is kinda mean, because your compiler is not complaining. That's because you actually are assigning your properties (=null) themselves and this is correct but certainly not intended here ;)!
Changing it to the above one should do the trick.

Related

Check whether username is already in database

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.

LINQ query does not return child fields

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

Wcf service saving changes to database using entity framework

I am trying to update/add data using wcf service and entity framework. I have 2 implementation of the same function. The first one is working perfectly. Here is the code for the first one:
public bool SaveEmployee(Employee employeeEntity)
{
Console.WriteLine("SaveEmployee has been executed");
using (var context = new iposEntities())
{
context.Database.Log = Console.Write;
using (var trans = context.Database.BeginTransaction())
{
try
{
if (employeeEntity.EmployeeID == 0)
{
context.employees.Add(new employee()
{
//EmployeeID=employeeEntity.EmployeeID,
NationalIDNo= employeeEntity.NationalIDNo,
FullNames= employeeEntity.FullNames,
Title = employeeEntity.Title.ToString(),
TitleOfCourtesy=employeeEntity.TitleOfCourtesy,
BirthDate=employeeEntity.BirthDate,
HireDate=employeeEntity.HireDate,
Address=employeeEntity.Address,
City=employeeEntity.City,
Phone=employeeEntity.Phone,
ReportsTo=employeeEntity.ReportsTo,
Salary=employeeEntity.Salary,
Password = employeeEntity.Password,
Status = Convert.ToSByte(employeeEntity.Status)
});
}
else
{
employee EmpEntity = context.employees.First(i => i.EmployeeID == employeeEntity.EmployeeID);
EmpEntity.NationalIDNo = employeeEntity.NationalIDNo;
EmpEntity.FullNames = employeeEntity.FullNames;
EmpEntity.Title = employeeEntity.Title.ToString();
EmpEntity.TitleOfCourtesy = employeeEntity.TitleOfCourtesy;
EmpEntity.BirthDate = employeeEntity.BirthDate;
EmpEntity.HireDate = employeeEntity.HireDate;
EmpEntity.Address = employeeEntity.Address;
EmpEntity.City = employeeEntity.City;
EmpEntity.Phone = employeeEntity.Phone;
EmpEntity.ReportsTo = employeeEntity.ReportsTo;
EmpEntity.Salary = employeeEntity.Salary;
EmpEntity.Password = employeeEntity.Password;
EmpEntity.Status = Convert.ToSByte(employeeEntity.Status);
context.Entry(EmpEntity).State = EntityState.Modified;
}
context.SaveChangesAsync();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine("An error occured during saving"+ex.Message);
}
}
}
return true;
}
The second implementation (which is not working) is here:
public bool SaveEmployee(Employee employeeEntity)
{
Console.WriteLine("SaveEmployee has been executed");
using (var context = new iposEntities())
{
context.Database.Log = Console.Write;
using (var trans = context.Database.BeginTransaction())
{
try
{
if (employeeEntity.EmployeeID == 0)
{
context.employees.Add(employeeEntity);
}
else
{
context.Entry(employeeEntity).State = EntityState.Modified;
}
context.SaveChangesAsync();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine("An error occured during saving"+ex.Message);
}
}
}
return true;
}
Here is a error message from Visual studio: Error 10 Argument 1: cannot convert from 'iPos.Interfaces.Employee' to 'iPos.Service.employee' C:\Dropbox\UniversalApp\iPos\iPos.Service\PosService.cs 241 51 iPos.Service
Please help what am i doing wrong? I believe my Employee POCO Class is Ok. Here is my POCO Class
public class Employee : IEditableObject, INotifyPropertyChanged
{
EmployeeData backupEmplData;
private int employeeID;
private string nationalIDNo;
private string fullNames;
private OccupationPositions title;
private string titleOfCourtesy;
private Nullable<System.DateTime> birthDate;
private Nullable<System.DateTime> hireDate;
private string address;
private string city;
private string phone;
private Nullable<int> reportsTo;
private Nullable<float> salary;
private string password;
private bool status;
private string photo;
public struct EmployeeData
{
internal int employeeID;
internal string nationalIDNo;
internal string fullNames;
internal OccupationPositions title;
internal string titleOfCourtesy;
internal Nullable<System.DateTime> birthDate;
internal Nullable<System.DateTime> hireDate;
internal string address;
internal string city;
internal string phone;
internal Nullable<int> reportsTo;
internal Nullable<float> salary;
internal string password;
internal bool status;
}
public Employee()
{
}
public enum OccupationPositions
{
GeneralEmployee,
CEO,
Casheer,
Accountant,
Foreperson,
InventoryOfficer,
StockManager,
supervisor,
Security,
SuppliesManager,
StaffManager,
HygeneStaff,
SalesRepresentative,
HR,
MarketingOfficer,
FinancialOfficer,
Receptionist,
MarketingManager,
PurchasingManager,
Consultant,
}
public Employee(int employeeID, string nationalIDNo, string fullNames, OccupationPositions title, string titleOfCourtesy, Nullable<System.DateTime> birthDate, Nullable<System.DateTime> hireDate, string address, string city, string phone, Nullable<int> reportsTo, Nullable<float> salary, string password, bool status)
{
this.backupEmplData = new EmployeeData();
backupEmplData.employeeID = employeeID;
EmployeeID = employeeID;
backupEmplData.nationalIDNo = nationalIDNo;
NationalIDNo = nationalIDNo;
backupEmplData.fullNames = fullNames;
FullNames = fullNames;
backupEmplData.title = title;
Title = title;
backupEmplData.titleOfCourtesy = titleOfCourtesy;
TitleOfCourtesy = titleOfCourtesy;
backupEmplData.birthDate = birthDate;
BirthDate = birthDate;
backupEmplData.hireDate = hireDate;
HireDate = hireDate;
backupEmplData.address = address;
Address = address;
backupEmplData.city = city;
City = city;
backupEmplData.phone = phone;
Phone = phone;
backupEmplData.reportsTo = reportsTo;
ReportsTo = reportsTo;
backupEmplData.password = password;
Password = password;
backupEmplData.status = status;
Status = status;
}
public void BeginEdit()
{
this.backupEmplData.employeeID = EmployeeID;
this.backupEmplData.nationalIDNo = NationalIDNo;
this.backupEmplData.fullNames = FullNames;
this.backupEmplData.title = Title;
this.backupEmplData.titleOfCourtesy = TitleOfCourtesy;
this.backupEmplData.birthDate = BirthDate;
this.backupEmplData.hireDate = HireDate;
this.backupEmplData.address = Address;
this.backupEmplData.city = City;
this.backupEmplData.phone = Phone;
this.backupEmplData.reportsTo = ReportsTo;
this.backupEmplData.salary = Salary;
this.backupEmplData.password = Password;
this.backupEmplData.status = Status;
}
public void CancelEdit()
{
EmployeeID=this.backupEmplData.employeeID;
NationalIDNo= this.backupEmplData.nationalIDNo;
FullNames= this.backupEmplData.fullNames;
Title= this.backupEmplData.title;
TitleOfCourtesy=this.backupEmplData.titleOfCourtesy;
BirthDate=this.backupEmplData.birthDate;
HireDate=this.backupEmplData.hireDate;
Address=this.backupEmplData.address;
City=this.backupEmplData.city;
Phone=this.backupEmplData.phone;
ReportsTo=this.backupEmplData.reportsTo;
Salary=this.backupEmplData.salary;
Password = this.backupEmplData.password;
Status = this.backupEmplData.status;
}
public void EndEdit()
{
this.backupEmplData.employeeID = EmployeeID;
this.backupEmplData.nationalIDNo=NationalIDNo;
this.backupEmplData.fullNames=FullNames;
this.backupEmplData.title=Title;
this.backupEmplData.titleOfCourtesy=TitleOfCourtesy;
this.backupEmplData.birthDate=BirthDate;
this.backupEmplData.hireDate=HireDate;
this.backupEmplData.address=Address;
this.backupEmplData.city=City;
this.backupEmplData.phone=Phone;
this.backupEmplData.reportsTo=ReportsTo;
this.backupEmplData.salary=Salary;
this.backupEmplData.password=Password;
this.backupEmplData.status = Status;
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField=false)]
public int EmployeeID
{
get
{
return employeeID;
}
set
{
employeeID = value;
NotifyPropertyChanged("EmployeeID");
}
}
[DataMember(IsRequired = true)]
[Required]
public string NationalIDNo {
get
{
return nationalIDNo;
}
set
{
nationalIDNo = value;
NotifyPropertyChanged("NationalIDNo");
}
}
[DataMember(IsRequired = true)]
[Required]
public string FullNames {
get
{
return fullNames;
}
set
{
fullNames = value;
NotifyPropertyChanged("FullNames");
}
}
[DataMember(IsRequired = true)]
[Required]
[Display(Name = "Position")]
public OccupationPositions Title
{
get
{
return title;
}
set
{
title = value;
NotifyPropertyChanged("Title");
}
}
[DataMember(IsRequired = true)]
public string TitleOfCourtesy {
get
{
return titleOfCourtesy;
}
set
{
titleOfCourtesy = value;
NotifyPropertyChanged("TitleOfCourtesy");
}
}
[DataMember(IsRequired = true)]
[Required]
public Nullable<System.DateTime> BirthDate {
get
{
return birthDate;
}
set
{
birthDate = value;
NotifyPropertyChanged("BirthDate");
}
}
[DataMember(IsRequired = true)]
[Required]
public Nullable<System.DateTime> HireDate {
get
{
return hireDate;
}
set
{
hireDate = value;
NotifyPropertyChanged("HireDate");
}
}
[DataMember(IsRequired = true)]
public string Address {
get
{
return address;
}
set
{
address = value;
NotifyPropertyChanged("Address");
}
}
[DataMember(IsRequired = true)]
public string City {
get
{
return city;
}
set
{
city = value;
NotifyPropertyChanged("City");
}
}
[DataMember(IsRequired = true)]
[Required]
public string Phone {
get
{
return phone;
}
set
{
phone = value;
NotifyPropertyChanged("Phone");
}
}
[DataMember(IsRequired = true)]
[Display(Name="On Contract")]
public bool Status
{
get
{
return status;
}
set
{
status = value;
NotifyPropertyChanged("Status");
}
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField = false)]
public Nullable<int> ReportsTo {
get
{
return reportsTo;
}
set
{
reportsTo = value;
NotifyPropertyChanged("ReportsTo");
}
}
[DataMember(IsRequired = true)]
public Nullable<float> Salary {
get
{
return salary;
}
set
{
salary = value;
NotifyPropertyChanged("Salary");
}
}
[DataMember(IsRequired = true)]
[Required]
public string Password {
get
{
return password;
}
set
{
password = value;
NotifyPropertyChanged("Password");
}
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField = false)]
public string Photo
{
get
{
return photo;
}
set
{
photo = value;
NotifyPropertyChanged("Photo");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Looks like you have 2 versions of Employee:
one in 'iPos.Interfaces.Employee'
another in 'iPos.Service.employee'
Even if they use the same source code, for the compiler they are 2 different classes.
Just use only one.

How do I populate the data from my Stored Procedure into my winform?

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....

Getting object reference not set to an instance of object for Business layer code attached

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
);

Categories

Resources