Advanced Error Detection - No OK if response is SharePoint-Error-Page

Oct 22, 2012 at 10:43 AM

unwanted: response.StatusCode == 200 if SharePoint-Error-Page --> no Failure

work around: analyze response

public static bool GetWebPage(string URL, string UserName, string Password, string Domain, string AuthType)
{
    try
    {
        // Create a request for the URL.  
        WebRequest request = WebRequest.Create(URL);

        request.Proxy = null;

        // If required by the server, set the credentials.
        if ((UserName == null) || (UserName == ""))
        {
            request.Credentials = CredentialCache.DefaultCredentials;
        }
        else
        {
            CredentialCache myCache = new CredentialCache();
            myCache.Add(new Uri(URL), AuthType, new NetworkCredential(UserName, Password, Domain));
            request.Credentials = myCache;
        }

        // Get the response.
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        // Display the status.
        // Console.WriteLine (response.StatusDescription);

        if ((int)response.StatusCode >= 400)
        {
            throw new Exception("HTTP ERROR! StatusCode:" + (int)response.StatusCode);
        }
        string responseHeader = "";
        for (int i = 0; i < response.Headers.Count; ++i)
        {
            responseHeader += string.Format("{0}: {1}", response.Headers.Keys[i], response.Headers[i]);
            Console.WriteLine("\tHeader Name:{0}, Value :{1}", response.Headers.Keys[i], response.Headers[i]);
        }
        string sharepointErrorHeader = "SharePointError";
        string sharePointError = response.GetResponseHeader(sharepointErrorHeader);
        if (!string.IsNullOrEmpty(sharePointError) && !"0".Equals(sharePointError))
        {
            throw new Exception("SharePoint Header ERROR! " + responseHeader);
        }

        // Get the stream containing content returned by the server.
        Stream dataStream = response.GetResponseStream();

        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);

        string responseFromServer = reader.ReadToEnd();
        if (responseFromServer.Contains("errorPageTitleSpan"))
        {
            throw new Exception("SharePoint ERROR-Page!");
        }
        // Cleanup the streams and the response.
        reader.Close();
        dataStream.Close();
        response.Close();
        log.AddSuccess();
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("");
        log.AddFailure(URL, ex.Message);
        return false;
    }
}