12

i have a problem in certain company in germany. They use proxy in their network and my program cant communicate with server.

IE works with this settings:

Their settings

It means: Automatically detect settings

This is the code:

public static bool CompleteValidation(string regKey)
{
    string uri = "***";

    int c = 1;
    if (Counter < 5) c = 6 - Counter;
    string response = "";
    try
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
        request.AllowWriteStreamBuffering = true;
        request.Method = "POST";
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        request.Headers.Add(HttpRequestHeader.AcceptLanguage, "pl,en-us;q=0.7,en;q=0.3");
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
        request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
        request.KeepAlive = true;

        //proxy settings
        string exepath = Path.GetDirectoryName(Application.ExecutablePath);
        string proxySettings = exepath + @"\proxy.ini";
        WebProxy wp = new WebProxy();
        if (File.Exists(proxySettings)) {
            request.Proxy = WebRequest.DefaultWebProxy;
            IniFile ini = new IniFile(proxySettings);
            string user = ini.IniReadValue("Proxy", "User");
            string pass = ini.IniReadValue("Proxy", "Password");
            string domain = ini.IniReadValue("Proxy", "Domain");
            string ip = ini.IniReadValue("Proxy", "IP");
            string port_s = ini.IniReadValue("Proxy", "Port");
            int port = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                if (!string.IsNullOrEmpty(port_s))
                {
                    try
                    {
                        port = Convert.ToInt32(port_s);
                    }
                    catch (Exception e)
                    {
                        ErrorLog.AddToLog("Problem with conversion of port:");
                        ErrorLog.AddToLog(e.Message);
                        ErrorLog.ShowLogWindow();
                    }
                    wp = new WebProxy(ip, port);
                } else {
                    wp = new WebProxy(ip);
                }

            }
            if (string.IsNullOrEmpty(domain))
                wp.Credentials = new NetworkCredential(user, pass);
            else
                wp.Credentials = new NetworkCredential(user, pass, domain);
            request.Proxy = wp;
        }

        string post = "***";
        request.ContentLength = post.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        StreamWriter writer = null;
        try
        {
            writer = new StreamWriter(request.GetRequestStream()); // Here is the WebException thrown
            writer.Write(post);
            writer.Close();
        }
        catch (Exception e)
        {
            ErrorLog.AddToLog("Problem with request sending:");
            ErrorLog.AddToLog(e.Message);
            ErrorLog.ShowLogWindow();
        }
        HttpWebResponse Response = null;
        try 
        {
           Response  = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception e)
        {
            ErrorLog.AddToLog("Problem with response:");
            ErrorLog.AddToLog(e.Message);
            ErrorLog.ShowLogWindow();
        }

        //Request.Proxy = WebProxy.GetDefaultProxy();
        //Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
        string sResponseHeader = Response.ContentEncoding; // get response header

        if (!string.IsNullOrEmpty(sResponseHeader))
        {
            if (sResponseHeader.ToLower().Contains("gzip"))
            {
                byte[] b = DecompressGzip(Response.GetResponseStream());
                response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
            }
            else if (sResponseHeader.ToLower().Contains("deflate"))
            {
                byte[] b = DecompressDeflate(Response.GetResponseStream());
                response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b);
            }
        }
        // uncompressed, standard response
        else
        {
            StreamReader ResponseReader = new StreamReader(Response.GetResponseStream());
            response = ResponseReader.ReadToEnd();
            ResponseReader.Close();
        }
    }
    catch (Exception e)
    {
        ErrorLog.AddToLog("Problem with comunication:");
        ErrorLog.AddToLog(e.Message);
        ErrorLog.ShowLogWindow();
    }

    if (response == "***")
    {
        SaveKeyFiles();
        WriteRegKey(regKey);
        RenewCounter();
        return true;
    }
    else
    {
        return false;
    }

}

My program logs it as:

[09:13:18] Searching for hardware ID
[09:13:56] Problem with response:
[09:13:56] The remote server returned an error: (407) Proxy Authentication Required.
[09:15:04] problem with comunication:
[09:15:04] Object reference not set to an object instance.

If they write user and pass into proxy.ini file, program works. But the problem is they cant do that. And somehow IE works without it. Is there any way to get those settings from IE or system?

Kaminari
  • 1,387
  • 3
  • 17
  • 32
  • First of all, in the catch (Exception e) get rid of e.message and just log e. This way you get a stack trace and you can figure out what object is null. – mattypiper Jan 10 '12 at 18:09
  • ttymatty: its still not complete code but the problem is earlier than `Object reference not set to an object instance.` Look at `The remote server returned an error: (407)` when trying to `Response = (HttpWebResponse)request.GetResponse();`. Response is null because it wasnt authorized. – Kaminari Jan 10 '12 at 18:50

2 Answers2

22

Use GetSystemWebProxy to return what the system default proxy is.

    WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy();

But every HttpWebRequest should automatically be filled out with this information by default. For example, the following snippet in a standalone console application should print the correct information on a system with a PAC file configured.

    HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");

    // Obtain the 'Proxy' of the  Default browser.  
    IWebProxy proxy = myWebRequest.Proxy;
    // Print the Proxy Url to the console.
    if (proxy != null)
    {
        Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
    } 
    else
    {
        Console.WriteLine("Proxy is null; no proxy will be used");
    }
mattypiper
  • 1,222
  • 8
  • 8
  • Isn't it the same thing as: `request.Proxy = WebRequest.DefaultWebProxy;` ? – Kaminari Jan 10 '12 at 18:47
  • Yes you are right. If you execute the code I posted, does the system have a proxy or not? It's hard to tell with "automatic configuration" selected in Internet Options. – mattypiper Jan 11 '12 at 17:30
  • It's not working. Where else can be a problem? In request headers? – Kaminari Jan 11 '12 at 18:20
  • If you execute the console code I posted, does the system have a proxy or not? – mattypiper Jan 12 '12 at 17:51
  • Yes of course. I wrote earlier: "If they write user and pass into proxy.ini file, program works." – Kaminari Jan 12 '12 at 19:41
  • You are missing my point. I posted code that will tell you if the system is even aware of a proxy. According to the IE screenshot you posted, it is not aware of a proxy, it is set to "autoconfiguration". If my suspicion is true, using `WebRequest.DefaultWebProxy` will buy you nothing because there isn't a proxy configured on the end user's system. However I'm not sure and I asked you to try executing those 6 lines of code so that we can verify whether it is even possible to use this API to determine the proxy settings. My suspicion is that it's a network proxy and therefore the API is useless. – mattypiper Jan 13 '12 at 16:38
  • If DefaultWebProxy doesn't work (please verify), then you could investigate using WPAD: http://stackoverflow.com/questions/191023/how-does-windows-actually-detect-lan-proxy-settings-when-using-automatic-confi – mattypiper Jan 13 '12 at 16:40
9

Use DefaultNetworkCredentials to return system proxy credentials.

request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
Yuriy
  • 91
  • 1
  • 3