Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

11/15/10

PInvoke SetWindowText PowerShell Script

P/Invoke examples for the SetWindowText Windows API Function.
These examples set the window text/title for Notepad.exe.
#get notepad window handle
$notepad = get-process notepad
$notepad.mainWindowHandle //100000, intptr structure

$pinvoke::setWindowText($notepad.mainWindowHandle, "a")

#auto-convert int to intptr
$pinvoke::setWindowText(100000, "b")

#create intptr
#out-null to suppress bool result
$pinvoke::setWindowText((new-object intPtr(100000)), "c") | out-null

$pinvoke::setWindowTextCustomWrapper(100000)

Implementation #1 simply exposes the SetWindowText method, the member definition uses C# syntax.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);

'@

Implementation #2, same as #1 but written on one line.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition '[DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern bool SetWindowText(IntPtr hwnd, String lpString);'

Implementation #3, SetWindowText is private, add custom wrapper method.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SetWindowText(IntPtr hwnd, String lpString);

public static void SetWindowTextCustomWrapper(IntPtr handle)
{
string customText = string.Format("handle: {0}", handle);
SetWindowText(handle, customText);
}

'@


2/5/10

Generic Array to String Function

ArrayToString returns an array as a formatted string. This generic function works with arrays of all types.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Array
    {
        public static string ArrayToString<T>(T[] array, string format)
        {
            return ArrayToString(array, format, 16);
        }

        public static string ArrayToString<T>(T[] array, string format, int stringBuilderItemCapacity)
        {
            var sb = new StringBuilder(array.Length * stringBuilderItemCapacity);
            foreach (T item in array)
            {
                sb.AppendFormat(format, item);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

type Array =
  
  //stringBuilderItemCapacity is an optional int parameter
  static member ArrayToString(array:'a[], format:string, ?stringBuilderItemCapacity:int) =
    
    let stringBuilderItemCapacity =
      match stringBuilderItemCapacity with
        | Some(stringBuilderItemCapacity) -> stringBuilderItemCapacity
        | None -> 16

    let sb = new StringBuilder(array.Length * stringBuilderItemCapacity)
    array |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function arrayToString($array, $format)
{
  $array | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bytes = { 0, 1, 255 };
int[] ints = { int.MinValue, -1, 0, 256, int.MaxValue };
float[] floats = { -9.99f, 0f, 3.14159f };
char[] chars = { 'a', 'b', 'c', '1', '2', '3' };
string[] strings = { "xyz", "789" };

Debug.WriteLine(Array.ArrayToString(bytes, "{0}", 3));
Debug.WriteLine(Array.ArrayToString(bytes, "{0} "));
Debug.WriteLine(Array.ArrayToString(ints, "{0} "));
Debug.WriteLine(Array.ArrayToString(floats, "{0} "));
Debug.WriteLine(Array.ArrayToString(chars, "{0}", 1));
Debug.WriteLine(Array.ArrayToString(chars, "{0},", 2));
Debug.WriteLine(Array.ArrayToString(strings, "{0} ", 4));

//F#
let bytes = [|0uy; 1uy; 255uy|]
let ints = [|Int32.MinValue; -1; 0; 256; Int32.MaxValue|]
let floats = [|-9.99f; 0.0f; 3.14159f|]
let chars = [|'a'; 'b'; 'c'; '1'; '2'; '3'|]
let strings = [|"xyz"; "789"|]

Array.ArrayToString(bytes, "{0}", 3) |> (fun s -> printfn "%s" s)
Array.ArrayToString(bytes, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(ints, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(floats, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0}", 1) |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0},", 2) |> (fun s -> printfn "%s" s)
Array.ArrayToString(strings, "{0} ", 4) |> (fun s -> printfn "%s" s)

#PowerShell
[byte[]]$bytes = 0, 1, 255
[int[]] $ints = [int32]::MinValue, -1, 0, 256, [int32]::MaxValue
[single[]] $floats = -9.99, 0, 3.14159
[char[]] $chars = 'a', 'b', 'c', '1', '2', '3'
[string[]] $strings = 'xyz', '789'

arrayToString $bytes '{0}'
arrayToString $bytes '{0} '
arrayToString $ints '{0} '
arrayToString $floats '{0} '
arrayToString $chars '{0}'
arrayToString $chars '{0},'
arrayToString $strings '{0} '

Output
01255
0 1 255 
-2147483648 -1 0 256 2147483647 
-9.99 0 3.14159 
abc123
a,b,c,1,2,3,
xyz 789 


8/19/09

Hash Functions

GetHash returns the hash value of a byte array.
GetHashStr returns the hash value of a string.

These functions can use any of the hash classes from the System.Security.Cryptography namespace, e.g. MD5, SHA1, SHA256, SHA512.
//C#
using System;
using System.Security.Cryptography;
using System.Text;

namespace ExpressionSoftware.Security.Crypt
{
    public static class Hash
    {
        public static byte[] GetHash(byte[] bs, Type hashType)
        {
            return HashAlgorithm.Create(hashType.Name).ComputeHash(bs);
        }
        
        public static byte[] GetHashStr(string input, Type hashType)
        {
            byte[] bs = Encoding.UTF8.GetBytes(input);
            return GetHash(bs, hashType);
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.Security.Crypt
open System
open System.Security.Cryptography
open System.Text

module Hash =
  let GetHash(bs:byte[], hashType:Type) =
    HashAlgorithm.Create(hashType.Name).ComputeHash bs

  let GetHashStr(input:string, hashType:Type) =
    Encoding.UTF8.GetBytes input
    |> (fun bs -> GetHash(bs, hashType))

#PowerShell
function getHash($bs, $hashType)
{
  $hashType::create().computeHash($bs)
}

function getHashStr($inputStr, $hashType)
{
  getHash ([system.text.encoding]::utf8.getBytes($inputStr)) $hashType
}

Examples
//C#
byte[] bs = Encoding.UTF8.GetBytes("foo");
byte[] hash = Hash.GetHash(bs, typeof(SHA1));
Debug.WriteLine(Byte.BytesToString(hash, "{0} "));
11 238 199 181 234 63 15 219 201 93 13 212 127 60 91 194 117 218 138 51  //output

//F#
let hash = Hash.GetHashStr("foo", typeof<SHA1>)
Byte.BytesToString(hash, "{0:x} ")
|> (fun s -> printfn "%s" s)
b ee c7 b5 ea 3f f db c9 5d d d4 7f 3c 5b c2 75 da 8a 33  //output

#PowerShell
$hashType = [system.security.cryptography.SHA1]
$hash = getHashStr 'foo' $hashType
bytesToString $hash '{0:X}'
BEEC7B5EA3FFDBC95DDD47F3C5BC275DA8A33  #output

8/18/09

Bytes to String Function

BytesToString returns a byte array as a formatted string.

02-05-10 This function has been replaced with a generic version - Generic Array to String Function.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Byte
    {
        public static string BytesToString(byte[] bs, string format)
        {
            var sb = new StringBuilder(bs.Length * 4);
            foreach (byte b in bs)
            {
                sb.AppendFormat(format, b);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

module Byte =
  let BytesToString(bs:byte[], format:string) =
    let sb = new StringBuilder(bs.Length * 4)
    bs |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function bytesToString($bs, $format)
{
  $bs | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bs = { 102, 111, 111 };
Debug.WriteLine(Byte.BytesToString(bs, "{0}"));  //default format
102111111  //output

//F#
let bs = [|102uy; 111uy; 111uy|]
Byte.BytesToString(bs, "{0:d4}-")  //4 digit width format
|> (fun s -> printfn "%s" s)
0102-0111-0111-  //output

#PowerShell
[byte[]]$bs = 102,111,111
bytesToString $bs '{0:x} ' #hex format
66 6f 6f  #output

8/14/09

Listing Users From the Windows Event Log

GetEventLogUsers returns a list of users from the Windows EventLogs, e.g. Application, Security, System. This function returns the entire dataset, unsorted. See examples for sorting and returning distinct lists.

Note: This function works on Windows XP, but not Window Server 2008.
//C#
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ExpressionSoftware.EventLogs
{
    public static class EventLogQuery
    {
        public static IEnumerable GetEventLogUsers(string logName)
        {
            EventLog log = new EventLog(logName);
            var users = from e in log.Entries.Cast()
                        select e.UserName;
            return users;
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.EventLogs
open System.Diagnostics

module EventLogQuery =
  let GetEventLogUsers logName =
    let log = new EventLog(logName)
    log.Entries
    |> Seq.cast
    |> Seq.map (fun x -> x.UserName)

#PowerShell
function getEventLogUsers($logName)
{
  $log = new-object system.diagnostics.eventLog($logName)
  $log.entries | %{$_.username}
}

Examples
//C#
var users = EventLogQuery.GetEventLogUsers("security");
users = users.Distinct().OrderBy(u => u);
foreach (string user in users)
{
    Debug.WriteLine(user);
}

//F#
let users = EventLogQuery.GetEventLogUsers "security" |> Seq.distinct |> Seq.sort
for user in users do
  printfn "%s" user

#PowerShell
getEventLogUsers 'security' | sort-object | get-unique

Output
DEV\john
NT AUTHORITY\ANONYMOUS LOGON
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM