I have function which calculates quantity .Its working fine but some due to null values in field it does not return anything . these field can be null .i want to calculate only where both fields are not null. i think i need to use foreach but i dont know the way how can i use it here .
Help appreciated
private double Get_Quantity()
{
try
{
double sum = 0;
sum = (double)(from s in ManagerClass.oSqlData.table
where s.Demand.Order.Order_ID == Order_ID
where s.Demand.Order.Order_Date >= ManagerClass.startDate && s.Demand.Order.Order_Date <= ManagerClass.EndDate
select s.ValueA - s.ValueB ).Sum();
return sum;
}
catch
{
return 0;
}
}
Try like this;
sum = (double)(from s in ManagerClass.oSqlData.table
where (s.Demand != null && s.Demand.Order != null && s.Demand.Order.Order_ID == Order_ID)
&& (s.Demand != null && s.Demand.Order != null && s.Demand.Order.Order_Date >= ManagerClass.startDate && s.Demand.Order.Order_Date <= ManagerClass.EndDate)
&& s.ValueA != null
&& s.ValueB != null
select s.ValueA - s.ValueB).DefaultIfEmpty(0).Sum();
Related
When the check against the emailaddress is added to the if statement, as per below, the if statement if (origin.Equals(true)).
bool origin = false;
Contact contact = item as Contact;
foreach (Item subItem in contactItems)
{
Contact subcontact = subItem as Contact;
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine(contact.DisplayName + " " + subcontact.DisplayName);
Console.WriteLine(contact.EmailAddresses[EmailAddressKey.EmailAddress1]);
subcontact.Delete(DeleteMode.HardDelete);
}
catch
{
Console.WriteLine("Cannot delete" + " " + subcontact.DisplayName);
}
}
origin = true;
}
}
If I remove the if (origin.Equals(true)) or removed && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])) from the other if statement, the contact goes through the try-catch block.
Can anyone see why?
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)) && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)) && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
should be:
if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null)
&& ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName))
&& ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))
the problem as I can see, is in the amount of ( ) you use, which I believe is incorrect.
Try to clean up your if statements to prevent these types of mistakes from happening, since this one was pretty long, and a few of your parenthesis are unnecessary
EDIT:
I tried running some code and it works. I did make some mistakes in the sample of the IF statement I mentioned above.. Maybe try copying my code, and substituting your specific code into it. It should work this way.
public static void Main()
{
bool origin = false;
int[] t = {0,4,6,8,5,6,4,5};
foreach(int i in t){
if ((true || (true && true)) // if ((contact.DisplayName.Equals(subcontact.DisplayName) || (contact.DisplayName is null && subcontact.DisplayName is null))
&& ((true && true) || (true)) // && ((contact.CompanyName is null && subcontact.CompanyName is null) || (contact.CompanyName.Equals(subcontact.CompanyName)))
&& ((true && true) || (true))) // && ((contact.EmailAddresses[EmailAddressKey.EmailAddress1] is null && subcontact.EmailAddresses[EmailAddressKey.EmailAddress1] is null) || (contact.EmailAddresses[EmailAddressKey.EmailAddress1].Equals(subcontact.EmailAddresses[EmailAddressKey.EmailAddress1])))))
{
if (origin.Equals(true))
{
try
{
Console.WriteLine("here");
}
catch
{
Console.WriteLine("Cannot delete" );
}
}
origin = true;
}
}
}
I suggest a little Helper:
private bool EqualOrBothNull( string fromContact, string fromSubcontact )
{
if ( fromContact == null && fromSubcontact == null ) return true;
if ( fromContact != null && fromContact.Equals(fromSubcontact) ) return true;
return false;
}
then you can use it like this:
if ( EqualOrBothNull( contact.DisplayName, subContact.DisplayName ) &&
EqualOrBothNull( contact.CompanyName, subContact.CompanyName ) &&
EqualOrBothNull( contact.EmailAddresses[EmailAddressKey.EmailAddress1],
subContact.EmailAddresses[EmailAddressKey.EmailAddress1])
)
{
// ...
}
This increases readability and will make it easier to find the bug if any.
Thanks for all the potential answers unfortunately they didn't fix the issue, the code is much easier to read though! In the end I separated the email address check to another IF statement which seems to be working
I have managed to pull out the FirstorDefault() in the Query, however, some of these address types in the database actually have more than 1 address: therefore, I am trying to build an array of every address regarding each one.
The current code:
int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
queryID = busIDs[counter];
var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
int gath = 0;
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
var address = gathered[gath] as tblbus_address;
string test = "";
while (gath != address.Address1.Length)
{
var all = address.Address1;
test += address.Address1.ToString() + ",";
}
busAddr.Add(test);
}
else
{
busAddr.Add("No address for this type exists...");
}
counter++;
gath++;
}
I am receiving an error:
Index was outside the bounds of the array.
at this line:
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
Can anyone point me in the right direction? I know this structure is the issue but I cannot think how to approach the situation.
You are trying to get the element gathered[gath] when there are no items in gathered. Adding a check for null and Any will help you
if(gathered!=null && gathered.Any()
&& (gathered[gath] as tblbus_address) != null
&& !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
...
...
}
I am curious as to why this is giving me an error:
Input string was not in a correct format.
This error occurs because the screen is null so it should fail the check and not cause an exception.
if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)
First check if it is not null. Also use double && as single checks both arguments. Also you are better off with double.TryParse in case when input is in not numeric.
if (textDisplay.Text != null && double.Parse(textDisplay.Text) >= -2147483647)
Better version:
double value = 0;
if (double.TryParse(textDisplay.Text, out value) && value >= -2147483647)
Use TryParse instead of Parse and it won't raise exception and return boolean if it is valid
double res = 0;
if(double.TryParse("asd", out res))
{
var a = res;
};
try && instead
if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)
or
double #num;
if(double.TryParse(textDisplay.Text, out #num) && #num >= -2147483647)
return #num;
if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)
You should use double '&':
if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)
Use TryParse so It will not throw any error when TextBox value is empty or null
double displayValue = 0;
double.TryParse(textDisplay.Text, out displayValue)
if (displayValue >= -2147483647)
I think this will be an easy one, i think im missing something.
if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))
this code gives me the error that when casting cant be a number that is infinite.
Ive also tried:
if (((int)row.Cells["Pareto"].Value <= 50) && ((string)row.Cells["Pareto"].Value != null))
if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != ""))
any help would be great!
Im using winforms in visual studio 10 using C#.
error: "When casting from a number, the value must be less than infinite"
More of the Code if your interested:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//countpg
//countPg++;
pgtothold = Convert.ToSingle(row.Cells["Qty"].Value);
countPg += pgtothold;
//if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))
if ((Convert.ToDouble(row.Cells["Pareto"].Value)) && ((int)row.Cells["Pareto"].Value <= 50)
{
//top 50
//top++;
tempTop = Convert.ToSingle(row.Cells["Qty"].Value);
top += tempTop;
}
else
if (((int)row.Cells["Pareto"].Value > 50) && ((int)row.Cells["Pareto"].Value <= 100) && (row.Cells["Pareto"].Value != ""))
{
//50-100
tempMidt = Convert.ToSingle(row.Cells["Qty"].Value);
tmid += tempMidt;
}
else
if ((row.Cells["Pareto"].Value != null) && ((int)row.Cells["Pareto"].Value <= 50))
I think you want this. If the thing is null, it doesn't evaluate the rest of the AND.
I suggest you to use:
var data = System.Convert.ToInt32(row.Cells["Pareto"].Value);
if( data <=50 )
{
----
}
that will fail to 0 if the content is DBNull ( if this is acceptable ), so your code will result cleaner and safer.
The result from the datatable is most likely of type decimal. So try this:
if (((decimal)row.Cells["Pareto"].Value <= 50.0m) && (row.Cells["Pareto"].Value != null))
I am still in the process of learning Asp.Net. I have a question . I was using an if condition in which i was checking dataset values. It is throwing me an exception whenever it is checking the condition as the dataset has not got any value. How to overcome this.
Code for this is here:
DataSet ds = merchant.getIsactiveIsconfirmedforcancelaccount(merchantID);
if (_merchant.PackageID == (int)CommonHelper.Package.Free && _merchant.AccountStatus.Contains("Awaiting"))
{
spnMerchantActiveStatus.InnerHtml = ApplicationData.MSG_AWAITING_CONFIRMATION;
}
***else if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" && (ds.Tables[0].Rows[0]["Active"]).ToString() == "N")***
{
_merchant.AccountStatus = "Cancelled";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else if(_merchant.PackageID != (int)CommonHelper.Package.Free && ds1.Tables[0].Rows.Count == 0 && (ds2.Tables[0].Rows[0]["ConfirmationSrc"]).ToString() == "Admin")
{
_merchant.AccountStatus = "Free Trial";
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
else
spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
The exception here is "There is no row at position 0."
Seems like you do not have any rows in your tables[0]. You can add condition to check is rows > 0 and then continue with other conditions in the IF.
You are assuming you have rows in your DataSet.
Instead of
if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
you should do something like
if ((ds.Tables[0].Rows.Count() > 0) &&
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
But you really need to do fuller error checking than just that one condition affectin you right now.
EDIT: If it's not obvious why the above works, read up on short-circuiting of logical operators: http://msdn.microsoft.com/en-us/library/2a723cdk(VS.71).aspx
Try changing your else statement :
else if (
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")
{
_merchant.AccountStatus = "Cancelled"; spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
}
To
if ((null != ds.Tables[0]) && ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True") && ((ds.Tables[0].Rows[0]["Active"]).ToString() == "N"))
So that you check that the data set is not null before you check conditions on it.
or (as other posters say) check that you actually have rows in the dataset.
ds.Tables[0].Rows.Count() != 0