c# selenium verify all links with navigating through them StaleElementReferenceException console application - c#

I keep getting a StaleElementReferenceException error when I try to find all links and navigate through them in my console application, I have the following code and tried all day to fix it yesterday but with no result:
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting the browser...");
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.site.ro");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Gathering the Links...");
List<IWebElement> links = new List<IWebElement>();
try
{
foreach (IWebElement item in driver.FindElements(By.TagName("a")))
{
try
{
if (item.Displayed == true)
{
item.Click();
Console.WriteLine("Item is displayed \a\n" + "Navigating to link...");
} else
{
continue;
}
Random r1 = new Random();
Random r2 = new Random();
Random r3 = new Random();
var last = r3.Next(1, 10) * 700;
var mseconds = r2.Next(1, 10) * 500;
var time = mseconds + r1.Next(1, 10) * 300;
Console.WriteLine("Waiting for " + (time + last) + " miliseconds before next link");
System.Threading.Thread.Sleep(time + last);
driver.Navigate().Back();
System.Threading.Thread.Sleep(2000);
}
catch (Exception e2)
{
Console.WriteLine(e2);
Console.ReadLine();
}
}
}
catch (Exception e1)
{
Console.WriteLine(e1);
Console.ReadLine();
}
Console.WriteLine("Test finished.");
driver.Quit();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
}

driver.FindElements(By.TagName("a")) is finding for you all the links on the page.
Then you are going to the another page using the first link : item.Click();
Finally you are going back driver.Navigate().Back();
But that's not the initial page (by selenium's opinion). And all the links stored at the first step are gone because your initial page is gone. That's why you can't click the second of them.
You need to refind all the links after each driver.Navigate().Back();
Or better store all the hrefs to a list like linksList.Add(Item.getAttribute("href")); and use stored hrefs.

Related

Selenium webdriver C# checking for text

Trying to write a test that checks if some words are on the page.
I'm getting a no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='webform - submission - questionnaire - form - ajax']/section[2]"} message and the test for textIsOnThePage fails, everything else passes. Haven't used C# for a long time and trying out testing for the first time, what am I missing with textIsOnThePage ? This is the Xpath that the browser gives me.
public class Tests
{
IWebDriver driver;
String test_url = "http://mytesturl.com";
private readonly Random _random = new Random();
public void start_browser()
{
driver = new EdgeDriver(#"C:\Users\ADMIN\Downloads\edgedriver_win64");
driver.Manage().Window.Maximize();
}
//I run some tests on the page
public void test_page()
{
driver.Url = test_url;
driver.Navigate().GoToUrl("http://mytesturl.com");
Thread.Sleep(5000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
try {IWebElement sButton2 = driver.FindElement(By.XPath("//button[#class='agree-button eu-cookie-compliance-secondary-button']"));
js.ExecuteScript("arguments[0].click()", sButton2);
} catch (Exception) { }
for (int a = 0; a < 10; a++)
{
Thread.Sleep(2500);
//I call out my method
TextIsOnThePage("weigh", "weight");
Thread.Sleep(2500);
}
private void TextIsOnThePage(string textToFind, string warning)
{
driver.Url = test_url;
driver.Navigate().GoToUrl("http://mytesturl.com");
Thread.Sleep(5000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var element = driver.FindElement(By.XPath("//*[#id='webform - submission - questionnaire - form - ajax']/section[2]"));
if (!string.IsNullOrEmpty(element.Text) && element.Text.Contains(textToFind))
{
Console.WriteLine("Text for " + warning + "is present");
}
else
{
Console.WriteLine(warning + " test failed");
}
}
public void close_Browser()
{
driver.Quit();
}
}

Telegram Flood prevention

There was such a problem: I ran the program many times and now it throws the following error FloodException: Flood prevention. Telegram now requires your program to do requests again only after 73611 seconds have passed (TimeToWait property). If you think the culprit of this problem may lie in TLSharp's implementation, open a Github issue please.
I attach the code below:
using System;
using System.Text;
using System.Windows.Forms;
using TeleSharp.TL;
using TeleSharp.TL.Messages;
using TLSharp.Core;
namespace tgBM
{
public partial class Form1: Form
{
string phone;
string code;
int n = 1;
StringBuilder sb = new StringBuilder ();
TelegramClient client = new TelegramClient (2646156, "08ec188e0bdee432e568120348f5f13a"); // create a client with parameters
public Form1 ()
{
InitializeComponent();
}
string str = "";
public async void authAsync()
{
var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
foreach (var element in dialogs.Chats)
{
TLChat chat = element as TLChat;
if (element is TLChannel)
{
var offset = 0;
TLChannel channel = element as TLChannel;
if (channel.Title == "TOPLES")
{
TLChannel ch = element as TLChannel;
TLInputPeerChannel inputPeer = new TLInputPeerChannel() {ChannelId = ch.Id, AccessHash = (long) ch.AccessHash};
while (n! = 11)
{
try
{
TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
(new TLRequestGetHistory() {Peer = inputPeer, Limit = 20, AddOffset = offset, OffsetId = 0});
var msgs = res.Messages;
if (res.Count> offset)
{
offset + = msgs.Count;
foreach (TLAbsMessage msg in msgs)
{
if (msg is TLMessage)
{
TLMessage message = msg as TLMessage;
str + = n.ToString () + "\ t" + message.Id + "\ t" + message.FromId + "\ t" + message.Message + Environment.NewLine;
}
if (msg is TLMessageService)
continue;
n ++;
}
}
else
break;
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
break;
}
}
}
}
textBox3.Text = str;
}
}
private async void button1_Click (object sender, EventArgs e)
{
phone = textBox1.Text;
await client.ConnectAsync (); // make a connection
var hash = await client.SendCodeRequestAsync(phone);
}
private async void button2_Click (object sender, EventArgs e)
{
code = textBox2.Text;
var user = await client.MakeAuthAsync(phone, await client.SendCodeRequestAsync(phone), code);
authAsync();
}
}
}
In a comment, you said are in a testing phase.
In this case, you should read https://core.telegram.org/api/auth#test-accounts
According to this page, there are 3 ways to perform tests while limiting the risk for FLOOD_WAIT errors:
Connect to the Test servers instead of the Production servers (seems not possible with TLSharp)
Use Test accounts with phone numbers 99966XYYYY (only available on Test servers)
Connect as a user with the phone number you use to create the API ID/Hash
I can do all that with WTelegramClient (TLSharp is no longer maintained and cannot connect to Telegram servers anymore)

Winforms background worker gets stuck

I am trying to build a simple code that joins csv files into one distinct file, but my background worker seems to have a mind of its own and my code gets stuck every time.
Here is my code for joining the file using the background worker:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (string.IsNullOrEmpty(saveFilePath))
{
this.Invoke(new MethodInvoker(delegate
{
btnBrowseSave.PerformClick();
}));
}
if (!string.IsNullOrEmpty(saveFilePath))
{
if (dragEventArgs != null)
files = (string[])dragEventArgs.Data.GetData(DataFormats.FileDrop);
int filesCount = 0, rowsCount = 0;
foreach (string file in files)
{
filesCount++;
int fileTotalLines = File.ReadAllLines(file).Length;
this.Invoke(new MethodInvoker(delegate
{
lblFileName.Text = "Loading file: " + file.Substring(file.LastIndexOf("\\") + 1);
lblTotalFiles.Text = "File " + filesCount + " of " + files.Length;
}));
using (StreamReader reader = new StreamReader(file))
{
using (StreamWriter writer = new StreamWriter(saveFilePath))
{
while (!reader.EndOfStream)
{
try
{
while (stopPosition > rowsCount)
{
reader.ReadLine();
rowsCount++;
}
string email = reader.ReadLine().Trim();
if (!string.IsNullOrEmpty(email) && !dicEmails.ContainsKey(email))
{
dicEmails.Add(email, null);
writer.WriteLine(email);
}
rowsCount++;
stopPosition++;
backgroundWorker.ReportProgress((rowsCount * 100 / fileTotalLines), (int)ProgressType.Row);
if (backgroundWorker.CancellationPending)
return;
}
catch (Exception ex)
{
hadReadErrors = true;
}
}
}
}
backgroundWorker.ReportProgress(0, (int)ProgressType.Row);
backgroundWorker.ReportProgress((filesCount * 100 / files.Length), (int)ProgressType.File);
}
}
}
catch (Exception ex)
{
hadReadErrors = true;
MessageBox.Show(ex.Message);
}
finally
{
backgroundWorker.Dispose();
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
switch ((int)e.UserState)
{
case (int)ProgressType.Row:
lblFileProgress.Text = e.ProgressPercentage + "%";
fileProgressBar.Value = e.ProgressPercentage;
break;
case (int)ProgressType.File:
lblTotalProgress.Text = e.ProgressPercentage + "%";
totalProgressBar.Value = e.ProgressPercentage;
break;
}
}
catch (Exception ex) { }
}
When I run in debug mode and go with the debugger I don't see any problems, but when I let the code run it self it gets stuck and crashes.
Can someone PLEASE help me and tell me what am I missing out here ?
Here is the exception:
Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in
'C:\Users\Develop\Desktop\ExcelBuilder\ExcelBuilder\bin\Debug\ExcelBuilder.vshost.exe'.
Additional information: The CLR has been unable to transition from COM context 0x90fb78
to COM context 0x90fc30 for 60 seconds. The thread that owns the destination
context/apartment is most likely either doing a non pumping wait or processing a very
long running operation without pumping Windows messages. This situation generally has
a negative performance impact and may even lead to the application becoming non
responsive or memory usage accumulating continually over time. To avoid this problem,
all single threaded apartment (STA) threads should use pumping wait primitives
(such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
I did a small example of your program, trying to guess what it must do (https://github.com/anderson-rancan/stackoverflow_28798348, drag and drop 4 files to the groupbox, lorem?.csv), and there is a few things that you should consider:
never try/catch a unknown exception, every exception or something you cannot deal with (https://msdn.microsoft.com/en-us/library/ms182137.aspx)
when using a BackgroundWorker on a form, use the "sender" for references to it, it's a thread safe object to your method (https://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx)
maybe you are updating too fast your form, change your Invoke method to BeingInvoke, and do the update async (https://msdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.110).aspx)
So, just fixing that was possible to run it, like this:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bckw = (BackgroundWorker)sender; // Recommended way, thread safe
try
{
if (string.IsNullOrEmpty(saveFilePath))
{
this.Invoke(new MethodInvoker(delegate
{
btnBrowseSave.PerformClick();
}));
}
if (!string.IsNullOrEmpty(saveFilePath))
{
if (dragEventArgs != null)
files = (string[])dragEventArgs.Data.GetData(DataFormats.FileDrop);
int filesCount = 0, rowsCount = 0;
foreach (string file in files)
{
filesCount++;
double fileTotalLines = File.ReadAllLines(file).Length;
this.BeginInvoke(new MethodInvoker(delegate
{
lblFileName.Text = "Loading file: " + file.Substring(file.LastIndexOf("\\") + 1);
lblTotalFiles.Text = "File " + filesCount + " of " + files.Length;
})); // Invoke async, way too fast this...
using (StreamReader reader = new StreamReader(file))
{
using (StreamWriter writer = new StreamWriter(saveFilePath))
{
while (!reader.EndOfStream)
{
try
{
while (stopPosition > rowsCount)
{
reader.ReadLine();
rowsCount++;
} // why are you using that? it won't get TRUE
string email = reader.ReadLine().Trim();
if (!string.IsNullOrEmpty(email) && !dicEmails.ContainsKey(email))
{
dicEmails.Add(email, null);
writer.WriteLine(email);
}
rowsCount++;
stopPosition++;
bckw.ReportProgress((int)Math.Round(rowsCount * 100 / fileTotalLines, 0), (int)ProgressType.Row);
if (bckw.CancellationPending)
return;
}
catch (Exception ex)
{
hadReadErrors = true;
throw; // Throw it again, or you won't know the Exception
}
}
}
}
bckw.ReportProgress(0, (int)ProgressType.Row);
bckw.ReportProgress((filesCount * 100 / files.Length), (int)ProgressType.File);
}
}
}
catch (Exception ex)
{
hadReadErrors = true;
MessageBox.Show(ex.Message);
}
finally
{
bckw.Dispose();
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//try
//{
switch ((int)e.UserState)
{
case (int)ProgressType.Row:
lblFileProgress.Text = e.ProgressPercentage + "%";
if (e.ProgressPercentage <= fileProgressBar.Maximum)
fileProgressBar.Value = e.ProgressPercentage;
break;
case (int)ProgressType.File:
lblTotalProgress.Text = e.ProgressPercentage + "%";
totalProgressBar.Value = e.ProgressPercentage;
break;
}
//}
//catch (Exception ex) { } // Don't catch everything
}
Finally, may I suggest another approach?
You're reading the file two times: one to get the number of lines, and another to read each line. Try to do this just once, you'll get a better result.

My C# multi-threaded console application seems to not be multithreaded

Here's my C# console program that uses Powerpoint to convert ppt files to folders of pngs. This is supposed to be an automated process that runs on its own server.
I expect that as soon as a thread creates an image from a file, it should immediately remove the images and the source file.
The actual behavior is that, if five threads are running, it'll wait for five folders of images to be created before any thread can move any files. I'm able to see the images being created, and compare that with the Console readout, so I can see that a thread isn't trying to move the file.
Only after all the other threads have made their images, will any thread try to move the files. I suspect this is wrong.
This is an Amazon EC2 Medium instance, and it appears to max out the CPU, so five threads might be too much for this.
I also find that I can hardly use Windows Explorer while this program is running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static int currThreads = 0;
static void Main(string[] args)
{
var inDir = args[0];
var outDir = args[1]+"\\";
var procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
Thread[] converterThreads = new Thread[threadLimit];
while (true)
{
System.Threading.Thread.Sleep(1000);
var filePaths = Directory.GetFiles(inDir, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".pptx") && !s.Contains("~$") || s.EndsWith(".ppt") && !s.Contains("~$"));
var arrPaths = filePaths.ToArray();
for(var i=0; i< arrPaths.Length; i++)
{
if (currThreads < threadLimit && currThreads < arrPaths.Length)
{
Console.WriteLine("currThreads= " + currThreads + " paths found= " + arrPaths.Length);
try
{
var fileNameWithoutExtension = arrPaths[currThreads].Replace(inDir, "").Replace(".pptx", "").Replace(".ppt", "").Replace("\\", "");
var filenameWithExtension = arrPaths[currThreads].Substring(arrPaths[currThreads].LastIndexOf("\\") + 1);
var dir = arrPaths[currThreads].Replace(".pptx", "").Replace(".ppt", "");
Conversion con = new Conversion(arrPaths[currThreads], dir, outDir, procDir, filenameWithExtension, fileNameWithoutExtension);
converterThreads[i] = new Thread(new ThreadStart(con.convertPpt));
converterThreads[i].Start();
Console.WriteLine(converterThreads[i].ManagedThreadId + " is converting " + fileNameWithoutExtension);
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to convert {0} ", arrPaths[i]) + e);
}
}
}
for (var i = 0; i < converterThreads.Length; i++)
{
if (converterThreads[i] != null)
{
if (!converterThreads[i].IsAlive)
{
converterThreads[i].Abort();
converterThreads[i].Join(1);
Console.WriteLine("thread " + converterThreads[i].ManagedThreadId + " finished, "+currThreads+" remaining");
converterThreads[i] = null;
}
}
}
if (currThreads == 0)
{
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
class Conversion{
static int numberOfThreads=0;
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
int elapsedTime;
System.Timers.Timer time;
public Conversion(String input, String output, String outDir, String processDir, String nameWith, String nameWithout)
{
this.input = input;
this.output = output;
this.outDir = outDir;
process = processDir;
this.nameWith = nameWith;
this.nameWithout = nameWithout;
numberOfThreads++;
Console.WriteLine("number of threads running: " + numberOfThreads);
Program.currThreads = numberOfThreads;
time = new System.Timers.Timer(1000);
time.Start();
time.Elapsed += new ElapsedEventHandler(OnTimedEvent);
elapsedTime = 0;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
elapsedTime++;
}
public void convertPpt()
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
try
{
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed");
}
moveFile();
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
Console.WriteLine("moving dir " + output);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
finally
{
numberOfThreads--;
Program.currThreads = numberOfThreads;
Console.WriteLine("took " + elapsedTime + "seconds");
}
}
}
}
Every 1000ms you get a list of files in inDir and potentially start a thread to process each file. You have very complex logic surrounding whether or not to start a new thread, and how to manage the lifetime of the thread.
The logic is too complex for me to spot the error without debugging the code. However, I would propose an alternative.
Have a single thread watch for new files and place the file path into a BlockingCollection of files for processing. That thread does nothing else.
Have N additional threads that retrieve file paths from the BlockingCollection and process them.
This is known as a Producer / Consumer pattern and is ideal for what you are doing.
The example code at the bottom of the linked MSDN page shows an implementation example.
On a side note, you are catching and swallowing Exception e3. Don't catch something you will not handle, it hides problems.

Custom compiler flicker open then close

Im working with the custom compiler from MSDN website. When I try to compile/run some test code (drag and drop to .exe), the console window opens then closes instead of staying open until I choose to close it. How do I keep it open?
Source: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx#S8
Program.cs
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
} //if
add a Console.ReadLine();
at the last inside the try block
try this
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
Console.Readkey();
}
} //if
else
{
Console.WriteLine("no args");
Console.ReadKey();
}
EDIT:--- passing argument problem
i have made this program and it works perfectly as far as getting filename as arguments
please have a look
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
else
{
Console.WriteLine("NO ARGS");
var fileName = Console.ReadLine();
Main(new string[] { fileName });
}
}
}

Categories