Check whether username is already in database - c#

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.

Related

Object loses data when PutParcable

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.

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

C# LINQ to SQL Invalid Object Name

public class AMCOMDB : DataContext
{
public Table<student> allStudents;
public Table<aClass> allClasses;
public AMCOMDB(string connection) : base(connection) { }
}
[Table(Name = "student")]
public class student
{
private string _studentName;
[Column(IsPrimaryKey =true,Storage ="_studentName")]
public string studentName
{
get { return this._studentName; }
set { this._studentName = value; }
}
private string _LARType;
[Column(Storage ="_LARType")]
public string LARType
{
get { return this._LARType; }
set { this._LARType = value; }
}
private string _studentType;
[Column(Storage = "_studentType")]
public string studentType
{
get { return this._studentType; }
set { this._studentType = value; }
}
private string _aviationLevel;
[Column(Storage = "_aviationLevel")]
public string aviationLevel
{
get { return this._aviationLevel; }
set { this._aviationLevel = value; }
}
private string _airDefenseLevel;
[Column(Storage = "_airDefenseLevel")]
public string airDefenseLevel
{
get
{
return this._airDefenseLevel;
}
set
{
this._airDefenseLevel = value;
}
}
private string _emergencyContact;
[Column(Storage = "_emergencyContact")]
public string emergencyContact
{
get
{
return this._emergencyContact;
}
set
{
this._emergencyContact = value;
}
}
[Table(Name = "grades")]
public class grades
{
private string _studentName;
[Column(IsPrimaryKey = true, Storage = "_studentName")]
public string studentName
{
get
{
return this._studentName;
}
set
{
this._studentName = value;
}
}
private int _ET;
[Column(Storage = "_ET")]
public int ET
{
get
{
return this._ET;
}
set
{
this._ET = value;
}
}
private int _CP;
[Column(Storage = "_CP")]
public int CP
{
get
{
return this._CP;
}
set
{
this._CP = value;
}
}
private int _SB;
[Column(Storage = "_SB")]
public int SB
{
get
{
return this._SB;
}
set
{
this._SB = value;
}
}
private int _EC;
[Column(Storage = "_EC")]
public int EC
{
get
{
return this._EC;
}
set
{
this._EC = value;
}
}
private int _finalGrade;
[Column(Storage = "_finalGrade")]
public int finalGrade
{
get
{
return this._finalGrade;
}
set
{
this._finalGrade = value;
}
}
}
[Table(Name = "classes")]
public class aClass
{
private string _classNumber;
[Column(IsPrimaryKey = true, Storage = "_classNumber")]
public string classNumber
{
get
{
return this._classNumber;
}
set
{
this._classNumber = value;
}
}
private string _courseSeries;
[Column(Storage = "_courseSeries")]
public string courseSeries
{
get
{
return this._courseSeries;
}
set
{
this._courseSeries = value;
}
}
private string _courseNumber;
[Column(Storage = "_courseNumber")]
public string courseNumber
{
get
{
return this._courseNumber;
}
set
{
this._courseNumber = value;
}
}
private string _distanceLearning;
[Column(Storage = "_distanceLearning")]
public string distanceLearning
{
get
{
return this._distanceLearning;
}
set
{
this._distanceLearning = value;
}
}
private string _classStartDate;
[Column(Storage = "_classStartDate")]
public string classStartDate
{
get
{
return this._classStartDate;
}
set
{
this._classStartDate = value;
}
}
private string _classEndDate;
[Column(Storage = "_classEndDate")]
public string classEndDate
{
get
{
return this._classEndDate;
}
set
{
this._classEndDate = value;
}
}
private string _primaryInstructor;
[Column(Storage = "_primaryInstructor")]
public string primaryInstructor
{
get
{
return this._primaryInstructor;
}
set
{
this._primaryInstructor = value;
}
}
private string _secondaryInstructor;
[Column(Storage = "_secondaryInstructor")]
public string secondaryInstructor
{
get
{
return this._secondaryInstructor;
}
set
{
this._secondaryInstructor = value;
}
}
private string _location;
[Column(Storage = "_location")]
public string location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
private string _TDYCosts;
[Column(Storage = "_TDYCosts")]
public string TDYCosts
{
get
{
return this._TDYCosts;
}
set
{
this._TDYCosts = value;
}
}
private string _studentCount;
[Column(Storage = "_studentCount")]
public string studentCount
{
get
{
return this._studentCount;
}
set
{
this._studentCount = value;
}
}
private List<grades> _classGrades;
[Column(Storage = "_classGrades")]
public List<grades> classGrades
{
get
{
return this._classGrades;
}
set
{
this._classGrades = value;
}
}
AMCOMDB ADB = new AMCOMDB(connectionString);
if (ADB.DatabaseExists())
{
var stud = ADB.GetTable<student>();
var clas = ADB.GetTable<aClass>();
IQueryable<string> query = from c in stud
where c.studentName.Length > 5
orderby c.studentName.Length
select c.studentName.ToUpper();
foreach (string name in query)
{
}
//var q = from a in ADB.GetTable<student>()
// select a;
//dtStudents = LinqQuerytoDataTable(q);
//var q1 = from a in ADB.GetTable<aClass>()
// select a;
//aClass c = new aClass();
//dtClasses = reformatDataTable(q1);
}
I receive the following when I try to get information from the database at (foreach (string name in query))
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'student'.
I also get this when I first create the database:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll
Additional information: Unable to determine SQL type for 'System.Collections.Generic.List`1[WindowsFormsApplication1.Form1+grades]'.
remove the word Name that is what worked for me
[Table("student")]
public class student

C# How to load data to messagebox

I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}

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