I am using firefox webdriver. I want to store all the cookies and cache files into a custom directory. But its taking a temp directory instead of my directory . Here is my code:
FirefoxProfile firefoxProfile = new FirefoxProfile(path, false);
MessageBox.Show(firefoxProfile.ProfileDirectory); //Its showing blank
driver = new FirefoxDriver(firefoxProfile);
MessageBox.Show(firefoxProfile.ProfileDirectory); //Its showing the temp dir
//not my custom dir
How to make it take my directory and store all the cookies and files there ?
Thanks.
EDIT:
I need to make the selenium profile directory fixed (as it is changing all the time). So that I can use previous cookies and cache files. Can you give me any idea or any alternate way to accomplish it ?
You could just find the temp file path as you are already then copy your files into this folder with system commands after creating the driver. Then you would have access to them, though this is a little hacky but should work ( unless I've missed something crucial here, which I feel I may have :) )
FirefoxProfile.ProfileDirectory refers to a generated profile directory(obviously, available after browser instance creation only).
As per Selenium source code, profile directory is generated as a random directory in temp folder, hence could not be changed
// creates a random folder name in Path.GetTempPath()
this.profileDir = GenerateProfileDirectoryName();
and
public string ProfileDirectory
{
get
{
return this.profileDir;
}
}
Whereas the profileDirectory you specify during FirefoxProfile creation is used to load user.js.
Quote from mozillaZine:
A user.js file is an alternative method of modifying preferences,
recommended for advanced users only.
Upd.
The only way to solve your issue I could see, besides digging into selenium sources, is changing temp folder location before starting the webdriver to your desired folder and then changing it back to it's original value for current user.
Upd2.
Another possible solution(although not tried yet) is specifying ProfileDirectory from a previous webdriver run as profileDirectory for a new instance of FirefoxProfile for another instance of webdriver. Given that all the files from profileDirectory are copied to the generated temp folder, that could help you achieve desired functionality.
Is it absolutely necessary for you to use firefox? If you are using IE, won't this be taken care? From selenium jar help contents
-ensureCleanSession: If the browser does not have user profiles,make
sure every new session has no artifacts from previous sessions. For
example, enabling this option will cause all user cookies to be
archived before launching IE, and restored after IE is closed.
So, if you don't use that option while running tests in IE your cookies will stay. I haven't tried in webdriver, but I have seen the cookie being retained while using Selenium 1.
Related
I'm automating tests using Selenium and C# and I need to open an external app from the browser. The problem is, I always get this notification and it blocks the test execution.
Does anyone know how to deal with this?
Chrome stores the settings for the acceptance of protocol handlers in the user profile. When running Chrome from Selenium, Chrome doesn't seem to use the standard Chrome user profile by default, and instead uses some default settings that are not persisted.
To get around this, you can launch Chrome from the command line manually and manually specify a new --user-data-dir=c:\foo\bar profile location. (Point it to a new/empty directory and Chrome will populate it for you.)
Using this manually-launched browser, navigate to the page you need to interact with, activate the link, click the "always open" checkbox, and run the program once.
Next, close Chrome and save a copy of the entire new user profile directory. When you run your Selenium tests, make sure to always pass Chrome the same command line options pointing it to that user profile. These settings are now persisted, so the link will open without user intervention in the future. (This question may be of help to feed the right command line args to Chrome.)
For repeatable tests, you will probably want to save a static copy of this profile and redeploy it whenever you launch Selenium.
If you are using Javascript+Selenium or WebdriverJS then use this :
chromeOptions = {
'args': ['--test-type',
'--start-maximized',
'use-fake-ui-for-media-stream',],
'prefs': {
protocol_handler: {
excluded_schemes: {
'yourprotocolname': false
}
}
},
};
I am developing a Windows Phone 8 application but am having a lot of issues with file access permission exceptions hindering the approval of my application when ever I try accessing files in the "local" folder (this only happens after the application has been signed by the WP store, not when deployed from Visual Studio). To solve this I have moved all file operations to IsolatedStorage and this seems to have fixed the problems.
I only have one problem left though. My application needs to make use of the file extension system to open external files and this seems to involve the file first being copied to the local folder where after I can then manually copy it into IsolatedStorage. I have no problem in implementing this but it seems that a file access permission exception also occurs once the system tries to copy the external file into the local folder.
The only way I think this can be solved is if I can direct the system to directly copy into IsolatedStorage but I cannot figure how to do this or if it is even possible. It seems as if though the SharedStorageAccessManager can only copy into a StorageFolder instance but I have no idea how to create one that is directed into IsolatedStorage, any ideas?
PS. Do you think that the Microsoft system might be signing my application with some incompetent certificate or something because there is not a hint of trouble when I deploy the application from Visual Studio, it only happens when Microsoft tests it or when I install it from the store using the Beta submission method.
Below is a screenshot of the catched exception being displayed in a messagebox upon trying to open a file from an email:
EDIT:
Just to make it even clearer, I do NOT need assistance in figuring out the normal practice of using a deep link uri to copy an external file into my application directory. I need help in either copying it directly into isolatedstorage or resolving the file access exception.
Listening for a file launch
When your app is launched to handle a particular file type, a deep link URI is used to take the user to your app. Within the URI, the FileTypeAssociation string designates that the source of the URI is a file association and the fileToken parameter contains the file token.
For example, the following code shows a deep link URI from a file association.
/FileTypeAssociation?fileToken=89819279-4fe0-4531-9f57-d633f0949a19
Upon launch, map the incoming deep link URI to an app page that can handle the file
// Get the file token from the URI
// (This is easiest done from a UriMapper that you implement based on UriMapperBase)
// ...
// Get the file name.
string incomingFileName = SharedStorageAccessManager.GetSharedFileName(fileID);
// You will then use the file name you got to copy it into your local folder with
// See: http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.storage.sharedaccess.sharedstorageaccessmanager.copysharedfileasync(v=vs.105).aspx
SharedStorageAccessManager.CopySharedFileAsync(...)
I've inline the information on how to do this from MSDN http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987(v=vs.105).aspx
Read that documentation and it should be clear how to use the APIs as well as how to setup your URI mapper.
Good luck :)
Ok I figured it out. The "install" directory is actually restricted access but for some reason the Visual Studio signing process leaves the app with enough permissions to access this folder. The correct procedure of determining a relative directory is not to use "Directory.GetCurrentDirectory()" but rather to use "ApplicationData.Current.LocalFolder". Hope this helps!
I have a code which is similar this:
string file;
using (StreamReader r = new StreamReader("xml.xml"))
{
file = r.ReadToEnd();
}
XElement xml = XElement.Parse(file);
using (XmlWriter w = XmlWriter.Create("xml.xml")) //The point of problem!
{
w.WriteStartDocument();
...;
w.WriteEndDocument();
}
When I try run it like a console application is everything all right. But problems start when I want to use it in an ASP.NET application. At the using line it throws UnauthorizedAccessException exception with a description "access to the path is denied". Why?
You need to check which account your application Pool is using to access your server files/folders, for example, make one code to copy one file to application folder, check all security info, copy and paste on this problem folder, normally use this account "IIS_IURRS" give full control to test only...
If IIS/the web server is configured correctly, an account with a very limited set of permissions is used. As your path points to the application directory, it is very likely that the application pool account is not allowed to write to this location.
If you run the code in a console application, your user's permissions are applied and it is more than likely that you are allowed to write to the output folder of the project as Visual Studio writes the build output there under your account.
I would not recommend to change the application pool account or the permissions of the application folder in the file system - it is a very sensible limitation that limits the amount of trouble an attacker can possibly make.
Therefore I'd recommend to either move the file to a folder that the account can write to without changing permissions or define a special one outside of the application folder hierarchy that the account is given permissions to.
Also keep in mind that multiple users might access the file at the same time, so a database might be a better choice to store the data.
While using Selenium WebDriver as web automation framework, I have a question -
how can I configure Google Chrome and Internet Explorer to save downloaded files to specific (not default) folder and also without showing additional "save file" windows.
Webdriver has a FirefoxProfile for Mozilla Firefox browser, but what about other browsers?
Example for Firefox :
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.helperApps.alwaysAsk.force", false);
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", "\\Somedir\");
profile.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.SetPreference("browser.download.useDownloadDir", true);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip, application/x-gzip");
With Chrome, it can be done, it is just not as easy and straightforward as Firefox profile manipulation is.
Since the WebDriver bindings expose the ability to add in 'custom' abilities and command line parameters, you can give it any of the command line switches that Chrome knows about:
http://peter.sh/experiments/chromium-command-line-switches/
With this, we can give Chrome a profile to load, just as you do with Firefox.
However the WebDriver bindings don't expose the options as well as the Firefox profiles. So it has to be done manually.
Firstly, find out where your profiles live:
Go to this URL in Chrome.
chrome://version/
It will tell you what profile it's currently loading (and what command switches it is using). Copy the Profile Path into Explorer and go to it.
It should be, by default, using the Default profile directory. Go up on level in explorer, so you sit in the User Data folder.
Next step, create a new profile for Selenium to use. Open Chrome, go to Settings > Users > Add a new user. Give it a name.
Once created, Chrome will open up a new Chrome window for that user. Next step is to force Chrome, for this user only, to save downloads in a certain place.
This can be done either two ways. In the Chrome UI, go to the Settings, and change the download directory and ensure the checkbox next to it is unchecked, or to get a little more creative...
All Chrome preferences are stored in a file, stored in the users directory. You should have an explorer window open already, sitting at the User Data folder in Chrome's user folder. You should hopefully see it's created a new profile (probably called Profile 1). Go into it.
Now look for a file called Preferences (no extension).
Edit it with Notepad (it's a text document, with JSON).
Look for the download section, it will look like this:
"download": {
"directory_upgrade": true,
"extensions_to_open": ""
},
Add in this key, putting in the path you want to save your files to:
"default_directory": "PATH",
Make sure you escape any slashes in the path, with another backslash, in the same way it is escaped when you use the Visual Studio debugger.
For instance, C:\Bob\Jim\Downloads should be input as C:\\Bob\\Jim\\Downloads.
Save this file.
Now you have a profile where the downloads go to a certain place. How to make Chrome use this profile? You tell it which profile to open up at launch. The command line would be:
--profile-directory="Profile 1"
(Replace Profile 1 with whatever it is called in the User Data folder, if it isn't called that).
OK, we can tell Chrome to load up a particular profile, but how do we tell Selenium to do this too? Easy! Add it in as an 'additional command line switch'.
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument(#"--profile-directory=""Profile 1""");
Selenium will take care on ensuring that command line switch is passed down to Chrome.
(Note: if anyone knows of an easier solution, let me know!).
As for IE, I have tested this on IE8 and IE9 and it works OK. IE can take into consideration a registry key for where the default downloads location is. I cannot comment on IE7 or below though.
Navigate to, using regedit to (it is a per Windows user settings):
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer
Add in a string value called Download Directory. It's value will be the exact location of where you want the downloads to go. No need to escape the path BTW.
Simply ensure the user you are logged into under Windows has set this value, and there will be no more setup needed.
Please try the below code for chrome. Even I'm looking for a similar option for IE.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
How can I get the path of a file on my computer or on the local area network.
I would to show a window that allows me to browse the file system when I click a button, and I want to select a file and get the path to the file. How can I do this?
P.S. I'm not looking to upload the file; I just want to get the path.
The web application is running on the server, and you don't have access to the client file system at all. Can you imagine how much of a vulnerability that would be? I know I don't want the sites I visit inspecting my file system...
EDIT: Question is for a WinForms application
For a WinForms application, you can use the OpenFileDialog, and extract the path with something like this:
If you're looking for the file path:
string path = OpenFileDialog1.FileName; //output = c:\folder\file.txt
If you're looking for the directory path:
string path = Path.GetDirectoryName(OpenFileDialog1.FileName); //output = c:\folder
In general, the System.IO.Path class has a lot of useful features for retrieving and manipulating path information.
To do this in VB.NET use the FolderBrowserDialog.
Due to security restrictions browsers include for user safety, you can't manipulate the client file system directly. You can only use to let them pick a file, and even then it only sends the filename, not the whole path.
The FileSystem API in HTML5 allows for file manipulation, but only within a sandbox for your site specifically, not browsing across the network or other files on the client system.
Instead, provide your users easy steps on how they should use My Computer (or whatever equivalent on other OS's) to navigate to the file and copy & paste the path into a simple text input box.
Have you taken a look at the Path class from System.IO ?