Best windows questions in July 2011

10 votes

How can I use aero glass to cover my entire forms? Here is an example of what I mean:

enter image description here

[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
    public int Left;
    public int Right;
    public int Top;
    public int Bottom;
}

[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMargins);

Then you can enable it on your form like so:

MARGINS marg = new MARGINS() { Left = -1, Right = -1, Top = -1, Bottom = -1 };
DwmExtendFrameIntoClientArea(form.Handle, marg);

Concatenating a stack string with a heap string gives odd results

10 votes

I am sure the following has a rational explanation but I am nevertheless a bit baffled.

The issue is with a function which creates a _TCHAR[CONSTANT], a _TCHAR*, concatenates them and returns the result.

For some reason the call to whatTheHeck() from _tmain() returns gibberish.

_TCHAR* whatTheHeck(_TCHAR* name) {
    _TCHAR Buffer[BUFSIZE];
    DWORD dwRet;
    dwRet = GetCurrentDirectory(BUFSIZE, Buffer);
    _TCHAR* what = new _TCHAR[BUFSIZE];
    what = _tcscat(Buffer, TEXT("\\"));
    what = _tcscat(what, name);
    return what;
}

int _tmain(int argc, _TCHAR* argv[]) {

    _TCHAR* failure = whatTheHeck(TEXT("gibberish);")); // not again ..
    _tprintf(TEXT("|--> %s\n"), failure);

    _TCHAR* success = createFileName(TEXT("readme.txt")); // much better
    _tprintf(TEXT("|--> %s\n"), success);

    return 0;
}

In contrast, when going with heap things work as expected.

_TCHAR* createFileName(_TCHAR* name) {
    _TCHAR* Buffer = new _TCHAR[BUFSIZE];
    DWORD dwRet;
    dwRet = GetCurrentDirectory(BUFSIZE, Buffer);
    Buffer = _tcscat(Buffer, TEXT("\\"));
    Buffer = _tcscat(Buffer, name);
    return Buffer;
}

Why the difference?

Is it because _tcscat() concatenates memory addresses instead of their contents and return purges the stack?

There are lots of problems with your code. Let's take it apart, shall we:

_TCHAR* whatTheHeck(_TCHAR* name)   // We're inside a local scope
{
    _TCHAR Buffer[BUFSIZE];         // "Buffer" has automatic storage

    _TCHAR* what = new _TCHAR[BUFSIZE];  // "what" points to newly allocated dyn. memory

    what = _tcscat(Buffer, TEXT("\\"));  // Oh no, we overwrite "what" - leak!
                                         // Now what == Buffer.

    what = _tcscat(what, name);  // Equivalent to "_tcscat(Buffer, name)"

    return Buffer;               // WTPF? We're returning a local automatic!
 }

As you can see, you are both causing a memory leak with a gratuitious and reckless new, and you are also returning the address of a local object past its lifetime!

I would strongly recommmend

  1. reading the documentation for strcat and understanding "source" and "destination",
  2. not using strcat, but a safer version like strncat,
  3. not using strncat, but instead std::string.

including windows.h causes clashing with local variable name

8 votes

I am including windows.h in one of my h files (in order to use CaptureStackBackTrace), in a Visual-Studio project. At first I got some compiler errors because of the use of min/max std methods and the macro with same name in windows.h, but this seems to be solved by #define NOMINMAX, as I read in other SO posts. (I say "seems" because I can't be sure till my whole project builds ok again).

The problem is that some local variable names now break the build. The line:

int grp1;

inside a class method, causes the following error:

error C2143: syntax error : missing ';' before 'constant'

while the cpp file compiles ok if I change the variable name to grp1_.

Of course I can just change the variable name, but nevertheless I've got a feeling that I am doing something wrong - am I? Or is this a known issue when including windows.h? Is there any other, more elegant solution other than changing the variable name?

dlg.h contains the line

#define grp1        0x0430

You could exclude it by defining WIN32_LEAN_AND_MEAN.

New Windows Application - What language?

7 votes

We are currently in pre phase of developing a desktop application for windows. But when hearing all the latest discussions on Windows 8, Silverlight, WPF, Jupiter I don't know what to believe anymore. Is it wrong starting a new project with WPF now? Should I switch to Silverlight? Or should I wait until more details of Windows 8 comes out?

Interesting topic, main point is if you do it windows based (Winforms or WPF) or web based (ASP.NET MVC or Silverlight).

For a new business application we are just starting now, business wants windows based because they want more features, IT wants web based to have no deployment issues and easier support on a centralized server instead of trying to figure out what the client machines has...

In fact I believe WPF is ready for LOB (even if there are still less third party controls comparing to winforms).

I would not invest on SL because still requires a plugin and with MVC / Ajax and HTML5 you can do the same and more with no plugins required and having same UI running on all browsers and platforms ( I focus very much of have my web app running also in iPad and Android tablets with no changes )...

Main point is the architecture, how you distribute it across servers and tiers so to have well distributed workloads and good reliability... then if you have a UI windows based or web based, as long these UIs consume the same server components exposed as WCF end points for example... is more a "kind" of detail...

How to check if network shared EXE file is used by more than one user?

6 votes

I have an application which sits on a server in the network shared folder. Many users in network, can use that file simultaneously. I would like to perform an update of that EXE file and to do this, I would like to know who in network (besides me) is currently using that file.

Is it possible to check this programmatically? For example: to list all user names who are using that file now? Or atleast to retrieve number of locks on that file?

Thanks.

To list the open shared files in a machine you can use ADSI (Active Directory Service Interfaces).

In order to use these interfaces from delphi you must import the Active DS type library

enter image description here

Then access the IADsFileServiceOperations interface, which contains a method called Resources this method return a collection with all the shared resources opened.

Check this sample code

{$APPTYPE CONSOLE}

uses
  ActiveDs_TLB,
  Variants,
  ActiveX,
  SysUtils;


function ADsGetObject(lpszPathName:WideString; const riid:TGUID; out ppObject):HRESULT; safecall; external 'activeds.dll';


procedure ListSharedResourcesInUse;
var
  FSO           : IADsFileServiceOperations;
  Resources     : IADsCollection;
  Resource      : OleVariant;
  pceltFetched  : Cardinal;
  oEnum         : IEnumvariant;
begin
  //establish the connection to ADSI
  ADsGetObject('WinNT://./lanmanserver', IADsFileServiceOperations, FSO);
  //get the resources interface 
  Resources := FSO.Resources;
  //get the enumerator
  oEnum:= IUnknown(Resources._NewEnum) as IEnumVariant;
  while oEnum.Next(1, Resource, pceltFetched) = 0 do
  begin
    Writeln(Format('Resource %s User %s',[Resource.Path,Resource.User]));
    Resource:=Unassigned;
  end;
end;


begin
 try
    CoInitialize(nil);
    try
      ListSharedResourcesInUse;
    finally
      CoUninitialize;
    end;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

How can I so date and time formatting in Java that respects the user's OS settings

6 votes

I am running my Java app on a Windows 7 machine where my regional settings are set up to format dates as YYYY-mm-dd and time as HH:mm:ss (e.g. "2011-06-20 07:50:28"). But when I use DateFormat.getDateTimeInstance().format to format my date I do not see that instead I get "20-Jun-2011 7:50:28 AM". What do I need to do to format dates in the way that my customers have their OS setup to display dates?

Here is what my code in question looks like:

File selGameLastTurnFile = selectedGame.getLastTurn ().getTurnFile ();
Date selGameModifiedDate = new Date (selGameLastTurnFile.lastModified());
if (selectedGame.isYourTurn ())  {
    gameInfo = Messages.getFormattedString ("WhoseTurnIsIt.Prompt.PlayTurn",  //$NON-NLS-1$
            FileHelper.getFileName (selGameLastTurnFile), 
            DateFormat.getDateTimeInstance().format(selGameModifiedDate));
}  else  {
    gameInfo = Messages.getFormattedString ("WhoseTurnIsIt.Prompt.SentTurn",  //$NON-NLS-1$
            selGameLastTurnFile.getName (), 
            DateFormat.getDateTimeInstance().format(selGameModifiedDate));
}

The Messages.getFormattedString calls are using MessageFormat to put the date into a sentence that will look like this:

Play the turn 'QB Nat vs Ian 008' (received 20-Jun-2011 7:50:28 AM)

However my OS settings are setup to format the date as I described above and I expected to see this:

Play the turn 'QB Nat vs Ian 008' (received 2011-06-20 07:50:28)

I searched here and other Java programming sites and could not find the answer but this seems like such an obvious thing to want to do that I feel like I am missing something obvious.

You can't do this in pure Java. There is no way Sun/Oracle could make this system independent.

A quick browse of the .NET libraries gives this page - to quote:

The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. If the CultureInfo.UseUserOverride property is set to true, the properties of the CultureInfo.DateTimeFormat object, the CultureInfo.NumberFormat object, and the CultureInfo.TextInfo object are also retrieved from the user settings.

I would suggest that you do this in a way that is system dependent upon Windows if you need this functionality (e.g. access the Windows registry as @laz suggested).

Windows File Systems?

6 votes

I have finished developing an archive format in managed C# that is way too flexible to be just an archive. I wish to use it as a file system.

It is well organized, very fast, and has both low-level and high-level API functions. It supports on-the-fly encryption and compression, password protection, Windows Explorer-specific file metadata (such as creation/modification/access time and attributes), 2^63 - 1 size HDDs, etc.

If it is possible to make Windows recognize and use my filesystem, I would learn Visual C++ just for the sake of implementing it. Are custom file systems even supported in Windows? (7 is a must, others are optional.) If they are, how do I make/implement them?

If I have to use some 3rd party library, it must be free. I don't want to use CallbackFileSystem because it's not free.


Maybe some readers are curious why I chose not to make my own driver. The reason is signing. Drivers, to work well on 64bit systems (at least my Windows 7) must be signed.
Now, I don't have the money to buy digital certificates from trusted sources... So no drivers for me... I use x64 Windows 7 on most of my machines so it would be an enormous waste to write the driver for x86...

Well, it is possible, once I have tried this approach. I've based on these samples: http://www.acc.umu.se/~bosse/

p.s. Also you don't need file system, you need a driver

How to correctly implement "As Administrator" or "Run As Administrator" in .NET application for selected operations?

6 votes

I'm looking for correct way to allow elevating privileges for selected operations.

Something similar many products offer.

For example if you have UAC turned on and you are using Total Commander (running with basic privileges) when browsing restricted folders you will get:

enter image description here

If you push As Administrator you will get common User Access Control dialog asking if you want to grant the process required permissions. Is it something similar possible in .NET application (even with Win32 support)?

  1. How should be such functionality correctly implemented?
  2. Do I need to run external process to get elevated privileges just for selected functionality?

I'm not looking for solution which will demand running the main process as administrator.

You're going to have to factor the target operation functionality into a separate component that will be run elevated. This can be either an executable that requires elevation or a COM component (which could presumably be a COM wrapper for a .NET component). Details are available at http://msdn.microsoft.com/en-us/library/bb756990.aspx, with the When to Add the Shield Icon to Your Application's User Interface being particularly pertinent.

Start external app with ShellExecuteEx and wait until it become initialized.

5 votes

I have an application which needs to run several other applications in chain. I am running them via ShellExecuteEx. The order of running each of the apps is very important cause they are dependant on each other. For example:

Start(App1);

If App1.IsRunning then
  Start(App2);
If App2.IsRunning then
  Start(App3);
.........................
If App(N-1).IsRunning then
  Start(App(N));

Everything works fine but there is a one possible problem: ShellExecuteEx starts the application, and return almost immediately. The problem might arise when for example App1 has started properly but has not finished some internal tasks, it is not yet ready to use. But ShellExecuteEx is already starting App2 which depends on the App1, and App2 won't start properly because it needs fully initialized App1.

Please note, that I don't want to wait for App(N-1) to finish and then start AppN.

I don't know if this is possible to solve with ShellExecuteEx, I've tried to use

SEInfo.fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_NOASYNC;

but without any effect.

After starting the AppN application I have a handle to the process. If I assume that the application is initialized after its main window is created (all of Apps have a window), can I somehow put a hook on its message queue and wait until WM_CREATE appears or maybe WM_ACTIVATE? In pressence of such message my Application would know that it can move on.

It's just an idea. However, I don't know how to put such hook. So if you could help me in this or you have a better idea that would be great:)

Also, the solution must work on Windows XP and above.

Thanks for your time.

Edited

@Cosmic Prund: I don't understand why did you delete your answer? I might try your idea...

You can probably achieve what you need by calling WaitForInputIdle() on each process handle returned by ShellExecute().

Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.

IOException insufficient disk space when accessing Citrix mounted drive

5 votes

I'm having a really strange problem. I'm trying to download some file and store. My code is relatively simple and straight forward (see below) and works fine on my local machine.

But it is intended to run on a Windows Terminal Server accessed through Citrix and a VPN. The file is to be saved to a mounted network drive. This mount is the local C:\ drive mounted through the Citrix VPN, so there might be some lag involved. Unfortunately I have no inside detail about how exactly the whole infrastructure is set up...

Now my problem is that the code below throws an IOException telling me there is no space left on the disk, when attempting to execute the write() call. The directory structure is created alright and a zero byte file is created, but content is never written.

There is more than a gigabyte space available on the drive, the Citrix client has been given "Full Access" permissions and copying/writing files on that mapped drive with Windows explorer or notepad works just fine. Only Java is giving me trouble here.

I also tried downloading to a temporary file first and then copying it to the destination, but since copying is basically the same stream operation as in my original code, there was no change in behavior. It still fails with a out of disk space exception.

I have no idea what else to try. Can you give any suggestions?

public boolean downloadToFile(URL url, File file){                                                                  
    boolean ok = false;                                                                                             

    try {                                                                                                           
        file.getParentFile().mkdirs();                                                                              

        BufferedInputStream  bis = new BufferedInputStream(url.openStream());                                       
        byte[]            buffer = new byte[2048];                                                                  
        FileOutputStream     fos = new FileOutputStream(file);                                                      
        BufferedOutputStream bos = new BufferedOutputStream( fos , buffer.length );                                 
        int size;                                                                                                   
        while ((size = bis.read(buffer, 0, buffer.length)) != -1) {                                                 
            bos.write(buffer, 0, size);                                                                             
        }                                                                                                           
        bos.flush();                                                                                                
        bos.close();                                                                                                
        bis.close();                                                                                                

        ok = true;                                                                                                  
    }catch(Exception e){                                                                                            
        e.printStackTrace();                                                                                        
    }                                                                                                               

    return ok;                                                                                                      
}

Have a try with commons-io. Esspecially the Util Classes FileUtils and IOUtils

After changing our code to use commons-io all file operations went much smouther. Even with mapped network drives.

C++ compiling on Windows and Linux: ifdef switch

5 votes

I want to run some c++ code on Linux and Windows. There are some pieces of code that I want to include only for one operating system and not the other. Is there a standard #ifdef that once can use?

Something like:

  #ifdef LINUX_KEY_WORD
    ... // linux code goes here.
  #elif WINDOWS_KEY_WORD
    ... // windows code goes here.
  #else 
    std::cerr << "OS not supported" << std::endl;
  #endif

The only correct answer is: https://sourceforge.net/apps/mediawiki/predef/index.php?title=Operating_Systems

5 votes

In that program I want to increment IP address. And I see output like that:

125.23.45.67
126.23.45.67
127.23.45.67 
128.23.45.67
129.23.45.67
130.23.45.67
131.23.45.67
132.23.45.67
133.23.45.67
134.23.45.67

But I want to see output like this:

124.23.45.67
124.23.45.68
124.23.45.68 
124.23.45.70
124.23.45.71
124.23.45.72
124.23.45.73
124.23.45.74
124.23.45.75
124.23.45.76

Here is program code:

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include "winsock2.h"
#pragma comment(lib,"wsock32.lib")

void main()
{
in_addr adr1;
in_addr adr2;
int i;

adr1.s_addr=inet_addr("124.23.45.67");
adr2.s_addr=inet_addr("as.34.34.56");
if (adr1.s_addr!=INADDR_NONE)
    cout << " adr1 correct" << endl;
else
    cout << " adr1 incorect " << endl;

if (adr2.s_addr!=INADDR_NONE)
    cout << " adr2 correct" << endl;
else
    cout << " adr2 incorect" << endl;

cout << inet_ntoa(adr1) << endl;
cout << inet_ntoa(adr2) << endl;

for (i=0;i<10;i++)
{
    adr1.s_addr ++;
    cout << inet_ntoa(adr1) << endl;
}
}

Big endian and little endian gets another one! Use htonl and ntohl to convert back and forth.

for (i=0;i<10;i++)
{
    adr1.s_addr  = htonl(ntohl(adr1.s_addr) + 1);

    cout << inet_ntoa(adr1) << endl;
}

create .exe from c# windows application

5 votes

I have a created a visual studio 2010 project that creates a windows form - it references numerous other dll's.

How can I wrap this up in to a single .exe file?

ILMerge is what you are looking for with the /t:exe option.

A sample call would look like this:

ilmerge.exe exefile.exe [dlls-to-internalize.dll ..] /out:exefile-out.exe /t:exe

A sample usage of using ILMerge to pack up multiple dlls into one and internalizing them can be found here: dotlesscss buildfile

More info on using ILMerge can be found on the ILMerge Website. You can also get it through NuGet via Chocolatey

It allows you to pack multiple .NET assemblies into one file by rewriting the references. You can also internalize your dependencies in case you are supplying a library to someone and don't want to cause dependency conflicts with libraries you are internally using.

Delete a file opened for exclusive access in the same process

5 votes

My windows program receives information from another program via directory/file interface. That is the other program drops files into a special directory. My program periodically scans the directory, finds the files, processes and then deletes them.

I use CreateFile() function to open such files. To ensure that the other program has finished writing to the file and closed it, I set the dwShareMode parameter to 0. If CreateFile fails with a sharing error I just skip the file until the next itteration.

The problem is that DeleteFile() fails with the ERROR_SHARING_VIOLATION error while the file is opened by my program.

I could close the file before deleteing it, but I would like to avoid the possibility of some other program opening the file just before I delete the file.

I use this code to open files

CreateFile(filePath,DELETE|FILE_READ_DATA,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL)

Is it possible to achieve what I want: open the file exclusively an then delete it, so that no other program can interfere between openning and deleteting the file.

Pass in FILE_SHARE_DELETE for dwShareMode. Note that this will still allow other applications (as well as your own) to call DeleteFile() while you are reading the file, but according to the documentation of DeleteFile() it won't be deleted until you call CloseHandle() to close your read handle.

The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED.

Other applications will not be able to read or write the file as long as you don't specify FILE_SHARE_READ or FILE_SHARE_WRITE respectively. Although with FILE_SHARE_DELETE then can move the file, but that would be it.

Windows Phone 7 Development guideline

3 votes

Guys I am new to Windows Phone Development in .Net Can any one guide me the correct path to start from scratch. Any links to understand the architecture?

You could start with Windows Phone 7 in 7 Minutes to get a quick overview, then move onto the Windows Phone 7 Jumpstart series on Channel9 for more depth on individual subject areas.

How to enclose every line in a file in double quotes with sed?

3 votes

This is what I tried: sed -i 's/^.*/"$&"/' myFile.txt

It put a $ at the beginning of every line.

here it is

sed 's/\(.*\)/"\1"/g'

Sending HTTP request in Perl

1 votes

How can I send a request like this in Perl on Windows?

GET /index.html HTTP/1.1
Host: www.example.org
Cookie: test=quest

You can do this using sockets:

use IO::Socket;
my $sock = new IO::Socket::INET (
                                 PeerAddr => 'www.example.org',
                                 PeerPort => '80',
                                 Proto => 'tcp',
                                );
die "Could not create socket: $!\n" unless $sock;
print $sock "GET /index.html HTTP/1.0\r\n";
print $sock "Host: www.example.org\r\n";
print $sock "Cookie: test=quest\r\n\r\n";
print while <$sock>;
close($sock);

but you might want to consider using LWP (libwww-perl) instead:

use LWP::UserAgent;
$ua = LWP::UserAgent->new;

$req = HTTP::Request->new(GET => 'http://www.example.org/index.html');
$req->header('Cookie' => 'test=quest');

# send request
$res = $ua->request($req);

# check the outcome
if ($res->is_success) { print $res->decoded_content }
else { print "Error: " . $res->status_line . "\n" }

You might try reading the LWP cookbook for an introduction to LWP.

Can xcopy transfer the files in a subdirectory, but not the directories themselves?

1 votes

Essentially, what I want to do is copy *.txt from the current directory as well as all the subdirectories. If I do xcopy /s /e C:\source C:\dest, it copies not just the files, but the directory structure as well. I need only the files to be copied, so C:\dest contains nothing but *.txt files. I checked the documentation for both xcopy and robocopy, but I couldn't find any parameters that allowed this functionality.

How about using a FOR loop? It'll execute lots of copy commands, but give it a try:

FOR /R C:\source %%f IN (*.txt) DO xcopy /s "%%f" "C:\dest"

Does concurrent READ/WRITE access to memory by itself cause errors/violations?

1 votes

If I have a multiprocessor setup and two threads that access the same memory (let's say the same actual byte or word, not only "the same area"), does this cause errors by itself?

What if two threads are not only reading, but also writing and combining reading and writing (say, thread 1 tries to read at the same time as thread 2 is trying to write, or if both are trying to write at the same time). Will this cause an error/BSOD/AV, or is the only problem that the behaviour is undefined? (that one of the threads will get wrong data, dependent on the actual timings)

1) No, threads are free to read/write everywhere in program application memory. (Ok, it is possible to protect some part of memory, like program code memory to protect it.)

2) Any CPU core has own cache and data is first copied and than modified in cache line after that is copied at appropriate (unpredictable) time back to RAM. There are special cpu instruction (like lock) which must be executed together with other instruction (like cmpxchg) to ensure atomic (interlocked) RAM read, write or modify, some instructions are atomic by default.

Remember: the atomic (interlocked) RAM access can be only 1, 2, 4 or 8 (and 16 under 64bit CPU) bytes long. For longer memory structures you must ensure corresponding locking (sinhronisation) mechanism like Critical Section to avoid uncontroled memory access by several threads.