Selenium2 wait for specific element on a page - wait

I am using Selenium2(2.0-b3) web driver
I want to wait for a element to be present on the page. I can write like below and it works fine.
But I do not want to put these blocks for every page.
// Wait for search to complete
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
System.out.println("Searching ...");
return webDriver.findElement(By.id("resultStats")) != null;
}
});
I want to convert it into a function where I can pass elementid and the function waits for a specified time and returns me true of false based on element is found or not.
public static boolean waitForElementPresent(WebDriver driver, String elementId, int noOfSecToWait){
}
I am reading that wait does not return till page is loaded etc, but I want to write the above method so that i can click on link to a page and call waitForElementPresent method to wait for element in next page before I do anything with the page.
Can you please help me write the method, I am getting into issue because I do not know how to restructure the above method to be able to pass parameters.
Thanks
Mike

This is how I do that in C# (checks every 250 milliseconds for the element to appear):
private bool WaitForElementPresent(By by, int waitInSeconds)
{
var wait = waitInSeconds * 1000;
var y = (wait/250);
var sw = new Stopwatch();
sw.Start();
for (var x = 0; x < y; x++)
{
if (sw.ElapsedMilliseconds > wait)
return false;
var elements = driver.FindElements(by);
if (elements != null && elements.count > 0)
return true;
Thread.Sleep(250);
}
return false;
}
Call the function like this:
bool found = WaitForElementPresent(By.Id("resultStats"), 5); //Waits 5 seconds
Does this help?

You can do like this, new a class and add below method:
public WebElement wait4IdPresent(WebDriver driver,final String elementId, int timeOutInSeconds){
WebElement we=null;
try{
WebDriverWait wdw=new WebDriverWait(driver, timeOutInSeconds);
if((we=wdw.until(new ExpectedCondition<WebElement>(){
/* (non-Javadoc)
* #see com.google.common.base.Function#apply(java.lang.Object)
*/
#Override
public WebElement apply(WebDriver d) {
// TODO Auto-generated method stub
return d.findElement(By.id(elementId));
}
}))!=null){
//Do something;
}
}catch(Exception e){
//Do something;
}
return we;
}
Do not try to implement interface ExpectedCondition<>, that's a bad idea. I got some problems before. :)

from here:
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});

Related

ASP .NET MVC - how to change view when thread will finished

I want to make ActionResult with run a thread. When thread are running I will return View with loading but when thread finished the ActionResult return the another View
My code look like:
private static void ExecuteScrapper()
{
ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromFile(HostingEnvironment.MapPath("/PythonScript/main.py"));
var searchPath = pythonEngine.GetSearchPaths();
searchPath.Add(HostingEnvironment.MapPath("/PythonScript/"));
searchPath.Add(HostingEnvironment.MapPath("/PythonScript/drivers/"));
pythonEngine.SetSearchPaths(searchPath);
var result = pythonScript.Execute();
}
private ScrapperEnum.ScrapperOperations scraperParam;
private Thread t = new Thread(new ThreadStart(ExecuteScrapper));
public ActionResult RunScrapper(ScrapperEnum.ScrapperOperations operation)
{
scraperParam = operation;
t.Start();
bool run = false;
while(t.IsAlive)
{
if(!run)
{
run = true;
return View("ScrapperLoadingView");
}
}
return RedirectToAction("Scrapper");
}
I don't know exactly how to do that, because when in this code I return ScrapperLoginView it will break while so the function don't switch the View
You just need to add an else if I'm correct
while(t.IsAlive)
{
if(!run)
{
run = true;
return View("ScrapperLoadingView");
}
else
{
return RedirectToAction("Scrapper");
}
}
}

Loop in string and get word between 2 character and save to list

we have string example :
www.example.com/default.aspx?code-1/price-2/code-4/
i want to get integers from code and price and save to list of integers.
for example , 1 and 4 are codes , 2 is price for filter in site.
InBetween = GetStringInBetween("Brand-", "/", Example, false, false);
please help me.
Below is a simple program that completes your requirement.
class Program
{
public void GetCodesAndPrice(string url,out List<int> listOfCodes, out List<int> listOfPrice )
{
listOfCodes=new List<int>();
listOfPrice = new List<int>();
url = url.Substring(url.IndexOf('?')+1);
var strArray = url.Split('/');
foreach (string s in strArray)
{
if(s.ToLower().Contains("code"))
listOfCodes.Add(GetIntValue(s));
else if(s.ToLower().Contains("price"))
listOfPrice.Add(GetIntValue(s));
}
// Now you have list of price in "listOfPrice" and codes in "listOfCodes",
// If you want to return these two list then declare as out
}
public int GetIntValue(string str)
{
try
{
return Convert.ToInt32(str.Substring(str.IndexOf('-') + 1));
}
catch (Exception ex)
{
// Handle your exception over here
}
return 0; // It depends on you what do you want to return if exception occurs in this function
}
public static void Main()
{
var prog = new Program();
List<int> listOfCodes;
List<int> listOfPrice;
prog.GetCodesAndPrice("www.example.com/default.aspx?code-1/price-2/code-4/", out listOfCodes,out listOfPrice);
Console.ReadKey();
}
}
It is complete console program. Test it and Embed in your program. Hope this will help you

Caliburn Micro: How to add text to the bottom of a list box and display it

I'm trying to figure out how to add text to the bottom of a list box and display it. In WPF with code behind, I would grab the ScrollViewer and manipulate it, but I can't figure out how to do it with Caliburn...
You have a couple options.
1) In your ViewModel you can call GetView and cast it to your view type and get a reference to the ScrollViewer. Something like:
var myView = this.GetView() as MyView;
var myScrollView = myView.MyScrollView;
That works fine but isn't ideal if you're trying to not couple the view to the view model.
Option 2) is to implement IResult, see docs here.
public class ScrollViewResult : IResult
{
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
private ScrollViewResult ()
{
}
public void Execute (ActionExecutionContext context)
{
var view = context.View as FrameworkElement;
var scrollViewer = FindVisualChild<ScrollViewer>(view);
//do stuff to scrollViewer here
Completed (this, new ResultCompletionEventArgs { });
}
private static TChildItem FindVisualChild<TChildItem> (DependencyObject obj)
where TChildItem : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount (obj); i++)
{
var child = VisualTreeHelper.GetChild (obj, i);
if (child != null && child is TChildItem)
return (TChildItem)child;
var childOfChild = FindVisualChild<TChildItem> (child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
//this isn't required of course but comes in handy for
//having a static method and passing parameters to the
//ctor of the IResult
public static IResult DoSomething ()
{
return new ScrollViewResult ();
}
Then you can call it like:
public IEnumerable<IResult> SomeAction()
{
yield return ScrollViewResult.DoSomething();
}

Read File and Return Synchronously (Metro App)

I am writing a Metro App.
I am trying to read a file and return a float[] from the data. But no matter what I do, the function seems to return null. I have tried the solutions to similar questions to no luck.
For example if I use:
float[] floatArray = new ModelReader("filename.txt").ReadModel()
The result will be a null array.
However if I use:
new ModelReader("filename.txt")
The correct array will be printed to the console because "Test" also prints the array before returning it. This seems very weird to me.
Please give me some guidance, I have no idea what is wrong.
public class ModelReader
{
float[] array;
public ModelReader(String name)
{
ReadModelAsync(name);
}
public float[] ReadModel()
{
return array;
}
private async Task ReadModelAsync(String name)
{
await readFile(name);
}
async Task readFile(String name)
{
// settings
var path = #"Assets\models\" + name;
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// acquire file
var file = await folder.GetFileAsync(path);
// read content
var read = await Windows.Storage.FileIO.ReadTextAsync(file);
using (StringReader sr = new StringReader(read))
{
Test test = new Test(getFloatArray(sr));
this.array = test.printArray();
}
}
private float[] getFloatArray(StringReader sr) { ... }
public class Test
{
public float[] floatArray;
public Test(float[] floatArray)
{
this.floatArray = floatArray;
}
public float[] printArray()
{
for (int i = 0; i < floatArray.Length; i++)
{
Debug.WriteLine(floatArray[i]);
}
return floatArray;
}
}
You're trying to get the result of an asynchronous operation before it has completed. I recommend you read my intro to async / await and follow-up with the async / await FAQ.
In particular, your constructor:
public ModelReader(String name)
{
ReadModelAsync(name);
}
is returning before ReadModelAsync is complete. Since constructors cannot be asynchronous, I recommend you use an asynchronous factory or asynchronous lazy initialization as described on my blog (also available in my AsyncEx library).
Here's a simple example using an asynchronous factory approach:
public class ModelReader
{
float[] array;
private ModelReader()
{
}
public static async Task<ModelReader> Create(string name)
{
var ret = new ModelReader();
await ret.ReadModelAsync(name);
return ret;
}
...
}

Make multiple asynchronous calls and do something when they are completed

I have run into this problem across multiple programming languages and I was just wondering what the best way to handle it is.
I have three method calls that fire off asynchronously. Each one has a callback. I want to do something only when all three callbacks have completed.
What is the best way to code this? I usually end up with all these public bool flags and as you add more calls the code gets more convoluted.
Coming from C#, I would probably use WaitHandle.WaitAll. You can create an array of ManualResetEvent objects (one for each task to be completed), and pass that array to WaitAll. The threaded tasks will get one ManualResetEvent object each, and call the Set method when they are ready. WaitAll will block the calling thread until all tasks are done. I'll give a C# code example:
private void SpawnWorkers()
{
ManualResetEvent[] resetEvents = new[] {
new ManualResetEvent(false),
new ManualResetEvent(false)
};
// spawn the workers from a separate thread, so that
// the WaitAll call does not block the main thread
ThreadPool.QueueUserWorkItem((state) =>
{
ThreadPool.QueueUserWorkItem(Worker1, resetEvents[0]);
ThreadPool.QueueUserWorkItem(Worker2, resetEvents[1]);
WaitHandle.WaitAll(resetEvents);
this.BeginInvoke(new Action(AllTasksAreDone));
});
}
private void AllTasksAreDone()
{
// OK, all are done, act accordingly
}
private void Worker1(object state)
{
// do work, and then signal the waiting thread
((ManualResetEvent) state).Set();
}
private void Worker2(object state)
{
// do work, and then signal the waiting thread
((ManualResetEvent)state).Set();
}
Note that the AllTasksAreDone method will execute on the thread pool thread that was used to spawn the workers, and not on the main thread... I assume that many other languages have similar constructs.
If you really only want to wait for all to finish:
Create volatile counter
Synchronize access to counter
Increase counter on start
Decrease on callback fired
Wait for counter to reach 0
Use a semaphore.
Futures are very easy to use. Futures look like normal functions, except that they execute asynch.
The classes:
public struct FutureResult<T>
{
public T Value;
public Exception Error;
}
public class Future<T>
{
public delegate R FutureDelegate<R>();
public Future(FutureDelegate<T> del)
{
_del = del;
_result = del.BeginInvoke(null, null);
}
private FutureDelegate<T> _del;
private IAsyncResult _result;
private T _persistedValue;
private bool _hasValue = false;
private T Value
{
get
{
if (!_hasValue)
{
if (!_result.IsCompleted)
_result.AsyncWaitHandle.WaitOne();
_persistedValue = _del.EndInvoke(_result);
_hasValue = true;
}
return _persistedValue;
}
}
public static implicit operator T(Future<T> f)
{
return f.Value;
}
}
Here I use futures to simulate a deadlock:
void SimulateDeadlock()
{
Future> deadlockFuture1 = new Future>(() =>
{
try
{
new SystemData(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)
.SimulateDeadlock1(new DateTime(2000, 1, 1, 0, 0, 2));
return new FutureResult { Value = true };
}
catch (Exception ex)
{
return new FutureResult { Value = false, Error = ex };
}
});
Future> deadlockFuture2 = new Future>(() =>
{
try
{
new SystemData(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)
.SimulateDeadlock2(new DateTime(2000, 1, 1, 0, 0, 2));
return new FutureResult { Value = true };
}
catch (Exception ex)
{
return new FutureResult { Value = false, Error = ex };
}
});
FutureResult result1 = deadlockFuture1;
FutureResult result2 = deadlockFuture2;
if (result1.Error != null)
{
if (result1.Error is SqlException && ((SqlException)result1.Error).Number == 1205)
Console.WriteLine("Deadlock!");
else
Console.WriteLine(result1.Error.ToString());
}
else if (result2.Error != null)
{
if (result2.Error is SqlException && ((SqlException)result2.Error).Number == 1205)
Console.WriteLine("Deadlock!");
else
Console.WriteLine(result2.Error.ToString());
}
}
For those using JavaScript, consider using the pattern discussed at this Stackoverflow question:
javascript: execute a bunch of asynchronous method with one callback

Resources