List<IWebElement> shittyBiz = new List<IWebElement>();
var myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
for (int i = 0;i<=1000;i++){
myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
foreach (IWebElement business in myEles)
{
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var starRating = " ";
try
{
starRating = business.FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title");
}
catch (OpenQA.Selenium.NoSuchElementException)
{
MessageBox.Show("No stars");
continue;
}
starRating = Regex.Replace(starRating, #"[A-Za-z\s]", string.Empty);
float stars = float.Parse(starRating);
MessageBox.Show(stars.ToString());
if (stars <= 3)
{
//shittyBiz.Add(starRating);
MessageBox.Show("Shitty");
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
var bizName = business.FindElement(By.CssSelector(".biz-name"));
MessageBox.Show(bizName.Text);
shittyBiz.Add(bizName);
var bizLocation = business.FindElement(By.CssSelector(".secondary-attributes"));
MessageBox.Show(bizLocation.Text);
shittyBiz.Add(bizLocation);
}
else
{
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
MessageBox.Show("Too good");
}
}
try
{
driverGC.FindElement(By.CssSelector("div.arrange_unit > a.u-decoration-none")).Click();
continue;
}
catch (OpenQA.Selenium.NoSuchElementException)
{
MessageBox.Show("No more pages");
return;
//driverGC.Quit();
}
}
I can get the program to run fine the first time, but after it uses the try at the end, to go to the next page, i get the StaleElementReferenceException error almost immediately on the starRating in the first try. I have tried everything that I can think of, but not sure why it is throwing me that error.
When the DOM is refreshed or changed the driver loses all the elements it previously located. After moving to the new page myEles is not valid any more and that's why you get StaleElementReferenceException on business when you trying to use it to locate another element. The solution is to locate myEles each iteration and keep the location using indexes with for loop
int size = 1;
for (int i = 0; i < size; ++i)
{
var myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
size = myEles.Count();
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var starRating = " ";
try
{
starRating = myEles[i].FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title");
}
//...
// and don't forget to go back
driver.Navigate().Back();
}
Related
I've been searching this page and other pages in this matter. I know it's not possible to get the data inside the while loop with direct assigning of variables, so I've tried to put it to label before and it works but only to the first value of the finalcred and finaldeb. It will not reset to fetch another value, so my real question is; Is there any other way to get the value inside the while loop and use it outside?
I have tried to declare it outside while and assign default value and the result will always be the default. It will not change.
r = t.NewRow();
//somecode..all good here
while (counterdate <= monthval)
{
//allgood in this part
totalcred = 0;
totaldeb = 0;
balance = 0;
crednum = 0;
debnum = 0;
if (readgetcode1.HasRows)
{
while (readgetcode1.Read())
{
readgetcred.Read();
readgetdeb.Read();
if (readgetdeb.HasRows)
{
debnum = Convert.ToDecimal(readgetdeb.GetValue(0));
}
else
{
debnum = 0;
}
if (readgetcred.HasRows)
{
crednum = Convert.ToDecimal(readgetcred.GetValue(0));
}
else
{
crednum = 0;
}
totalcred += crednum;
totaldeb += debnum;
if (strType == "Debit")
{
balance = totaldeb - totalcred;
}
else
{
balance = totalcred - totaldeb;
}
allbal += balance;
}
}
else
{
allbal = 0;
}
if (readprevCred.HasRows)
{
prevBalNum = Convert.ToDecimal(readprevBal.GetValue(0));
}
else
{
prevBalNum = 0;
}
if (strType == "Debit")
{
finaldeb = prevBalNum + allbal;
finalcred = 0;
}
else
{
finalcred = prevBalNum + allbal;
finaldeb = 0;
}
counterdate++;
}//while counterdate looping
r["accntCode"] = codevalue;
r["accntName"] = accntnameval;
r["DebitAmount"] = finaldeb;//this is the problem
r["CreditAmount"] = finalcred;;//this is the problem
t.Rows.Add(r);
//while readcodecheck in counter for code
Is there a way to remove sections of a document where i can specify the beginning and ending tags?
i need a way that i can remove a section of the document by passing in both my start and end catches, (##DELETEBEGIN and ##DELETEEND)
for example i have this in my document:
Hello, welcome to this document
##DELETEBEGIN{Some values to check in the code}
Some text that will be removed if the value is true
##DELETEEND
Final Line
If you need to delete text from ##DELETEBEGIN to ##DELETEEND, where ##DELETEBEGIN is not at the beginning of a Paragraph and ##DELETEEND is not at the end of a Paragraph, this code should work.
DocX document = DocX.Load("C:\\Users\\phil\\Desktop\\text.docx");
bool flag = false;
List<List<string>> list1 = new List<List<string>>();
List<string> list2 = new List<string>();
foreach (Novacode.Paragraph item in document.Paragraphs)
{
//use this if you need whole text of a paragraph
string paraText = item.Text;
var result = paraText.Split(' ');
int count = 0;
list2 = new List<string>();
//use this if you need word by word
foreach (var data in result)
{
string word = data.ToString();
if (word.Contains("##DELETEBEGIN")) flag = true;
if (word.Contains("##DELETEEND"))
{
flag = false;
list2.Add(word);
}
if (flag) list2.Add(word);
count++;
}
list1.Add(list2);
}
for (int i = 0; i < list1.Count(); i++)
{
string temp = "";
for (int y = 0; y < list1[i].Count(); y++)
{
if (y == 0)
{
temp = list1[i][y];
continue;
}
temp += " " + list1[i][y];
}
if (!temp.Equals("")) document.ReplaceText(temp, "");
}
document.Save();
I have to give some credit to this post for looping through each word.
I think i have found a solution to this, at least it works for me, please let me know if there is anything i can do better:
the deleteCommand would be the ##DELETEBEGIN string and the deleteEndCommand would be the ##DELETEEND
private void RemoveSection(DocX doc, string deleteCommand, string deleteEndCommand)
{
try
{
int deleteStart = 0;
int deleteEnd = 0;
//Get the array of the paragraphs containing the start and end catches
for (int i = 0; i < doc.Paragraphs.Count; i++)
{
if (doc.Paragraphs[i].Text.Contains(deleteCommand))
deleteStart = i;
if (doc.Paragraphs[i].Text.Contains(deleteEndCommand))
deleteEnd = i;
}
if (deleteStart > 0 && deleteEnd > 0)
{
//delete from the paraIndex as the arrays will shift when a paragraph is deleted
int paraIndex = deleteStart;
for (int i = deleteStart; i <= deleteEnd; i++)
{
doc.RemoveParagraphAt(paraIndex);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public List<Location2D> Path(Location2D start, Location2D goal)
{
openset = new List<NodeInfo>(); // The set of tentative nodes to be evaluated, initially containing the start node.
closedset = new List<NodeInfo>(); // The set of nodes already evaluated.
path = new List<Location2D>(); // The path result.
came_from = new Dictionary<Location2D, Location2D>();
NodeInfo Start = new NodeInfo();
Start.SetLoction(start.X, start.Y);
Start.H = GetHValue(start, goal);
openset.Add(Start);
while (openset.Count > 0) { // while openset is not empty
NodeInfo current = CheckBestNode(); //the node in openset having the lowest f_score[] value
if (current.Location.Equals(goal)) {
ReconstructPathRecursive(current.Location);
return path;
}
for (int i = 0; i < 8; i++) { // neighbor nodes.
NodeInfo neighbor = new NodeInfo();
neighbor.SetLoction((ushort)(current.Location.X + ArrayX[i]), (ushort)(current.Location.Y + ArrayY[i]));
bool tentative_is_better = false;
if (closedset.Contains(neighbor))
continue;
if (!map.Cells[neighbor.Location.X, neighbor.Location.Y].Walkable) { closedset.Add(neighbor); continue; }
Double tentative_g_score = current.G + DistanceBetween(current.Location, neighbor.Location);
if (!openset.Contains(neighbor)) {
openset.Add(neighbor);
neighbor.H = GetHValue(neighbor.Location, goal);
tentative_is_better = true;
} else if (tentative_g_score < neighbor.G) {
tentative_is_better = true;
} else {
tentative_is_better = false;
}
if (tentative_is_better) {
came_from[neighbor.Location] = current.Location;
neighbor.G = tentative_g_score;
}
}
}
return null;
}
private void ReconstructPathRecursive(Location2D current_node)
{
Location2D temp;
if (came_from.TryGetValue(current_node, out temp)) {
path.Add(temp);
ReconstructPathRecursive(temp);
} else {
path.Add(current_node);
}
}
so am Implementing A* Algorithm and when it find the Goal it goes to the ReconstructPathRecursive
and then the app crash and throw this exception An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
and This thread is stopped with only external code frames on the call stack. External code frames are typically from framework code but can also include other optimized modules which are loaded in the target process.
idk what's wrong!
It doesn't really have to be recursive, because it's tail recursive. So you can rewrite it like this:
private void ReconstructPathIterative(Location2D current_node)
{
Location2D temp;
while (came_from.TryGetValue(current_node, out temp))
{
path.Add(temp);
current_node = temp;
}
path.Add(current_node);
}
That only helps if the path was simply too long to fit on the stack, not if it was infinite.
I fixed it by adding NodeInfo Parent {get; set; } as a filed inside the NodeInfo class, and I add new List<NodeInfo> called Nodes when tentative is better :-
if (tentative_is_better) {
neighbor.Parent = current;
nodes.Add(neighbor);
neighbor.G = tentative_g_score;
}
then when it finds the goal :-
if (current.Location.Equals(goal)){
ReconstructPath(current);
path.Reverse();
return path;
}
where ReconstructPath :-
private void ReconstructPath(NodeInfo current) {
if (current.Parent == null) return;
path.Add(current.Parent.Location);
ReconstructPath(current.Parent);
}
and it works fine now.
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)
I have an issue with a Loop that doesn't actually loop. I've posted a simplified version of my code below. Basically, using the NPOI excel library, I have an excel file with data on the first and second sheet, so I need to do a loop to get through both sheets.
Below is what I have done so far, however this only works through the first sheet and then exits. It fails to increment the variable w. As you can see, there are other loops implemented in this code which function fine so I don't get it.
It's been a very long day and perhaps I'm missing something very simple. I could have it placed wrong or something. If anyone else can spot what I might be doing wrong I'd be very grateful :)
public class SalesFileProcessor : ISalesProcessor
{
public List<FTPSalesRow> ProcessSalesFile(string filename)
{
try
{
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
int numberOfSheets = 2;
//Loop through sheets - does not work
for (int w = 0; w <= numberOfSheets; w++)
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheetAt(w);
HSSFRow row = null;
for (int i = 1; i <= sheet.LastRowNum; i++)
{
FTPSalesDetails t = null;
int currentColumn = 0;
try
{
ModelContainer ctn = new ModelContainer();
row = sheet.GetRow(i);
if (row == null)
{
continue;
}
t = new FTPSalesDetails
{
RowNumber = i,
InvoiceDate = GetCellValue(row.GetCell(0)),
CountrySoldIn = GetCellValue(row.GetCell(1)),
NetUnitsSold = GetCellValue(row.GetCell(2)),
Item = GetCellValue(row.GetCell(3)),
ProductCode = GetCellValue(row.GetCell(5)),
};
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
int Qty = int.Parse(t.NetUnitsSold);
for (int x = 0; x < Qty; x++)
{
ItemSale ts = new ItemSale
{
ItemID = GetItemID(t.ProductCode),
ManufacturerID = GetManufacturerID("Samsung"),
DateSold = DateTime.Now,
};
ctn.AddToItemSales(ts);
ctn.SaveChanges();
}
}
catch (IndexOutOfRangeException) { }
}
} //End Loop - the one that doesn't work
}
}
catch (IOException exp)
{
throw new FTPSalesFileProcessingException("Could not open the Sales data file", exp);
}
catch (Exception exp)
{
throw new FTPSalesFileProcessingException("An unknown eror occured during processing the file", exp);
}
return null;
}
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
I'm going to guess that this is being hit, causing your entire function to exit. If you are trying to exit out of that iteration of the for loop try a break; instead, or a continue as Mike M pointed out in the comments.
For what you say, assuming your variables are all ok that is the loop is not empty... have you checked you're not hiting this line in the first iteration?
if (t.ProductCode == null && t.NetUnitsSold == null)
{
return null;
}
Looking at the code, the only obvious thing sticking out to me is:
HSSFSheet sheet = templateWorkbook.GetSheetAt(w);
HSSFRow row = null;
for (int i = 1; i <= sheet.LastRowNum; i++)
I would guess that sheet.LastRowNum either equals 0 or 1.
Maybe the indexOutOfRangeException is thrown and thats beacuse you have only one iteration, or instead of <= you sholud use <. Does the sheet numbers start with zero ?