Best windows questions in January 2012

How to make my application be considered as a communication program in Windows

16 votes

I'm making a program that uses the Speech library and I'd like to get all other sounds muted or reduced when the lady is talking.

I've been looking for a way to mute other applications manually, but I've seen an option in Windows in the communication tab (inside the sound options) that mentions that window can manage this for me. Like in this picture:

enter image description here

So basically, what does it take for my application to be considered as a communication application (such as Skype)?

I believe the communication apps are implementing something related to the IAudioVolumeDuckNotification interface. The C++ example provided also references WM_VOLUME_DUCK and WM_VOLUME_UNDUCK windows messages which may be enough (but don't appear to be google-able or documented).

UPDATE

The .NET Core Audio API project on CodePlex appears to provide a .NET wrapper.

UPDATE

A sample C++ implementation of IAudioVolumeDuckNotification as well as an example of notifying the ducked state can be found in the MSDN DuckingMediaPlayer sample application. It actually works (I tried it). A combination of PInvoke'ing a couple methods and the .NET wrapper for the interface should be enough to get you on your way.

Can you detect a debugger attached to your process using Div by Zero

11 votes

Can you detect whether or not a debugger is attached to your native Windows process by using a high precision timer to time how long it takes to divide an integer by zero?

The rationale is that if no debugger is attached, you get a hard fault, which is handled by hardware and is very fast. If a debugger is attached, you instead get a soft fault, which is percolated up to the OS and eventually the debugger. This is relatively slow.

most debuggers used by reverse engineers come with methods to affect (remove) 99% of the marks left by debuggers, most of these debuggers provided exception filtering, meaning the speed difference would be undetectable.

its more productive to prevent the debugger attaching in the first place, but in the long run you'll never come out ahead unless you make the required effort investment unfeasable.

Is there any big advantages of having its C++ developping applications running on a 64 bit mode?

10 votes

I just noticed that by instance famous application like chrome didn't have any 64 versions at least under windows.

In my firm I write applications which run under 64 bits version of windows in 32 bits mode.

I am wondering if I could have some advantages/performance gain to build applications in 64 bits mode rather than in 32 bits

Thanks.

Edit :

Typically, in which kind of software, the increase of registers number will be benefict ?

64 (x86_64) bits is mainstream now. 2 big advantages here:

  • Available more memory without any tricks
  • More general-purpose and additional processor registers

But you have small disadvatage too:

  • More memory consumption (usually like 20-30% bigger than 32 bit)

I think Google Chrome runs in 32 bit mode in Windows because there are too much 32 bit plugins (like Flash). Also there is linux version for 64 bit.

Edit for additional question

Typically you will get benefits if your application uses math (64-bit integer arithmetic), coding/encoding/packing/unpacking, cryptography.

Also look at IBM 64-Bit Computing Decision-Maker’s Guide http://www.onitecservice.com.br/produtos/arquiv_pdf/nocona64bit_onitec_service.pdf

What types of applications will and won’t take advantage of the switch from 32-bit to 64-bit computing?

In order from greatest to least benefit, the types are:

  • I/O intensive — Any application that spends more time fetching data from devices than processing it: database back-end, e-commerce, CRM, ERP, SAP, SAS, various business-critical and vertical applications, and any other application that has large memory requirements. In general these applications should see significant performance improvements from 64-bit hardware, operating systems and device drivers, as well as the elimination of memory overlays and other performance inhibitors.
  • Compute-intensive — High Performance Computing (HPC) and scientific/technical computing, including life sciences, geophysical research; high-end graphics rendering; streaming video, and any other application that spends more of its time processing data than retrieving it.
  • Gateway/security infrastructure — SSL servers, directory services, Internet caching and database front-ends. These applications may obtain benefit from the switch. You should contact the individual software vendors to find out their plans for exploiting 64-bit features.
  • Standard infrastructure — This class generally will see little benefit from 64-bit computing. Applications include file and print servers, low-volume/noncritical business applications, and legacy applications that are unlikely to be rewritten for 64 bits.

Migrating bad system into our current system with tons of data

10 votes

I inherited of a system when my company bought another company. This system is a mix of LAMP and .NET.

  1. 1 Windows server running asp.net that controls third-party validation used only for apis and webservice - (let's call it WIN)
  2. 8 LAMP servers (web, reports, cron, repositories etc...) - (let's call it NEW)

Our current environment:

14 LAMP servers (web, mail, repositories, etc...) - (let's call it CURRENT)

The good news is the NEW code is pretty straigt foward. A few millions lines of code (which most are apis, third party) and I can convert it to the CURRENT system. The NEW and CURRENT use both CentOs which will make the transision easy, except the Windows server that I have no idea what to do now.

Now the bad news. The NEW system database schema is not good at all. It is not normalized and the queries are slow (database queries and the code too). My first idea is to redesign them to a more normalized structure that matches the CURRENT code but I don't work. The tables from the NEW system are gigantic. The NEW system has 7 databases, over 10000 tables, the smallest tables have over 100k rows and some tables have over 500 millions rows. One of the database has most of the tables with over 25 millions rows each.

Is it safe to migrate or should I keep both running? If I should migrate I want to know what will the safest solution for me in order to migrate the Windows and NEW system into my CURRENT system?

First of all, moving the WIN + NEW systems into the CURRENT system will take time. so you have to make sure when you start migrating/converting everything, you know where you going. Migrating might not be an easy task and you can run into issues you never thought after you started the process.

Your idea of migrating the NEW system has pros and cons and you need to make sure it goes smoothly in order to get a good and reliable product at the end.

Pros:

  • only one system to maintain: you don't want to maintain 3 systems;
  • one code/database environement: PHP vs ASP.NET and MSSQL vs MySQL;
  • centralized code/database;
  • one coding (code and database) standard;
  • save/sell equiments (you will migrate the code to your 14 servers, maybe you don't need the other 9 (WIN+NEW), so you can sell or keep them for the next projects)

cons:

  • higher risk (crash, incompatibility, unknown feature you need to understand etc..);
  • cheaper than migrating or re-designing everything
  • risk of failure is lower than migration (since you already know both system works)
  • planning, control, implementation, quality assurance: very bad if one of these fail;
  • expensive: migrating can be expensive in time and money;

This is a big database, changing/optimizing this will take a significant investment in labor hours. This is not something you can easily do in few hours. This can take weeks maybe months in order to successfully migrate data to the CURRENT system without errors. If you can, you can start by migrating common or similarities from both database schema, like clients or products. This way, you import data that the CURRENT system can run without errors and also your code will recognise. The users of your CURRENT system can immediately start managing these items/records without issue. As of new or records your CURRENT system does not recognise, you can simply re-design these tables and migrate them to the CURRENT system (then update your current code).

As of code migration, if the code from the NEW system is good enough and match your standard you can keep it. This will save time in development, just make sure you update the queries and servers connections. On the other hand, if it's like spaghetti code, you will have to understand what the code do. This can also take a significant investment in labor hours. I can recommend here to standardize this one and organize your code the same way you organize it on the CURRENT one. You can centralize your code in one common folder using a common file and folder structure. You can put all your common libraries, 3rd parties etc.. there so when you call the CURRENT and the NEW code, it loads the same PHP class. This will make your ease your transitions from the NEW to CURRENT system. This way, you know all your required files at in the same place and very easy to maintain. Specially if your code requires required files that requires files. If you code is all around your servers, you can create an NFS if you like this idea.

Now, what I can suggest is to start with a Parallel Adoption . This way you make sure all systems are working properly and are healthy. Then slowly migrate data/code to the CURRENT system until everything is completed. This won't be easy and you have to identify which part of the NEW + WIN systems you have to migrate first. My recommendation will be to migrate the WIN system. Because this is independent of the CURRENT and NEW systems, as long you display the same output you should be fine. Search for open source or similar validations in PHP or if you can't find any, build them. This way this WIN system can easily be migrated to your current organization structure and coding standards. Performing tests and quality assurances will be easy and you can be completed very quickly.

Once this WIN is migrated, you need to identify what you need to transfer first to the CURRENT system. For example, if the NEW and CURRENT system has "clients", gather all the information from the NEW system and move them to the CURRENT system using a script (manually or scripted). Then, you can migrate clients elements like products, billing statement or any other records that are related to these clients). Repeat these steps until all the data are migrated. This way, you don't have to re-design any tables or change any codes from the NEW system, everything is saved on the CURRENT system and everything works correctly.

I won't recommend the big bang adoption for this case .

easyphp .htaccess rules

8 votes

i need to rewrite rules in my installation of easyphp on windows 7.

i need to make sure the rules are loaded correctly and i don't have to create tons of rules. also, when i copy the .htaccess to my server (which is linux) i want to make sure its working properly.

i have no experience with this and here's what i found diging the internet:

RewriteRule (.*) index.php?s=$1

now, if i have basic page like 'contact-us' its ok but if i have sub pages it does not. how can i create sub folders?

thank you

Here's what you need to do:

RewriteEngine On
RewriteBase /
RewriteRule ^([a-z0-9_\-]+)/?$ index.php?main=$1 [NC,L] 
RewriteRule ^([a-z0-9_\-]+)/([a-z0-9_\-]+)/?$ index.php?main=$1&sub=$2 [NC,L]

This will allow you to have pages like:

http://www.domain.com/mainpage/ or
http://www.domain.com/mainpage or
http://www.domain.com/mainpage/subpage/ or
http://www.domain.com/mainpage/subpage

/? Means the slash is optional

[NC] This makes the test case-insensitive - differences between 'A-Z' and 'a-z' are ignored, both in the expanded TestString and the CondPattern. This flag is effective only for comparisons between TestString and CondPattern. It has no effect on filesystem and subrequest checks.

[L] The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed.

All the information about flags and rules: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

Windows: Separating input from 2 Mice

8 votes

Initially, I want to use 2 mice for an application with separate pointers and interaction between the 2 mice(e.g. selecting a rectangular area). Later I might want to have a second pointer available generally in windows. I thought this might be possible by simulating a stylus pen with the second mouse.

My main question though is: Am I right to use a system hook as opposed to RawInput, DirectInput or InputX?

If using a system hook I presume I need to use WH_MOUSE_LL rather than WH_MOUSE even if the application is running on one thread? My preferred language is C#, but again I presume that using DLL imports means I can do anything that's possible in C++ or C.

Using system hook is the way to go in WINDOWS. You can use C# with InteropServices and the apropriate COM+ objects, altough creating a C++ class and wrapping it would be a better approach. I've done it myself with keyboard events. I could LOG all keyboards typing... And yes, you have to use WH_MOUSE_LL.

Process being killed by a third party application (Sprint Smartview)

8 votes

Recently two users of our software from the same company started experiencing random closures (no error messages, crash dialogs, quit dialogs etc). We were able to isolate what the two systems had in common down to a particular piece of software (a mobile broadband device manager). When this software is running our software randomly closes within a ~2 minute time frame. If we exit the broadband manager our software runs indefinitely without issue.

I can think of no reason why there would be any interaction between our software and theirs. The network is not accessed by our software and the broadband modem isn't even plugged in in any case.

We provided a work around for the customer (run our software as Administrator or exit the mobile broadband manager before running our software) but we want to resolve the problem so they don't need to worry about doing either of these things.

I attached a remote debugger to our software but I wasn't quite sure where to look to investigate exactly how our software is dying. Debugging just ends with exit code 0 when our process is ended.

My question is, how can I investigate how/why a Win32 process is being killed and what can I do to prevent it from happening?

Edit: I opened the broadband manager and the DLLs it uses in a hex editor and there references to an executable with the exact same name as ours. So I guess that's the link. Renaming our executable fixes the problem for our users but not, unfortunately, the stupidity of the Sprint SmartView.

Edit: To help the rare other developer this hits: If your executable is named phoenix.exe and your end users are running Sprint SmartView, that's why your program is randomly dying. Renaming your executable will resolve this (or spend several months of your life trying to figure out who to notify at Sprint to get this truly resolved). The file that mentions phoenix.exe specifically is WwanCoreSdk.dll.

If your app is 32 bit, try to check out WinAPIOverride32. It will show you all syscalls done by program, so If you are able to time killing your program correctly in log from mentioned manager, it should make it easier to explain why it is happening.

Is DLL always have the same Base Address?

7 votes

I'm studying about windows and DLL stuffs and I have some question about it. :)

I made a simple program that loads my own DLL. This DLL has just simple functions, plus, minus.

This is the question : if I load some DLL (for example, text.dll), is this DLL always have the same Base Address? or it changes when I restart it? and can I hold the DLL's Base Address?

When I test it, it always have same Base Address, but I think when I need to do about this, I have to make some exception about the DLL Base Address.

The operating system will load your DLL in whatever base address it pleases. You can specify a "preferred" base address, but if that does not happen to be available, (for whatever reason, which may well be completely out of your control,) your DLL will be relocated by the operating system to whatever address the operating system sees fit.

Is there a way to instantly check whether a directory is in use?

7 votes

I want to move a directory and all of its subdirectories with Directory.Move.

Before I do that, however, I want to check whether any of the files and subfiles in the directory and its subdirectories are being used by other processes.

Then, before the move, I'd like to lock the directory to other processes, so I can be sure that Directory.Move won't throw any exceptions.

What is the best way to accomplish that?

I would like to avoid checking for the usage of the individual files file by file, because the fact that the file isn't used when the software checks for it does not mean that it won't be used when the movement process starts.

There is no way to lock the folder (+ sub folders) so you'll always end up with a race condition and there is no guarantee that there will be no exception.

There is always the possibility that something changes in between the check and the move so things can go wrong.

Just try to move the folder and retry later if not succeeding.

See also: Delphi: Check whether file is in use (this is a similar question, just ignore the Delphi part)

Selecting specific records in a SQL Server database from C#

6 votes

I am currently trying to grab some rows from a SQL Server database using C# that are of the following criteria:

  • From the RamResults database
  • in the Results table
  • where the Date column is equal to the current date

I have the following so far:

// Open the same connection with the same connection string.
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString))
{
   con.Open();
   // Read specific values in the table.
   using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM RamResults WHERE Date == @Form1.date", con))
   {
      SqlCeDataReader reader = com.ExecuteReader();
      while (reader.Read())
      {
         int resultsoutput = reader.GetInt32(0);
         MessageBox.Show(resultsoutput.ToString());
      }
   }
}

Using SELECT Result FROM RamResults WHERE Date == Form1.date throws an error:

There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = = ]

Although if I take out the WHERE statement e.g.

SELECT Result FROM RamResults

it works perfectly

Description

2 things

  1. Use = instead of == because this is the right equals operator in T-SQL. Your Query should be like this

    SELECT Result FROM RamResults WHERE Date = @Date

  2. You forget to pass in the parameter.

Sample

// Open the same connection with the same connection string.
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString))
{
    con.Open();
    // Read specific values in the table.
    using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM RamResults WHERE Date = @Date", con))
    {
        com.Parameters.AddWithValue("@Date", Form1.date);
        SqlCeDataReader reader = com.ExecuteReader();
        while (reader.Read())
        {
            int resultsoutput = reader.GetInt32(0);
            MessageBox.Show(resultsoutput.ToString());
        }
    }
}

Minimize Size of Textblock

6 votes

Currently, if I have a <TextBlock> element with font size 200, the entire element takes up much more space than needed.

Wasted Space

The blue outline (from Blend) shows the space the element takes up, when easily half of that is needed. Is there anyway I can eliminate that space such that my elements are not spaced out so much? I've tried margin, padding etc but most methods don't seem to work.

Ideal

Ideally I would want the <textblock> to take up only the amount of space indicated by the red box

Edit:

With Lower Cased Letters

In response to stijn7, some space is indeed reserved for other letters (g,p,q etc). However there still is a lot of space at the top (1 is the highest character in Segoe UI). If clipping the textblock is not possible, is there anyway I can resize it such that there is no wasted space?

The problem here is that the TextBlock has the height incorporates the ascender and descender on order to render characters with a range of heights. The character you have chosen happens to span the font x-height, but not beyond. In order to achieve the effect you are after you will need a slightly lower level text rendering API, I would suggest trying the FormattedText class:

Provides low-level control for drawing text in Windows Presentation Foundation (WPF) applications.

This class has a MaxTextHeight property. I have not tried this, but there is a chance it will give you the information you require.

Java to EXE good or bad idea?

6 votes

I have been wondering for a long time about converting Java projects to EXE.

The advantages relies in the faster deployment on Windows where the user simply double clicks the EXE and the application is launched where is with Java, he has to run certain commands.

But EXE is really not what the Java was intended for which is portability.

So what do you think, Java to EXE good or bad idea?

I found some interesting article here.

Update

Wow, so may contradicting views so far. I would like you guys to add the pros and cons of the JAVA to EXE.

Since my expertise is with Java Web Start, which is for launching desktop apps. with a GUI, please consider my advice to be targeted mostly at those types of apps.


Other people have commented on the OS specific nature of an EXE. I always have to wonder why people choose Java to develop Windows specific desktop apps., since the Visual Studio software for Windows would probably make both GUI development (no x-plat Java layouts to bend your head around) and deployment (just guessing it can produce an EXE) easier.

OTOH only you can say what is the best development tool/language for this use-case.


As to the potential disadvantages of creating an EXE, I note at the JavaFAQ on EXEs.

There are a number of good reasons not to package your application in an executable. Daniel Sjöblom notes:

  • It will probably not be any faster. Modern virtual machines don't interpret bytecodes, they actually employ a JIT compiler to produce native, compiled code. Check Sun's site for further information on JIT compilers.
  • Static compilation increases the size of your application multifold, since all of the libraries you are using need to be linked into the application.
  • You lose 'free' upgrades to your program. Anytime your user downloads a new faster virtual machine, your app gets a speed boost. If you are using an exe, you will not get this benefit.

Jon A. Cruz details some of the extra steps in the development process required to create an exe. He points out that developers making native exe's need to:

  • Validate the latest versions of the compilation product from the vendor. If critical bugs are found, it can't be used to build a shipping product until those are addressed. Work that needs to be done each time a revision comes out from the vendor.
  • Submit the software through a QA cycle. Once engineering thinks things are done, they need to be verified. So every shipping version and update of a product needs to go through complete testing cycles.
  • Further, since native compilation is per target platform, the QA cycle needs to be done completely for each target platform, which multiplies effort required.
  • Shelf space. Maybe not a big deal nowadays, but could be.
  • Then one needs to get all customers to upgrade to the proper version. Either have free updates (in which case the business needs to absorb the cost of producing updates) or alternatively needs to handle clients not all updating.

Jon notes futher: When you ship standard Java bytecodes, VM problems are the responsibility of the platform or VM vendor. However, when you ship compiled binaries, they become your responsibility (even if they're actually bugs in the vendor's compilation product).

...


Of course, my first choice for deploying Java rich client apps. is using Java Web Start. Putting some of the benefits/features of web-start in point form:

JWS provides many appealing features including, but not limited to:

  • splash screens
  • desktop integration
  • file associations
  • automatic update (including lazy downloads and programmatic control of updates)
  • partitioning of natives & other resource downloads by platform, architecture or Java version,
  • configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.)
  • easy management of common resources using extensions ..

I decided to highlight auto-update since with the gradual shift from apps. delivered on disk to apps. delivered over a network, auto-update is becoming more common. JWS still provides the best update experience (very configurable, mostly transparent to the user) I've seen.

And of course, JWS works on OS' for desktop PCs for which Java is available.


Update

..does Java web apps require internet connection?

(Note that name is 'Java Web Start'.)

Sure it does. At least for the initial installation. Update checks can be specified to continue to launch the previously installed version of the app. if the user is not currently connected.

But then, (in my estimation) there are more machines (such as Netbooks) with no CD/DVD drive, than there are without internet connections. If you want to sell to the larger market, look to the network to deliver the app.

C++ Memory Barriers for Atomics

6 votes

I'm a newbie when it comes to this. Could anyone provide a simplified explanation of the differences between the following memory barriers?

  • The windows MemoryBarrier();
  • The fence _mm_mfence();
  • The inline assembly asm volatile ("" : : : "memory");
  • The intrinsic _ReadWriteBarrier();

If there isn't a simple explanation some links to good articles or books would probably help me get it straight. Until now I was fine with just using objects written by others wrapping these calls but I'd like to have a better understanding than my current thinking which is basically along the lines of there is more than one way to implement memory barriers under the covers.

Both MemoryBarrier (MSVC) and _mm_mfence (supported by several compilers) provide a hardware memory fence, which prevents the processor from moving reads and writes across the fence.

The main difference is that MemoryBarrier has platform specific implementations for x86, x64 and IA64, where as _mm_mfence specifically uses the mfence SSE2 instruction, so it's not always available.

On x86 and x64 MemoryBarrier is implemented with a xchg and lock or respectively, and I have seen some claims that this is faster than mfence. However my own benchmarks show the opposite, so apparently it's very much dependent on processor model.

Another difference is that mfence can also be used for ordering non-temporal stores/loads (movntq etc).

GCC also has __sync_synchronize which generates a hardware fence.

asm volatile ("" : : : "memory") in GCC and _ReadWriteBarrier in MSVC only provide a compiler level memory fence, preventing the compiler from reordering memory accesses. That means the processor is still free to do reordering.

Compiler fences are generally used in combination with operations that have some kind of implicit hardware fence. E.g. on x86/x64 all stores have a release fence and loads have an acquire fence, so you just need a compiler fence when implementing load-acquire and store-release.

How do I check if my Delphi console app is redirected to a file or pipe?

6 votes

I have a console app that must disable or enable some operations when output is redirected (externally) to a file or pipe (myapp.exe > Foo.bar)

How I can check if my Delphi console app is redirected to a file or pipe?

you can use the GetStdHandle and GetFileType functions.

first you retrieve the console output handle using the GetStdHandle function and then you can check the type of the handle with the GetFileType function.

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows,
  SysUtils;


function ConsoleRedirected: Boolean;
var
  FileType : DWORD;
begin
  FileType:= GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
  Result  := (FileType=FILE_TYPE_PIPE) or (FileType=FILE_TYPE_DISK);
end;


begin
  try
    if ConsoleRedirected then
      Writeln('Hello From File')
    else
      Writeln('Hello Console');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.