PowerShell: Generics and how to get Restriction codes from webservice exceptions

By mortl92 on Jan 25, 2013

These functions allows you to create generic objects of different types (Lists and Dictionaries) and to read the Restriction-code and Error-code of SoapExceptions.
For more details about the usage please read this post: http://blog.coolorange.com/2013/01/25/updatefileproperties-from-vault-api-in-powershell

How to use it:

creating and filling the list

$list = New-List string
$list.Add("test string")

creating and filling the dictionary

$dic = New-Dictionary string int
$dic.Add("some Key",10)

reading the error code and restriction code from the soap-exception

try
{
$webservice.SomeFunction();
}Catch
{
$e=$.Exception.InnerException
$res=GetErrorAndRestrictionCodesString $e
if($res[1] -ne $null)
{
LogFile "Webservice call is restricted! Error:$
StackTrace:..." "ERROR"
LogFile "Code: $($res[0]) | RestricionCode: $($res[1])" "ERROR"
}
}else
{
LogFile "Webservice failed with error:$_ StackTrace:..." "ERROR"
}
}

#function for creating generic lists and dictionaries
function New-List([type] $type)
{
  $base = [System.Collections.Generic.List``1]
  $qt = $base.MakeGenericType(@($type))
  New-Object $qt
}
function New-Dictionary([type] $keyType, [type]$valueType){  
    $base = [System.Collections.Generic.Dictionary``2]
    $ct = $base.MakeGenericType(($keyType, $valueType))
    New-Object $ct
}

#function for reading the restriction code of soap-exceptions
function GetErrorAndRestrictionCodesString($e) 
{
   $se = [System.Web.Services.Protocols.SoapException]$e 
    $errorCode = $null; 
    $restrictionCodes = ""; 
   $restrictionErrors = @( "1092", "1387", "1633" );       

    if ($se -ne $null) 
    { 
        try 
        { 
            $errorCode = $se.Detail["sl:sldetail"]["sl:errorcode"].InnerText.Trim(); 

            if ($restrictionErrors -contains $errorCode) 
            { 
                $nodes = $se.Detail["sl:sldetail"]["sl:restrictions"].ChildNodes; 

                foreach ($node in $nodes) 
                {
                    if ($node.Name -eq "sl:restriction") 
                    { 
                        $element = [System.Xml.XmlElement] $node; 
                        if ($element -ne $null)
                        {
                            $restrictionCodes = $element.GetAttribute("sl:code");
                        }
                    } 
                } 
            } 
        } 
        catch 
        { } 
    }
    return @($errorCode,$restrictionCodes)
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.