How to do a inner join using LINQ [duplicate] - c#

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.

Related

in what moment using System.Runtime.Caching dispose the objects [duplicate]

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

xamarin form cannot keep last state

I am trying to keep the state of some variable of my xamarin form when I close the app and start it but is not working
I have 2 variable "isconnected" and "eric"
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
After closing the app when I restart it and trying to get the values of my variable like this :
((bool)App.Current.Properties["UserIsConnected"] ))
((string)App.Current.Properties["userName"] ))
I have this error:
System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.
How can I saved my variable and get them when restart the app?
thanks in advance for your help
You need to check if the value is exist before we get the value of it. You can do it like this:
private async Task saveDataAsync() {
if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
//Do something awesome.
bool UserIsConnected = ((bool)App.Current.Properties["UserIsConnected"]);
string name = ((string)App.Current.Properties["userName"]);
System.Diagnostics.Debug.WriteLine("UserIsConnected= " + UserIsConnected +" name =" + name);
}
else {
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
}
}
You seem to be saving a property with the key "isconnected" and trying to retrieve it with a different key ("UserIsConnected").
EDIT:
OK, thanks for clearing that the error I pointed out was a typo. As for the problem, try this instead:
App.Current.Properties.Add("UserIsConnected", true);
await App.Current.SavePropertiesAsync();
And make sure you check if the key exists before using it:
if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
//Do something awesome.
}

NetSuite SuiteTalk TransactionSearchAdvanced: recordList equals null

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.

NullReferenceException generated after executing in 'Try' block [duplicate]

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.

How to get a list of defects in QC11.0 via C# OTA using BugFilter

I have successfully connected to QC using VBscript via the OTA interface. In VbScript I had the following code to filter out defects and get load them in a list.
BugFilter.Filter("BG_STATUS") = "Not Canceled and NOT Closed"
BugFilter.Filter("BG_PROJECT") = "Business*"
Set BugList = BugFilter.NewList()
The above worked flawlessly in Vbscript.
In C#.NET (4.0), I am able to connect to QC successfully but when I try to apply the filter , it give me a error..
TDConnection qcc = new TDConnection();
qcc.InitConnectionEx(sr);
qcc.ConnectProjectEx("XXXX", "------", "----", "-----");
if (qcc.Connected)
{
Console.WriteLine("connected");
BugFactory bf = (BugFactory)qcc.BugFactory;
bf.Filter["BG_STATUS"] = "Not Canceled and NOT Closed";
bf.Filter["BG_PROJECT"] = "Business*";
List bugs = (List)bf.NewList(bf.Filter);
on the last line of code , it gives me the following error "Could not convert argument 0 for call to NewList."
I am relative new to C#, Can anybody help me here?
Try bg.Filter.text()
You'd need to check the method, 'cause I do that in java. But there is a method by that name. How I normally do that is like this:
List bugs = (List)bg.NewList();
I usually pass a string into the bug factory by using the .Text property of the Filter object rather than the filter object itself.
For example, I've had success with handling the filtering like this:
var tdFilter = (TDFilter)bf_filter;
tdFilter["BG_STATUS"] = "Not Canceled and NOT Closed";
tdFilter["BG_PROJECT"] = "Business*";
var bugs = bf.NewList(tdFilter.Text);

Categories