How do I check if a network drive is online/offline without my program hanging? - delphi

I want to do some IO operations (reading files, listing folder content, etc) on a shared/network folder (\\JoulePC\Test\). If the folder is offline then the program will freeze for quite a while EVERY TIME I try to access it.
What I need to build is something like this:
function DriveIsOnline(Path: string): Boolean;
The function should return an answer quickly (under 1 second). I would use the DriveIsOnline before performing any IO operations on that remove folder.
__
The API function GetDriveType will return 1 (which means 'The root path is invalid') if the drive is offline. Will it be logically correct to consider this answer ('1') as an indication that the drive is offline?

Related

How do I view the source code of a GW-BASIC .BAS file?

I have an old .BAS file that I'm trying to view and for which I'm running into some problems. Searching online seems to indicate that I should be able to just open it in NOTEPAD.EXE or similar, but doing so gives me gibberish, like this:
þ*©¿TÜ…7[/C̸yõ»€¹Ù<Ñ~Æ-$Ì™}³nFuJ,ÖYòÎg)ʇŒ~Š¯DËðïþSnhœJN
‰=É™2+df”c).vX»[šû'Û9¹8%ñx5m#8úV4ÊBº)Eª;Iú¹ó‹|àÆ„72#Ž§i§Ë #îÑ?
í‘ú™ÞMÖæÕjYе‘_¢y<…7i$°Ò.ÃÅR×ÒTÒç_yÄÐ
}+d&jQ *YòÎg)ʇŒ~Š¯DË?úŽ©Ž5\šm€S{ÔÍo—#ìôÔ”ÜÍѱ]ʵ¬0wêÂLª¡öm#Å„Ws雦 X
Ô¶æ¯÷¦É®jÛ ¼§
”n ŸëÆf¿´ó½4ÂäÌ3§Œ®
I know the file is sound, because I can open it in GW-BASIC. However, list does not seem to work to view the file, and trying to save the file in ASCII format from within GW-BASIC, didn't work either. Both just gave me an "Illegal function call" error:
GW-BASIC 3.22
(C) Copyright Microsoft 1983,1984,1986,1987
60300 Bytes free
Ok
LOAD"Pwrharm
Ok
LIST
Illegal function call
Ok
SAVE "Pwrharm2",A
Illegal function call
Ok
RUN
[Program runs successfully]
Then again, the run command works just fine. What am I doing wrong?
You're not doing anything wrong; the file was originally saved in GWBASIC with the ,P option. There is a 'hack' to unprotect it, described at https://groups.google.com/forum/#!topic/comp.os.msdos.misc/PA9sve0eKAk - basically, you create a file (call it UNPROT.BAS) containing only the characters 0xff 0x1a, then load the protected file, then load UNPROT.BAS, and you should then be able to list and save the program.
If you can't LIST or EDIT a GW-BASIC .BAS file that you LOADed from disk, it means that the file was originally SAVEd in protected format via SAVE filespec, P.
The 1988 "Handbook of BASIC - third edition" by David I. Schneider describes it as follows:
A program that has been SAVEd in protected format can be unprotected with the following technique.
(a) Create a file called RECOVER.BAS with the following program.
10 OPEN "RECOVER.BAS" FOR OUTPUT AS #1
20 PRINT #1, CHR$(255);
30 CLOSE #1
(b) LOAD the protected program into memory.
(c) Enter LOAD "RECOVER.BAS"
The formerly protected program will now be in memory and can be LISTed or EDITed, and reSAVEd in an unprotected format. This technique appears to work with most versions of BASIC. I have used it successfully with IBM PC BASIC, Compaq BASIC, and several versions of GW-BASIC. LOADing the file RECOVER.BAS will also restore a program after a NEW command has been executed.

What could cause an unexpected 'File In Use' Error

I have a Delphi5 application which exports a file (.pdf) and a very small metadata file to a network location. The intention is that these 2 files should be processed, and then removed, by a polling .NET application.
My approach is to
Write the metadata file with the extension '.part'
Generate the .pdf
Rename the .part file to .dat
The .NET process is looking for files with the extension '.dat' only, so I would expect there to be no conflict between the 2 reader/writers. However, the .NET process is occasionally logging the following error ...
System.IO.IOException: The process cannot access the file '\\server\Path\FileName.dat' because it is being used by another process.
(I say occasionally - we are currently testing, so when volumes increase this may become much more of an issue)
The Delphi code looks like this :
AssignFile(FTextFile, Format('%s\%s.part', [DMSPath, FullFileName]));
try
try
ReWrite(FTextFile);
Writeln(FTextFile, MetaDataString);
finally
CloseFile(FTextFile);
end;
except
raise ELogFileException.Create( LOGFILEWRITEFAILURE );
end;
Then there is a separate method which performs the following lines of code
if FindFirst(Format('%s\*.part',[DMSPath]), faAnyFile, SearchRec) = 0 then begin
repeat
OldName := Format('%s\%s',[DMSPath, SearchRec.Name]);
NewName := Format('%s\%s',[DMSPath, ChangeFileExt(SearchRec.Name, '.dat')]);
RenameFile(OldName, NewName);
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
I cannot see anything inherently wrong with this code and we have a couple of remedies in mind, but I have 2 questions
Should I try a different technique to more reliably protect the '.dat' file until it is fully ready
What circumstances could be causing this?
So far there has been one suggested cause - Antivirus software.
Any suggestions as to how the file might be produced differently? Note that my application is Delphi5; I wondered if there was a newer, more 'atomic' version of the 'MoveFileA' WinApi call I could use.
In the past, we had a problem with file being locked like that. Investigation pointed to Windows' Prefetch. The file being affected were not on a network directory though.
As far as I know, Prefetch only work on process startup and/or while booting (Controlled by a registry key), so it might not apply to your current situation.
You can check the "C:\"Windows"\Prefetch\" directory. If prefetch is active, it should contains multiple *.pf files. If there is one with your executable filename, it might be worth investigating.
Personally speaking, because there are multiple files involved, I'd create a separate lock file (eg, myfile.lck) that you write first. If the polling app sees it in the folder, then it stops looking for other files. Once that file is gone, then it dives deeper. I don't know if this would solve the problem you're encountering or not, but I'd give it a try. (Files with .dat extensions are frequently created by malicious evildoers, so they can raise spurious issues through other sources, like AV software. A lock file with 0 bytes in it is generally harmless and disregarded.)

Why is COMMON_APPDATA returned as a null string on Windows XP

One of my users at a large university (with, I imagine, the aggressive security settings that university IT departments general have on their computers) is getting an empty string returned by Windows XP for CSIDL_COMMON_APPDATA or CSIDL_PERSONAL. (I'm not sure which of these is returning the empty string, because I haven't yet examined his computer to see how he's installed the software, but I'm pretty sure it's the COMMON_APPDATA...)
Has anyone encountered this or have suggestions on how to deal with this?
Here's the Delphi code I'm using to retrieve the value:
Function GetSpecialFolder( FolderID: Integer):String;
var
PIDL: PItemIDList;
Path: array[0..MAX_PATH] of Char;
begin
SHGetSpecialFolderLocation(Application.Handle, FolderID, PIDL);
SHGetPathFromIDList(PIDL, Path);
Result := Path;
end; { GetSpecialFolder }
ShowMessage(GetSpecialFolder(CSIDL_COMMON_APPDATA)); <--- This is an empty string
Edit:
Figuring out this API made me feel like I was chasing my tail - I went in circles trying to find the right call. This method and others similar to it are said to be deprecated by Microsoft (as well as by a earlier poster to this question (#TLama?) who subsequently deleted the post.) But, it seems like most of us, including me, regularly and safely ignore that status.
In my searches, I found a good answer here on SO from some time ago, including sample code for the non-deprecated way of doing this: what causes this error 'Unable to write to application file.ini'.
If you want to find out why an API call is failing you need to check the return values. That's what is missing in this code.
You need to treat each function on its own merits. Read the documentation on MSDN. In the case of SHGetSpecialFolderLocation, the return value is an HRESULT. For SHGetPathFromIDList you get back a BOOL. If that is FALSE then the call failed.
The likely culprit here is SHGetSpecialFolderLocation, the code that receives the CSIDL, but you must check for errors whenever you call Windows API functions.
Taking a look at the documentation for CSIDL we see this:
CSIDL_COMMON_APPDATA
Version 5.0. The file system directory that contains application data for all users. A typical path is C:\Documents and Settings\All
Users\Application Data. This folder is used for application data that
is not user specific. For example, an application can store a
spell-check dictionary, a database of clip art, or a log file in the
CSIDL_COMMON_APPDATA folder. This information will not roam and is
available to anyone using the computer.
If the machine has a shell version lower than 5.0, then this CSIDL value is not supported. That's the only documented failure mode for this CSIDL value. I don't think that applies to your situation, so you'll just have to see what the HRESULT status code has to say.

Yaws process died

I do performance testing of our Erlang application with OpenSTA. The test runs with 100 virtual users. At some point the following errors start popping up:
Yaws process died: {{badmatch,{error,eacces}},
[{yaws_server,ut_read,1},
{yaws_server,deliver_dyn_file,5},
{yaws_server,aloop,3},
{yaws_server,acceptor0,2},
{proc_lib,init_p_do_apply,3}]}
The test continues to run. I cannot find info about this error. Does eacces mean Error accessing a resource?
EDIT: As pointed out by #Muzaaya Joshua the call file:read_file(UT#urltype.fullpath) crashes in function ut_read(UT). I recompiled the module and printed the context. The error is eacces and UT holds:
{urltype,yaws,
{file_info,14088,regular,read_write,
{{2011,9,13},{11,51,42}},
{{2011,10,17},{17,59,44}},
{{2011,3,16},{13,18,58}},
33206,1,3,0,0,0,0},
"/handler.yaws",
"c:/Temp/harmony/script/../www/handler.yaws",
"/",undefined,undefined,"text/html",
"/handler.yaws",undefined}
This file handler.yaws is the entry point of our app and is called on every request. When I run the test with 100 or less virtual users I don't see these errors. So how can it be Missing permission for reading the file, or for searching one of the parent directories. as the error is described in the read_file documentation?
Thanks in advance.
Martin
eacces means access denied, the error codes are described at the end of the file documenation: http://www.erlang.org/doc/man/file.html#write_file_info-2
Yaws has failed to open a file. This is a file read permission denied to the user running yaws application. If you add permissions to the user running yaws to own all folders concerning yaws, this may be fixed. to check it out, try running yaws as root , if at all these paths are owned by root. The yaws_server.erl source file at the point is as follows:
ut_read(UT) ->
?Debug("ut_read() UT.fullpath = ~p~n", [UT#urltype.fullpath]),
case yaws:outh_get_content_encoding() of
identity ->
case UT#urltype.data of
undefined ->
?Debug("ut_read reading\n",[]),
{ok, Bin} = file:read_file(UT#urltype.fullpath),
?Debug("ut_read read ~p\n",[size(Bin)]),
Bin;
B when is_binary(B) ->
B
end;
deflate ->
case UT#urltype.deflate of
B when is_binary(B) ->
?Debug("ut_read using deflated binary of size ~p~n",
[size(B)]),
B
end
end.
The line in bold in the above source is where the bad match occurs.
Check wether yaws is running as a user with permissions to access its folders such as the doc root, ssl folders and other paths that yaws may access files. Does the user running yaws have access to all required files ?
In windows, this makes it easy. Now go to your Local disk C, Program Files (In windows 7, could be Program Files (x86)), lastly to where yaws is installed. This will be a folder: Yaws-VERSION e.g. Yaws-1.89. Now, when you right click this, you select Properties, then in the pop-up window you select Security. Under Security, you click edit. Now under Group or usernames, you select each user (and each type of account) and give it all permissions i.e. read, write, full control e.t.c. click Apply, wait for windows to perform the changes, then click Ok and close. Your users must now have all required permissions.
I managed to fix this errors by increasing the file size of the allowed in cache files in the YAWS configuration max_size_cached_file. This made our .yaws file to be loaded in memory and not accessess with file:read_file all the time. Hopefully this will save someone else couple of hours (or days :))

Bootstrap Hard disk access

I'm trying to write a bootstrap loader for the fun of it, I've been using guides such as:
http://www.omninerd.com/articles/PC_Bootstrap_Loader_Programming_Tutorial_in_ASM
http://hem.passagen.se/danma/nboot.htm
http://en.skelix.org/skelixos/tutorial01.php
I'm able to successfully copy over sectors from a floppy disk but when I try to access a harddisk I'm returned an error code from all int 13 functions other than reset. reset disk doesn't return an error.
Is there something special I have to do before int 13 works for hard disks?
Not that I'm aware of. Have you seen http://gaztek.sourceforge.net/osdev/boot/index.html ? That has a list of examples, at least one of which claims to be reading a file from "C:\" (presumably a DOS-formatted harddisk)

Resources