Windows: Network connections timing out too quickly on temporary connectivity loss

If you have a rather unstable network where you tend to loose connectivity for a short time frequently, you might notice that established connections (e.g. ssh connections using putty) will get lost. You can then immediately reconnect but it’s still a pain.

The issue is not really with the software loosing the connection (e.g. putty) but rather with the Windows network configuration. A single application cannot set the network settings for the whole application or a specific session to prevent this problem. To solve this problem, you will need to tweak a few Windows network settings.

Basically tweaking these settings means increasing the TCP timeout in Windows. This can be done in the registry.

The relevant TCP/IP settings are:

  • KeepAliveTime
  • KeepAliveInterval
  • TcpMaxDataRetransmissions

These parameters are all located at the following registry location: \HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Tcpip\Parameters.

On Windows versions which are not based on Windows NT (i.e. Windows 95, Windows 98 and Windows ME), these parameters are located under: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP.

KeepAliveTime

The KeepAliveTime parameters controls how long the TCP driver waits until the a keep-alive packet is sent over an idle TCP connection. A TCP keep-alive packet is simply an ACK packet sent over the connection with the sequence number set to one less than the current sequence number for the connection. When the other end receives this packet, it will send an ACK as a response with the current sequence number. These communication is used to make sure that the remote host at the other end of the connection is still available and make sure the connection is kept open.

Since TCP keep-alives are disabled by default, the application opening the connection needs to specifically enable them.

The value is the number of milliseconds of inactivity before a keep-alive packet is sent. The default is 7,200,000 milliseconds (ms) i.e. 2 hours.

Note that the default of 2 hours might be to high in some cases. Having a high KeepAliveTime brings two problems:

  1. it may cause a delay before the machine at one end of the connection detects that the remote machine is no longer available
  2. many firewalls drop the session if no traffic occurs for a given amount of time

In the first case, if your application can handle reconnect scenario, it will take a very long time until it notices the connection is dead and it would have been able to handle it properly if it failed fast.

In the second case, it’s the opposite, the connection is articially closed by the firewall inbetween.

If you encounter one of these cases on a regular basis, you should consider reducing the KeepAliveTime from 2 hours to 10 or 15 minutes (i.e. 600,000 or 900,000 milliseconds).

But also keep in mind that lowering the value for the KeepAliveTime:

  • increases network activity on idle connections
  • can cause active working connections to terminate because of latency issues.

Setting it to less than 10 seconds, is not a good idea except if you have a network environment with with a very low latency.

KeepAliveInterval

If the remote host at the other end of the connection does not respond to the keep-alive packet, it is repeated. This is where the KeepAliveInterval is used. This parameter determines how often this retry mechanism will be triggered. This is basically the wait time before another keep-alive packet is sent. If at some point in time the remote hosts responds to the keep-alive packet, the next keep-alive packet will be again sent based on the KeepAliveTime parameter (assuming the connection is still idle).

The value is the number of milliseconds before a keep-alive packet is resent. The default is 1,000 milliseconds (ms) i.e. 1 second. If the network connectivity losses sometimes last a few minutes, it’d make sense increasing this parameter to 60,000 milliseconds i.e. 1 minute.

TcpMaxDataRetransmissions

Of course this retry process cannot go on for ever. If the connection is not only temporarily lost but lost for good, then the connection needs to be closed. This is where the parameter TcpMaxDataRetransmissions is used. This parameter defines the number of keep-alive retries to be performed before the connection is aborted.

The default value is to perform 5 TCP keep-alive retransmits. If you experience network instability and lose connections too often, you should consider increasing this value to 10 or 15.

Note that starting with Windows Vista, this parameter doesn’t exist anymore and is replaced by a hard-coded value of 10. After 10 unanswered retransmissions, the connection will be aborted. But you can still control the time frame which a connection could survive a temporary connectivity loss by adapting the KeepAliveInterval parameter.

Also note that this parameter only exists in Windows NT based versions of Windows. On old systems running Windows 95, Windows 98 or Windows ME, the corresponding parameter is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\MaxDataRetries.

Summary

Tweaking the parameters above, one can configure the Windows TCP driver so that connections can survive small connectivity losses. Remember that after changing these settings, you’ll need to reboot the machine (it’s Windows after all…).

If you cannot modify TcpMaxDataRetransmissions because you have a newer version of Windows, you can still reach the same results by increasing KeepAliveInterval instead.

Also note that issues with lost connections in unstable networks seems to especially affect Windows Vista and later. So if you move from Windows XP to let’s say Windows 7 and you experience such issues, you should first add the KeepAliveTime¬† and KeepAliveInterval parameters to the registry, reboot, check whether it’s better and possibly increase the value of KeepAliveInterval if required.

All parameters above should be stored in the registry as DWORD (32bit value).

Visual Studio 2012: mspdb110.dll is missing when executing editbin.exe

I was having some issues using an OCX in an old application I had recompiled using Visual Studio 2012. One thing I found is that it might be related to a compatibility issue with Data Execution Prevention (DEP). Since I couldn’t recompile the OCX and didn’t have direct access to the linker settings, I went for using editbin.exe to apply a /NXCOMPAT:NO. But when I ran the following:

C:\Users\benohead>"c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\editbin.exe" /NXCOMPAT:NO myfile.exe

I got a system error from link.exe saying:

The program can’t start because mspdb110.dll is missing from your computer. Try reinstalling the program to fix this problem.

The cause for this error is that I executed the command in the wrong DOS prompt. Not the one where I had executed vcvars32.bat. So I just executed vcvars32.bat:

"c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\vcvars32.bat"

And gave it another try. Now no error message was displayed.

Visual C++: module unsafe for SAFESEH image, unable to generate SAFESEH image

Using Visual Studio 2012, I was building from the command line a software which was built until now using an older version (guess it was Visual Studio 2005). There were of course many things I had to change in the code itself (so much for portability…). And of course I had to upgrade the project in the solutions to VS2012 (using the devenv /upgrade command).

After converting the projects and modifying the code, I got the following error messages on a few projects:

error LNK2026: module unsafe for SAFESEH image.

fatal error LNK1281: Unable to generate SAFESEH image.

This means that the linker was started with the option meaning /SAFESEH “image has safe exception handlers” (also note that we only got this because we’re still building 32bit targets). The error occurs because some input modules were not compatible with the safe exception handlers feature of the linker. In our case it was some third party lib files for which I did not have the source code. These lib files are not be compatible with safe exception handlers is because they were created with an older version of the Visual C++ compiler.

But this is easy to fix. You just need to tell the linker not to produce an image with a table of safe exceptions handlers even if it thinks that all modules are compatible with the safe exception handling feature.

If you work in the Visual Studio Editor, you can right-click on your DLL project, go to Properties > Linker > Advanced and set “image has safe exception handlers” to No.

If like me you’re working from the command line, you can edit the .vcxproj file by opening it and searching for the <link> tags. Add the following to each <link> tag (there will be one per target e.g. one for debug and one for release):

<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>

It doesn’t matter where exactly you add it, it just needs to be between <link> and </link>.

If you call the linker yourself, you can also add /SAFESEH:NO to the command line.

After making this change, you can build your project again and the error will be gone.

OleViewer: STG_E_FILENOTFOUND and IDataObject interface viewer only supports IID_IDataObject

I had some problems loading a type library (TLB file) when building a Visual C++ project, so I wanted to have a look at the TLB file using the OleViewer. So I started the OleViewer as Administrator from C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\x64. When opening the TLB file I got the following error message:

LoadTypeLib(my tlb file) failed.
STG_R_FILENOTFOUND ($80030002)

The issue here was that I started the 64bit version of the OleViewer. With the 32bit version (present directly in C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin), this error was gone, so it could actually load the file but I got another error message:

IDataObject interface viewer only supports IID_IDataObject

Solving this was easy but kind of confusing. I went to the View menu, unchecked “Expert Mode” then opened the TLB file. And the error message was gone. After that I checked it again but could still open the TLB file. Eveb after closing the OleViewer and opening it again, I was able to load the TLB file.

I’m still not 100% sure what happened here… Another thing I did after removing the Expert Mode and before reopening my TLB file was to open a few object classes in the tree on the left. At least of them was the Microsoft Web Browser (under Controls). So if unchecking the Expert Mode alone doesn’t help, you could try this.

It looks like the error message I got above means that iviewers.dll in-process server was not properly registered. The OleViewer uses iviewers.dll to parse the type library. Somehow after the things I’ve done above, the registration was fine. Of course if it still doesn’t work for you, you can try registering it yourself using regsvr32 iviewers.dll.

Somewhere inbetween I’ve also try using but also had a problem with the same TLB file (also it worked for others). After the problem was solved with OleViewer, OleWoo was also able to open the TLB file. So I guess OleWoo parses the TLB the same way OleViewer does.

And actually after that Visual Studio 2012 wasn’t complaining anymore about the TLB file. Before that I got the following error message on the line where I import the TLB file:

error C1084: Cannot read type library file: ‘my tlb file’: Error loading type library/DLL.

So it looks like Visual Studio had the same issue with iviewers.dll as OleViewer and OleWoo but unfortunately only said it couldn’t load the type library instead of giving me a more precise error message…

Even if I don’t really get what happend here, I’m glad it’s solved ūüôā

Generating new certificate in XAMPP for Windows

Since I had an older version of XAMPP for Windows installed, it was still using openssl 1.0.1e in which the heartbleed vulnerability was not yet fixed. So I installed the latest version and since the certificate in there was from 2013 I was not really sure whether it was safe or not so I decided to generate a new one. Here’s a short description how to do it.

Open a DOS prompt and navigate to the apache\bin directory in your XAMPP for Windows installation:

cd /D D:\Software\xampp\apache\bin

We’ll first define a couple of environment variables so that we do not need to provide them every time as parameter to openssl:

set OPENSSL_CONF=D:\Software\xampp\apache\conf\openssl.cnf
set RANDFILE=C:\Temp\.rnd

Now we’re ready to start. Generating a certificate involves 3 steps:

  1. Generating an RSA private key
  2. Generating a certificate sign request
  3. Generating a certificate

Note that since we are generating a self sign certificate, we can combine these 3 steps into 1 as described here.

Once the certificate is generated you can install it as shown here.

Generating an RSA private key

You can generate the key by executing the following:

D:\Software\xampp\apache\bin>openssl genrsa -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
............++++++
...........++++++
e is 65537 (0x10001)

This will create a file called server.key with a content similar to:

—–BEGIN RSA PRIVATE KEY—–
MIICXwIBAAKBgQDkQxjDD36nH9lfch9m+CS3TzIHYqrkEd0XGg+ki4E0QyP+Me9W
mJvPfEh8Gn9Iw18o4je9UN8gVWszm6GqBT0z3ryC10ZwQvi+hB+fRWNX3dC+cam8
EwA+NE3tVRGCHcjo73IFMixIsKfJ/1Rdj8lV0IX5PBform1hI6ao8jXH4QIDAQAB
AoGBAImgEtv5CaoGP++WRWy2DJ0heM6PJO4h/yWgpvHU0vAJ0ze+L8oMdVUiYCnD
aB8c/NEPo//XNNCv79TL7ystwXnTLlLR05n90Ta3SBFex1Pp48Rn7vLReZmiTrMc
6P7hqlKYCny+5zcx9gNzYJ73OsRoJGy0wdRRy6lRB87iiRDhAkEA9wz9Vc9vpDie
xsMVMfeEC7hOzUCHd3bX0Ye8BYBTVslQAZmrBQZv3Z59W+MSM3aJT6vPYtsMwIWH
zdvI7z/4nQJBAOyH3yuROrzrqFIe5YlyKLxeLx28T0IdYS1zwt064zfgMyi3eWG+
CAibg81cAMqlDhMzden8/CTYZYEQIhD6/xUCQQCA0tcvbdGrcpLo1kUxHv5OFjeR
M/rvwprbecoDnFzYvnTnwLe7ERY4HDMGPSv6he8oClFEHTFTGs4r/FWU3GjJAkEA
oYpeQawLOLGdoJBXZdqgtZ2BgkZ0vwu/rcIs6NjqC+RELF+6N6YIaJCFoMBgDgZS
KYzw0CCmuCdOk6nICl7RzQJBANeQEfc+FT3r3mdVLnyXraAjPxo+RFDZvWqQJiJY
MJUFZ9SPiaiNzVZhMijmAR3klnOz1XZlRhC/z9fzDJVopGk=
—–END RSA PRIVATE KEY—–

Note you can find instructions saying to use the -des3 option. Do not this will cause your key to contain a pass phrase:

D:\Software\xampp\apache\bin>openssl genrsa -des3 -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
......++++++
.........................++++++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

Which will lead to such an error loading the key from XAMPP:

[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02577: Init: SSLPassPhraseDialog builtin is not supported on Win32 (key file D:/Software/xampp/apache/conf/ssl.key/server.key)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02311: Fatal error initialising mod_ssl, exiting. See D:/Software/xampp/apache/logs/error.log for more information
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02564: Failed to configure encrypted (?) private key localhost:8443:0, check D:/Software/xampp/apache/conf/ssl.key/server.key
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
AH00016: Configuration Failed

Generating a certificate sign request

You can then use the key to generate a certificate sign request using the following command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -key server.key -out server.csr
Loading 'screen' into random state - done
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:mypassword
An optional company name []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field). Also choose a different challenge password than mypassword.

This will create a file called server.csr containing something like:

—–BEGIN CERTIFICATE REQUEST—–
MIIBgjCB7AIBADAoMRIwEAYDVQQKDAlsb2NhbGhvc3QxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA5EMYww9+px/ZX3IfZvgk
t08yB2Kq5BHdFxoPpIuBNEMj/jHvVpibz3xIfBp/SMNfKOI3vVDfIFVrM5uhqgU9
M968gtdGcEL4voQfn0VjV93QvnGpvBMAPjRN7VURgh3I6O9yBTIsSLCnyf9UXY/J
VdCF+TwX6K5tYSOmqPI1x+ECAwEAAaAbMBkGCSqGSIb3DQEJBzEMDApteXBhc3N3
b3JkMA0GCSqGSIb3DQEBBQUAA4GBAKdmonasFGzPFiY8pgQThwIUvHo7her3SiPL
VkZqGbLT4NjoB2Yp7zi2qZ59qGLFHNFsfeBfnJZMFP2pGBbO1dW/2H1R0ogX95Ci
jIhwZFZD6xwpPkIWpau2dS1i5Q7kyBeGp/krfNHr/kSAUvaavq1R581yL2b5/ClY
9ARH/He/
—–END CERTIFICATE REQUEST—–

You probably do not need the -nodes option since it only applies when using openssl to generate a key using the req command. But I’d rather use it here although I do not need it than forget it when generating both the key and the certificate in a single step using the req command.

Generating a certificate

Now we need to generate the certificate using the following:

D:\Software\xampp\apache\bin>openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Loading 'screen' into random state - done
Signature ok
subject=/O=localhost/CN=localhost
Getting Private key

If you get such an error:

unable to write 'random state'

it means you forgot to set the second environment variables as shown in the beginning of this post.

Generating a self-signed certificate in one step

When generating a self-signed certificate you can combine this all to one step using only the req command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -x509 -keyout server.key -out server.crt
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
............++++++
............++++++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field).

Installing the certificate

Now we just need to copy the key and the certificate to the apache installation:

D:\Software\xampp\apache\bin>copy /Y server.crt d:\Software\xampp\apache\conf\ssl.crt
        1 file(s) copied.

D:\Software\xampp\apache\bin>copy /Y server.key d:\Software\xampp\apache\conf\ssl.key
        1 file(s) copied.

After a restart of the Apache web server, your new certificate will be available.

Java: Could not find main class. Program will exit.

In order to make a runnable (executable) JAR file which can be started by double clicking the JAR file, you just need to add a manifest file to the JAR file which references the main class to be executed. To do this, just create a file called manifest.txt and add the following contents:

Main-Class: com.benohead.app.Main

Replace com.benohead.app.Main by the fully qualified name of your main class (the class containing the static main method to be executed). Make sure that there is a newline after the fully qualified name since it could make problems later on if it is missing. You can then make the JAR file using your class files and the manifest file:

jar -cvfm MyJarFile.jar manifest.txt com/benohead/app/*.class

A manifest.mf file created and added instead of the manifest.txt file. When you double click on the create JAR file, the main class will be automatically executed. Now, you may be able to run the JAR file like this on some machine but it might also fail on other machines, with the following error message:

Could not find main class. Program will exit.

You may also notice that the following works on some machines where the double click doesn’t work:

java -jar MyJarFile.jar

The problem is probably that you compiled your code with a new version of the JDK (e.g. JDK 6) but an old version of JRE (e.g. JRE 5) is used on double click. You may wonder why it is a problem when you double click but not when you run it from the command line. The answer is that you might be using different versions on the JRE when double clicking and when call java from the command line. To check this, you can execute the following two commands. To check the version used on double click:

ftype | find "jarfile"

It will return something like this:

jarfile=”C:\Program Files\Java\jre1.5.0_14\bin\javaw.exe” -jar “%1” %*

This shows that JRE 5 is used on double click. If you compiled your code using JDK 6 it will be a problem. To check the version used from the command line:

java -version

It will return something like this:

java version “1.6.0_20” Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) Client VM (build 16.3-b01, mixed mode)

In this case it is using JRE 6 which is the reason why it worked from the command line. So how do you fix it ? There are two ways to do it:

  1. Reinstall the new JRE. It should then fix the file association in the OS
  2. Fix the file association manually

For the second one, you can execute the following in a command prompt:

ftype jarfile="C:\Program Files\Java\jre6\bin\javaw.exe" -jar "%1" %*

Of course you need to find the path to the new JRE and use it instead of the path above. Depending on your operating you can use the command below to find it:

where javaw

(where is some kind of Windows equivalent to the which command under Linux and is available from Windows 2003 Server onwards, so including Windows Vista, Windows 7 and Windows 8) Note that to check whether the problem is really a java version issue, you can also start the JAR file from the command line using the same version as used in the double click scenario e.g.:

"C:\Program Files\Java\jre1.5.0_14\bin\javaw.exe" -jar MyJarFile.jar

If you have a version issue, you should get an exception along the lines:

“Exception in thread “main” java.lang.UnsupportedClassVersionError: com/benohead/app/Main (Unsupported major.minor version 50.0)”).

Here’s for your reference a mapping of java versions to major.minor versions:

Java Version Major Version
Java 1.1          45.0
Java 1.2          46.0
Java 1.3          47.0
Java 1.4          48.0
Java 5             49.0
java 6             50.0
java 7             51.0
java 8             52.0

This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value 0x0501 or higher is recommended

While building a product originally written with Visual Studio 6 on my machine (Windows 7 and Visual Studio 2010), I got for a few sub-projects the following error message:

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include\atlcore.h(35): fatal error C1189: #error : This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value 0x0501 or higher is recommended.

Using findstr, I could see that _WIN32_WINNT was not set in those projects. So the solution was easy. I just had to add the following to the beginning of stdafx.h in those projects:

#ifndef WINVER				// Allow use of features specific to Windows XP or later.
#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
#endif

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif

After that the projects could build successfully.

Windows: Port 80 is already in use

I wanted to start the Apache web server using XAMPP and got an error message that port 80 was already in use. My first thought was that IIS might be running on port 80. But on this machine I hadn’t installed IIS. So I executed the following to check which process might be using it:

c:\> netstat -nabo
...
  TCP    [::]:80                [::]:0                 LISTENING       4
 Can not obtain ownership information
...

So it’s process ID 4. I also used TCPView from Sysinternals and also saw that the process ID 4 was using this port. The process name was shown as “System”. In Task Manager, the image name for process ID 4 was System and the description was “NT Kernel & System”. It didn’t help me much either.

So I went through the list of running services and saw a service called “Web Deployment Agent Service” with the description “Remote agent service for the Microsoft Web Deploy 3.5.”. After stopping this service I was able to start Apache on port 80 successfully.

You can check the services by pressing Windows-R to get to the Run prompt, typing services.msc and pressing enter.

If this doesn’t help, I’d recommend searching for a service called “World Wide Web Publishing Service” and stop it. And of course, if IIS is running, you should stop it.

Windows: log first login and last logout (and sleep) time every day

Since I have to keep track of when I started working and when I stopped working (because of some legal regulations), I was using an app on my iphone to check in and out of work. But often I either was in a hurry and forgot it or forgot my phone at home or had no battery left… So I’ve decided to try and automate this.

I’d need to cover the following:

  1. Log an entry on the first login on the machine every day.
  2. Log an entry on the last logout on the machine every day.
  3. account for the fact that I usually do not logout but send the computer into sleep mode
  4. and in the morning I then wake from sleep

First we’ll create two batch files logging the times we’ve started and ended work.

Create a login.bat file somewhere with the following contents:

type %USERPROFILE%\loginlogoff.log | findstr /R "login.*%date%"
if errorlevel 1 echo login at %time% %date% >> %USERPROFILE%\loginlogoff.log

This basically checks whether the file %USERPROFILE%\loginlogoff.log already contains an entry with login and today’s date. If yes, there is nothing to do since it’s not the first login event today. If not, we write an entry in the file with the current time and date.

Then create a logout.bat file with the following contents:

type %USERPROFILE%\loginlogoff.log | findstr /v /R "logout.*%date%" > %USERPROFILE%\loginlogoff.tmp
type %USERPROFILE%\loginlogoff.tmp > %USERPROFILE%\loginlogoff.log
echo logout at %time% %date% >> %USERPROFILE%\loginlogoff.log

It first creates a copy of the file excluding all logout events which occured today, copies the file and adds a logout event. This basically will replace an logout event which occured on the same day with the latest one.

Now we need to have these scripts executed automatically. My computer at work is a Windows machine, so the obvious choice was to go some scheduled tasks. You can create a scheduled task on logon. But there’s no option for logoff. One option for the logoff issue could be to use the ONEVENT option of schtasks.exe. But it’s kind of a pain (never really worked reliably).

Here comes gpedit.msc. I can define there scripts which are to be run on logon and logoff:
gpedit logon logoff

To start it, click on the Start button, select Run… and type gpedit.msc (then press OK). You then have to navigate to Local Computer policy / User Configuration / Windows Settings / Scripts (Logon/Logoff).

There you will see two entries:

  • Logon
  • Logoff

Right click on Logon, select Properties, Then click Add, Browse and select the login.bat file created above. Press OK twice.
The do the same thing for Logoff and select the logout.bat file created above.

This takes care of the scenarios 1 and 2 above. Now we need to handle the sleep and wake triggers. There will be handled by scheduled tasks created using schtasks.exe:

SCHTASKS /Create /TN LogWake /TR %USERPROFILE%\login.bat /SC ONEVENT /EC System /MO *[System/EventID=1]
SCHTASKS /Create /TN LogSleep /TR %USERPROFILE%\logoff.bat /SC ONEVENT /EC System /MO *[System/EventID=42]

Here you’ll have to replace %USERPROFILE%\login.bat and %USERPROFILE%\logout.bat by the paths to the two batch files created above.

The event ID 1 will be triggered a few seconds after a wake from sleep. It might be trigger many times during the day but we do not care since we’ll only log the first one.
The event ID 42 will be triggered when the computer goes into sleep mode.

That’s it. You’ll then get a file at %USERPROFILE%\loginlogoff.log containing something like this:

login at  8:31:01,33 08.11.2012 
logout at  18:37:41,49 08.11.2012

Windows: Change first day of the week

On my machine, since I’m using the US regional settings, the week starts on Sunday:

Windows clock first day of week sunday
Windows clock first day of week sunday

It’s usual for the US and Australia but in Europe everybody considers the week to start on Monday, not Sunday. So you’d expect this:

Windows clock first day of week monday
Windows clock first day of week monday

In Windows 7 you can change it in the regional settings:

Regional settings first day of week sunday
Regional settings first day of week sunday

You can change there the first day of the week to Monday:

Regional settings first day of week monday
Regional settings first day of week monday

Now on Windows XP, you do not have this drop down list for the first day of the week. It’s automatically set based on the regional settings. But you can change it in the registry (HKEY_CURRENT_USER\Control Panel\International -> iFirstDayOfWeek):

Registry first day of week sunday
Registry first day of week sunday

There change 6 (Sunday) to 0 (Monday):

Registry first day of week monday
Registry first day of week monday

This also works on Windows 7 (but it’s easier to change it in the regional settings).