Best windows questions in September 2010

D support for COM

10 votes

Wikipedia says the following: "On Microsoft Windows, D can access COM (Component Object Model) code."

What kind of support for COM is present in D? Does it make life easier than using COM in C++. I've found this link on the D page but it doesn't tell me too much.

Juno has a new version .5.1 that has lots of great ways of connecting to Word, Excel, FrameMaker, Trados, etc. So, it is possible and easy. Something like this:

scope word = new DispatchObject("Word.Application");
scope wDocs = word.get("Documents");

char[] dd  = dir ~ r"\";

char[][] docs = GetFilesFromDir(dir ~ r"\", "*." ~ fromType, true);
if (docs.length == 0)
{
  info.text = "Did not find any " ~ std.string.toupper(fromType) ~
    " files in the directory... \n\nExiting...";
  return;
}
foreach(char[] d; docs)
{
  scope wDoc = wDocs.call("Open", d);//"Normal", false, 0);
  char[] txt = std.path.getName(d);  // original file ie. test if it was test.doc
  txt ~= ".doc";
  if (std.file.exists(txt))
    std.file.remove(txt);

  wDoc.call("SaveAs",
      txt,      // FileName
      0,        // FileFormat wdFormatDOC = 0
      false,    // LockComments
      "",       // Password
      false,    // AddToRecentFiles
      "",       // WritePassword
      false,    // ReadOnlyRecommended
      false,    // EmbedTrueTypeFonts
      false,    // SaveNativePictureFormat
      false,    // SaveFormsData
      false,    // SaveAsAOCELetter
      65001,    // Encoding 65001 is UTF8
      false,    // InsertLineBreaks
      false,    // AllowSubstitutions
      0         // LineEnding Const wdCRLF = 0
      );
  wDoc.call("Close");
}
word.call("Quit");

I'd like to run a command over ssh from a windows box running using c#

9 votes

Note that this has to be on a windows box as I am using c# to access information about windows

(I need information from both a windows box and a linux box, plus I think that making a program/script that runs without gui and accesses windows from a linux box without user intervention would be more difficult, if this is not true please tell me, I would love to do get this running on *nix with only the part that access windows info running on windows).

There is a nice c# api to get this information from windows, on *nix its simple enough to run a command and parse the output to my needs.

There doesn't seem to much decent advice about using ssh from c# out there, sharpSSH and Granados seem to have not been updated for years, are they decent? should I be possible worried about security issues?

(the info I'm retrieving isn't sensitive but if the ssh implementation might have unpatched security flaws(if they haven't been updated for years) I'm worried about someone stealing my credentials.

Are there any other decent c# ssh libraries. If the command output is simple should I just run plink/putty(is it difficult to run a windows cmd shell for plink, and capture output(and is there a way to do it without the shell popping up)?

P.S. while the commercial library seems nice I prefer something free (as in cost and free in source if possible).

It is quite easy to call plink without the shell popping up.

The trick to not show a window is to set ProcessStartInfo.CreateNoWindow = true.
Add some error handling to this and you're done.

--- PlinkWrapper.cs ---

using System.Collections.Generic;
using System.Diagnostics;

namespace Stackoverflow_Test
{
    public class PlinkWrapper
    {
        private string host { get; set; }
        /// <summary>
        /// Initializes the <see cref="PlinkWrapper"/>
        /// Assumes the key for the user is already loaded in PageAnt.
        /// </summary>
        /// <param name="host">The host, on format user@host</param>
        public PlinkWrapper(string host)
        {
            this.host = host;
        }

        /// <summary>
        /// Runs a command and returns the output lines in a List&lt;string&gt;.
        /// </summary>
        /// <param name="command">The command to execute</param>
        /// <returns></returns>
        public List<string> RunCommand(string command)
        {
            List<string> result = new List<string>();

            ProcessStartInfo startInfo = new ProcessStartInfo("plink.exe");
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.CreateNoWindow = true;
            startInfo.Arguments = host + " " + command;
            using (Process p = new Process())
            {
                p.StartInfo = startInfo;
                p.Start();
                while (p.StandardOutput.Peek() >= 0)
                {
                    result.Add(p.StandardOutput.ReadLine());
                }
                p.WaitForExit();
            }

            return result;
        }
    }
}

--- END PlinkWrapper.cs ---

Call it like

PlinkWrapper plink = new PlinkWrapper("albin@mazarin");
foreach (var str in plink.RunCommand("pwd"))
    Console.WriteLine("> " + str);

and the output will be like

> /home/albin

The nice thing with plink is that it is well proven and integrates well with pageant.

When would I use PowerShell over traditional applications?

8 votes

I've been hearing a lot about PowerShell recently, and was wondering whether there's any reason to use PowerShell instead of (for example) a console application or Windows service using WMI behind the scenes.

What are the benefits and advantages of PowerShell? What is it for?

PowerShell can do lots of things that a .NET console application can do, but it's still a scripting language. But it's a heck of a lot better than the batch file language or VBScript/JScript. It's strengths include being able to use UNIX-like pipes and filters but with objects instead of dumb text. It can also create CLR and COM objects and invoke their properties and methods.

However, if you are writing anything complex, you'd be better served writing a compiled program so you have the benefits of finding errors at compile time and having a better IDE. Also, if you want to run a PowerShell script, PowerShell must be installed on the computer where you're running it.

How to disable .NET Framework exception handling and use my own instead?

8 votes

I've developed a .NET 4 software and I'm ready to send it to beta users. If an unhandled exception is thrown in the software, I would like to catch it, log it and send the logs to me. I've already implemented this functionality and it seems to be running fine when I run it in debug mode with Visual Studio. However, when I've built a release version of the software and installed it, Microsoft .NET Framework starts to catch exceptions before my code. I get a popup with an error message: "Unhandled exception has occurred in a component in your application. If you click Continue, the application will ignore this error and attempt to continue."

To test the crashing, I created a crash down button which throws an exception. This crash down logs itself and the exception handler logs all received unhandled exceptions. When I look at the log of the release version, I can only see the log message from crash down but not from the exception handler.

I've attached my own exception handler with this code:

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Is there some way to disable the exception catching of .NET Framework or is there a better way to attach my own exception handler?

UPDATE: I'm using WPF. I'll look into the DispatcherUnhandledException and let you know if it solves the problem.

UPDATE #2: Unfortunately adding handler to Application.Current.DispatcherUnhandledException didn't solve the problem. Apparently this debugging popup is created by JIT (Just-In-Time) debugger which is included with Visual Studio. I'll have to test the software with a "civilian" Windows and see if the exceptions are catched there too.

UPDATE #3: For some reason the Release built with Visual Studio works but the Release built with MSBuild scripts and Dotfuscator does not.

I finally solved the problem. The problem was not caused by listening to wrong exceptions but due to missing a DLL from the released version.

After adding listeners for DispatchedUnhandledException and ThreadException events I no longer got the strange Microsoft .NET Framework popup which allowed the user to continue running the software after exception. However my own exception handling was still broken at this point.

Because the software was already crashing down at the moment when the exception handler was supposed to kick in, I had a catch (Exception) around the exception handler. After removing this catch I finally got the correct error message with release version and added the missing DLLs.

The lesson I learned (again) is: do not use empty catch (Exception) block. It is evil.

What is dll hijacking?

7 votes

Simple question: What is dll hijacking?

I read a lot about which applications are vulnerable, but not a lot of depth as to why.

Answers appreciated.

The basics are simple. Windows has a search path for DLLs, much the same way it has a $PATH for finding executables. If you can figure out what DLLs an app requests without an absolute path (triggering this search process), you can then place your hostile DLL somewhere higher up the search path so it'll be found before the real version is, and Windows will happilly feed your attack code to the application.

So, let's pretend your system's DLL search path looks something like this:

a) .     <--current working directory of the application, highest priority, first check
b) \windows
c) \windows\system32
d) \windows\syswow64   <-- lowest priority, last check

and some application Foo.exe requests "bar.dll", which happens to live in the syswow64 (d) subdir. This gives you the opportunity to place your malicious version in a), b), or c) and it will be loaded into the app automatically whenever the app requests bar.dll. And now your foo is well and trully bar'd.

As stated before, even an absolute full path can't protect against this, if you can replace the DLL with your own version.

And of course, this isn't really limited to Windows either. Any OS which allows for dynamic linking of external libraries is theoretically vulnerable to this.

choice between win32 APIs and .NET framework

7 votes

I have to develop an application for windows that will enable controlling the mouse through web cam by recognizing hand gestures. I will be using vc++ 2008 for development. But I am confused whether to go with .NET framework or core win32 APIs. Performance is very important for my application. As per the book "Beginning Visual C++ 2008" by Ivor Horton, there is a small performance penalty associated in using .NET framework. I wanted to know on what all factors the penalty depends upon and will it be feasible to use .NET framework for my application.

If you are acquainted with Win32 API, then go Win32 API. It is the natural choice in your case since most of your source code will be video capturing, image processing, algorithms, and interfaces to mouse in Windows. When you are interested in performance, be closer to the hardware avoiding thick layers like .NET.

I believe that .NET is for complex business applications not for real-time applications or device drivers.

redhat cygwin vs cygwin ? any diffrence ?

7 votes

i just notice that there is a redhat cygwin at http://www.redhat.com/services/custom/cygwin/ , is there any difference ?

1 . redhat builds cygwin so its faster.

(5:15:46 AM) adamramadhan: version ?
(5:15:53 AM) adamramadhan: 1.8 and 1.7.7 ?
(5:15:59 AM) adamramadhan: why can that happen ?
(5:16:17 AM) snoopy left the room ("Saliendo").
(5:16:30 AM) r15 [~anuj@122.177.232.122] entered the room.
(5:17:00 AM) MartinCo: adamramadhan, because RHAT builds cygwin, the released version are behind the lates build

From the Wikipedia page I've changed the links for this context,

Cygwin was originally developed by Cygnus Solutions, which was later acquired by Red Hat. It is free and open source software, released under the GNU General Public License version 2. Today it is maintained by employees of Red Hat, NetApp and many other volunteers.

Red Hat Cygwin is at release 1.8 at the moment (cygwin.dll),
This is when the regular Cygwin is at release 1.7.7 (cygwin1.dll).

The Cygwin library, utilities, and numerous applications are available for free download under the terms of the GPL. Red Hat offers developer and user support for this software, as well as license contracts for the Cygwin library and its utilities. The Red Hat Cygwin official installation utility can be used for both initial installation and automated updating.

From the Cygwin FAQ,
Can I bundle Cygwin with my product for free?

Only if you comply with Cygwin's license very carefully. If you choose to distribute cygwin1.dll, you must be willing to distribute the exact source code used to build that copy of cygwin1.dll as per the terms of the GPL. If you ship applications that link with cygwin1.dll, you must either provide those applications' source code under a GPL-compatible license, or purchase a cygwin license from Red Hat.

Can I build a Cygwin program that does not require cygwin1.dll at runtime?

No. If your program uses the Cygwin API, then your executable cannot run without cygwin1.dll. In particular, it is not possible to statically link with a Cygwin library to obtain an independent, self-contained executable.

If this is an issue because you intend to distribute your Cygwin application, then you had better read and understand http://cygwin.com/licensing.html, which explains the licensing options. Unless you purchase a special commercial license from Red Hat, then your Cygwin application must be Open Source.

Keeping memory usage within available amount

7 votes

I'm writing a program (a theorem prover as it happens) whose memory requirement is "as much as possible, please"; that is, it can always do better by using more memory, for practical purposes without upper bound, so what it actually needs to do is use just as much memory as is available, no more and no less. I can figure out how to prioritize data to delete the lowest value stuff when memory runs short; the problem I'm trying to solve is how to tell when this is happening.

Ideally I would like a system call that returns "how much memory is left" or "are we out of memory yet?"; as far as I can tell, no such thing exists?

Of course, malloc can signal out of memory by returning 0 and new can call a handler; these aren't ideal signals, but would be better than nothing. A problem, however, is that I really want to know when physical memory is running out, so I can avoid going deep into swap and thereby making everything grind to a halt; I don't suppose there's any way to ask "are we having to swap yet?" or tell the operating system "don't swap on my account, just fail my requests if it comes to that"?

Another approach would be to find out how much RAM is in the machine, and monitor how much memory the program is using at the moment. As far as I know, there is generally no way to tell the former? I also get the impression there is no reliable way to tell the latter except by wrapping malloc/free with a bookkeeper function (which is then more problematic in C++).

Are there any approaches I'm missing?

The ideal would be a portable solution, but I suspect that's not going to happen. Failing that, a solution that works on Windows and another one that works on Unix would be nice. Failing that, I could get by with a solution that works on Windows and another one that works on Linux.

I think the most useful and flexible way to use all the memory available is to let the user specify how much memory to use.

Let the user write it in a config file or through an interface, then create an allocator (or something similar) that will not provide more than this memory.

That way, you don't have to find statistics about the current computer as this will allways be biased by the fact that the OS could also run other programs as well. Don't even talk about the way the OS will manage cache, the differences between 32 and 64 bit making adress space limit your allocations etc.

In the end, human intelligence (assuming the user know about the context of use) is cheaper to implement when provided by the user.

In Python, how can I get the correctly-cased path for a file?

6 votes

Windows uses case-insensitive file names, so I can open the same file with any of these:

r"c:\windows\system32\desktop.ini"
r"C:\WINdows\System32\DESKTOP.ini"
r"C:\WiNdOwS\SyStEm32\DeSkToP.iNi"

etc. Given any of these paths, how can I find the true case? I want them all to produce:

r"C:\Windows\System32\desktop.ini"

os.path.normcase doesn't do it, it simply lowercases everything. os.path.abspath returns an absolute path, but each of these is already absolute, and so it doesn't change any of them. os.path.realpath is only used to resolve symbolic links, which Windows doesn't have, so it's the same as abspath on Windows.

Is there a straightforward way to do this?

This python-win32 thread has an answer that doesn't require third-party packages or walking the tree:

import ctypes

def getLongPathName(path):
    buf = ctypes.create_unicode_buffer(260)
    GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
    rv = GetLongPathName(path, buf, 260)
    if rv == 0 or rv > 260:
        return path
    else:
        return buf.value

Limiting Starts or Run Time for Evaluation Software in C# and Windows

6 votes

Are there any good ways to limit the number of times an application can start or limit how long it can be used for under Windows 7 and using C#?

As far as I can see the registry can be easily edited, there are programs to report any kind of file access, virtual machines can be used to change the system time back to when the application was installed, etc. For every idea I can think of there is a (usually) trivial work around.

I want to avoid the need for an internet connection. I.e. I don't want the software to request permission to start each time using hashes, etc.

I see third party license systems that have this kind of functionality. If implementing these approaches is always lame, how do they do it so it isn't lame?

Note: I don't want to "crack" a third party system. I already have my own license system that I want to improve. Generic, plausible ideas are all that I am looking for.

thanks, Andy

This is not the answer to your question, just something to think about. No matter how complicated your protection system is, it will be easily cracked. Even with online checking, it can, and will be cracked if someone wants it really bad.

That said, the people who would want to crack your program AREN'T your customers, they never were, and they never will be. If you make your protection system ubreakable (and there are no unbreakable protection system), those people will just not use your program and will find some other which they can crack.

On the other hand, people who are your customers won't try to crack it and will buy the original. Ask yourself - do you really want to waste your time, energy and money for somebody that is not your customer, and probably slow down the system for somebody who actualy is?

That said, I believe you should make some kind of protection system, but go with that which is fast and easy to implement and least obtrusive.

Resources for Windows Aero Glass and Compositing (DWM)

6 votes

I am looking for good resources for learning to use the Win32/GDI APIs or whatever supercedes it to draw and paint directly using the Win32 API to a glass form.

While I am using Delphi, I tagged this as Delphi or Visual C++. Any code samples and articles that you can find would be appreciated. MSDN articles do not seem to be written about this.

As a goal, let's imagine you want to either: (a) Reproduce what Google Chrome does (tabs as part of the glass frame) (b) Reproduce what MS Office 2010 does (save button on the glass frame, referred to in MFC for VS 2010, as "Quick Access Toolbar" (see picture below).

I am not using MFC, but if examining the MFC sources would be a good source of information, I am curious to know where in the MFC sources or BCG original sources (I have both) are implemented the Quick Access Toolbar rendering/painting code.

alt text

Update: A related neato link from one of the answers below shows the NC (nonclient) Paint message, and how to handle it when painting on a glass frame, and an MSDN article about it here.

This is a subset of my "Glass" bookmarks folder, the result of a lot of research / searching on this topic. I've found all of these useful for learning about glass and solving various problems drawing on it. Most of these include Delphi code, but I've noted where it's for another language.

Plain Glass links

  • Using translucent windows with Delphi: good introduction (from the very basics) for using Glass in Delphi forms
  • Custom drawing on glass: covers how to draw a bitmap or other image on a glass area of the window. Covers alpha channels etc too, good overview
  • Using glass in a VC++ project: covers turning glass on, drawing text, handling notifications etc - a good general introduction to how it works. A lot of the underlying details are handled by the VCL (eg the GlassFrame property and TForm internals look after a lot of this) but it's very useful to understand the basics of how it's implemented at an API level anyway
  • How to draw on the non-client area: this shows how to draw something like Office's toolbar in the title bar. .Net code, but translatable
  • Setting up a custom title bar: very detailed article about non-client-area drawing (in Delphi, so Delphi code). Followed up by part 2, which demonstrates completely taking over the entire window and mimicking the standard title bar yourself. These two articles will let you mimic Office and Chrome as you requested in the question
  • How to set up various VCL controls to work best on a glass area: the VCL does not support glass very well. You'll often get artifacts, or controls simply not drawing properly at all, no matter what you do to try and solve it. This article lists the basic VCL visual components (labels, buttons, progress bars, etc) and what to set up for each so they draw perfectly, or at least 'as well as possible' when they're placed on a glass area

Advanced, or tangentially related:

5 votes

Is there a way in Windows (which works in Windows CE) to check if a printer is attached and communicating to LPT1 in C++?


[Edit] More info:

We are currently working with a generic Windows CE printer driver - pcl.dll - by passing it into CreateDC, to get the DC for the printer.

We can't call PrintDlg() to show the print dialog because it is "too complicated looking," but we also can't call it with PD_RETURNDEFAULT because we do not want to use the default printer. So, we are manually setting up a DEVMODE structure to pass in to CreateDC.

After we have the DC, we call GetDeviceCaps() to get the info for the printer (such as page-width, etc), then StartPage()/EndPage()/ExtTextOut() to print.

However, if there is no printer attached, the program freezes for about a minute before giving an "Abort/retry/fail?" dialog (I don't know what point in this process it is freezing). Other software doesn't freeze when you attempt to print, so there must be a way of preventing this...

I would also recommend enumerating devices, but you could try the following functions to see if it hangs quickly and gracefully (I don't currently have any way of testing this...):

CreateFile("LPT1:", 0, 0, NULL, OPEN_EXISTING, ...);
DeviceIOControl(HANDLE, IOCTL_PARALLEL_STATUS, ...);

It is possible that this returns a failure better than trying to print with the DC. If it works, don't forget to call CloseHandle() on the HANDLE returned from CreateFile before opening your DC for printing.

Is there a programmatic way I can hook into user logins and logouts (Windows SBS 2003) with the goal of simple logging?

5 votes

I'm trying to write a central reporting tool that will allow time tracking based on Windows users logging into a domain. Initially I was going to create a small executable that would run on 'all users' start-up on each computer, track the logged in username and update a central database.

The main problems with this would be having to manage the versions on a machine by machine basis and deal with rare but possible instances of the tool failing on specific machines and not being immediately obvious.

Instead I would prefer to create a centralised version but I'm finding the MSDN and Windows SBS 2003 docs very hard to dig through for the answer.

Basically I would like to hook into the 'login' and 'logout' functions on the server and track all information from there. Are there natural extension points here?

Obviously an alternative may be to parse the event logs for the information (but to this point I can't find any windows logs that say 'who' is logging in or out).

Any guidance on the direction or documentation to look at would be really appreciated.

Are there natural extension points here?

No. Or rather, you don't plug into login/logout unless you want to replace the login module (e.g. for a different authentication mechanism): not something trivial to do—too easy to open up security holes (and I expect not a good idea, if not impossible, in .NET).

But as Windows (all NT derived versions) includes the ability to log all logins and logouts, the information you need can be recorded in the Security event log. There are then a number of options for getting at the information.

First: enable audit of login/logout.

This is best done with group policy. For the local machine enable the options in SecPol.msc (local security policy MMC snapin): Local Policies | Audit Policy

Second: read the event log

In the Security Event Log look for logon events (id 4624), there is some documentation of these events here.

Automation of this (e.g. via a scheduled read of the event log) or forwarding events should be easy enough.

Windows: Is it *possible* to create a (virtual) video card driver?

5 votes

i want to create a virtual monitor. The way this would work is that the virtual monitor would appear in a window on my desktop. As far as Windows knows it is just another monitor.

It occurs to me that it would, as a practical matter, have to be done as video card driver (i.e. rather than the video going out a wire to an LCD panel, it would go into another window on the desktop).

Does what i'm describing sound, technically, possible? (from a DDK point of view)

Note: i can't use a virtual pc, because no virtual PC has resolutions high enough for my needs. Also because it's not what i asked for.

Note: My reasons are unimportant, but i can make some up:

I'd say it's definitely possible, since that's what virtualization tools do for their guest utilities, but I wouldn't be able to tell you how in details. I'd suggest looking at the VirtualBox guest driver code as a starting point: http://www.virtualbox.org/browser/trunk/src/VBox/Additions/WINNT/Graphics

(This is released under GPL as far as I'm aware.)