Thursday 26 December 2019

ColourText changes the colour of the text to be printed. This technique is the ONLY one that will work on all Windows version.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.

To use

ColourText <ColourOfText> <ColourOfTextWhenFinished> [Text]

Also the CLS command becomes interesting. Color command without parameters resets all colours to startup colours.

To get the colour code add the following numbers together. Use Calculator in programmers mode. These are hex numbers. They can be added together eg Red + Blue + FG Intensity = 13 = D. As 10+ wasn't used the background will be black. Colour codes MUST be two characters, eg 08 not 8.

FOREGROUND_RED = &H4     '  text color contains red.
FOREGROUND_INTENSITY = &H8     '  text color is intensified.
FOREGROUND_GREEN = &H2     '  text color contains green.
FOREGROUND_BLUE = &H1     '  text color contains blue.
BACKGROUND_BLUE = &H10    '  background color contains blue.
BACKGROUND_GREEN = &H20    '  background color contains green.
BACKGROUND_INTENSITY = &H80    '  background color is intensified.
BACKGROUND_RED = &H40    '  background color contains red.

So black background is 0 while white is F0 (adding 10 + 20 + 40 + 80). Red on white is f4.



REM 2 files follow
REM ColourText.bat
REM Compiles ColourText.vb to ColourText.exe
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\ColourText.exe" "%~dp0\ColourText.vb" /verbose
pause



'ColourText.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication  
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

Sub Main()
    Dim hOut as Long
    Dim Ret as Long
    Dim Colour As Long
    Dim Colour1 As Long
    Dim Text As String
    hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
    Colour = CLng("&h" & Split(Command(), " ")(0))
    Colour1 = Clng("&h" & Split(Command(), " ")(1))
    Text = Mid(Command(), 7)
    Ret = SetConsoleTextAttribute(hOut,  Colour)
    Console.Out.WriteLine(text)
    Ret = SetConsoleTextAttribute(hOut, Colour1)
End Sub
End Module

Wednesday 25 December 2019

GetConsoleColour.exe prints the current console colour and returns an errorlevel with the value

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
;Two files follow
REM GetConsoleColour.bat
REM This file compiles GetConsoleColour.vb to GetConsoleColour.exe
REM GetConsoleColour.exe prints the current console colour and returns an errorlevel with the value
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\GetConsoleColour.exe" "%~dp0\GetConsoleColour.vb" 
pause




'GetConsoleColour.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication 
 
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Declare Function GetConsoleScreenBufferInfo Lib "kernel32" (ByVal hConsoleOutput As Integer, ByRef lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Integer
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

  _
Public Structure COORD
 Public x As Short
 Public y As Short
End Structure

  _
Public Structure SMALL_RECT
 Public Left As Short
 Public Top As Short
 Public Right As Short
 Public Bottom As Short
End Structure

  _
Public Structure CONSOLE_SCREEN_BUFFER_INFO
 Public dwSize As COORD
 Public dwCursorPosition As COORD
 Public wAttributes As Integer
 Public srWindow As SMALL_RECT
 Public dwMaximumWindowSize As COORD
End Structure 


Sub Main()
 Dim hOut as IntPtr
 Dim Ret as Integer
 Dim CSBI as Console_Screen_Buffer_Info
 hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
 Ret = GetConsoleScreenBufferInfo(hOut, CSBI)
 Console.Writeline(Hex(CSBI.wAttributes))
 Environment.ExitCode = CSBI.wAttributes
End Sub
End Module

Wednesday 18 December 2019

Decoding Errors

Informational Posts

Decoding Errors
Decoding Errors
 
-2147220978 style numbers are 32 bit signed integers, convert to hex with calculator.
 
Windows errors (smallish numbers) and  COM HResults (typically, but with exceptions, start with an 8 as in 0x80040154) are defined in WinError.h, except 8007nnnn where you look up the Window error number that it contains.
 
As a general rule Windows errors are less than 65,535 (0xFFFF). Errors starting 0x80000001 are Component Object Model (COM) HResults. Errors starting 0xC0000001 are NTStatus results. Errors starting 0xD0000001 are also NTStatus values returned in a HResult.
 
NTStatus errors (typically but not always start with an C as in 0xC0000022) are defined in NTStatus.h. 
 
.h files are the best source because it includes the symbolic name of the error which can give clues such as the source of the error. FormatMessage doesn't give the symbolic name only the description.
 
You get these files by downloading the Platform SDK (it's gigabytes)

https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/
 
If you just want the two files I have them on my skydrive so I can reference them anywhere I go.

https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 (but they are from 2006)
 
Note internet errors (12,000 - 12,999) are windows errors but are specified in wininet.h also available above. 
 
There are errors defined in other .h files. But 99% are in the three above.
 
Structure of HResults and NTStatus Codes
 
The most significant bit in HResults, and the two most significant bits in NTStatus are set on error. Hence Hresults start 8 on error and NTStatus starts C on Error. The next 14 or 15 bits are reserved and some specify the facility - what area the error is in. This is the third and fourth number when reading hex. EG 0xnn07nnnn - An HResult facility code 7 is a normal Windows' error (returned from a COM program - hence it's returned as a HResult). Facility codes are defined in Winerror.h for HResults and NTStatus.h for NTStatus codes. They are different.
 
 
To Decode 0x8003nnnn Errors
 
HResults with facility code 3 means the HResult contains OLE Structured Storage errors (0x0 to 0xff). These are the same as Dos error codes. These don't seem to be in Windows' header files and the list of codes is at the end of this post.

 
To Decode 0x8004nnnn Errors
 
HResults with facility code 4 means the HResult contains OLE errors (0x0 to 0x1ff) while the rest of the range (0x200 onwards) is component specific errors so 20e from one component will have a different meaning to 20e from another component.

 

This is why the source of the error is extra important for errors above 0x80040200.

 

To Decode 0x8007nnnn Errors
 
HResults with facility code 7 means the HResult contains a Windows' error code. You have to look up the Windows' error code not the HResult.

 
To decode 0x80070002. The 0x means it's a hexadecimal number, the 8 means error, the first 7 means it a windows error, and the rest of the number, 2, is the actual Windows error.
 
To look up the error we need it in decimal format. Start Calculator (Start - All Programs - Accessories - Calculator) and choose View menu - Scientific, then View menu - Hex. Enter 2. Then View menu -  Decimal. It will say 2.
 
Start a Command Prompt (Start - All Programs - Accessories - Command Prompt) and type
 
net helpmsg 2
 
and it will say
 
The system cannot find the file specified.
 
or look it up in winerror.h
 
//
// MessageId: ERROR_FILE_NOT_FOUND
//
// MessageText:
//
// The system cannot find the file specified.
//
#define ERROR_FILE_NOT_FOUND             2L
 
To Decode 0x8019nnnn Errors
 
HResults with facility 0x19 are HTTP errors. Codes under 16,384 (0x4000) are the same as HTTP errors, eg HTTP status 404: The requested URL does not exist on the server is 0x80190194 (0x194 = 404). Codes 16,384 and higher are BITS specific.

To Decode 0xDnnnnnnn Errors
 
HResults starting 0xD are an HResult with a NTStatus value in it. Just cange the lead D to a C and treat as an NTStatus (Hresult = NTStatus OR 10000000).

 

Wednesday 11 December 2019

Brief Introduction to the Windows' Debugger

Informational Posts

Brief Introduction to the Windows' Debugger
Windbg is from Debugging Tools For Windows.

Download and install Debugging Tools for Windows

 http://msdn.microsoft.com/en-us/windows/hardware/hh852363

Install the Windows SDK but just choose the debugging tools.

Create a folder called Symbols in C:\

Start Windbg. File menu - Symbol File Path and enter

 srv*C:\symbols*http://msdl.microsoft.com/download/symbols

then (for example)

 windbg -o -g -G c:\windows\system32\cmd.exe /k batfile.bat

There is an automatic breakpoint set after loading but before any code runs and one at the end after all code has finished but before being terminated. This allows you to examine memory etc before and after the code has run. Press g to continue.

You can press F12 to stop it and kb will show the call stack (g continues the program). If there's errors it will also stop and show them. You may be able to press g to ignore and continue.

 

Type lm to list loaded modules, x *!* to list the symbols and bp symbolname to set a breakpoint

F12           - break into program 
g             - continue 
p             - Step 
kb            - list call stack 
lm            - list loaded modules 
x *!*         - list all symbols 
ln <address>
- lists the nearest symbols to that address - used when you have a crash address 
bp symbolname - sets a breakpoint 
da <address>
- displays the ascii data found at that address 
dda <address>
- displays the value of the pointer 
dv            - display local variables 
kv 10         - displays last 10 stack frames 

-----------------------------------------------------------------
 
If programming in VB6 then this environmental variable link=/pdb:none stores the symbols in the dll rather than seperate files. Make sure you compile the program with No Optimisations and tick the box for Create Symbolic Debug Info. Both on the Compile tab in the Project's Properties.
 
Also CoClassSyms (microsoft.com/msj/0399/hood/hood0399.aspx) can make symbols from type libraries. 

-----------------------------------------------------------------

WinDbg can also analyse Blue Screen Crash Dumps (and indeed application crash dumps).

Dump Files
 
Dump files are files containing the state of the machine when it crashed. We can analyse the file to identify the driver (or program) causing the crash. See the last section on how to get them analysed by a volunteer.
 
Analyse Dump Files

If you want to analyse your own dump files.
 
You need to start Explorer as Administrator to access the files in C:\windows\Minidump. Right click Explorer and choose Run As Administrator.

Download and install Debugging Tools for Windows

 http://msdn.microsoft.com/en-us/windows/hardware/hh852363

Install theWindows SDK but just choose the debugging tools.

Create a folder called Symbols in C:\

Start Windbg. File menu - Symbol File Path and enter

 srv*C:\symbols*http://msdl.microsoft.com/download/symbols
 
Close and reopen WinDbg. File menu - Open Crash Dump

This will analyse the crash dump. You need to close and reopen WinDbg for each dump file analysed. Because you are downloading symbols from the internet WinDbg will appear to be doing nothing. But it's downloading. Be patient.
 
You are looking for a driver or system library that the crash occurred in at the end of the listing. Find the file, right click then Properties - Details tab. If it shows a driver you'll need to update the driver identified. Most drivers are in c:\windows\system32\drivers.
 

.

Tuesday 3 December 2019

Command Prompt Cheat Sheet

Informational Posts

Command Prompt Cheat Sheet

**CMD Cheat Sheet**

First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common.

**Getting Help**

For general help. Type `Help` in the command prompt. For each command listed type `help <command>` (eg `help dir`) or `<command> /?` (eg `dir /?`).

Some commands have sub commands. For example  `schtasks /create /?`.

The `NET` command's help is unusual. Typing `net use /?` is brief help. Type `net help use` for full help. The same applies at the root - `net /?` is also brief help, use `net help`.

References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.

--------------------------
**Punctuation**

    &    seperates commands on a line.
    
    &&    executes this command only if previous command's errorlevel is 0.
    
    ||    (not used above) executes this command only if previous command's 
    errorlevel is NOT 0
    
    >    output to a file
    
    >>    append output to a file
    
    <    input from a file
    
    2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
    
    2>&1 Redirects command error output to the same location as command output. 
    
    |    output of one command into the input of another command
    
    ^    escapes any of the above, including itself, if needed to be passed 
    to a program
    
    "    parameters with spaces must be enclosed in quotes
    
    + used with copy to concatinate files. E.G. copy file1+file2 newfile
    
    , used with copy to indicate missing parameters. This updates the files 
    modified date. E.G. copy /b file1,,
    
    %variablename% a inbuilt or user set environmental variable
    
    !variablename! a user set environmental variable expanded at execution 
    time, turned with SelLocal EnableDelayedExpansion command
    
    %<number> (%1) the nth command line parameter passed to a batch file. %0 
    is the batchfile's name.
    
    %* (%*) the entire command line.
    
    %CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor (from set /?).
    
    %<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. 
    Single % sign at command prompt and double % sign in a batch file.
    
    \\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
    
    : (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
    
    . (win.ini) the LAST dot in a file path separates the name from extension
    
    . (dir .\*.txt) the current directory
    
    .. (cd ..) the parent directory
    
    
    \\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off. 
    
    
    
    
    < > : " / \ | Reserved characters. May not be used in filenames.
    
    
    
    Reserved names. These refer to devices eg, 
    
    copy filename con 
    
    which copies a file to the console window.
    
    CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, 
    
    COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, 
    
    LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
    
    CONIN$, CONOUT$, CONERR$
    
    --------------------------------
    
    Maximum path length              260 characters
    Maximum path length (\\?\)      32,767 characters (approx - some rare characters use 2 characters of storage)
    Maximum filename length        255 characters

--------------------------------
**Starting a Program**


See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows. 

If a full path isn't given then Windows looks in

 1. The directory from which the application loaded. 
    
 2. The current directory for the parent process. 
    
 3. Windows NT/2000/XP: The 32-bit Windows system directory. Use the
    GetSystemDirectory function to get the path of this directory. The
    name of this directory is System32. 
    
 4. Windows NT/2000/XP: The 16-bit Windows system directory. There is no
    function that obtains the path of this directory, but it is
    searched. The name of this directory is System. 
    
 5. The Windows directory. Use the GetWindowsDirectory function to get
    the path of this directory. 
    
 6. The directories that are listed in the PATH environment variable.

**Specify a program name**
--------------------------

This is the standard way to start a program.

    c:\windows\notepad.exe

In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

**Use Start command**
--------------------------

`Start` starts programs in non standard ways.

    start "" c:\windows\notepad.exe

`Start` starts a program and does not wait. Console programs start in a new window. Using the `/b` switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try 

    start shell:cache

Also program names registered under `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths` can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.


**Use Call command**
-------------------------

Call is used to start batch files and wait for them to exit and continue the current batch file.


--------------------------------
**Keys**

**Ctrl + C** exits a program without exiting the console window.

For other editing keys type `Doskey /?`

Speaking Clock in VBScript.


'One file follows
'SpeakingClock.vbs
'Speaks the time continuously
Set speech = CreateObject("sapi.spvoice")
Do
If Hour(Now) < 12 then
Var = Hour(Now) & " AM"
else
Var = Hour(Now) - 12 & " PM"
End If

speech.Speak Var & " and " & Minute(Now) & " minutes and " & Second(Now) & " seconds"
wscript.sleep 5
Loop

Monday 2 December 2019

RunAsAdminConsole.exe eleates a existing console or runs a command leaving the console elevated. The program prompts for credentials.

This uses the inbuilt compilers in Windows 10 - there are three VB.NET compilers and three C# compilers - just copy each text file into the same folder and double click the batch file to make the program.
REM Three files follow
REM RunAsAdminConsole.bat
REM This file compiles RunAsAdminconsole.vb to RunAsAdminconsole.exe using the system VB.NET compiler.
REM Runs a command elevated using a manifest OR elevates the current console without parameters.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\RunAsAdminconsole.vb" /win32manifest:"%~dp0\RunAsAdmin.manifest" /out:"%~dp0\RunAsAdminConsole.exe" /target:exe
REM To use
rem RunAsAdminconsole 
pause



;RunAsAdminConsole.vb
imports System.Runtime.InteropServices 
Public Module MyApplication  
  
 Public Sub Main ()
  Dim wshshell as object
  WshShell = CreateObject("WScript.Shell")
  Shell("cmd /k " & Command())
 End Sub 

End Module 


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="*"
    name="Color Management"
    type="win32"
/>
<description>Serenity's Editor</description>
<trustinfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
<security> 
    <requestedprivileges> 
        <requestedexecutionlevel level="requireAdministrator" uiAccess="false"/> 
    </requestedPrivileges> 
</security> 
</trustInfo> 

</assembly>