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))
{
...
...
}
Related
Im using the following code to split up a string and store it:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
The problem is i am getting
Index was outside the bounds of the array.
When proxyAdrs[2] is not there.
Sometimes proxyAdrs[2] will be there sometimes not.
How can i solve this?
Just check the length of the array returned in your if statement
if( proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
The reason you are getting the exception is that the split is returning array of size less than the index you are accessing with. If you are accessing the array element 2 then there must be atleast 3 elements in the array as array index starts with 0
You can check the length of array before accessing its element by index.
Change
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
To
if(proxyAdrs.Length > 2 )
{
item.Username = proxyAdrs[2];
}
Try this:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs.Length > 3 && proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
Check the length of proxyAdrs before you attempt to subscript a potentially non-existent item.
if ( proxyAdrs.Length > 1 ) {
item.Username = proxyAdrs[2];
}
It is that your i which might be lower than the 2 you are trying to set in as index :)
if i >= 2 then you can do all of the follwing:----
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
}
else I suggest you get out :D
But again, checking proxyAdrs.Lenght would be the best.
There are two options that may help you, depending of whether or not you form incoming data (variable linesProxy):
If you do form incoming data: Always include all parts of the string. In your case, always ensure you have 4 (assuming proxyAdrs[3] is the last) parts by adding additional : between 1st and 3rd values if no value for 2nd is provided. Thus after .Split() operation (ensure you don't activate RemoveEmptyStrings option ) your proxyAdrs[2] will be null and your sample will be fine.
Otherwise: if proxyAdrs[2] is the only part the can be empty following snippet can prevent crashing:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 3)
{
if(proxyAdrs[2] != null)
item.Username = proxyAdrs[2];
if (proxyAdrs[3] != null)
item.Password = proxyAdrs[3];
}
else
{
if(proxyAdrs[2] != null)
item.Password = proxyAdrs[2];
}
try
{
objCommonDD = new CommonDropDownBLL();
objCommonDDEntity = new CommonDropdownEntity();
//string strState=contextKey.ToString();
string[] contextKeySplit = contextKey.Split('^');
string strState = contextKeySplit[0].ToString();
string strPin = contextKeySplit[1].ToString();
objCommonDDEntity.TableName = "PCOM_PINCODES";
objCommonDDEntity.DeleteField = "";
objCommonDDEntity.TextField = "RTRIM(PIN_CITY_NAME) AS PC_DESC";
objCommonDDEntity.ValueField = "DISTINCT PIN_CITY_CODE AS PC_CODE";
objCommonDDEntity.StrCondition = " AND PIN_COUNTRY_CODE='IND' AND UPPER(PIN_CITY_NAME) LIKE UPPER('" + prefixText + "%') AND PIN_STATE_NAME='" + strState + "' AND PIN_CODE='" + strPin + "' ORDER BY PC_DESC";
DataTable dtCity = new DataTable();
dtCity = objCommonDD.GetData(objCommonDDEntity);
string[] items = new string[dtCity.Rows.Count];
int i = 0;
for (i = 0; i < dtCity.Rows.Count; i++)
{
items.SetValue(dtCity.Rows[i]["PC_DESC"].ToString(), i);
}
return items;
}
Here, Space is a class with (xposition, yposition, zposition, length, depth, height) as its elements and there is a list of type space.
I need to check with in the list whether it follows some conditions which are in if condition.
If it satisfies, then I merge the two spaces into single space. After that, I remove both the spaces which I have used. It actually means merging of two spaces into single space.
The new List is created. Again I treat it as new list and do the same procedure until it does not satisfies the conditions.
My problem is, it is going into infinite loop. I want to resolve this.
public class MergeSpace
{
public List<Space> Mergespace(List<Space> Listofspaces)
{
foreach (Space space1 in Listofspaces)
{
foreach (Space space2 in Listofspaces)
{
//int count = 0;
if ((space1.sheight == space2.sheight)
&& (space1.sdepth == space2.sdepth)
&& (space2.xposition == space1.xposition + space1.slength)
&& (space2.yposition == space1.yposition)
&& (space2.zposition == space1.zposition)
&& (space1.semptyspace == true)
&& (space2.semptyspace == true))
{
Space space = new Space();
space.xposition = space1.xposition;
space.yposition = space1.yposition;
space.zposition = space1.zposition;
space1.slength = space1.slength + space2.slength;
space.sheight = space1.sheight;
space.sdepth = space1.sdepth;
space.semptyspace = true;
Listofspaces.Add(space);
Listofspaces.Remove(space1);
Listofspaces.Remove(space2);
Mergespace(Listofspaces);
}
public class MergeSpace
{
public List<Space> Mergespace(List<Space> Listofspaces)
{
List<Space> mergedspacelist = new List<Space>();
int count=0;
foreach (Space space1 in Listofspaces)
{
foreach (Space space2 in Listofspaces)
{
//int count = 0;
if ((space1.sheight == space2.sheight)
&& (space1.sdepth == space2.sdepth)
&& (space2.xposition == space1.xposition + space1.slength)
&& (space2.yposition == space1.yposition)
&& (space2.zposition == space1.zposition)
&& (space1.semptyspace == true)
&& (space2.semptyspace == true))
{
Space space = new Space();
space.xposition = space1.xposition;
space.yposition = space1.yposition;
space.zposition = space1.zposition;
space1.slength = space1.slength + space2.slength;
space.sheight = space1.sheight;
space.sdepth = space1.sdepth;
space.semptyspace = true;
mergedspacelist .Add(space);
count++;
}
}
}
if(count>0)
{
Mergespace(mergedspacelist );
}
}
i dont know what your actual need is, i think this will avoid the infinite loop
Your conditions always will satisfy for same instance of Space. The instance will merge with itself.
if (!space1.Equals(space2))
{
if ((space1.sheight == space2.sheight)
...
}
I'm trying to select only those rows which have Parent ID = 0
int predecessor = Parent;
StringBuilder valuePath = new StringBuilder();
valuePath.Append(Parent.ToString());
DataRow[] drPar;
while (true)
{
drPar = dt.Select("MenuID=" + predecessor);
if (drPar != null)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
break;
}
drPar[0]["ParentID"].ToString().Equals("0") is giving me
Out of Bound exception ..
Help Please !
DataTable.Select does not return null when there's no matching DataRow but an array with Length==0.
But apart from that, why are you using an "infinite" loop for only one statement?
So this should work:
drPar = dt.Select("MenuID=" + predecessor);
if (drPar.Length != 0)
{
if (drPar[0]["ParentID"].ToString().Equals("0"))
{
// ...
}
}
The array drPar must be empty to give this error as it is the only index you use in your code.
Try
if (drPar != null && drPar.Length > 0)
I want to write a check for some conditions without having to use try/catch and I want to avoid the possibilities of getting Index Out of Range errors
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
So the problem I am facing is that in the second check I need to see whether I have one Item that is not empty. However, If I don't have Element[1], I get the Index Out of Range exception. The problem is that there could be 2 Elements and one(or both) of them may have empty Object arrays. The code will have to be executed only if one of thos Item strings is not empty.
Hopefully, I explained it well. How do I go about avoiding getting that exception under any condition?
Alright, you need some better null checking and some more cautious code here.
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
is just unacceptable.
First, let's null check
if (array != null)
{
if (array.Element != null)
for simplicity, you could use &&
if (array != null && array.Element != null)
then, inside that if, we use a for loop (since you're stuck on arrays) and null check it
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
then, since you have nested arrays, we loop again. This is called a nested loop, and it's generally bad practice, I'll show you why it works in a second.
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
Now, with all of that ugly nested loopyness, we've found out that your Item is not null.
On top of that, you have access to ALL of the potential values here, and can group them as you like. Here's how I would put the whole thing together for simplification.
List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
for (int i = 0; i < array.Element.length; ++i)
{
//bool found = false;
if (array.Element[i] != null && array.Element[i].Object != null)
{
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
arrayValues.Add(array.Element[i].Object[o].Item);
//if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
//found = true;
//break;
}
}
}
//if (found)
// break;
}
}
if (arrayValues.Count > 0)
{
//do stuff with arrayValues
}
Could use a LINQ method ElementAtOrDefault(index)
so if the element is not found it will be null.
var currentElem = Elems.ElementAtOrDefault(i);
if(currentElem != null)
// do something
else
// do something
Could you do something like:
if(array.Element[0] != null || array.Element[1] != null){
//execute code
}
Your code is probably subject to refactor.
I assume it can work this way:
var obj = array.Element.FirstOrDefault(x => x.Object.Length > 0);
if (obj != null)
{
if (obj.Object[0].Item.Length != 0)
{
// do whatever is necessary
}
}
I think you can put your check in right before your first if Check.
if (array.Length > 1 && array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
This should just short-circuit out if your array doesn't have both Elements.
Place both tests together using the short-circuit && so that the second test doesn't occur if the first fails:
object element0 = array.Element[0].Object;
object element1 = array.Element[1].Object;
// Ensure at least one Object array has a non-empty value.
if ((element0.Length > 0 && !string.IsNullOrEmpty((string)element0.Object[0].Item))
|| (element1.Length > 0 && !string.IsNullOrEmpty((string)element1.Object[1].Item)))
{
// ...
}
I am presuming it is Object[1] causing the exception--you weren't clear on that. If it is Element[1] that causes the exception (or both), then you need to pre-test the length of the array:
if ((array.Element[0].Length != 0 && HasValue(array.Element[0].Object))
|| (array.Element[1].Length > 1 && HasValue(array.Element[1].Object)))
{
// ...
}
// <summary>
// Returns true if the specified string array contains a non-empty value at
// the specified index.
// </summary>
private bool HasValue(System.Array array, int index)
{
return array.Length > index &&
!string.IsNullOrEmpty((string)array.Object[index].Item);
}
for (long i = 0; i <= (output3.Length); i++)
{
output1.WriteByte(output3[i]); -----> index out of range exception correct it
output1.WriteByte(output3rx[i]);
}
I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.
Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}
If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;
How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.
if (virtuals.Result == null)
make this
if (virtuals == null)