private: System::Void link1_Click(System::Object^ sender, System::EventArgs^ e)
{
navigate(url1);
}
private: System::Void navigate(System::String^ url)
{
for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
{
if (webpageelement->GetAttribute("u"))
this->webBrowser->Document->GetElementById("u")->SetAttribute("value", url);
}
for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
{
if (webpageelement->GetAttribute("value") == "Go")
webpageelement->InvokeMember("click");
}
}
i have many other buttons that call the function navigate() but i will only post one coz they are all the same except the value of url. my question is how can i make my application to stop from exiting/have an error if i click the button even if the webpageelement("u") is not present in the form. coz if i click it even if the form is not yet loaded completely i got messagebox said unhandled exception error, i want to change that to something else or just ignore it and let my application try it again. thx
Using exception handling for such simple check is an overkill. Simply do following:
HtmlElement ele = this->webBrowser->Document->GetElementById("u");
if (ele != null)
ele->SetAttribute("value", url);
Using try and catch can give you some basic way... For example
for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
{
try
{
if (webpageelement->GetAttribute("u"))
this->webBrowser->Document->GetElementById("u")->SetAttribute("value", url);
}
catch (Exception^ ex)
{
// Do something here, can be blank...
// This will try the above code, if it doesn't work it will continue without any error popup
}
}
Related
It looks like paypal has updated their plugin lately and my code stopped working. I tried using Selenium IDE but when I record using it I do not see the Accept Cookie modal popup. I am able to get pass login as below, but I tried many different way to get to submit payment button with no luck. Help appreciated.
public IDictionary<string, object> vars { get; private set; }
vars = new Dictionary<string, object>();
_driver.SwitchTo().Frame(0);
vars["WindowHandles"] = _driver.WindowHandles;
_driver.FindElement(By.CssSelector(".paypal-button")).Click();
vars["win8061"] = waitForWindow(2000);
vars["root"] = _driver.CurrentWindowHandle;
_driver.SwitchTo().Window(vars["win8061"].ToString());
_driver.FindElement(By.Id("email")).SendKeys(paypalEmail);
_driver.FindElement(By.Id("btnNext")).Click();
_driver.FindElement(By.Id("password")).SendKeys(paypalPassword);
_driver.FindElement(By.Id("btnLogin")).Click();
//The problem is here!!!
var element = _driver.FindElement(By.Id("payment-submit-btn"));
Actions builder = new Actions(_driver);
builder.MoveToElement(element).Perform();
public string waitForWindow(int timeout)
{
try
{
Thread.Sleep(timeout);
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
var whNow = ((IReadOnlyCollection<object>)_driver.WindowHandles).ToList();
var whThen = ((IReadOnlyCollection<object>)vars["WindowHandles"]).ToList();
if (whNow.Count > whThen.Count)
{
return whNow.Except(whThen).First().ToString();
}
else
{
return whNow.First().ToString();
}
}
Had same issue recently after PayPal made some kind of changes to their "Pay" button. All of the sudden it stopped working. Below is what worked for me. There is no logic behind it, besides "just because it works".
After PayPal login; in your case after:
_driver.FindElement(By.Id("btnLogin")).Click();
Use:
Thread.Sleep(1000);
_driver.FindElement(By.Id("acceptAllButton")).Click();
try
{
_driver.FindElement(By.Id("payment-submit-btn")).Click();
}
catch
{
_driver.FindElement(By.Id("payment-submit-btn")).Click();
}
In a WPF app that follows the MVVM pattern, I've run across a common issue where a user clicks on a button which fires an event in the ViewModel. This event should enable a "Please Wait" spinner animation, do some processing which may take a few seconds, then hide the spinner. I'm not really sure of a good pattern I can use to make sure the spinner animation always appears.
As an example, I have a login process which does the following:
Displays spinner (set property on VM to true, spinner is bound to it)
Attempt to connect to server (can take a few seconds depending on connection)
On a failure, display a failure message
On success, save off some info about the user so it's available to the rest of the app.
What I'm finding is that the spinner never actually appears. I have tried wrapping the longer-running process in a Task.Run call, but that hasn't seemed to help.
Here's an approximation of what the code looks like:
// When true, spinner should be visible
protected bool _authenticatingIsVisible = false;
public bool AuthenticatingIsVisible
{
get { return _authenticatingIsVisible; }
set
{
_authenticatingIsVisible = value;
NotifyOfPropertyChange(() => AuthenticatingIsVisible);
}
}
public void Login()
{
try
{
AuthenticationIsVisible = true;
AuthCode result = AuthCode.NoAuthenticated;
Task.Run(() => { result = _client.Authenticate() }).Wait();
AuthenticationIsVisible = false;
if (result == AuthCode.Authenticated)
{
// Bit of misc. code to set up the environment
// Another check to see if something has failed
// If it has, displays a dialog.
// ex.
var error = new Error("Something Failed", "Details Here", Answer.Ok);
var vm = new DialogViewModel() { Dialog = error };
_win.ShowDialog(vm);
return;
}
else
{
DisplayAuthMessage(result);
}
}
finally
{
AuthenticationIsVisible = false;
}
}
The proper way would be not to block the UI thread (which is what you are doing right now with .Wait()), and use AsyncAwait instead.
private Task<AuthCode> Authenticate()
{
return Task.Run<AuthCode>(()=>
{
return _client.Authenticate();
});
}
public async void Login()
{
AuthenticationIsVisible = true;
AuthCode result = await Authenticate();
AuthenticationIsVisible = false;
}
While downloading a file, it shows download progress in the notification or somewhere.
But i think it is not by default in cn1 app. I want to add progress listener. How to make it work??
if (!FileSystemStorage.getInstance().exists(filename)) {
com.codename1.io.Util.downloadUrlToFile(PdfUrl, filename, true);
}
In my case used the code below.
/**
* Adaptation of Util.downloadUrlTo
*/
private boolean downloadUrlToAdapt(String url, final String fileName, boolean storage, final Slider slider) {
final ConnectionRequest cr = new ConnectionRequest();
cr.setPost(false);
cr.setFailSilently(true);
cr.setUrl(url);
if (storage) {
cr.setDestinationStorage(fileName);
} else {
cr.setDestinationFile(fileName);
}
NetworkManager.getInstance().addProgressListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt instanceof NetworkEvent) {
NetworkEvent e = (NetworkEvent) evt;
if (e.getProgressPercentage() >= 0) {
slider.setText(e.getProgressPercentage() + "%");
slider.setProgress(e.getProgressPercentage());
}
}
}
});
NetworkManager.getInstance().addToQueueAndWait(cr);
return cr.getResponseCode() == 200;
}
I needed to show video download progress. I hope it helps.
The way the browser downloads a file locally is a special case for browsers and unrelated to apps. You can just invoke Display.execute with a file and the browser will download it that way although I'm guessing its not what you want since it will not be accessible to you after the fact.
You can show progress using NetworkManager's progress listener. Showing the progress in the notification area is an Android specific behavior and uncommon on iOS. But you might be able to use some of the local notification features https://www.codenameone.com/blog/local-notifications.html
I used it the same way as Sadart Abukari.
Only thing I changed is I used the ToastBar.Status instead to display the progress
[...]
NetworkManager.getInstance().addProgressListener((evt) -> {
if (evt instanceof NetworkEvent) {
NetworkEvent e = (NetworkEvent) evt;
if (e.getProgressPercentage() >= 0) {
status.setProgress(e.getProgressPercentage());
}
}
});
NetworkManager.getInstance().addToQueueAndWait(cr);
//Clear the ToastBar
status.clear();
return cr.getResponseCode() == 200;
}
I'm trying to wrap the Event Async Programming model used in RIA Services in a Task.
I have followed the standard way of using a TaskCompletionSource and implemented the following extension method:
public static Task<IEnumerable<T>> LoadAsync<T>(this DomainContext source, EntityQuery<T> query) where T : Entity
{
TaskCompletionSource<IEnumerable<T>> taskCompletionSource = new TaskCompletionSource<IEnumerable<T>>();
source.Load(
query,
loadOperation =>
{
if (loadOperation.HasError && !loadOperation.IsErrorHandled)
{
taskCompletionSource.TrySetException(loadOperation.Error);
loadOperation.MarkErrorAsHandled();
}
else if (loadOperation.IsCanceled)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.TrySetResult(loadOperation.Entities);
}
},
null);
return taskCompletionSource.Task;
}
I then use this in the following way:
var task = _context.LoadAsync(_context.GetPlayersQuery());
task.Start();
task.Result;
The problem though is that I get an InvalidOperationException stating that "Start may not be called on a promise-style task". I have tried not starting the task, but then the loadOperation callback never fires.
Can anyone see what I am doing wrong here?
Thanks in advance
Problem is solved. Under the hood the DomainContext.Load() method is already operating in an asynchronous manner. There must have been some conflict with trying to wrap an already asynchronous method in a task.
However, even if I still follow the EAP correctly with the code below, I still get the InvalidOperationException of 'start cannot be called on a promise-style task'
public static Task<IEnumerable<T>> LoadAsync<T>(this DomainContext source, EntityQuery<T> query) where T : Entity
{
TaskCompletionSource<IEnumerable<T>> taskCompletionSource = new TaskCompletionSource<IEnumerable<T>>();
var loadOperation = source.Load(query);
loadOperation.Completed += (obj, args) =>
{
if (loadOperation.HasError && !loadOperation.IsErrorHandled)
{
taskCompletionSource.TrySetException(loadOperation.Error);
loadOperation.MarkErrorAsHandled();
}
else if (loadOperation.IsCanceled)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.TrySetResult(loadOperation.Entities);
}
};
return taskCompletionSource.Task;
}
Try this instead
var result = await _context.LoadAsync(_context.GetPlayersQuery());
Try using
task.ContinuewWith(Action<Task<T>> continuation)
That worked for me, as I too got that exception when using task.Start
I have a problem with crossdomain.xml that is located on Facebook photo servers. The first problem arises when Silverlight asks for clientaccesspolicy.xml ā Facebook servers return 403 ā Access Denied which is fine, since they also have crossdomain.xml deployed on their servers. Silverlight then asks for that crossdomain.xml and the response it gets is exactly this:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain- policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" secure="false" to-ports="*" />
<site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
Then I played for a while with this, deployed that crossdomain.xml to my own servers and a got the same results ā a security exception. Then I started moving things out and came to a conclusion that everything will work as desired if I only remove the to-ports="*" attribute? Does anyone has an idea how to overcome this, has anyone had the same problem before or is it something that Iām doing wrong?
I have run into the same issue while trying to programmatically retrieve images from Facebook. The strange part is that if you point a Silverlight image control to the Facebook image url, the image is retrieved and displayed without error. This got me thinking and I have come up with a viable workaround that seems to work consistently for my situation. I hope you find it useful too.
var uri = new Uri("http://graph.facebook.com/mglace/picture/", UriKind.Absolute);
var bmp = new BitmapImage();
bmp.ImageOpened += (sender, e) => { /* Do something here with the sender (which is the BitmapImage) */ };
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = uri;
Create a BitmapImage object, set an event handler for the ImageOpened event and set the CreateOptions property to BitmapCreateOptions.None. Finally, set the UriSource to the Facebook image you want to retrieve. The image is downloaded immediately because we set the CreateOptions to None (the default value is DelayedCreation). You can then perform any actions you would like in the ImageOpened event handler.
I wanted to encapsulate this logic in my service layer and beef up the error handling and such so I wrapped it in a Reactive Extensions observable to make it easier to use. Here is my final code snippet:
public IObservable<BitmapImage> GetProfilePhoto(string profileId)
{
return Observable.Create<BitmapImage>(
observer =>
{
// This handler handles a successful fetch
EventHandler<RoutedEventArgs> openedHandler =
(sender, args) =>
{
try
{
observer.OnNext(sender as BitmapImage);
observer.OnCompleted();
}
catch (Exception ex)
{
observer.OnError(ex);
}
};
// This handler handle a failure
EventHandler<ExceptionRoutedEventArgs> failedHandler =
(sender, args) => observer.OnError(args.ErrorException);
var url = string.Format("http://graph.facebook.com/{0}/picture/", profileId);
var uri = new Uri(url, UriKind.Absolute);
BitmapImage bmp = null;
try
{
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
bmp = new BitmapImage();
bmp.ImageOpened += openedHandler;
bmp.ImageFailed += failedHandler;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = uri;
});
}
catch (Exception ex)
{
observer.OnError(ex);
}
return () =>
{
// Cleanup the event handlers
if (bmp != null)
{
bmp.ImageOpened -= openedHandler;
bmp.ImageFailed -= failedHandler;
}
};
});
}
And usage:
GetProfilePhoto("mglace")
.Subscribe(image => { /* Do something with the image in here*/ },
error => { /* Handle any errors in here */ },
() => { /* Finalization code goes here */ });
I hope someone out there finds this useful.
This is still not resolved in Silverlight 5. Facebook doesn't seem concerned too.