Could not start a new session using Selenium RemoteWebDriver for SauceLabs - saucelabs

Following Code for SauceLabs through Selenium was working properly but now giving error:
static WebDriver driver;
public static final String URL = "http://" + USERNAME + ":" + ACCESS_KEY + "#ondemand.saucelabs.com:80/wd/hub";
#BeforeClass
public static void setupTest() throws MalformedURLException {
DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setCapability("platform", Platform.MAC);
caps.setCapability("version", "52");
driver = new RemoteWebDriver(new URL(URL), caps);
}
Error:
org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Driver info: driver.version: RemoteWebDriver
I have checked for both Chrome and Firefox. Can anyone please suggest if I am missing anything here. As the code was working properly before, can it be proxy issue?

There were additional spaces.
Try public static final String URL = "http"+USERNAME+":"+ACCESS_KEY+"#oandemand.saucelabs.com:80/wd/hub";

Related

Google Recaptcha work local and get error on live

This is an old site based on dot.net and iis
I try to add the option of google recaptcha to my site
but I got the error
The underlying connection was closed: An unexpected error occurred on a receive
This is my current code (as I said this is work on the local dev)
public static string Validate(string EncodedResponse)
{
var client = new System.Net.WebClient();
string PrivateKey = Utils.GetConfigValue("reCAPTCHA.SecretKey");
var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
ReCaptchaClass captchaResponse = js.Deserialize<ReCaptchaClass>(GoogleReply);
return captchaResponse.Success;
}

HttpMediaTypeNotAcceptableException: Could not find acceptable representation spring mvc

This is driving me crazy! I'm trying to serve a JPG image. I am sure this method was working fine the other day, so I don't know what's changed. I've tried many different things to get it to work but I can't seem to get past the exception.
Basically I'm trying to serve an image from the database.
I thought maybe the actual bytes are corrupt so I wrote them to a file, and checked the file content. Just in Finder on Mac, the file in the temp directory looks fine in the preview application so I'm pretty sure it's not the content itself causing the problem.
This is the controller method:
#RequestMapping(value="/binaries/**", method = RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_GIF_VALUE,
MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, "application/javascript"})
public #ResponseBody
ResponseEntity<byte[]> serveResource(WebRequest webRequest, HttpServletResponse response, String uri) throws IOException {
String path = (String)request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE );
BinaryFile bf = binaryService.findByUri(path);
String tmpdir = System.getProperty("java.io.tmpdir");
File dest = new File(tmpdir + File.separator + bf.getFileName());
FileUtils.writeByteArrayToFile(dest, bf.getResource());
logger.debug("file written: " + dest.getAbsolutePath());
// response.addHeader("Cache-Control", "public, max-age=3600");
if (webRequest.checkNotModified(bf.getLastModifiedDate().toDate().getTime()))
{
return null;
};
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(bf.getResource());
}
This is the exception:
Request: http://localhost:8080/binaries/products/shortcode_1/test_image2.jpg raised org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Anyone have any ideas? It's Spring 4.1.4.RELEASE
Oh never mind, I figured out what changed. I'd overridden the MessageConverters because I was working on some Jackson stuff, so the fix was that I needed to manually add back the ByteArrayHttpMessageConverter.
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter(){
ByteArrayHttpMessageConverter bam = new ByteArrayHttpMessageConverter();
List<org.springframework.http.MediaType> mediaTypes = new LinkedList<org.springframework.http.MediaType>();
mediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_JPEG);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_PNG);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_GIF);
mediaTypes.add(org.springframework.http.MediaType.TEXT_PLAIN);
bam.setSupportedMediaTypes(mediaTypes);
return bam;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter mapper = new MappingJackson2HttpMessageConverter();
ObjectMapper om = new ObjectMapper();
om.registerModule(new JodaModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setObjectMapper(om);
converters.add(mapper);
converters.add(byteArrayHttpMessageConverter());
super.configureMessageConverters(converters);
}

Appharbor Background worker Issue - Error : "Terminated with exitcode -2147467259"

I have hosted 1 background worker on app-harbor for sending email. From last 3 to 4 days it is not working, I am getting error “Terminated with exitcode -2147467259”.
Below is script using in background worker:
static void Main(string[] args)
{
while (true)
{
//Worker_Process_For Send Email
EmailCls.SendEmail_ByMailGun("a#b.com", "a#b.com", "Testing Shailesh-live", "body-live");
}
}
public static IRestResponse SendEmail_MailGun(string from ,string to ,string subject,string body)
{
RestClient client = new RestClient();
client.BaseUrl = ConfigurationManager.AppSettings["mailgun_baseurl"].ToString();// "https//api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", ConfigurationManager.AppSettings["mailgun_key"].ToString());
var mailgun_domain = ConfigurationManager.AppSettings["mailgun_domain"].ToString();
RestRequest request = new RestRequest();
request.AddParameter(mailgun_domain,mailgun_domain, ParameterType.UrlSegment);
request.Resource = "{" + mailgun_domain + "}/messages";
request.AddParameter("from", from);
request.AddParameter("to", to);
request.AddParameter("subject", subject);
request.AddParameter("html", body);
request.Method = Method.POST;
return client.Execute(request);
}
The given script working fine in local machine but not from appharbor .
We recently added a new logging module which gives you real-time access to your background worker's STDOUT and STDERR.
You can start a log session by clicking the "Logging" link in the application's nav bar. That should give you more output to help identify and resolve this issue.
I just Changed application Start Object[ which was not set in past ]in Application property window and rebuild and hosted it on app-harbor and my application started working f9.

ChromeDriver console application hide

I have created a player which will automate chrome using selenium and ChromeDriver in C#. It's working fine.
Issue what I am facing is, when it creates an object for ChromDriver, it will start ChromeDriver application, which gets pop up and then Chrome will load. It's perfect as that application is loading that chrome for me.
Is there anyway, that I can open that ChromeDriver hidden?
Modifying source code in WebDriver\DriverService.cs is not necessary for this in latest WebDriver. You just need to instantiate ChromeDriverService and set HideCommandPromptWindow to true and then instantiate ChromeDriver by that service and ChromeOptions. I am giving C# code example below
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
return new ChromeDriver(chromeDriverService, new ChromeOptions());
No, there is no way to hide the console window of the chromedriver.exe in the .NET bindings without modifying the bindings source code. This is seen as a feature of the bindings, as it makes it very easy to see when your code hasn't correctly cleaned up the resources of the ChromeDriver, since the console window remains open. In the case of some other languages, if your code does not properly clean up the instance of ChromeDriver by calling the quit() method on the WebDriver object, you can end up with a zombie chromedriver.exe process running on your machine.
Yes, you need modify source code in WebDriver\DriverService.cs in Start(); add:
this.driverServiceProcess.StartInfo.CreateNoWindow = true;
This is possible now, using the headless option. Might not have been available then.
Running Chrome Headless
Translated into C#, you can do this:
ChromeOptions options = new ChromeOptions();
options.AddArgument("headless");
ChromeDriver driver = new ChromeDriver(options);
Now the browser window is invisible, while the rest of the program stays the same.
As an update to this question. Yes, you can hide command prompt window in Selenium 2.40.0 and up. Please note that hiding command prompt window is not recommended but you can do it. As the question refers to C# you do it with the next code:
ChromeDriver
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
var driver = new ChromeDriver(driverService, new ChromeOptions());
InternetExplorerDriver
var driverService = InternetExplorerDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
var driver = new InternetExplorerDriver(driverService, new InternetExplorerOptions());
PhantomJSDriver
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
var driver = new PhantomJSDriver(driverService);
drv.Manage().Window.Position = new Point(3000, 3000);
will fix your problem.
I did this using c#, but like JimEvan's repply, I had some problems with "zombies chromedrivers and cmd zombies". After doing "headless mode" and "hiding" the prompt window.
Don't forget to close your chrome driver instance correcly.
To solve this, doing a little google how kill some process, I kill these two process, before open another chrome driver again :
static void Main(string[] args)
{
ChromeDriverService _chromeDriverService;
ChromeOptions _chromeOptions;
IWebDriver _driver;
//set ChromeDriverService, to hide prompt widow
_chromeDriverService = ChromeDriverService.CreateDefaultService("YOUR CHROME DRIVER PATH HERE");
_chromeDriverService.HideCommandPromptWindow = true;
//set ChromeOptions, to hide ChromeDriver
_chromeOptions = new ChromeOptions();
_chromeOptions.AddArguments("headless");
_driver = ChromeDriver(_chromeDriverService, _chromeOptions);
//do your things...
}
//call this method before run your chrome driver, to close some ghost chromeDriver or prompt window
private static void CloseGhostsChromeDriver()
{
Process[] cmd = Process.GetProcessesByName("cmd");
Process[] chromeDriver = Process.GetProcessesByName("chromedriver");
Process[] workers = chromeDriver.Concat(cmd).ToArray();
foreach (Process worker in workers)
{
worker.Kill();
worker.WaitForExit();
worker.Dispose();
}
}
In updated version of ChromeDriver you don't need to edit the source code just with:
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
If you want to hide the console that is opened when launching chrome, firefox, etc.. you will need a helper class like this:
static class WindowsUtils
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
// Delegate to filter which windows to include
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
/// <summary> Get the text for the window pointed to by hWnd </summary>
public static string GetWindowText(IntPtr hWnd)
{
int size = GetWindowTextLength(hWnd);
if (size > 0)
{
var builder = new StringBuilder(size + 1);
GetWindowText(hWnd, builder, builder.Capacity);
return builder.ToString();
}
return String.Empty;
}
/// <summary> Find all windows that match the given filter </summary>
/// <param name="filter"> A delegate that returns true for windows
/// that should be returned and false for windows that should
/// not be returned </param>
public static IEnumerable<IntPtr> FindWindows(EnumWindowsProc filter)
{
IntPtr found = IntPtr.Zero;
List<IntPtr> windows = new List<IntPtr>();
EnumWindows(delegate (IntPtr wnd, IntPtr param)
{
if (filter(wnd, param))
{
// only add the windows that pass the filter
windows.Add(wnd);
}
// but return true here so that we iterate all windows
return true;
}, IntPtr.Zero);
return windows;
}
/// <summary> Find all windows that contain the given title text </summary>
/// <param name="titleText"> The text that the window title must contain. </param>
public static IEnumerable<IntPtr> FindWindowsWithText(string titleText)
{
return FindWindows(delegate (IntPtr wnd, IntPtr param)
{
return GetWindowText(wnd).Contains(titleText);
});
}
}
An then you can create your Selenium driver like this (also hidding the Firefox window).. If you want to use Chrome only have to do some minor changes... I prefreer Firefox because Chrome sometimes don't work with headless option:
FirefoxOptions options = new FirefoxOptions();
options.SetPreference("permissions.default.image", 2); //prevent download images
options.AddArguments(new string[] { "--headless", "'--disable-gpu'" }); //no window, no gpu
driver = new FirefoxDriver(options);
WindowsUtils.ShowWindow(WindowsUtils.FindWindowsWithText("geckodriver.exe").FirstOrDefault(), 0); //0 to hide, 1 to show
This solution will help you. Please note that hiding command prompt window is not recommended.
ChromeDriver
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
var driver = new ChromeDriver(driverService, new ChromeOptions());
I know this isn't what you want but it could help if used in certain situations.
Writing driver.quit() will terminate the chrome window and the terminal it has open.

AppHarbor NopCommerce running issue

I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062

Resources