Sunday, September 25, 2011

Test-Website

The following function might be useful for checking whether a web page is up or down in PowerShell:

function Test-Website([string][parameter(mandatory=$true)]$Url, [string]$Content)
{
    $webRequest = [System.Net.WebRequest]::Create($Url) 
    $webRequest.CookieContainer = New-Object System.Net.CookieContainer;
    
    try {
        $response = $webRequest.GetResponse() 
    }
    catch {
        return $false
    }
    
    if($response.StatusCode -ne 200) {
        return $false
    }
    
    $responseStream = $response.GetResponseStream()
    $sr = New-Object IO.StreamReader($responseStream)
    $result = $sr.ReadToEnd()

    return $result -match $Content
}

Wednesday, September 21, 2011

Dump all properties of an object to a string in C#

It is often useful to dump all the properties of an object for debugging. This trivial implementation is good, although it only dumps the top level properties:

static string DumpAllProperties(object obj)
{
    return string.Join(", ", 
        TypeDescriptor.GetProperties(obj)
            .Cast()
            .Select(p => string.Format(CultureInfo.CurrentCulture, "{0} = {1}", p.Name, p.GetValue(obj))));
}