I've seen a few questions asking if it's possible to check if a specific download is completed, or if a specific download has been completed successfully. (to which the answer appears to be no.)
What I want to know: Is it possible to see if selenium is currently downloading any file? I.e. it doesn't matter if it's one file, or 20. Something like a small boolean check would be ideal.
When chrome is downloading a file you can check your downloads folder for the temp file (*.crdownload) that Chrome uses. When the download finishes that file is "replaced" by the actual filename/type.
/// <summary>
/// Looks for a file with the given extension (Example: "*.crdownload") in the current user's "Download" folder.
/// </summary>
public static string LocateDownloadedFile(string fileExtension)
{
// Get the default downloads folder for the current user
string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
FileInfo[] filesFound = di.GetFiles(fileExtension);
if (filesFound.Length == 0)
{
// do stuff
}
else
{
// do other stuff
}
}
Related
An eclipse plugin is needed to allow users to input a script and run that script through the IDE. For this I've implemented an eclipse plugin, using the multi-page editor template. I added the extension org.eclipse.debug.ui.launchShortcuts and provided a reference to my implementation of the interface org.eclipse.debug.ui.ILaunchShortcut. This interface requires to provide an implementation of these methods:
public void launch(final ISelection selection, final String mode);
public void launch(final IEditorPart editor, final String mode);
When the user - e.g. me - right clicks the file from the project explorer, selects "run as" and selects the launcher I provided, then the implementation of this launch method is hit. The first method - i.e. the ISelection version - is hit when selecting the file from the project explorer. The second method - i.e. the IEditorPart version - is hit when right clicking the editor zone and selecting the launcher through the "run as" option from the context menu.
I now need to find out how I can retrieve the contents of that editor page. In the first method I believe I could retrieve the filename with the below code:
IFile file = (IFile) ((IStructuredSelection) selection).getFirstElement();
String path = file.getFullPath().makeAbsolute().toString();
However, the that path is relevant with respect to the root of the project. I don't know how to retrieve the path of the root of the project.
The implementation of the second method is more problematic given I don't know how to find the path based on the IEditorPart.
I hope you can help. Many thanks
If you are asking how to get the file that the editor is current editing you can use something like:
IPath filepath = null;
IEditorInput input = editor.getEditorInput();
IFile file = input.getAdapter(IFile.class);
if (file != null) {
filepath = file.getFullPath();
}
if (filepath == null) {
ILocationProvider locationProvider = input.getAdapter(ILocationProvider.class);
if (locationProvider != null) {
filepath = locationProvider.getPath(input);
}
}
which tries to get the IFile frpm the editor directly and if that fails tries for a location provider.
I need to navigate to a web site that ultimately contains a .pdf file and I want to save that file locally. I am using CEFSharp to do this. The nature of this site is such that once the .pdf appears in the browser, it cannot be accessed again. For this reason, I was wondering if once you have a .pdf displayed in the browser, is there a way to access the source for that file in the cache?
I have tried implementing IDownloadHandler and that works, but you have to click the save button on the embedded .pdf. I am trying to get around that.
OK, here is how I got it to work. There is a function in CEFSharp that allows you to filter an incoming web response. Consequently, this gives you complete access to the incoming stream. My solution is a little on the dirty side and not particularly efficient, but it works for my situation. If anyone sees a better way, I am open for suggestions. There are two things I have to assume in order for my code to work.
GetResourceResponseFilter is called every time a new page is downloaded.
The PDF is that last thing to be downloaded during the navigation process.
Start with the CEF Minimal Example found here : https://github.com/cefsharp/CefSharp.MinimalExample
I used the WinForms version. Implement the IRequestHandler and IResponseFilter in the form definition as follows:
public partial class BrowserForm : Form, IRequestHandler, IResponseFilter
{
public readonly ChromiumWebBrowser browser;
public BrowserForm(string url)
{
InitializeComponent();
browser = new ChromiumWebBrowser(url)
{
Dock = DockStyle.Fill,
};
toolStripContainer.ContentPanel.Controls.Add(browser);
browser.BrowserSettings.FileAccessFromFileUrls = CefState.Enabled;
browser.BrowserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
browser.BrowserSettings.WebSecurity = CefState.Disabled;
browser.BrowserSettings.Javascript = CefState.Enabled;
browser.LoadingStateChanged += OnLoadingStateChanged;
browser.ConsoleMessage += OnBrowserConsoleMessage;
browser.StatusMessage += OnBrowserStatusMessage;
browser.TitleChanged += OnBrowserTitleChanged;
browser.AddressChanged += OnBrowserAddressChanged;
browser.FrameLoadEnd += browser_FrameLoadEnd;
browser.LifeSpanHandler = this;
browser.RequestHandler = this;
The declaration and the last two lines are the most important for this explanation. I implemented the IRequestHandler using the template found here:
https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/RequestHandler.cs
I changed everything to what it recommends as default except for GetResourceResponseFilter which I implemented as follows:
IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (request.Url.EndsWith(".pdf"))
return this;
return null;
}
I then implemented IResponseFilter as follows:
FilterStatus IResponseFilter.Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
{
BinaryWriter sw;
if (dataIn == null)
{
dataInRead = 0;
dataOutWritten = 0;
return FilterStatus.Done;
}
dataInRead = dataIn.Length;
dataOutWritten = Math.Min(dataInRead, dataOut.Length);
byte[] buffer = new byte[dataOutWritten];
int bytesRead = dataIn.Read(buffer, 0, (int)dataOutWritten);
string s = System.Text.Encoding.UTF8.GetString(buffer);
if (s.StartsWith("%PDF"))
File.Delete(pdfFileName);
sw = new BinaryWriter(File.Open(pdfFileName, FileMode.Append));
sw.Write(buffer);
sw.Close();
dataOut.Write(buffer, 0, bytesRead);
return FilterStatus.Done;
}
bool IResponseFilter.InitFilter()
{
return true;
}
What I found is that the PDF is actually downloaded twice when it is loaded. In any case, there might be header information and what not at the beginning of the page. When I get a stream segment that begins with %PDF, I know it is the beginning of a PDF so I delete the file to discard any previous contents that might be there. Otherwise, I just keep appending each segment to the end of the file. Theoretically, the PDF file will be safe until you navigate to another PDF, but my recommendation is to do something with the file as soon as the page is loaded just to be safe.
guys, now I have an issue, it really makes me wonder.
I'm currently developing a Windows 8 RT app, the app store data to local, so I choice to use the SQLite for WinRT(include the SQLite.cs SQLiteAsync.cs, SQLite3.dll) , the SQLite for WinRT store the database file in the application temporary folder by default
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false): this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The default of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
{
DatabasePath = databasePath;
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE
var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = storeDateTimeAsTicks;
BusyTimeout = TimeSpan.FromSeconds (0.1);
}
assign to the app temporary folder path.
Now I want to save the database file to another folder, like document folder, in order to save the user data and behavior, import the data when user re-install the app. So I change the save folder, the code as follow
StorageFolder sourceFolder = await KnownFolders.DocumentsLibrary.GetFolderAsync(FolderName);
DatabasePath = Path.Combine(sourceFolder.Path, DBName);
SQLite3.SetDirectory(/*temp directory type*/2, storeFloderPath);
but it throw an excetion at:
var r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero);
Handle = handle;
if (r != SQLite3.Result.OK)
{
throw SQLiteException.New(r, String.Format("Could not open database file: {0} ({1})", DatabasePath, r));
}
it says cannot open the file. I think maybe the problem is 'SQLite3.SetDirectory(/temp directory type/2, storeFloderPath)', the '2' is the stand temp directory type. These no official document, so I try the argument from 0 to 6, it did't work as well, the exception as same as original.
Anyone know how to do it, or it has some error in my codes.
Thanks in advance.
Thanks all you answers, I found a sick way to solve it, When I want to open the database connection in other folder, firstly copy the database file to the application local folder(Windows.Storage.ApplicationData.Current.LocalFolder), and then connect to the database file, and then it successed.
But I wish the developer of the SQLite for WinRT could remark the problem, and fix it
I am trying to downgrade a document using VSTO.
I have a webservice, that receive a byte array. This byte is from the current active document.
The webservice can only handle a 2007/2003 word doc file.
So I want to use the
document.DowngradeDocument();
But the webservice report an error, when sending the byte array.
If a do a SaveAs and force word to save as 2007/2003 doc format, then there is no problem.
So my question is:
1) Why is DowngradeDocument() function not working. Why is it not doing a proper downgrade.
2) Do I need to do something else when I have called DowngradeDocument()
This must be in memory, since the file a happen to be working on, is not saved on disk.
// Dennis
Thank you for taking the time to read this
--- edit d. 20120904 ---
I cant use the webservice error, since it does not make sense of the error.
It says that it can finde the file, and this is an error within and application at the other side.
So I have tryed, to save a document in the right format, and one that was downgraded.
Used the same code. One work and the other did not.
But here is how I save the file as a temp. Before I call this function I have done a document.DowngradeDocument();
So I need, when it save to also change the format, while calling the downgrade function.
In the documentation for this function, it is clear that all previous version of office can read it, if the function is called.
/// <summary>
/// Make a copy of ActiveDocument in current user temp folder, and get a byte[].
/// </summary>
/// <param name="filename"></param>
/// <param name="document"></param>
/// <param name="file"></param>
/// <returns></returns>
private byte[] MakeCopy(string filename, Document document, out FileInfo file)
{
// http://blogs.msdn.com/b/pranavwagh/archive/2008/04/03/how-to-do-a-save-copy-as-in-word.aspx
// http://stackoverflow.com/questions/12175273/serialize-current-activedocument-from-office-2007-add-in
Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.Visible = false;
{
// make a fil i Current user temp folder
// http://stackoverflow.com/questions/944483/how-to-get-temporary-folder-for-current-user
string tempPath = System.IO.Path.GetTempPath();
string fileName = Path.Combine(tempPath, GenerateValidFileName(filename)) + ".doc";
IPersistFile compoundDocument = document as IPersistFile;
compoundDocument.Save(fileName, false);
byte[] content = File.ReadAllBytes(fileName);
file = new FileInfo(fileName);
wdApp.Quit();
return content;
}
}
When starting the default browser like this:
Dim trgt1 As String = "http://www.vbforums.com/showthread.php?t=612471"
pi.FileName = trgt1
System.Diagnostics.Process.Start(pi)
It takes about 40 seconds to open the page.
If I do it like this, though this isn't the default browser
Dim trgt1 As String = "http://www.vbforums.com/showthread.php?t=612471"
pi.Arguments = trgt1
pi.FileName = "iexplore.exe" 'or firefox.exe
System.Diagnostics.Process.Start(pi)
it opens immediately. Is this a bug or a feature? I have tried this with both IE and FireFox set to be the default browser.
1
Windows is running through the registry looking for an appropriate application to open the document with (via explorer.exe).
2
You are explicitly telling windows to use xxx.exe to open the document.
Update for the moving target: ;-)
The reason it is so slow is that the Url you are specifying doesn't look like anything it knows how to open, with a browser or otherwise, and has to employ brute force in determining this.
If you wan to speed up launching with the default browser, get it from HKEY_CURRENT_USER\Software\Classes\http\shell\open\command and use #2.
Use this function to retrieve path of default browser
/// <summary>
/// Reads path of default browser from registry
/// </summary>
/// <returns></returns>
private static string GetDefaultBrowserPath()
{
string key = #"htmlfile\shell\open\command";
RegistryKey registryKey =
Registry.ClassesRoot.OpenSubKey(key, false);
// get default browser path
return ((string) registryKey.GetValue(null, null)).Split('"')[1];
}
Opens URL in default browser from within the C# program.
string defaultBrowserPath = GetDefaultBrowserPath();
try
{
// launch default browser
Process.Start(defaultBrowserPath, "http://www.yahoo.com");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
Opens URL in separate instance of default browser from within the C# program.
// open URL in separate instance of default browser
Process p = new Process();
p.StartInfo.FileName = GetDefaultBrowserPath();
p.StartInfo.Arguments = "http://www.yahoo.com";
p.Start();
From this blog post
I respectfully differ with the Sky. I have tried this on numerous machines now and the value
string key = #"htmlfile\shell\open\command";
seems to always default to IE even if Chrome is set to the default browser. Now, to be honest I have not tried this on machines with firefox set to the default browser only chrome, so it could do with more testing but the value does seem to only store IE from my testing.
Hope this helps those who use alternative browsers.
I am going to stick with process.start(url) as that pretty much guarantees that you get the users default browser every time. Let the framework handle it! that is why MS built it...