Best windows questions in October 2010

Eclipse Android SDK slow Content Assist performance

14 votes

Im running eclipse on my windows 7 machine, 6bit with 6gb ram and core 2 duo. Im currently running Eclipse 3.6 and android 2.2 SDK Im running jdk 1.6

Im noticing that when coding and the context popups to list methods of a class, it hangs Eclipse for up to 15 seconds. This is very frustrating.

One thing to note, when Eclipse hangs, my processor is maxed out, and is being worked by a java process. So its doing something whatever it is. But frequently everytime I finish an object with a period and the context box pops up, its becoming too painful to work with.

I changed some settings in the Eclipse.ini file such as: -Xms1024m -Xmx1024m --launcher.XXMaxPermSize 512m

Is there anything else I should look at:

After a google search

I have been able to find the bug report from Eclipse.

In short:

Caution: There are known issues with the ADT plugin running with Eclipse 3.6. Please stay on 3.5 until further notice.

  • To fix it, you will have to use Eclipse 3.5 and put your project in a newly created workspace. (If you keep the workspace from Eclipse 3.6, the problem will occur even on Eclipse 3.5.)

Is rebasing DLLs (or providing an appropriate default load address) worth the trouble?

13 votes

Rebasing a DLL means to fix up the DLL such, that it's preferred load adress is the load address that the Loader is actually able to load the DLL at.

This can either be achieved by a tool such as Rebase.exe or by specifying default load addresses for all your (own) dlls so that they "fit" in your executable process.

The whole point of managing the DLL base addresses this way is to speed up application loads. (Or so I understand.)

The question is now: Is it worth the trouble?

I have the book Windows via C/C++ by Richter/Nazarre and they strongly recommend[a] making sure that the load addresses all match up so that the Loader doesn't have to rebase the loaded DLLs.

They fail to argue however, if this speeds up application load times to any significant amount.

Also, with ASLR it seems dubious that this has any value at all, since the load addresses will be randomized anyway.

Are there any hard facts on the pro/cons of this?

[a]: In my WvC++/5th ed it is in the sections titled Rebasing Modules and Binding Modules on pages 568ff. in Chapter 20, DLL Advanced Techniques.

I'd like to provide one answer myself, although the answers of Hans Passant and others are describing the tradeoffs already pretty well.

After recently fiddling with DLL base adresses in our application, I will here give my conclusion:

I think that, unless you can prove otherwise, providing DLLs with a non-default Base Address is an exercise in futility. This includes rebasing my DLLs.

  • For the DLLs I control, given the average application, each DLL will be loaded into memory only once anyway, so the load on the paging file should be minimal. (But see the comment of Michal Burr in another answer about Terminal Server environment.)

  • If DLLs are provided with a fixed base address (without rebasing) it will actually increase address space fragmentation, as sooner or later these addresses won't match anymore. In our app we had given all DLLs a fixed base address (for other legacy reasons, and not because of address space fragmentation) without using rebase.exe and this significantly increased address space fragmentation for us because you really can't get this right manually.

  • Rebasing (via rebase.exe) is not cheap. It is another step in the build process that has to be maintained and checked, so it has to have some benefit.

  • A large application will always have some DLLs loaded where the base address does not match, because of some hook DLLs (AV) and because you don't rebase 3rd party DLLs (or at least I wouldn't).

  • If you're using a RAM disk for the paging file, you might actually be better of if loaded DLLs get paged out :-)

So to sum up, I think that rebasing isn't worth the trouble except for special cases like the system DLLs.

Windows Visual Themes: Gallery of Parts and States?

13 votes

Microsoft Windows lets programmers draw GUI elements using the look and feel of the current theme using functions like DrawThemeBackground and DrawThemeText. The elements are specified by Class, Part, and State, as described at the Parts and States page at MSDN.

Unfortunately, the page is not very informative (at all!). So the question is: is there somewhere a reference of all these parts and states, preferably with images of the elements (in the default Windows Vista/7 theme)?

I have created a small Windows application, programmed with the table at Parts and States. This application lets the programmer browse and explore all parts and states, using the current OS theme.

Parts and States Explorer
(High-Res)

It can be downloaded at

The (Delphi, Win32 API) source, which is too long to be posted here (due to hundreds of constants) is found at

How do you get the exact path to "My Documents"?

8 votes

In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see http://stackoverflow.com/questions/2414828/get-path-to-my-documents

Is there a simple way to do this in Python?

You could use the ctypes module to get the "My Documents" directory:

import ctypes

dll = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(300)
dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False)
print(buf.value)

Source: http://bugs.python.org/issue1763#msg62242

Modern books on native C++ development

8 votes

I was going through the Hilo tutorial series Developing C++ Applications for Windows 7; seemed pretty interesting.

What modern books that go into details of developing C++ based applications for Windows 7? It should show how to take advantage of Windows 7 features and based on "modern" C++ (templates, Unicode, etc.). Not looking for old school Petzold or MFC type books (sorry). Also should feature native code development (i.e. no Qt-/wx-type 3rd party libraries). The 3rd party libraries seems to be at least a generation behind and don't seem to leverage the latests features (ex. Ribbon, Animation etc.).

I'd recommend that you ensure you're familiar with the theory in winprog.org/tutorial, then Ivor Horton's book (below), and then finally check out the WTL library.

The examples on the ribbon code in the Hilo articles use the windows API, which relies on COM objects to create the ribbon. ATL constructs like the CComPtr manage the lifetime of the ribbon objects and interfaces.

Because of this, I'd recommend that you ensure that you understand the basics of writing COM client code - e.g. You should understand CoCreateInstance, QueryInterface and smart pointers. ATL Internals (search on Amazon) is the essential reference on COM, but it is heavy going.

WTL wraps the detail of creating the ribbon and accessing it, but WTL was made for COM programmers looking for a windowing API, so it's not an easy API to begin with if you don't have experience of COM programming with ATL.

WTL supports the latest windows features, like ribbons etc. Don't expect any books on the subject though, there aren't any. M$ open sourced WTL some years ago, so the code is available to read, so you can figure out how everything works by reading the code. It's quite advanced though, you may want to look at it after you've had a look at the alternatives first.

Google uses WTL for the UI for Chrome.

I suspect you should Start with Ivor Horton's beginning Visual C++ 2010, it'll be a good all round introduction.

If you're looking for a great programming book for windows though, you can't do better than windows via c/c++ by Jeff richter - by far the best windows coding book I've ever bought.

If you are interested in WTL, then look at Michael dunn's series wtl for mfc programmers on code project.

Finally, there is no one book that hand hold the would be c++ GUI developer through all this, and that's a big gap in the market. I've often wondered why no one has picked up on this, given the popularity of c++

Automatic updating of C# programs

7 votes

I'm writing a suite of programs for client PCs --

  • a Windows Service
  • a user-space Windows Forms application

I need to be able to publish an updated version of these programs and have the client PCs automatically and transparently (with no user interaction) update themselves. This update will be done over an unreliable 3G connection (EvDO). The applications will be continuously running, so the update will have to gracefully shutdown the service / close the applications, and then spin them up again after the update.

Before I spend time rolling my own solution, are there any pre-existing solutions for something similar?

Note: ClickOnce doesn't work here because of the Windows Service as well as several other reasons. I also can't take advantage of BITS because I'm running against Windows Azure, which lacks the BITS IIS plugin.

Why not consider shadow copy.

Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously, such as ASP.NET sites such as ASP.NET sites

Make the programs very simple shells. Then have them watch (FileWatcher) for updates to folder where they were loaded from (and where updates are delivered). Then dynamically reload the AppDomain.

See here and here for more info.

You can use the properties of the AppDomainSetup class as follows to configure an application domain for shadow copying:

Enable shadow copying by setting the ShadowCopyFiles property to the string value "true". By default, this setting causes all assemblies in the application path to be copied to a download cache before they are loaded. This is the same cache maintained by the common language runtime to store files downloaded...

Windows Search - IFilter search term highlighting

7 votes

My development team are having a problem having snippets of text shown for search results in windows 7 for our own custom files (note we are NOT talking about the preview pane that uses the IPreviewHandler interface). An example of what I mean for .txt files is shown below:

Search example

The text snippet shown here with the highlighted result is not shown for our own files, only the name of the file is.

We have implemented an IFilter for our files and this is indexing the file contents correctly (searching returns the correct results). It just wont show the snippet and highlight the search term.

We suspected it might be something to do with the cwcStartSource, and cwcLenSource values for the STAT_CHUNK in IFilter, but setting these to different values has so far yielded nothing.

Has anyone else had a similar experience or have any thoughts?

Thanks in advance.

You need to generate a Preview Handler for your file type.

It can also render enhanced previews of items in a Preview Pane without launching the default application, if the application has registered a Preview Handler. This can provide functionality such as file type-specific navigation (such a browsing a presentation using next/previous controls, or seeking inside a media file).[29] Preview handlers can also allow certain kind of selections (such as highlighting a text snippet) to be performed from the preview pane itself.

source

There's a bunch of code examples floating around for PDFs and such.

Take a peek here: CodePlex:Windows Preview Handler Pack

Edit:

To clarify, the search results pane in Windows 7 is a preview handler host. It has two main pieces: the Content View and the Preview Pane.

Windows Explorer also includes a view mode called the Content view, which is the default view when viewing search results. The Content view shows the name, location, some of the metadata tags associated with the file, a thumbnail image of the file, and a snippet of the file. This view mode also uses hit highlighting to show where the query term appears in the files, which makes it easy to understand why that file was returned in the search results list.

source

You need a Preview Handler for any custom file types if you want enhanced functionality like viewing the file contents for your custom file type.

In Windows Vista and later, Windows Search is integrated into all Windows Explorer windows for instant access to search.

...

Preview handlers and thumbnail handlers enable users to preview documents in Windows Explorer without having to open the application that created them.

source

To verify that you have implemented your custom file type correctly, you can try the File Type Verifier from the Windows 7 SDK, which will test the following things assosicated with your custom file:

  • Preview Handlers
  • Thumbnail Handlers
  • Property Handlers
  • Verb Handlers
  • Filters (IFilter)
  • Kind Associations
  • Perceived Types
  • Important Properties

Using the Content View

you can take advantage of the Content view by using either of two different approaches. You can use an existing set of properties and layout pattern, or you can create your own combination. These two approaches are described in detail:

For a general overview on the Content View, see this article:

Content View By File Type or Kind

Windows WCF client with internet proxy server showing error The server committed a protocol violation. Section=ResponseStatusLine

6 votes

Our team trying to create a windows application(c#) to call a WCF service using internet proxy server

Showing exception "The server committed a protocol violation. Section=ResponseStatusLine" while calling WCF service

Please give suggestion to solve this problem/any other alternative solution

//Code for creating proxy
public static DevicesServiceClient CreateProxy()
{
  var proxy = new DevicesServiceClient("BasicHttpBinding_IDevicesService");

  BasicHttpBinding binding = new BasicHttpBinding();
  binding.Security.Mode = BasicHttpSecurityMode.None;
  binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
  binding.UseDefaultWebProxy = false;
  binding.ProxyAddress = new Uri(string.Format("http://{0}:{1}", "192.168.0.20","808"));
  proxy.Endpoint.Binding = binding;

  proxy.ClientCredentials.UserName.UserName = "Username";
  proxy.ClientCredentials.UserName.Password = "Password";
}

Server stack trace:

at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at DevicesService.IDevicesService.CheckNetworkConnection(String ipAddress)

My client side code in app.config alt text

My server side code in web.config alt text

Code to call wcf service from windows client application using proxy server

            {
              var proxy = new DevicesServiceClient("BasicHttpBinding_IDevicesService");
              BasicHttpBinding binding = new                                                 BasicHttpBinding("BasicHttpBinding_IDevicesService");
              var proxySettings = ApplicationDetails.CheckProxySettings();

                Uri domainAddress;
                var strtemp = new string[] { };
                //WebProxy webproxy = new WebProxy();
                var networkCredentials = new NetworkCredential();
                if (proxySettings.ProxyServerType == "http")
                {
                    domainAddress = new Uri(string.Format("http://{0}:{1}", proxySettings.ProxyServerAddress, proxySettings.ProxyServerPort));
                }
                else if (proxySettings.ProxyServerType == "https")
                {
                    domainAddress = new Uri(string.Format("https://{0}:{1}", proxySettings.ProxyServerAddress, proxySettings.ProxyServerPort));
                }
                else
                {
                    domainAddress = new Uri(string.Format("http://{0}:{1}", proxySettings.ProxyServerAddress, proxySettings.ProxyServerPort));
                }
                //
                WebProxy webproxy = new WebProxy(domainAddress.ToString(), true, strtemp);
                //

                //networkCredentials.Domain = domainAddress.ToString();
                if (proxySettings.ProxyAuthentication == "1")
                {
                    networkCredentials.UserName = proxySettings.Username;
                    networkCredentials.Password = proxySettings.Password;
                }
                webproxy.Credentials = networkCredentials;
                webproxy.BypassProxyOnLocal = false;
                WebRequest.DefaultWebProxy = webproxy;
                binding.UseDefaultWebProxy = true;
                proxy.Endpoint.Binding = binding;

            }

How can I force display detection in Windows?

6 votes

I often boot my Windows 7 PC with the attached KVM switch focused on another computer. When I switch to the booted PC, the display resolution is wrong (and the second attached monitor is not detected).

I can correct this by right-clicking the desktop, choosing Screen Resolution and clicking Detect. This makes Windows detect attached displays and adjust to the most optimal resolution.

I would like to write a small utility to do this automatically. Which Win32 API call or C# object should I use?

You can try:

  1. You can use Spy++ to search for the windows that are open and take a look at their properties and messages.
  2. Use process to start "rundll32.exe shell32.dll,Control_RunDLL desk.cpl" or experiment with calling it directly to see if you can get a window handle, check below link for ideas.
  3. Use the code "send button click to external app" and modify it to search for a window with caption "Screen Resolution" and send a BN_CLICK to the childwindow with the caption "Detect".
  4. Since the computer is already on you might want to fire it up automatically on logon, for that use the task scheduler.

How to distinguish different types of NaN float in Python

6 votes

I'm writing Python 2.6 code that interfaces with NI TestStand 4.2 via COM in Windows. I want to make a "NAN" value for a variable, but if I pass it float('nan'), TestStand displays it as IND.

Apparently TestStand distinguishes between floating point "IND" and "NAN" values. According to TestStand help:

  • IND corresponds to Signaling NaN in Visual C++, while
  • NAN corresponds to QuietNaN

That implies that Python's float('nan') is effectively a Signaling NaN when passed through COM. However, from what I've read about Signaling NaN, it seems that Signaling NaN is a bit "exotic" and Quiet NaN is your "regular" NaN. So I have my doubts that Python would be passing a Signaling NaN through COM. How could I find out if a Python float('nan') is passed through COM as a Signaling NaN or Quiet NaN, or maybe Indeterminate?

Is there any way to make a Signaling NaN versus QuietNaN or Indeterminate in Python, when interfacing with other languages? (Using ctypes perhaps?) I assume this would be a platform-specific solution, and I'd accept that in this case.

Update: In the TestStand sequence editor, I tried making two variables, one set to NAN and the other set to IND. Then I saved it to a file. Then I opened the file and read each variable using Python. In both cases, Python reads them as a nan float.

I dug a bit for you, and I think you might be able to use the struct module in combination with the information on at Kevin's Summary Charts. They explain the exact bit patterns used for the various kinds of IEEE 754 floating point numbers.

The only thing you probably will have to be careful for, if I read the topics on this IND-eterminate value, is that that value tends to trigger some kind of floating point interrupt when assigned directly in C code, causing it to be turned into a plain NaN. Which in turn meant those people were advised to do this kind of thing in ASM rather than C since C abstracted that stuff away.. Since it is not my field, and that I am not sure to what extent this kind of value would mess with Python, I figured I'd mention it so you can at least keep an eye for any such weird behaviour. (See the accepted answer for this question).

>>> import struct

>>> struct.pack(">d", float('nan')).encode("hex_codec")
'fff8000000000000'

>>> import scipy
>>> struct.pack(">d", scipy.nan).encode("hex_codec")
'7ff8000000000000'

Referring to Kevin's Summary Charts, that shows that float('nan') is actually technically the Indeterminate value, while scipy.nan is a Quiet NaN.

Let's try making a Signaling NaN, and then verify it.

>>> try_signaling_nan = struct.unpack(">d", "\x7f\xf0\x00\x00\x00\x00\x00\x01")[0]
>>> struct.pack(">d", try_signaling_nan).encode("hex_codec")
'7ff8000000000001'

No, the Signaling NaN gets converted to a Quiet NaN.

Now let's try making a Quiet NaN directly, and then verify it.

>>> try_quiet_nan = struct.unpack(">d", "\x7f\xf8\x00\x00\x00\x00\x00\x00")[0]
>>> struct.pack(">d", try_quiet_nan).encode("hex_codec")
'7ff8000000000000'

So that's how to make a proper Quiet NaN using struct.unpack()--at least, on a Windows platform.

How to programmatically create a shortcut using Win32

6 votes

I need to programmatically create a shortcut using C++.

How can I do this using Win32 SDK?

What API function can be used for this purpose?

Try Windows Shell Links. This page also contains a C++ example. Descriptive Snippet:

Using Shell Links

This section contains examples that demonstrate how to create and resolve shortcuts from within a Win32-based application. This section assumes you are familiar with Win32, C++, and OLE COM programming.

AWTPermission Exception while implementing Automatic update desktop application using java web start

6 votes

I am working in a Desktop application that provides Online Backup of data. In my application i am trying to implement automatic software update feature. For this i am using java web start. I have done the following process for using java web start.

1> created jar with all resources. 2> created jnlp file as :

      <?xml version="1.0" encoding="UTF-8"?>
     <jnlp spec="1.0+" 
               codebase="http://cmswebusa.com/kapil"
              href="PixelVaultJNLP.jnlp">
                <information>
                        <title>PixelVault</title>
                          <vendor>globussoft</vendor>
                           </information>
                        <resources>
                     <!-- Application Resources -->       
                          <jar href="PixelVault.jar" main="true" />

                     </resources>
                   <application-desc
                   name="PixelVault"
                   main-class="com.pixelvault.systemtray.SysTray">
                   </application-desc>
                   <update check="background"/>
                </jnlp>

where PixelVault.jar is jar of the application which is on http server location.

while i am trying to download my application using command prompt run option by typing : javaws , i am getting AWT Permission Exception as:

java.security.AccessControlException: access denied "java.awt.AWTPermission"

it says "java.awt.AWTPermissionException""accessSystemTray". I am not getting how can i allow my application to use system tray.

Please guide to make changes in jnlp file or making any other change in my application.

I thanks to your all valuable suggestions that will help me to solve this problem.

To get rid of that error:

  • The JNLP will need to declare all-permissions within a security element.
  • The code will need to be digitally signed.

Note that the JNLP file has elements out of the correct order. Use JaNeLA to check the validity of the file as well as other aspects of the launch.

What is the best practice making a job queue system in php?

5 votes

There are plenty of queue systems like beanstalkd, gearman, etc., but what if you want to run the daemon as a service on windows, and do the processing of the jobs, stored in a sql database, your self?

Mainly I'm asking for suggestions for the best method to process jobs, locking them, etc.

Try to use CRON + ScriptAlone

Mercurial color extension in Windows Powershell

5 votes

Is there a way to enable color support for Mercurial in Powershell on Windows 7? The ColorExtension page says to add

[color]
mode = win32

to your .hgrc file, but it doesn't seem to make a difference.

Running hg status shows several files that have not yet been added to the repository, and I believe they should have a pink color (based off other terminals I've seen). This is what's displayed instead:

←[0;35;1;4m? samplefile.php←[0m
←[0;35;1;4m? anotherfile.php←[0m
←[0;35;1;4m? derpderp.xml←[0m
←[0;35;1;4m? derp_model.php←[0m
←[0;35;1;4m? stillnocolor.php←[0m

You probably need to update to the latest mercurial (1.6.4). Version 1.5.4 in particular didn't do win32 color properly (and there have been quite a few color-related and win32-related bugs fixed in recent builds).

You also need to make sure you're not specifying ANSI color mode. You can force win32:

[color]
mode = win32

What does "Ex" stand for in Windows API function names?

5 votes

In windows APIs and various other libraries where I have seen multiple entry points to methods I have noticed the use of the Ex abbreviation in scenarios such as MyApiCall and MyApiCallEx.

My assumption is that this stands for Extension or Extra could someone please confirm?

Any history on why Ex was chosen rather then MyApiCall2 or similar would also be appreciated.

I was under the impression it stood for extended, as in a more detailed interface for that particular library.

For example, CreateFile with 4 parameters is the typical version and CreateFileEx with 17 is the version offering more control and finer detail over how the file is opened, what occurs if it doesn't exist, etc, and is thus extended.

Compiling static TagLib 1.6.3 libraries for Windows

4 votes

I am having a super hard time compiling and using TagLib 1.6.3 in my Qt project. I've tried everything I can think of. TagLib claims that it is supported through CMake but I'm not having any luck. Furthermore, I'm confused about what kinds of files I even need for my Qt libs!

I've built *.a files, *.lib, and *.dll. From what I understand thus far... I believe that since I'm working in Windows *.lib is what I want. No matter what I do, I always end up with "undefined references" to any TagLib functions I try to use when I try to compile my Qt project. I have tried MinGW32, MSYS, Visual Studio 2008, and even cross-compiling for Windows on Linux. All turning up nothing.

What makes even less sense to me is that if I compile the same TagLib source with Qt on Mac (g++ I think?) it works fine! Somewhere in my Windows compilation procedures I have to be going wrong. I have been smacking my face on my desk for probably about 30 (on and off) hours trying to figure this out.

Since Qt uses minGW must I compile TagLib with the same compiler?

If I compile *.lib's with Visual Studio are they not compatible?

Are *.a libraries even usable in Windows? (assuming minGW)

I'm still trying to get a handle on this C++ stuff, but after reading countless forum threads and other questions I'm still coming up short. Here is what I have been working with in CMake currently...

cmake -G "MinGW Makefiles" -DENABLE_STATIC=ON -DHAVE_ZLIB=0 -DWITH_MP4=1 -DMAKE_TAGLIB_LIB=1
cmake --build ./

This generates a single *.a file of ~2MB in size. The working library on Mac was ~3MB, and the *.lib from Visual Studio was ~4MB in Release mode. Please someone save me from this C++ cross platform command line madness because I am at my wit's end. I would probably even pay you to just compiling me some %!$#&ing libraries. Thanks.

Since Mac works for you, I'm just talking about Win32.

Ok, this are my Taglib.pro and an excerpt of my project.pro: https://gist.github.com/449ea81ce92f52399f41. Check them out. My Taglib may be a bit outdated, so take care, some files you may have could be missing there. Also take care of the relative paths. They are all relative to the .pro file.

I just ran cmake . inside the taglib directory. This should result in a config.h and a taglib_config.h

You definitly only need the libTaglib.a when you use QtCreator and mingw-gcc. *.lib are MSVC specific!