In selenium2 (Webdriver)How to verify if an alert is present? and continue doing something if its not present!!!
I am doing this:
driver.findElement(By.id("btn_may_or_maynot_showalert")).click();
WebDriverWait wait = new WebDriverWait(driver, 2);
try{
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
catch (Exception e){
System.out.println("No alert");
}
driver.findElement(By.id("Cont_doing_something")).click();
This works fine But is there a better way?
No, you're doing things the way the library expects you to. However, one of the principles of the library is that you should always know what to expect of your automation code. That means you shouldn't run into an instance where the button "may or may not" cause an alert; you should already know whether pressing the button will cause an alert or not. If it does something other than what you expect, that's an exceptional condition, and an exception should be thrown.
Related
I have a process that takes a long time to finish executing, the user should be able to see a simple feedback when the process starts and finishes
something like this:
protected async void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Process started..\n";
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
await ProcessDelay();
sw.Stop();
TextBox1.Text += "Process finished.\n";
TextBox1.Text += "Elapsed Time (ms): " + sw.ElapsedMilliseconds.ToString() + "\n";
}
private async Task ProcessDelay()
{
await Task.Delay(5000);
}
Text value in TextBox is not updated until the execution of ProcessDelay() is done. What am I missing here?
Remember that when you're working with ASP.NET, you are working within a strict request+response paradigm. WebForms tries to hide this from you, but it's still one-response-per-request underneath. So, when you click a button in your browser, it sends a request to the web server, which executes the click code, returning a result. It can only return one result. So there's no way it can, say, make a change to part of the page and then later make another change.
To put it another way, async on ASP.NET yields to the ASP.NET runtime (that is, it returns the request thread to the thread pool). It does not yield to the browser (that is, it does not return a response).
To do what you want, you'll need an alternative technology. If the background work doesn't take too long, you could consider SignalR. Otherwise, you'll probably need a proper distributed architecture: a reliable queue connected to an independent background process. I describe a few approaches on my blog.
I'm using PNaCl and I'm in a situation where first I receive a message that is handled in the 'HandleMessage' function as the normal way, but then in the current HandleMessage execution, I need to wait for a user input that would come from an other message in order to complete the execution.
I'm wondering if this is possible to do that (handling a message while already waiting in the 'HandleMessage' function) ? And if so, can someone give me a trick ?
Thanks !
HandleMessage is currently called on one thread, the main thread. So you cannot receive a message while you are handling another message.
We typically suggest you spawn a new thread to do your work, and leave the main thread to handle messages, and queue them for the new thread to handle. Take a look at the nacl_io_demo example in the SDK for an example of this technique (found in examples/demo/nacl_io).
Another solution is to use a state machine; i.e. keep track of your current state in a variable instead of on the stack.
For example:
enum State {
STATE_INIT,
STATE_WAITING_FOR_INPUT,
STATE_DO_OTHER_STUFF,
};
State state_;
virtual void HandleMessage(const pp::Var& var_message) {
switch (state_) {
case STATE_INIT:
if (var_message.AsString() == "first_message") {
state_ = STATE_WAITING_FOR_INPUT;
// Do some work before you need the user input ...
}
break;
case STATE_WAITING_FOR_INPUT:
if (var_message.AsString() == "user_input") {
// Do more work, now that we've received input from the user...
state_ = STATE_DO_OTHER_STUFF;
}
break;
}
}
I am very new to Workflow Foundation development, and am worried that I am opening serious holes in our business process handling by not properly handling application / database exceptions in custom activities.
I would appreciate some steps that I could take to add this resiliency to my custom activities so that I can easily use the designer and other tools to ensure that, as far as I can, I do not create custom activities that are brittle and likely to cause workflow cleanup issues.
Here are some options, at different execution stages, that are available for you to use to handle exceptions.
First option (at activity/workflow execution time):
First of all, on custom activities, you should always try to treat exceptions inside it's execution. Some activities might not work but the overall workflow can continue and, in such cases, log the error to persistence and even show the user that something didn't work as expected but the thing will continue are good options.
That being said there'll always be cases where an activity have to (and even should) thrown exceptions and those should be treated at workflow level. Something like: if this exception occurs on this activity, do this, otherwise, do that.
Lets imagine you've a custom activity which persists something to DB:
public sealed PersistIntegerToDb : CodeActivity
{
public InArgument<int> ValueToPersist { get; set; }
protected override void Execute(CodeActivityMetadata metadata)
{
try
{
// persist
}
catch(SqlException exception)
{
// re throws the SqlException
throw new SqlException("'ValueToPersist' wasn't persisted.", exception);
}
}
}
Then, in your code or through designer you've available TryCatch activity to catch that error and treat it the way you want:
var workflow = new TryCatch
{
Try = new PersistIntegerToDb
{
ValueToPersist = 10
},
Catches =
{
new Catch<SqlException>
{
Action = new ActivityAction<SqlException>
{
Handler = new WriteLine
{
Text = "An error occurred and the value wasn't saved! Anyway workflow will continue..."
}
}
}
}
}
Or you can terminate it using TerminateWorkflow.
Second option (at design time):
Ok, but you can argue that client doesn't know that he have to handle those cases. In that case, and this is an usability option you might consider, instead of making available PersistIntegerToDb on the designer, you can provide an activity already surrounded by exceptions catches to handle, through IActivityTemplateFactory:
public sealed PersistIntegerToDbFactory : IActivityTemplateFactory
{
public Activity Create(DependencyObject target)
{
return new TryCatch
{
Try = new PersistIntegerToDb
{
ValueToPersist = 10
},
Catches =
{
new Catch<SqlException>
{
}
}
};
}
}
Now you just add PersistIntegerToDbFactoryas if it were a regular activity:
new ToolboxItemWrapper(typeof(PersistIntegerToDbFactory), null, "Persist Integer");
Third option (at validation time):
Never forget to validate workflow before execution!
var validationResults =
ActivityValidationServices.Validate(workflow);
foreach(var error in validationResults.Errors)
{
Console.WriteLine(string.Format(
"Validation error '{0}', generated on activity '{1}' in the property named {2}",
error.Message,
error.Source.DisplayName,
error.PropertyName));
}
Fourth option (at application execution time):
You can handle all not treated exception that might happen during execution, using OnUnhandledException event:
var wfApp = new WorkflowApplication(activity);
wfApp.OnUnhandledException +=
delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
{
if (e.UnhandledException is SqlException)
{
Console.WriteLine("Some data wasn't properly persited.");
}
else
{
Console.WriteLine("Unknown error: " + e.UnhandledException.GetType());
Console.WriteLine("With message: " + e.UnhandledException.Message);
}
Console.WriteLine("Ok, workflow will be abort");
return UnhandledExceptionAction.Abort;
};
Note that, at this stage, you can only Abort, Cancel and Terminate the workflow and that's the reason why you should 1) avoid throwing exceptions or 2) treat exceptions inside your workflow. OnUnhandledException is your last chance to end the workflow execution gracefully and should always be treated even if for logging purposes. Something like DivideByZeroExceptions can occur and are almost impossible to predict and catch at validation time, for example.
As far as custom activities goes you should treat them as any other piece of code. Handle the errors you can and let you can't handle the rest bubble up.
At the workflow level you can use the TryCatch activity and workflow persistence to deal with errors. Specially persistence is something people overlook often. Add Persist activities at appropriate steps in your workflow and set the workflow to abort on unhandled errors. Now you can go back in and reload the last good workflow state and retry the actions that cause an unhandled exception. A great way of recovering from failures with resources like databases that might be unavailable for some reason and then come back.
I am getting an error:
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
when I am redirecting my page from one to another.
I am using this code:
try
{
Session["objtwitter"] = obj_UserDetSumit;
Response.Redirect("TwitterLogin.aspx");
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
}
And I got a solution and I tried also this Response.Redirect("home.aspx",false);
It's not throwing an error but it's also not redirecting page.
Try - catch creates a thread around code within it in order to catch exceptions. When you Redirect you are effectively terminating execution of the thread thus causing an error since execution ended unnaturely (though this is by design). You should not Redirect from within try-catch and if you do you should use Response.Redirect( "some url", false ); and also specifically catch ThreadAbortException.
Reference here: http://msdn.microsoft.com/en-us/library/t9dwyts4.aspx
Response.Redirect calls the Response.End, which throws a ThreadAbortException, so you'd want to change your code to:
try
{
Response.Redirect("home.aspx");
}
catch(System.Threading.ThreadAbortException)
{
// do nothing
}
catch(Exception ex)
{
// do whatever
}
First, make sure that you are working with a debug build and not a release build of your project. And second, make sure that you are debugging in mixed mode (both managed and native) so that you can see all of the current call stack.
I'd try moving your Response.Redirect outside of the try catch block like this:
try
{
Session["objtwitter"] = obj_UserDetSumit;
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
return;
}
Response.Redirect("TwitterLogin.aspx");
Most people having this issue here resolved it with calling Response.Redirect("TwitterLogin.aspx", false); which doesn't explicitly kill the thread immediately. I'm not sure why this didn't work for you.
I think the issue is having your Response.Redirect inside of a try catch block. Calling Response.Redirect(url); calls Response.End();, which will throw a ThreadAbortException.
Make sure you're not trying to do any more processing after you do your redirect.
Using Reflector, you can see that Response.Redirect(url); calls Response.Redirect(url, true);
Passing true then calls Response.End(); which looks like this:
public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
....
}
Even though you don't have a finally in your code snippet, it may be trying to execute the "empty" finally, but can't because the thread is being aborted. Just a thought.
If you replace your code these line you won't get an exception in the first place
try
{
Response.Redirect("home.aspx", False);
//Directs the thread to finish, bypassing additional processing
Context.ApplicationInstance.CompleteRequest();
}
catch(Exception ex)
{
// exception logging
}
Hope it helps
I find myself using exception in web development even for conditions that are not really errors, let alone exceptional ones - just logic decisions, validations...
in a web page, I often write code like so:
try
{
int id;
if(!int.TryParse(txtID.Text, out id))
throw new Exception("ID must be an integer");
if(IdAlreadyExists(id))
throw new Exception("ID already exists in database");
//and so on...
}
catch(Exception ex)
{
SetErrorLine(ex.Message);
}
I was wondering if this is really the correct way of using exceptions and enforcing Business Logic in web development.
P.S.: I am using asp.net, and obviously I could use ASP.NET validators for some of these and also seperate UI from logic, but I'm trying to make a point on the general idea.
You've just answered your own question, really.
Exceptions are for exceptional circumstances. Assuming the code you posted is from a page that takes "ID" as input from the user, then it's not exceptional for user input to be bad. Use the validation infrastructure for that, or do it manually, but don't use exceptions for that.
Also, don't get into the habit of displaying Exception.Message to users. It is meant for developers to see to know what went wrong and how to fix it.
I wouldn't consider the first example to be an acceptable use of an Exception. A user could easily screw up entering that information, and user input should be validated anyways.
An exception should be 'exceptional'. Something that you don't expect to happen, shouldn't happen or really don't want to happen. Anything that can be validated or handled before needing to throw an exception should just be treated like an error.
Different communities differ in their acceptable use of exceptions. The Python community is a little bit more liberal with their use of exceptions: http://wiki.sheep.art.pl/Ask%20for%20Forgiveness
I'm a fan of using them as long as it doesn't disrupt the logic of your application.
Just wanted to add that for asp.net adding a global exception handler HttpModule to catch unhandled exceptions is a very clean way to train yourself out of try/catch/finally abuse.
Throw exceptions when the assumptions your methods take on are broken, or if a method simply cannot complete.
In your example, your IdAlreadyExists method might query a database. That method will assume that there is a database to connect to, you have enough memory to do what you need, and so on. If an assumption is broken, throw an exception.
I, for one, like to let lower level code throw exceptions, and higher level code catch exceptions. That's not a hard and fast rule, just a general guideline I like to follow. It's typically not necessary to throw exceptions to the same level, but I could imagine that it would make sense at times.
still missing the way it SHOULD be done
Set an error mesage and return.
Log error and dont display it to user.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int id = 0;
if(!int.TryParse(txtID.Text, out id))
{
SetErrorLine("Thats not a valid number dude! Need to go to school again");
return;
}
if(IdAlreadyExists(id))
{
SetErrorLine("I already have this entry in store. Sorry. Call again!");
return;
}
...the rest of your code
}
catch(Exception ex)
{
_log.Error(ex);
SetErrorLine("Something unexpected happened dear user ... ");
}
}
Edit: your comment
try {
string error = "";
int id = 10;
if(BO.DoSomething(out error, id, otherParams))
{
SetErrorLine(error);
return;
}
}
catch(Exception ex)
{
//log
}
My guess:
try {
string meaningfullErrorMessage= "";
int id = 10;
if(!BO.DoSomething(out meaningfullErrorMessage, id, otherParams))
{
SetErrorLine(meaningfullErrorMessage);
return;
}
}
catch(Exception ex)
{
//log
}