Showing posts with label windows. Show all posts
Showing posts with label windows. Show all posts

How To Detect If The Command Prompt Is Running Elevated

As I was setting up my Console2 shell tabs I was curious if running Console2 as an administrator would transfer the elevated privileges token to the tabs as well.

Turns out detecting this was not as straightforward as I thought it would be!

TL;DR

If you need to know how to detect if the command prompt is running elevated (or your script) use the following command:

whoami /groups
If the output contains these lines the process is running elevated:
Mandatory Label\High Mandatory Level Label            S-1-16-12288
                    Mandatory group, Enabled by default, Enabled group

The Long Answer

With the addition of User Account Control to Windows Vista the platform gained integrity levels – an integrity level indicates how much an application can be trusted to perform  actions on the system, e.g. accessing files or the registry and interacting with other processes. By adding this additional security feature to the OS it now has another indicator to help isolate (sandbox) programs and prevent them from going rogue on your system. Very cool!

The following integrity levels are supported:

  • Untrusted – processes that are logged on anonymously are automatically designated as Untrusted
  • Low – The Low integrity level is the level used by default for interaction with the Internet. As long as Internet Explorer is run in its default state, Protected Mode, all files and processes associated with it are assigned the Low integrity level. Some folders, such as the Temporary Internet Folder, are also assigned the Low integrity level by default.
  • Medium – Medium is the context that most objects will run in. Standard users receive the Medium integrity level, and any object not explicitly designated with a lower or higher integrity level is Medium by default.
  • High – Administrators are granted the High integrity level. This ensures that Administrators are capable of interacting with and modifying objects assigned Medium or Low integrity levels, but can also act on other objects with a High integrity level, which standard users can not do.
  • System – As the name implies, the System integrity level is reserved for the system. The Windows kernel and core services are granted the System integrity level. Being even higher than the High integrity level of Administrators protects these core functions from being affected or compromised even by Administrators.
  • Installer – The Installer integrity level is a special case and is the highest of all integrity levels. By virtue of being equal to or higher than all other WIC integrity levels, objects assigned the Installer integrity level are also able to uninstall all other objects.

 

For more info see the Windows Integrity Mechanism Design.

How to add Activity Notification to PuTTY

For over a decade PuTTY has been my Telnet/SSH client of choice for Windows. I mostly use it as a MUD client nowadays and missed one convenience feature: activity notifications. Chat clients all flash for attention when activity occurs and it would be a great addition to streamline my social mudlife, so I set out on a quest to add it…

First of all you need to have Microsoft Visual C++ installed to compile the sourcecode for Windows which can be found on the PuTTY Download page. Get the sources unzipped and load the workspace “putty-src\WINDOWS\MSVC\PUTTY.DSW”, you will need to go through a conversion to a Visual Studio 2008 solution when using VS2008. All code additions and changes are done in the file WINDOW.C in the “putty” project.

To support activity notification we need to know when there is activity and notify the user by making the window flash if the window is not active and it has not already done a flash. This brings us down to three problems to solve: detecting activity, knowing when the window is not active and flashing the window.

 

Flashing the PuTTY Window

PuTTY already has the option to use the window flash as a visual bell so that code can be used as a template. Notice how this feature also has been implemented in the PuTTY code itself to support flash on older Windows OSes that do not support the FlashWindowEx API method. (I have left this code in place, but it has not been tested.)

The following code snippet must be added at the end of the file:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS */
/* SNIPPET ID: {34060BBE-6F8C-4bc1-AF1F-97B3FC8D24A4} */
static void flash_window_timer_activity(void *ctx, long now)
{
    if (flashing && now - next_flash >= 0) {
      flash_window_activity(1);
    }
}
 
static void flash_window_activity(int mode)
{
   if(mode==0) {
      /* stop */
   } else if (mode==2)
   {
      /* start */
      if (!flashing && !activity_blink_done) {
         flashing = 1;
         activity_blink_done=TRUE;
         if (p_FlashWindowEx) {
            /* For so-called "steady" mode, we use uCount=2, which
            * seems to be the traditional number of flashes used
            * by user notifications (e.g., by Explorer).
            * uCount=0 appears to enable continuous flashing, per
            * "flashing" mode, although I haven't seen this
            * documented. */
            flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
               (cfg.beep_ind == B_IND_FLASH ? 0 : 2),
               0 /* system cursor blink rate */);
            /* No need to schedule timer */
         } else {
            FlashWindow(hwnd, TRUE);
            next_flash = schedule_timer(450, flash_window_timer_activity, hwnd);
         }
      }
   }
   else if(mode==1)
   {
      /* maintain */
      if (flashing && !p_FlashWindowEx) {
         FlashWindow(hwnd, TRUE);   /* toggle */
         next_flash = schedule_timer(450, flash_window_timer_activity, hwnd);
      }
 
   }
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS */

 

Add the following snippet to the forward declarations at the top of the file (surrounding code is show for reference to the location where it should be placed and must not be added):

#define TIMING_TIMER_ID 1234
static long timing_next_time;
 
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS */
/* SNIPPET ID: {D8B4F4A3-F870-4ded-B298-EEB71701D25D}*/
static void flash_window_activity(int mode);
static BOOL window_is_active=TRUE;
static BOOL activity_blink_done=FALSE;
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - FLASH METHODS FORWARD DECLARATIONS AND VARS*/
 
static struct {
    HMENU menu;

The activity_blink_done boolean ensures the window flash gets triggered only one time once the window has become inactive and activity occurs.

 

Detecting the Window Active State

There are several ways of doing this, I embarked on the adventure of using a handler for the WM_ACTIVATE message to keep track of the current state because it seemed to blend in well with the rest of the code in place. The handler also clears the activity_blink_done variable so a new flash will be triggered when necessary.

Add the following snippet at the end of the file:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
/* SNIPPET ID: {75B2CA9C-49F4-4eb5-AFCF-E3D743C37C44} */
int Do_WM_ACTIVATE(HWND a_hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   WORD wAction = LOWORD(wParam);
   WORD wMinimized = HIWORD(wParam);
 
   if(a_hwnd == hwnd) {
      switch(wAction)
      {
         case WA_INACTIVE:
            window_is_active = FALSE;
            activity_blink_done = FALSE;
            break;
         case WA_ACTIVE:
         case WA_CLICKACTIVE:
            if(!wMinimized)
               window_is_active = TRUE;
            break;
         default:
            break;
      }
   }
}
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */

 

With the message handler in place we need to hook it up in the window procedure. To do this we need to add a case statement for the WM_ACTIVATE message in the WndProc method. Insert the following code snippet right before default case handler (surrounding code shown for reference and must not be copied):

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
/* SNIPPET ID: {5AFAA3AB-FB28-45e9-9DE7-E56648A1B5AF} */
      case WM_ACTIVATE:
         Do_WM_ACTIVATE(hwnd, message, wParam, lParam);
         break;
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION */
      default:
         if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {

 

For completeness add a forward declaration below the previous forward declaration snippet we added:

/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION FORWARD DECLARATION */
/* SNIPPET ID: {D3292300-A6A3-402f-A0A5-CE259BD25EC0} */
int Do_WM_ACTIVATE(HWND a_hwnd, UINT message, WPARAM wParam, LPARAM lParam);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - WINDOW ACTIVE DETECTION FORWARD DECLARATION */

 

Detecting Session Activity

With the window flash and window state support in place all that is left to do is hooking it up to the session activity detection. Find the from_backend method and insert the code snippet below so the method resembles the code block:

int from_backend(void *frontend, int is_stderr, const char *data, int len)
{
/* MARK SLETTERINK - ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
/* SNIPPET ID: {9198643F-09DF-466f-971F-EB05EA15A85E} */
   if(!window_is_active)
      flash_window_activity(2);
/* MARK SLETTERINK - END OF ACTIVITY NOTIFICATION SUPPORT - SESSION ACTIVITY DETECTION */
   return term_data(term, is_stderr, data, len);
}

 

Enjoy!

That completes the code additions. Compile the code, fire up PuTTY and enjoy the new activity notification feature!

Quest complete! You gained 1 million XP.

More pain with NVidia...

It has been a while since I last tried to find a stable video driver and reader Gregg's question made me pull the trigger on another adventure in driver-installation-land. It has been a nightmare!

I started out with trying to reproduce the problem desribed in 'Black Screen after Vista Wakes Up from Sleep with NVidia Driver 7.15.11.7521' by installing the latest NVidia GeForce video driver available: GeForce Release 178 WHQL (Version: 178.24, Release Date: October 15, 2008, Operating System: Windows Vista 32-bit, Language: U.S. English, File Size: 85 MB). A reboot later the version number now was at 7.15.11.7824. A quick cycle through sleep-and-resume confirmed the problem was still there. Ouch! Reader Eddy had spent some time troubleshooting this issue as well and pointed out the resolution played a role in it, I am running in 1280x1024 32 bit color. So I changed the color bits from 32 to 16: problem still there, lowered the resolution to 1152x864: problem gone! (I skipped a number of steps here, if NVidia wants scientific data they can hire me and pay for my precious time). Unfortunately now the screen looks like somebody put Vaseline in my eyes. Yuck!

Ok, so the screen was ugly, but I could go through a sleep-and-resume cycle. Was it worth the ugly screen? Absolutely not! Time to run system restore and get back to my original driver setup...

Unfortunately kicking off system restore to my old restore point presented me with a blue screen during the process.

...

Eventually my system rebooted, Vista prompted me to its awareness of the crash, I sent the crash report and Microsoft pointed the finger at the NVidia SATA driver. Gaaaaa! Oh well, that was fun, I figured I would try system restore again only to find every single restore point had vanished. Automatic, Manual, they are all gone! Somebody pinch me! My screen looks like all pixels are smeared into eachother and I'm stuck with a broken driver setup. Wake me up from this nightmare!

Moving on...

My SATA driver is broken, Microsoft says I need to get latest from NVidia... I figured I could put NVidia to work for me this time and use the wizard from the website to determine the Motherboard software download I needed. The verdict? GeForce 6150LE / nForce 430 (nForce Driver Version 15.24 WHQL, Release Date: September 12, 2008). Sounds good. Download, install, reboot. This installer puts a driver for just about every piece of hardware they created on your system, and as it comes as a package I would expect them to work together very well. (GeForce 6150 LE driver version 7.15.11.7540, SATA driver version 10.3.0.42.) Unfortunately, a 'quick' sleep-and-resume cycle showed the problem was still there and Windows Update tells me there are updated drivers available for my nForce networking and SATA controller.

Installed GeForce 6150LE driver version 178.24 again and rebooted. Worked with the system for a couple of days and on my next reboot I blue-screened again. Installing the latest SATA driver through Windows Update seems to have resolved that issue. But for now I have disabled sleep mode.

Conclusion: Problem still not fixed.

Black Screen after Vista Wakes Up from Sleep with NVidia Driver Version 7.15.11.7521

It's actually not completely black, the top line of pixels still works properly! This problem started for me after I installed the driver update supplied by Windows NVidia_GeForce6150LE_v7.15.11.7521Update for the GeForce 6150 LE; Driver Provider: NVIDIA, Driver Date: 5/22/2008, Driver Version: 7.15.11.7521. Both manually forcing it and idling to sleep or hibernate produce the same results.

The rest of the system appears to be functioning properly and pressing the power button will turn off the system. Hitting the [WIN], typing 'shutdown /r /t 0' and pressing [enter] will reboot the system. Upon reboot the screen is fine again and neither the EventLog nor Reliability Monitor show any problems.

Rollback_Driver_ErrorI decided to roll back to the previous driver (7.15.11.6222, 7/6/2007), which produced four RunDLL error dialogs: "Error in NVCPL.DLL - Missing entry:NvCplRestorePersistence". Ouch!

Now the screen works properly when waking up, but I get greeted with that error dialog. Again, no errors or warning in the EventLog or Reliability Monitor.

Time for the windows cure-all... DAS (RE)BOOT!

Excellent! The reboot cleared up that issue.

Has anyone else experienced this issue? Did you resolve it? How?

Related posts:

Realtek HD Audio - upgrading from 6.0.1.5502 to 6.0.1.5548

The Software & Driver download page for my HP Pavilion a1750e had an updated audio driver on it, but I assumed Windows Update also had the latest Realtek HD Audio drivers for Vista. Since I religiously keep up to date with Windows Update I assumed I was running with the latest drivers. Alas, I was wrong mistaken!

What is going on here? Why do I have to pick those drivers up from HP? It looks like Microsoft would have to keep a lot of vendor specific updates available, considering this disclaimer found on the Realtek drivers download entry page.

Audio drivers available for download from the Realtek website are general drivers for our audio ICs, and may not offer the customizations made by your system/motherboard manufacturer. To be sure you obtain the full features/customizations provided in your original audio product, please download the latest drivers from your system/motherboard manufacturer's website.

Yuck! This is lawyer speak for "we don't do drivers, we're in the hardware business". Ergo, you want drivers? Go talk to your hardware vendor. And so I did. Current installed version 6.0.1.5502; Time to put the upgrade to version 6.0.1.5548 to the test. (Release date: 2008-03-01, Description: Realtek High Definition Audio driver update resolves excessive noise issue with HDMI audio.)

Strangely enough HP software updates still do not seem to be able to use a wizard style for their update dialog, so after running sp37324.exe I am presented with the plea to press YES! ClickYes

Ick! Ok, then. I wonder what the difference is between "No" and "Cancel". :)

Next up, a little progress dialog...

PleaseWait

Eeeep! No progress shown here, just the moving piece of green that shows it is busy. And after a bit the update is done; Time to click YES again, or No, or Cancel!

UpdateCompleted

I chose to be nice, and click YES, the system restarted, and I still had sound. Yay! Unfortunately all my audio configuration settings were wiped out again, so I had to set front and back channels to be split again, but that was the only heartache I got. And just to be sure I checked the version dialog:

driver-v6.0.1.5548-infopanel

Success!

My question to you, dear reader, is: Where do YOU pull your Realtek HD Audio driver updates from?

Monitor Your System Performance With Samurize

Have you ever wondered what is going on under the hood of your Windows system? Why is it so sluggish and slow (read: sloooooooooow)? Why is my harddisk continuously blinking? Or that CPU fan sounding like a jet engine? - As a software developer with a passion for code quality and performance I always strive to produce solid code and software algorithms, but you will not know how it actually behaves until you measure. Even though software the development environments of today come with an army of sophisticated tools to help you squeeze out the numbers during a test run they do not give you a general feel of how your system normally performs. Windows comes with perfmon, but configuration and interpretation of those graphs is a pain at best. Samurize to the rescue!!!

Samurize to the rescue!
Using Samurize and a little imagination you can build a very slick system status display that will make your friends turn green with envy! The configuration I use looks like this:
Once you have settled in on a base set of performance counters and how you would like them displayed, CPU-, Memory- and Disk-Usage histograms are a good place to start, it is easy to expand your configuration to include more items you want to monitor like SQL Server, Network traffic, etc. After creating and selecting your configuration you will want to set the display position to "docked" so the meters are always visible.

Here is a link to download the configuration I currently use.


I will explain how to interpret the different sections of this configuration in future posts.

Update: Replaced configuration file contents with a download link.

Vista SP1 upgrade with Realtek High Definition sound driver v6.0.1.5502 successful!

This weekend I was pleasantly surprised with an available download for Vista SP1 through windows update (why did it take so long?!?). I was fearful of losing my sound with the upgrade due to "SP1 not available cause #5", my driver version is v6.0.1.5502, but the upgrade went well (turns out I have a High Definition Audio Codec, not AC'97, ooops). The custom settings for the sound card were reset (I like to split all input/output jacks into different channels, the default ties them all together), but that was it. Sound is totally functional from the get-go!

Hurrah!

I haven't seen any difference in performance yet. Feels like same old Vista so far.


Related posts:

Environment.TickCount: Int32 (aka SIGNED integer)

Did you know that Environtment.TickCount returns a signed 32 bit integer? Did you know the sign on this property flips every 24.9 days? From the MSDN documentation: The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days. Ouch! Good thing windows updates get pushed once a month (and generally kindly coerce you to reboot); you might not notice the couple of days at the end when you're pulling negative numbers. But alas, today the negative tickcount decided to hit me. I was running unittests and noticed I was sending out negative request numbers?!? WTF! ROTFL! :) A little investigation turned up the culprit; trusty old TickCount wasn't that trusty after all. (That will teach me for stopping the windows update service to stop the reboot nagging, right?)
What happened to the days when you could boast about your system uptime? My linux box easily ran into hundreds of days (the resets were caused by power outtages)! What happened to my linux box?!?
What is a developer to do? Eureka! You can cast it to a Uint32! Twice the positive size, twice the fun, right?

UInt32 tickCount = (UInt32)Environment.TickCount;

Nah, you'll still wrap around after 59.8 days, which means you cannot use it to calculate the system uptime or measure time intervals... Here's how to calculate system uptime:

PerformanceCounter uptimeCounter = new PerformanceCounter("System", "System Up Time", true); uptimeCounter.NextValue();// init counter float uptime = uptimeCounter.NextValue(); // get uptime in secs TimeSpan uptimespan = TimeSpan.FromSeconds(uptime); Trace.WriteLine("Uptime: " + uptimespan.ToString());

And this is how you measure a time interval:

Stopwatch sw = new Stopwatch(); sw.Start(); // do lengthy stuff sw.Stop(); Trace.WriteLine("Elapsed: " + sw.Elapsed.ToString());

Enjoy! - Doc. How do YOU determine your system uptime programmatically?

My Latest Track