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
Related
I have this code:
var a = 2;
I type using(...){} above declaration
Then I`m getting:
using(...)
{
}
var a = 2;
visual studio adds tab to a declaration. I want to prevent this, how I can achieve it ?
Edit: I added braces as I don`t want to have a inside using.
That is because the using statement executes codes whitin the scope the variable whitin the using exists. The correct syntax for using is:
using (var disposeMe = new DisposeMe())
{
// here you use the disposeMe object during its lifetime
var a = 2;
} // here disposeMe gets disposed.
With regards,
John
I have a small C# console application who's sole purpose is to receive records from a "Saved Search" in NetSuite(via SuiteTalk). I've been able to successfully connect and receive records from NetSuite for my Saved Search(the search runs fine through the web interface too), however when I attempt to access the results of the "Saved Search" through my application, I am unable to view them because the search object that is returned does not contain any data in the "recordList" property:
//Connect
var dataCenterAwareNetSuiteService = new DataCenterAwareNetSuiteService("XXXXXX");
dataCenterAwareNetSuiteService.Timeout = 1000 * 60 * 60 * 2;
//Adds Credentials etc...
dataCenterAwareNetSuiteService.tokenPassport = createTokenPassport();
//Setup Preferences
var prefs = new Preferences();
prefs.warningAsErrorSpecified = true;
prefs.warningAsError = false;
dataCenterAwareNetSuiteService.preferences = prefs;
var searchPrefs = new SearchPreferences();
dataCenterAwareNetSuiteService.searchPreferences = searchPrefs;
dataCenterAwareNetSuiteService.searchPreferences.pageSize = 5;
dataCenterAwareNetSuiteService.searchPreferences.pageSizeSpecified = true;
dataCenterAwareNetSuiteService.searchPreferences.bodyFieldsOnly = false;
dataCenterAwareNetSuiteService.searchPreferences.returnSearchColumns = false;
//Search
var tranSearchAdv = new TransactionSearchAdvanced();
var tranSearchRow = new TransactionSearchRow();
var tranSearchRowBasic = new TransactionSearchRowBasic();
tranSearchAdv.savedSearchId = "XXXX";
tranSearchRowBasic.internalId =
new SearchColumnSelectField[] { new SearchColumnSelectField() };
tranSearchRowBasic.tranId =
new SearchColumnStringField[] { new SearchColumnStringField() };
tranSearchRowBasic.dateCreated =
new SearchColumnDateField[] { new SearchColumnDateField() };
tranSearchRowBasic.total =
new SearchColumnDoubleField[] { new SearchColumnDoubleField() };
tranSearchRowBasic.entity =
new SearchColumnSelectField[] { new SearchColumnSelectField() };
tranSearchRow.basic = tranSearchRowBasic;
tranSearchAdv.columns = tranSearchRow;
//No errors,
//this works correctly and returns the "Saved Search" with the correct "totalRecords"
//but results.recordList == null while results.totalRecords = 10000000+
var results = dataCenterAwareNetSuiteService.search(tranSearchAdv);
I appears to me that the "recordList" object is the principal way data is retrieved from the results of a search(Related Java Example, Another Here). This is also the way the example API does it.
I have run this on multiple "Saved Search's" with the same results. I don't understand how you can have more than one record in "totalRecords" and yet the "recordList" remains null? Is there some configuration option that has to be set to allow me to access this property. Or maybe it's a security thing, the API user I have setup should have full access, is there anything else that need to be granted access?
NetSuite SuiteTalk is not well documented, and most of the examples online are not in C#, and not dealing with the issues that I'm experiencing. These factors make it very difficult to determine why the previously mentioned behavior is occurring, or even, to discover any alternative methods for retrieving the resulting data from the source "Saved Search".
Does anyone have any insight into this behavior? Is this the correct method of retrieving results from SuiteTalk? Is there any configuration from the API or Web Side that needs to be changed?
Update 1
I've also tried using the alternative way of getting result data by accessing the "searchRowList" object from the "SearchResult" object(suggested by #AdolfoGarza) However it returns mostly empty fields(null) similar to the "recordList" property I do not see a way to retrieve "Saved Search" data from this method.
Try getting the results with results.searchRowList.searchRow , thats how it works in php.
I was able to resolve the issue by removing this line in the code:
tranSearchRow.basic = tranSearchRowBasic;
Then like #AdolfoGarza reccomended, retrieving the results from "basic" field in "results.searchRowList"
For some reason the template API that I was using was setting up a "TransactionSearchAdvanced" referencing a blank "TransactionSearchBasic" record, not sure why but this was causing the results from "searchRowList" to be null. After removing it I now get non-null values in the proper fields.
As for "recordList", it's still null, not sure why, but as I have my data I don't think I'll continue to dig into this.
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.
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.
So, here is my hopefully unique spin on this common problem.
I do my query, get my objects then pass the object into a form where it populates the form with the data from the object (this is not passed in by reference).
I then edit the values of the object that was queried (via the form) and then return a new object constructed from the values in the form.
I then want to update this to the database. Attach does nothing (runs but does not update). SubmitChanges also does nothing (and both do nothing when used together).
What am I missing?
Update: here is the code I am using:
// In constructor
_dataMap = new DataMapDataContext();
_addresses = _dataMap.AddressItems
.Where(address => address.InsertUserName == _currentUser.Name).ToList();
public void EditButtonClick()
{
using (AddAddressForm form = new AddAddressForm(_addresses[_currentAddress]))
{
form.Text = "Edit Address";
if (DialogResult.OK == form.ShowDialog())
{
_addresses[_currentAddress] = form.Item;
_dataMap.SubmitChanges();
DisplayItem();
}
}
}
You'll need to get the record from the database, update it's values and then call SubmitChanges()
using(MyDataContext db = new MyDataContext())
{
// get the record
Product dbProduct = db.Products.Single(p => p.ID == 1);
// set new values
dbProduct.Quantity = 5;
dbProduct.IsAvailable = false;
// save them back to the database
db.SubmitChanges();
}
Turns out I was doing almost everything right.
I just needed to pass in the object I was editing by reference. That way when it got changed, it was not a new object that was returned, but the same one (that Linq-to-SQL already knew about.)
These are the two lines from the code above that got changed:
AddressItem itemToEdit = _addresses[_currentAddress];
using (AddAddressForm form = new AddAddressForm(ref itemToEdit))