Is there a console log for asp.net? - asp.net

If I have IF statement like below:
If currentdate >= rating1 then
status = 2
ELSEIF currentdate >= rating2 then
daylight_savings_status = 0
ELSEIF currentdate >= rating3 then
daylight_savings_status = 1
ELSE
daylight_savings_status = 1
End If
Is there something like in javascript
console.log('test');
that I can test on the which IF statement is truth of the statement?
This way I be able to test it on the firebug(firefox).

For Server Side
C# & VB.Net
Server Side - This will show in the Visual Studio Output window.
System.Diagnostics.Debug.WriteLine(log data here)
Client Side JavaScript/Jquery - This will show in the browser devtools console window. Works on all popular browsers.
console.log(log data here)

I would try to output it to the clients console ONLY If the Console.WriteLine() function doesnt work for you.
Page.Response.Write("<script>console.log('" + msg + "');</script>");
Ultimately though you should try to write debug statements in your own console (with System.Diagnostics.Debug.WriteLine(...)) and not the client's.
NB
System.Diagnostics.Debug.WriteLine(...); gets it into the Immediate Window in Visual Studio 2008.
Go to menu Debug -> Windows -> Immediate:

This may be a moot point, but I wanted to make a note on this. As #snowYetis answer tells you the correct way to write to the system console for debugging puposes. My "trick" to making this a little more bearable during development is making a helper class somewhere in your project for you to import and use. One of the helper methods I ALWAYS implement in my projects is this one:
public void DebugLog(String msg)
{
System.Diagnostics.Debug.WriteLine(msg);
}
This way you only need to call your Helper.DebugLog(e.Message); when you want to log to console without having to dot your way into madness :)
Hope this helps someone

For outputting to your server console, use :
Console.WriteLine("test");

Related

Karate - how to send (write) log from browser (console, Firefox) when an error occurs [duplicate]

This question already has answers here:
Logging Messages from Java Class back to the Karate Report
(3 answers)
Closed 1 year ago.
While using Karate I need to receive information from browser console (e.g. Firefox) when an error occurs.
How can I do it with Karate?
1) Is there any way to save the browser console log? (or attach it to features report)?
In Selenium I use this to log browser console in case error occurs:
if (webDriver != null) {
LogEntries logs = webDriver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logs) {
LOG.error(entry.getLevel() + " " + entry.getMessage());
}
}
2) Is it possible to trigger it in similar way to take screenshot after scenario?
e.g (after scenario screenshot when some error occurs):
configuration:
karate.configure('afterScenario', read('afterScenarioScreenshot.js'));
afterScenarioScreenshot.js:
function()
{
if (karate.info.errorMessage) driver.screenshot()
}
Thank you for any idea.
The only suggestion I have is to use showProcessLog: true in the driver config.
Now you should see any FireFox process (console) logs in-line with the HTML report.
There may be ways to switch on the detailed logging that you want. Note that you can add command line options using addOptions in the driver config: https://firefox-source-docs.mozilla.org/testing/geckodriver/TraceLogs.html
The "WebDriver" way to switch the log level is by using the driver "capabilities". Refer the above link and see if you can set this for FireFox. It would be good if you post back your findings so that it helps others. In Karate, you use the webDriverSession to configure this.
The logs will be in some file. You should be able to write some code to scrape from it any time during a test if they don't show up in the HTML report.
If you need something more, please consider contributing code.

Selenium and wordpress: New post test

I've been looking a bit at Selenium, and I'm beginning to like it, since I know some Java programming and find both Java and C# pretty straight-forward for simple things like this.
However, I'm struggling with a test that creates a new post in Wordpress, from the Dashboard page:
This is the Selenium code (in C#):
(The Driver instance is, obviously, a driver class I've created - for starting the browser and connecting to the wordpress site.)
1: Driver.Instance.FindElement(By.Id("title)).SendKeys(title);
2: Thread.Sleep(1000);
3:
4: Instance.SwitchTo().Frame("content_ifr");
5: Thread.Sleep(1000);
6:
7: Driver.Instance.SwitchTo().ActiveElement().SendKeys("something");
Now, what happens is that the title is easily found (by ID, so I wouldn't expect problems there), and I can easily insert the title text (line 1).
But the inline frame for the post body is causing problems. When running the test, after the topic is filled in, the cursor changes to the body area (line 4) - as planned. However, nothing more happens. The SendKeys("string") method (ine 7) doesn't seem to work there.
Any ideas?
EDIT: Of course - an important piece of information is that the iframe in Wordpress simply loads a TinyMCE editor. So, in the page source, there's only a body tag with the javascript loading of the editor.
EDIT2: Of course, something suddenly changed. Without ANY change to the wordpress page, the "content_ifr" is now suddenly missing (?!!!!!?) The Selenium test fails with "unable to locate frame...", and it's also suddenly missing from the page source.
EDIT3: I also noticed something:
Driver.Instance.SwitchTo().Frame(iframe);
Driver.Instance.FindElement(By.Id("tinymce")).SendKeys("message body");
It's the SECOND line that makes the cursor switch to the mce field, not the line with the .SwitchTo(). However, I need the first line - the second line does nothing on its own. This is approaching something really stupid. I've been looking for a solution to this for a week - this doesn't exactly bode well for Selenium. The Selenium user group doesn't even want to answer when I ask them.
Also - if I skip the SendKeys() method in the second line, nothing happens. So, it seems that the two lines does ALLMOST what it should, right up to and including placing the cursor in the correct spot. But it never sends any text.
EDIT4 (last): After actually figuring out how to use IJavaScriptExecutor, it works using the solution(s) below.
Java method to handle TinyMCE editor would look like:
public void entersTopicOfBody(String textToBeTyped, WebDriver driver) {
driver.switchTo().frame("content_ifr");
WebElement body = driver.findElement(By.xpath("//body"));
body.click();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].innerHTML = '"+ textToBeTyped+"'", body);
driver.switchTo().defaultContent();
}
Below is some C# code that publishes a post. I think the main issues you have are due to timing issues.
I've done a bit of Selenium recently and I favour implicit waits: it waits for a maximum time period for the item to be available, but returns as soon as possible. So you can specify a max wait of 100 seconds, but if it finds it in 1 second, it will only wait 1 second. Much more efficient vs sleeping for an arbitrary length of time. See this post about Implicit and Explicit waits
But even with implicit waits, it may not solve all issues. When coding the sample below, I ran into the issue where the "Publish" button was disabled and re-enabled after some time. And that's when you have to look at the code to see what it is doing as well. It's times such as these where sleeps can help you fix the problem for a quick fix if you do not wish to debug too much: just be sure to set a large enough sleep time and be wary that it could be inconsistent in the future.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Support.Events;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
// enter your configurations here
driver.Navigate().GoToUrl("http://localhost/wordpress/wp-admin/post-new.php");
driver.FindElement(By.Id("user_login")).SendKeys("admin");
driver.FindElement(By.Id("user_pass")).SendKeys("yourpassword");
driver.FindElement(By.Id("wp-submit")).Click();
driver.FindElement(By.Id("title")).SendKeys("the title");
var iframe = driver.FindElement(By.Id("content_ifr"));
driver.SwitchTo().Frame(iframe);
// your solution which works in my instance
//driver.SwitchTo().ActiveElement().SendKeys("hello tiny mce from selenium");
// send keys with exact element
//driver.FindElement(By.Id("tinymce")).SendKeys("hello tiny mce from selenium");
// javascript - 1
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
var tinymce = driver.FindElement(By.Id("tinymce"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].innerHTML = 'hello tiny mce via javascript'", tinymce);
// javascript - 0
driver.SwitchTo().DefaultContent();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(11));
wait.Until((d) => { return !d.FindElement(By.Id("publish")).GetAttribute("class").Contains("disabled"); }); // wait for publish button to be enabled
driver.FindElement(By.Id("publish")).Click();
driver.FindElement(By.Id("message")); // wait for message on next page to verify it is posted
driver.Close();
}
}
}
A PHP version of olyv solution:
$content = 'my text';
$this->frame( 'content_ifr' );
$body = $this->byXPath( '//body' );
$body->click();
$script = 'arguments[0].innerHTML = "" + arguments[1] + ""; ';
$this->execute( [
'script' => $script,
'args' => [ $body->toWebDriverObject(), $content ],
]
);
$this->frame( null );
I know that I am a bit late to the party, but I just found a solution that is (I believe) much simpler than the answers given so far. So I decided to post it here in case it could help someone else.
There is no need to switch frames here. What you wanna do is 'click' on the button in the top right corner of the text editor that says "Text", which has id = "content-html". Now, you can 'send keys" to the textarea, which has id = "content".
Here is some Python code that does just this:
driver.find_element_by_id("content-html").click()
driver.find_element_by_id("content").send_keys("Some text...")
Hope it helps

VLC-Player in adobe Air App does not stop/quit

Well i have an adobe air , downloaded from below link.. it is wonderful app..
http://www.adobe.com/devnet/air/flex/articles/air_screenrecording.html
and this works fine. It captures my screen , record audio but it just does not stop or quit as vlc-player.exe continues to run in the task manager.
i tried lots of vlc- commands but it just does not stop once it starts capturing screen video.
I need help on it..
I know this is a old thread, but just in case someone wants to know...
You can't use rc-fake-tty because Windows doesn't support terminal. For Windows, tell VLC to run with only one instance, then send it the quit command as a separate NativeProcess call.
So, in the linked article, change the stopRecording() method to this:
public function stopRecording():void{
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = vlcFile;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("-I");
processArgs.push("rc"); //Remote control
processArgs.push("--one-instance");
processArgs.push("vlc://quit");
startupInfo.arguments = processArgs;
var killSwitch:NativeProcess = new NativeProcess();
killSwitch.start(startupInfo);
}
And make sure to add this:
processArgs.push("--one-instance");
To your initial screen record startupInfo in startRecording() method.
I quit using vlc for the same reason and started to write my recording application using .Net 4, but i am having less performance using c# now.
Edit:
VLC for windows does not support fake rc control so setting rc-fake-tty is useless. As the very last try, i wanna control is via socket. If you got it working this way, please make me informed.

How to test a confirm dialog with Cucumber?

I am using Ruby on Rails with Cucumber and Capybara.
How would I go about testing a simple confirm command ("Are you sure?")?
Also, where could I find further documentation on this issue?
The selenium driver now supports this
From Capybara you would access it like this:
page.driver.browser.switch_to.alert.accept
or
page.driver.browser.switch_to.alert.dismiss
or
page.driver.browser.switch_to.alert.text
Seems like there's no way to do it in Capybara, unfortunately. But if you're running your tests with the Selenium driver (and probably other drivers that support JavaScript), you can hack it. Just before performing the action that would bring up the confirm dialog, override the confirm method to always return true. That way the dialog will never be displayed, and your tests can continue as if the user had pressed the OK button. If you want to simulate the reverse, simply change it to return false.
page.evaluate_script('window.confirm = function() { return true; }')
page.click('Remove')
I've implemented these two web steps in /features/step_definitions/web_steps.rb:
When /^I confirm popup$/ do
page.driver.browser.switch_to.alert.accept
end
When /^I dismiss popup$/ do
page.driver.browser.switch_to.alert.dismiss
end
If you want to specifically test the message being displayed, here's a particularly hacky way to do so. I don't endorse it as beautiful code, but it gets the job done. You'll need to load http://plugins.jquery.com/node/1386/release, or change it to do cookies natively if you don't want jQuery.
Use this sort of story:
Given I am on the menu page for the current booking
And a confirmation box saying "The menu is £3.50 over budget. Click Ok to confirm anyway, or Cancel if you want to make changes." should pop up
And I want to click "Ok"
When I press "Confirm menu"
Then the confirmation box should have been displayed
And these steps
Given /^a confirmation box saying "([^"]*)" should pop up$/ do |message|
#expected_message = message
end
Given /^I want to click "([^"]*)"$/ do |option|
retval = (option == "Ok") ? "true" : "false"
page.evaluate_script("window.confirm = function (msg) {
$.cookie('confirm_message', msg)
return #{retval}
}")
end
Then /^the confirmation box should have been displayed$/ do
page.evaluate_script("$.cookie('confirm_message')").should_not be_nil
page.evaluate_script("$.cookie('confirm_message')").should eq(#expected_message)
page.evaluate_script("$.cookie('confirm_message', null)")
end
Updating this for current releases of Capybara. Most Capybara drivers today support the modal API. To accept a confirm modal you would do
accept_confirm do # dismiss_confirm if not accepting
click_link 'delete' # whatever action triggers the modal to appear
end
This can be used in Cucumber with something like
When /^(?:|I )press "([^"]*)" and confirm "([^"]*)"$/ do |button, msg|
accept_confirm msg do
click_button(button)
end
end
which will click the named button and then accept a confirm box with text matching msg
The capybara-webkit driver supports this as well.
Scenario: Illustrate an example has dialog confirm with text
#
When I confirm the browser dialog with tile "Are you sure?"
#
=====================================================================
my step definition here:
And(/^I confirm the browser dialog with title "([^"]*)"$/) do |title|
if page.driver.class == Capybara::Selenium::Driver
page.driver.browser.switch_to.alert.text.should eq(title)
page.driver.browser.switch_to.alert.accept
elsif page.driver.class == Capybara::Webkit::Driver
sleep 1 # prevent test from failing by waiting for popup
page.driver.browser.confirm_messages.should eq(title)
page.driver.browser.accept_js_confirms
else
raise "Unsupported driver"
end
end
Prickle adds some handy convenience methods for working with popups in selenium and webkit
This gist has steps to test a JS confirm dialog in Rails 2 and 3 with any Capybara driver.
It's an adaptation of a previous answer, but doesn't need the jQuery Cookie plugin.
Tried the above answers with no luck. In the end this worked for me:
#browser.alert.ok

Selenium IDE click() timeout

I have a simple page that returns an ajax success/error message on submission. The form is submitted using a standard ASP.Net linkbutton.
My Selenium test correctly clicks the linkbutton, however the click event times out and fails. The rest of the testcase conditions pass (as selenium is successfully clicking the link and the ajax success message is displayed).
All I can think is that for some reason click() is calling waitForPageToLoad which is why it is timing out. Is there any way to suppress this, or am I barking up the wrong tree?
Is there an alternative way to handle the click that doesn't care what happens after the event fires?
More Info: Selenium IDE 1.0.2 hosted in Firefox 3.5.2 on Vista (don't ask)
Workaround
I've managed to get my test to pass by creating my own click() function in user-extensions.js that does not call Selenium.decorateFunctionWithTimeout(). While my test does pass now, this is not really an ideal solution.
If you'd like to try this yourself, add the following to user-extensions.js (make sure you are referencing this file in your Se:IDE configuration via Tools | Selenium IDE | Options | Options | General | Selenium Core extensions)
Selenium.prototype.doBeatnicClick = function(locator) {
/**
* Clicks on a link, button, checkbox or radio button.
* Hacky workaround for timeout problem with linkbutton.
* Suspect there is an issue with Selenium.decorateFunctionWithTimeout()
*/
var element = this.browserbot.findElement(locator);
var elementWithHref = getAncestorOrSelfWithJavascriptHref(element);
if (browserVersion.isChrome && elementWithHref != null) {
var win = elementWithHref.ownerDocument.defaultView;
var originalLocation = win.location.href;
var originalHref = elementWithHref.href;
elementWithHref.href = 'javascript:try { '
+ originalHref.replace(/^\s*javascript:/i, "")
+ ' } finally { window._executingJavascriptHref = undefined; }';
win._executingJavascriptHref = true;
this.browserbot.clickElement(element);
}
this.browserbot.clickElement(element);
};
Reload Se:IDE and you'll have access to a new command, beatnicClick() which should work where you're experiencing a click() timeout.
Hopefully this will be patched, or fixed in the next release of Se:IDE.
I believe this is raised in the OpenQA Jira: http://jira.openqa.org/browse/SIDE-316. It has also been discussed here: http://clearspace.openqa.org/message/64455
Until the issue has been resolved you can revert to the 1.0b2 version of Selenium IDE http://release.seleniumhq.org/selenium-ide/1.0-beta-2/ but this wont install on Firefox 3.5.x unless you disable extensions.checkCompatability in about:config. See http://kb.mozillazine.org/Extensions.checkCompatibility
I was hitting what I assume is this bug when testing a GWT site with Selenium IDE 1.0.2. I just updated to 1.0.4 and don't have it any more.

Resources