Using Windows Defender API , I'm trying to do a scan for malwares on a folder.
Following The documentation I wrote the code:
MPRESOURCE_INFO ResourceInfo = { 0 };
MPSCAN_RESOURCES ScanResource = { 0 };
PMPRESOURCE_INFO ResourceInfoArray = NULL;
...
ResourceInfo.Scheme = L"dir";
ResourceInfo.Path = L"C:\\temp";
ResourceInfo.Class = 0;
// ResourceInfoArray was Allocated before
*ResourceInfoArray = ResourceInfo;
ScanResource.dwResourceCount = 1;
ScanResource.pResourceList = ResourceInfoArray;
// Opened hMpManager before using MpScanStart
hRetval = MpScanStart(hMpManager, MPSCAN_TYPE_RESOURCE, 0, &ScanResource, NULL, &ScanHnadle);
From which I get an error message: An unexpected problem occurred. Install any available updates, and then try to start the program again. For information on installing updates, see Help and Support.
However If I change the ResourceInfo definition to:
ResourceInfo.Scheme = L"file";
ResourceInfo.Path = L"C:\\temp\\MyFile.exe";
ResourceInfo.Class = 0;
It works great, detecting the file in the right way.
On the bottom line - the code works for files, but doesn't work for directories.
Does anyone know what am I doing wrong with the directory search?
Analyzing event logs created by MpCmdRun.exe I found out that it uses the scheme "folder" instead of "dir". That change made my code working.
ResourceInfo.Scheme = L"folder";
Folder paths do not have to end with backslash, but drives require it: (F:\).
Related
I tried to get a script to create a text file that could write/add the images name, but the function
FileID = CreateFileForWriting(filename) does not work, it shows that was used by other process
I did not get this, is this function not right format or something is wrong, thx
Number Totaln
totaln=countdocumentwindowsoftype(5)
String filename, text
Number fileID
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename))exit(0)
fileID = CreateFileForWriting(filename)
number i
for(i = 0; i <totaln; i++)
{
image imgSRC
imgSRC := GetFrontImage()
string imgname=getname(imgSRC)
WriteFile(fileID,"imgname")
Result("imgname")
}
Your code is nearly fine, but if you use the low-level API for file I/O you need to ensure that you close files you've opened or created.
Your script doesn't. Therefore, it runs fine exactly 1 time but will fail on re-run (when the file is still considered open.)
To fix it, you need to have closefile(fileID) at the end.
( BTW, if you script exits or throws after opening a file but before closing it, you have the same problem. )
However, I would strongly recommend not using the low-level API but the file streaming object instead. It also provides an automated file-closing mechanism so that you don't run into this issue.
Doing what you do in your script would be written as:
void writeCurrentImageNamesToText()
{
number nDoc = CountImageDocuments()
string filename
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename)) return
number fileID = CreateFileForWriting(filename)
object fStream = NewStreamFromFileReference(fileID,1) // 1 for auto-close file when out of scope
for( number i = 0; i <nDoc; i++ ){
string name = GetImageDocument(i).ImageDocumentGetName()
fStream.StreamWriteAsText( 0, name + "\n" ) // 0 = use system encoding for text
}
}
writeCurrentImageNamesToText()
I'm trying to trim a mp3 file.
using this code:
private void TrimMp3(string open, string save)
{
using (var mp3FileReader = new Mp3FileReader(open))
using (var writer = File.Create(save))
{
var startPostion = TimeSpan.FromSeconds(60);
var endPostion = TimeSpan.FromSeconds(90);
mp3FileReader.CurrentTime = startPostion;
while (mp3FileReader.CurrentTime < endPostion)
{
var frame = mp3FileReader.ReadNextFrame();
if (frame == null) break;
writer.Write(frame.RawData, 0, frame.RawData.Length);
}
}
}
"open" is the file I'm trimming and "save" is the location I'm saving.
The trimming works but not fully. The new file does start from 60 seconds but it keeps going and not stopping at 90 seconds. For example if the file is 3 minutes it will start at 1 minute and end at 3. Its like the while is always true. What am I doing wrong here?
Thanks in advance!
I have no idea what your Mp3FileReader is doing there. But your while loop looks odd. Does mp3FileRead.ReadNextFrame() also change mp3FileReader.CurrentTime ? If not then there is your problem.
You should atleast do mp3FileReader.CurrentTime + 1Frame. Otherwise your currenttime is never changed and loop will always be true
In NAudio 1.8.0, Mp3FileReader.ReadNextFrame does not progress CurrentTime, although I checked in a fix for that recently.
So you can either get the latest NAudio code, or make use of the SampleCount property on each Mp3Frame to accurately keep track of how far through you are yourself.
Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.
Thanks in advance
You can save your download to a fix location by using the profile. Check these discussions:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
As you have mentioned that you have covered the reading part. You can read it from that fixed location.
Below is the code snippet that can help resolve the above query:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as #BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension
Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.
Let say, how we test latest downloaded file in browser.
In existing test browser Open NewTab Window
Go to
downloads (chrome://downloads/)
Check if expected file is there
or not
Now same thing in selenium using java
driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName= element.getText();
I want to re-project an HDF from UTM(WGS84) to sinusoidal(WGS84), so I try to use GDALAutoCreateWarpedVRT to finished it. The code is below:
hSrcDS = (GDALDataset*)GDALOpen("HJ1ACCD1.hdf", GA_ReadOnly);
const char *pszSrcWKT = NULL;
char* pszDstWKT = NULL;
//pszSrcWKT = ProjectionStr;
pszSrcWKT=GDALGetProjectionRef(hSrcDS);
CPLAssert( pszSrcWKT != NULL &&strlen(pszSrcWKT) > 0 );
OGRSpatialReference oSRS;
oSRS.SetSinusoidal(0,0,0);
oSRS.SetWellKnownGeogCS("WGS84");
oSRS.exportToWkt(&pszDstWKT );
GDALWarpOptions*psWarpOptions = GDALCreateWarpOptions();
psWarpOptions->dfWarpMemoryLimit=500*1024*1024;
hDstDS=(GDALDataset*)(GDALDataset*)GDALAutoCreateWarpedVRT(hSrcDS,pszSrcWKT,pszDstWKT,GRA_Bilinear ,20,psWarpOptions);
GDALDriver *poDriverTiff;
poDriverTiff=GetGDALDriverManager()->GetDriverByName("GTIFF");
poDriverTiff->CreateCopy("d:\\toto.tif",(GDALDataset*)hDstDS,false,NULL,NULL,NULL);
When I set oSRS.SetSinusoidal(0,0,0),the result seems good, but the resolution is doubled (from 30 to 60). It's so weird.
According to the API docs for GDALAutoCreateWarpedVRT:
The GDALSuggestedWarpOutput() function is used to determine the bounds and resolution of the output virtual file which should be large enough to include all the input image
There is also a GDALSuggestedWarpOutput2() function to help suggest output file size for a similar set of requirements.
I have the following code (extract) to display Save As dialog:
char FileName[MAX_PATH] = "TestImage.jpg"
...
lpofn.lStructSize = sizeof(OPENFILENAME);
lpofn.hwndOwner = hWnd;
lpofn.hInstance = GetWindowInstance (hWnd);
lpofn.lpstrFilter = "JPG - JPEG File\0*.JPG\0TIF - TIFF File\0*.TIF\0PNG File\0*.PNG\0BMP - Bitmat File\0*.BMP\0";
lpofn.lpstrCustomFilter = NULL;
lpofn.nMaxCustFilter = NULL;
lpofn.nFilterIndex = 0;
lpofn.lpstrFile = FileName;
lpofn.nMaxFile = MAX_PATH;
lpofn.lpstrFileTitle = NULL;
lpofn.nMaxFileTitle = NULL;
lpofn.lpstrInitialDir = NULL;
lpofn.lpstrTitle = NULL;
lpofn.Flags = OFN_HIDEREADONLY | OFN_ENABLEHOOK | OFN_EXPLORER;
lpofn.nFileOffset = 0;
lpofn.nFileExtension = 0;
lpofn.lpstrDefExt = NULL;
lpofn.lCustData = NULL;
lpofn.lpfnHook = &UpdateFilename;
lpofn.lpTemplateName = NULL;
if(!GetSaveFileName(&lpofn)) return;
...
eg.
- User does save as, default File name = "TestImage.jpg", default Files of Type = JPG
- User changes Files of Type to PNG, File name control remains at "TestImage.jpg" instead of changing to "TestImage.png"
Am I doing something wrong? Is it possible to instruct GetSaveFileName() to change the extension, or do I have to have a custom save as dialog (any examples?)
I'm using Win32 API, VC6.
Update: here is the Hook function:
UINT CALLBACK UpdateFilename(HWND hdlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch (uiMsg)
{
case WM_NOTIFY:
// Check for CDN_TYPECHANGE etc
return FALSE;
}
return FALSE;
}
Note that the hook function does stop on breakpoints. I've purposely not proceeded further with handling CDN_TYPECHANGE until I can figure out why the look of the dialog changes when the hook is enabled and how to fix it.
Use a buffer for your suggested file name, not a static string.
char szFile[MAX_PATH];
szFile[0] = '\0';
lpofn.lpstrFile= szFile;
lpofn.nMaxFile = sizeof(szFile)/ sizeof(*szFile);
Besides that, it is a default Windows behaviour going well back to Win95 days. As you are using VS6.0, you stil have these DLLs. What I did then was to use:
lpofn.lpstrDefExt = (LPSTR)NULL
That prevents any extension from being added. I then checked lpofn.nFileExtension upon return to find out which extension was selected.
if (lpofn.nFileExtension == 0)
{
// add default extension, no extension was selected/entered by user
}
else
{
// there is an extension, save as entered.
}
In order to update the dialog while it is still running, you need to provide a pointer to an lpfnHook callback in the OPENFILENAME struct, and have the callback handle the CDN_TYPECHANGE notification. It can send the dialog a CDM_GETFILEPATH or CDM_GETSPEC message to get the current filename, tweak it as needed, and then send a CDM_SETCONTROLTEXT message to update the edit field (the ID of the filename edit field is 0x442) with the new value.
Update: There is nothing wrong with your hook code. GetSaveFileName() is deprecated starting in Windows Vista, replaced by (and becoming a wrapper around) the Common Item Dialog. The GSFN dialog UI is not altered by a hook in XP, so you must be using Vista+, in which case enabling the hook simply causes the wrapper to use different settings when invoking the CID internally. A lot of the new CID features are based on IShellItem, not filename strings, so the wrapper removes anything that cannot be represented as a old-style filename, and makes the dialog look like the old-style GSFN dialog in XP and earlier. So what you are seeing is normal behavior for GetSaveFileName() under Vista+! If you do not like it, then do not use GetSaveFileName() anymore. Use the new IFileSaveDialog interface instead. In fact, it natively changes the file extension for you if you configure multiple file types, designate one of them as the default extension, and then set an initial filename that matches the default extension. But if you wanted to, you can alternatively implement the IFileDialogEvents interface in your code to receive OnTypeChange notifications and then use the IFileDialog::SetFileName() method to update the displayed filename as neded.