This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am new to ASP.net C#. I have an application to get inputs from users and save in database. I have followed the N-tier architecture in creating this app upon request. I have created an object in the codebehind and set the input values to them and pass the object to a method in the Business Layer and also called a method in Data Access Layer to the Business Layer. The data is saved to the database within the method of the Data Access Layer. Please help.
Here's my codebehind :
try
{
OtherCompany om = new OtherCompany();
NDAStaff ns = new NDAStaff();
DateTime dt = Convert.ToDateTime(RadDatePicker1.SelectedDate);
om.Date = dt.ToShortDateString();
om.ComName = compName.Text;
om.RegNumber = compReg.Text;
om.Country = countryIncorp.Text;
om.RegOfficeAddress = officeAddr.Text;
om.ComRef = compRef.Text;
om.CoreBuss = busiCore.Text;
om.ComService = reqServ.Text;
int index = servList.Items.Count;
for (int i = 0; i < index; i++)
{
om.ReqServiceDetails[i] = servList.Items[i].Value;
}
om.ReprentName = fullName2.Text;
om.ReprentDesig = desigOther.Text;
om.Witness1Name = witFullName3.Text;
om.Witness1Desig = witDesig1.Text;
om.Witness1Address = witDept1.Text;
om.Witness2Name = witFullName4.Text;
om.Witness2Desig = witDesig4.Text;
om.Witness2Adress = witAddr4.Text;
ns.Staffname = fullName1.Text;
ns.Designation = desigSriLan.Text;
ns.Wit1Name = witFullName1.Text;
ns.Wit1Designation = witDesig1.Text;
ns.Wit1Department = witDept1.Text;
ns.Wit2Name = witFullName2.Text;
ns.Wit2Designation = witDesig2.Text;
ns.Wit2Department = witDept2.Text;
NDAGenProcessor ndap = new NDAGenProcessor();
OtherCompanyProcessor ocp = new OtherCompanyProcessor(om);
NDAstaffProcessor nsp = new NDAstaffProcessor();
int NADid = ocp.createNDAID();
//ndap.createPDF(om, ns, NADid);
ocp.getCompanyDetails(NADid);
nsp.addNDAstaffData(ns, NADid);
}
catch (Exception ex)
{
throw ex;
}
If you want to know what line of code causes the exception, than go to Debug->Exceptions and check the box Thrown Common Language Runtime Exceptions.
You will get so called First Chance Exception. Then debug your code and the debugger will stop in that very line which causes the exception.
Related
This question already has answers here:
What is the C# Using block and why should I use it? [duplicate]
(9 answers)
Closed 2 years ago.
I am using System.Runtime.Caching to persist variables in cache, but later i cannot access to them because are disposed and the program throws a ObjectDisposedException with the message: DbContext has been disposed
I didn't execute Object.Dispose(), so the class ObjectCacheare disposing it in background.
In what moment at what moment does it happen? after doing cache.add?
It can be avoided?
How i made it:
Making the list:
using (GesBrokerSuiteEntities ctx = new GesBrokerSuiteEntities())
{
rel_tareas_orquestador nuevoregistroOrquestador = new rel_tareas_orquestador();
nuevoregistroOrquestador.id_robot_hija = idProyindividual;
nuevoregistroOrquestador.id_robot_padre = 2;
nuevoregistroOrquestador.id_robot_tarea_padre = "2";
nuevoregistroOrquestador.id_robot_tarea_hija = idProyindividual - 1+"";
nuevoregistroOrquestador.id_tarea_hija = Int32.Parse(id2);
nuevoregistroOrquestador.id_tarea_padre = 2;
nuevoregistroOrquestador.sincronizada = 2;
nuevoregistroOrquestador.esperar_padre_completa = 2;
ctx.rel_tareas_orquestador.Add(nuevoregistroOrquestador);
listaRelTareasOrquestador.Add(ctx);
1-Adding the list to cache
CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);
cache.Add("listaOrquestador", listObject, cacheItemPolicy);
2-Then i get it in another method
listaRelTareasOrquestador = (List<GesBrokerSuiteEntities>)cache.Get("listaOrquestador");
After this, i cannot access to the content of the list because it disposed.
UPDATE: withing the using() works, the elements aren't disposed.
now the problem us this, when trying to get the saved values, it obtains the database rows:
nuevoregistroOrquestador.id_robot_hija = listaRelTareasOrquestador[0].rel_tareas_orquestador.FirstOrDefault().id_robot_hija;
I know it is executing a query in my DB, any way to obtain the data i saved previously? Like a local variable.
UPDATE 2
Now when i'm trying to access the values into the list,i am not receving the previous ones:
rel_tareas_orquestador nuevoregistroOrquestador = new rel_tareas_orquestador();
nuevoregistroOrquestador.id_robot_hija = listaRelTareasOrquestador[0].rel_tareas_orquestador.FirstOrDefault().id_robot_hija;
nuevoregistroOrquestador.id_robot_padre = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_padre;
nuevoregistroOrquestador.id_robot_tarea_padre = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_tarea_padre;
nuevoregistroOrquestador.id_robot_tarea_hija = registro.rel_tareas_orquestador.FirstOrDefault().id_robot_tarea_hija;
I know the methods are returning database values due to querys, how i can access to the list values i saved previously?
Visual Studio shows me that in debugging:
It is disposed immediately after the closing bracket (if you mean a construction like this):
using (var reader = new StringReader(manyLines))
{
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);
}
// reader disposed here
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a LINQ Statement to check if someone is entering the URL for a voucher Redemption. The way i get this voucher is by using a regular url, with an extra hashed CampaignID, Which is called my VoucherRedemption, as shown below.
if (Request.QueryString["voucherRedemption"] != null)
{
String VoucherRemption = Request.QueryString["voucherRedemption"];
MSCDatabaseDataContext MSCDB2 = new MSCDatabaseDataContext();
var getCampaign = from campaign in MSCDB2.Tbl_Campaigns
where campaign.Link.Contains(VoucherRemption)
select campaign;
var VoucherCampaign = getCampaign.FirstOrDefault();
campaignName.Value = VoucherCampaign.CampaignName;
campaignDescription.Value = VoucherCampaign.CampaignDescription;
txtStartDate.Text = VoucherCampaign.StartDate.ToString();
txtDateEnd.Text = VoucherCampaign.EndDate.ToString();
campaignAudience.Value = VoucherCampaign.Target.ToString();
txtDiscount.Text = VoucherCampaign.Discount.ToString();
txtTsCs.Text = VoucherCampaign.TermsConditions;
txtTsCs.ReadOnly = true;
CalendarExtender1.Enabled = false;
CalendarExtender2.Enabled = false;
txtStartDate.ReadOnly = true;
txtDateEnd.ReadOnly = true;
txtDiscount.ReadOnly = true;
txtEmail.Visible = true;
}
Now i keep getting a:
System.NullReferenceException: Object reference not set to an instance of an object.
But the weird thing is, is that yesterday it was working. But only yesterday. The other days it wasn't. Not its gone back to being broken. Is there somehow I can fix this?
Edit: I have checked that article, and still cant seem to find the problem. It was working yesterday
You don't have a null check after
var VoucherCampaign = getCampaign.FirstOrDefault();
this is very dangerous as it can return a default (aka null) at any time. The database connection could have failed, you got a timeout, there was no result from your query or you simply are not allowed to access the database. All would result in a null pointer when you try to use voucherCampaign. Try changing it to something like this:
.
var VoucherCampaign = getCampaign.FirstOrDefault();
if (VoucherCampaign == null) {
//print a error message here so you know soemthing is wrong
return;
}
//rest of your code
It wont resolve the reason why you get a null. But at least your application won't crash on a null pointer in this function. If you want to know why you don't get a return change the firstrodefault to a first and put a try catch around it. The exception in your catch block will hold more information about why your query did not work.
I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.
Consider follwing method of copying/cloning an object (all fields are copied into a new object)
public AangepastWerk CloneAdjustedWork(AangepastWerk pAdjustedWork)
{
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = pAdjustedWork.Verzorging,
VerzorgingId = pAdjustedWork.VerzorgingId
};
}
I have a form that opens up a childform where two objects (2 times the same object of the type mentioned above) is being passed. I open up the form like this:
//my selected Record
Record rec = DateGridAdjustedWorks.ActiveRecord;
AangepastWerk AWorkObject = (AangepastWerk)((DataRecord)rec).DataItem;
AangepastWerk AWorkObjectBackup = _Vm.CloneAdjustedWork(AWorkObject);
WindowModifyAdjustedWork windowForModify = new WindowModifyAdjustedWork(AWorkObject,AWorkObjectBackup, true);
windowForModify.Closing += new CancelEventHandler(OnModifyAWClosing);
windowForModify.ShowDialog();
In that childform I set the first object as DataContext. _adjustedWork and _adjustedWorkCopy are properties of the form
_adjustedWork = pAdjustedWork;
GridAdjustedWork.DataContext = AdjustedWork;
_adjustedWorkCopy = pAdjustedWorkCopy;
The Issue:
In the form i have the ability to alter the object while retaining the original object. the user can see the originalobject, so he has the possibilities to keep track of the changes (request by the user) BUT if i change something in my _adjustedWork (the object that is my datacontext) then my _adjustedWorkCopy (without any actions performed upon it in my code-behind) is changed aswell. My question to you bright minds is: Why does this happen and how do i work around it? What am i missing here (probably something very basic)?
I always do deep cloning with serializing to json.
In example with Servicestack you can:
var json = myObject.ToJson();
var clonedObject = json.FromJson<MyObject>();
return clonedObject;
Maybe this can help.
Found the reason why the Cloned Object recieved the changes as well
public AangepastWerk CloneAdjustedWork(AangepastWerk pAdjustedWork)
{
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = pAdjustedWork.Verzorging, <------------ Issue lies here
VerzorgingId = pAdjustedWork.VerzorgingId
};
}
pAdjustedWork.Verzorging is an object in this case. I needed to clone this object aswell.I assumed (incorrectly) that cloning as above mentionned would create a new separate 'VerzorgingsObject'.
The solution to my problem is:
MedicalCare_VM mcare_VM = new MedicalCare_VM();
return new AangepastWerk()
{
AangepastWerkID = pAdjustedWork.AangepastWerkID,
ArbeidsOngeval = pAdjustedWork.ArbeidsOngeval,
DatumCreatie = pAdjustedWork.DatumCreatie,
DatumLaatsteWijziging = pAdjustedWork.DatumLaatsteWijziging,
DatumOngeval = pAdjustedWork.DatumOngeval,
GewijzigdDoor = pAdjustedWork.GewijzigdDoor,
NietErkend = pAdjustedWork.NietErkend,
Stamnummer = pAdjustedWork.Stamnummer,
Verzorging = mcare_VM.CloneMedicalCare(pAdjustedWork.Verzorging),
VerzorgingId = pAdjustedWork.VerzorgingId
};
Cloning in:
Verzorging = mcare_VM.CloneMedicalCare(pAdjustedWork.Verzorging)
uses the same logic as mentioned before (copying every field).
Trying to create a prototype application that will post a new Requirement to HPQC 11.
I've managed to get a solid connection but when I attempt to add the blank requirement I get an AccessViolationException.
TDConnectionClass td = HPQC_Connect(); //Open a connection
ReqFactory myReqFactory = (ReqFactory)td.ReqFactory; //Start up the Requirments Factory.
Req myReq = (Req)myReqFactory.AddItem(DBNull.Value); //Create a new blank requirement (AccessViolationException)
myReq.Name = "New Requirement"; //Populate Name
myReq.TypeId = "1"; // Populate Type: 0=Business, 1=Folder, 2=Functional, 3=Group, 4=Testing
myReq.ParentId = 0; // Populate Parent ID
myReq.Post(); // Submit
Any ideas? I'm fairly new to C# and coding in general, so it's probably best to assume I know nothing.
After some significant working through the isse the following code works correctly:
private void HPQC_Req_Create_Click()
{
TDConnection td = null;
try
{
td = new TDConnection();
td.InitConnectionEx("server");
td.Login(HPQCUIDTextbox.Text.ToString(), HPQCPassTextbox.Text.ToString());
Console.WriteLine(HPQCPassTextbox.Text.ToString());
td.Connect("DEFAULT", "Test_Automation_Playground");
bool check = td.LoggedIn;
if (check == true)
{
Console.WriteLine("Connected.");
HPQCStatus.Text = "Connected.";
}
ReqFactory myReqFactory = (ReqFactory)td.ReqFactory;
Req myReq = (Req)myReqFactory.AddItem(-1); //Error Here
myReq.Name = "New Requirement 1";
myReq.TypeId = "1"; // 0=Business, 1=Folder, 2=Functional, 3=group, 4=testing
myReq.ParentId = 0;
myReq.Post();
Console.WriteLine("Requirement Created.");
HPQCStatus.Text = "Requirement Created.";
try
{
td.Logout();
td.Disconnect();
td = null;
}
catch
{ }
}
catch (Exception ex)
{
Console.WriteLine("[Error] " + ex);
try
{
td.Logout();
td.Disconnect();
td = null;
}
catch
{ }
}
This code requires that the Server be patched to QC 11 Patch 9 (Build 11.0.0.7274) in order to work. Previous versions cause errors, most notably the error in the question.
Requirements in ALM are hierarchical, when creating requirement you need to create it under some existing requirement.
What you want to do is get a hold of the root requirement, it's Id should be either 0 or 1, you can check it in ALM UI.
And then get an instance of ReqFactory from a property on that Root requirement.
And then add your requirement to that factory.
Also, make sure you are working on STA and not MTA thread.