how to handle proxy properly in .NET - c#

I have an Excel AddIn written in C#, which connects to server to get data via httpwebrequest
One client has proxy settings "Use Automatic Configuration Script" checked and it uses some script there.
My addin is not able to connect to server in this case.
So I open fiddler to check why it fails. Then my addin starts working.
I checked proxy settings with fiddler open, look, it is changed to "Use a proxy server for your LAN"
I want to do the same thing in my code, use the proxy setting from IE settings and use it in my code.
Do you know how to accomplish this?
What I have now is as below and does NOT work. Thanks
private static void SetProxyIfNeeded(HttpWebRequest request, Uri uri)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
if (_proxy == null)
{
_proxyUri = WebRequest.GetSystemWebProxy().GetProxy(uri);
_proxy = new WebProxy(_proxyUri, true)
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
if (_proxyUri != null && !string.IsNullOrEmpty(_proxyUri.AbsoluteUri) && !_proxy.Address.Equals(uri) && !IsLocalHost(_proxy))
{
_realProxy = true;
}
else
{
_realProxy = false;
}
}
//if there is no proxy, proxy will return the same uri
//do we need check if client.Proxy is null or not,
if (_realProxy)
{
request.Proxy = _proxy;
}
stopWatch.Stop();
Helper.LogError("\r\n Got proxy in " + stopWatch.ElapsedMilliseconds + "ms.\r\n");
}
In addition, I have a config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy usesystemdefault ="True" bypassonlocal="True"/>
</defaultProxy>
</system.net>
</configuration>
Edit:
client updates from their IT guy, looks like pac is downloaded but it is not used
I do not know why it is not used, I specify to use it in each request except cometd which has no way to specify proxy, maybe that's the issue?

If using an app.config for your AddIn is an option (I know this is tricky with Office Addins) you could handle all the proxy configuration there:
<configuration>
<system.net>
<defaultProxy>
<proxy
usesystemdefault="true"
bypassonlocal="true"
/>
</defaultProxy>
</system.net>
</configuration>
See <defaultProxy> Element (Network Settings) on MSDN for details.

Related

How to enable local network traffic in the c# application manifest file?

According to this. I need to enable local network traffic in the manifest file of c# application. Can anyone paste a sample code to enable it in application manifest file?
I tried to use fiddler proxy in httpclient however its not going to fiddler proxy. I stumbled upon this post and they says enable local network traffic in the manifest file https://social.msdn.microsoft.com/Forums/en-US/ce2563d1-cd96-4380-ad41-6b0257164130/winrt-using-httpclient-with-systems-proxy?forum=winappswithcsharp any help appreciated.
Current my application manifest are the following
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<system.net>
<connectionManagement>
<add address="*" maxconnection="6500" />
</connectionManagement>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
</configuration>
httpclient code this request is not going through fiddler.
string url_get_string = "http://localhost/php/tmp/test.php?Get_C="+ ID;
HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.CookieContainer = cookieJar;
handler.Proxy = new WebProxy("http://127.0.0.1:8888", false);
handler.UseProxy = true;
handler.UseDefaultCredentials = false;
var client = new HttpClient(handler);

How to read app.config file programmatically

I have config file for my app, my app.config is as below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value="192.168.130.5"/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy autoDetect="false"
bypassonlocal="true"
proxyaddress="192.168.130.6"
scriptLocation="https://ws.mycompany.com/proxy.dat"
usesystemdefault="true"
/>
</defaultProxy>
</system.net>
</configuration>
var proxy= ConfigurationManager.AppSettings["proxyaddress"];
will get "192.168.130.5",
How to get all proxy settings in system.net section in c#?
Updated: I changed my config to the following and get it:
string proxyURLAddr = ConfigurationManager.AppSettings["proxyaddress"];
Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Config" value="log4netConfig.xml" />
<add key="proxyaddress" value=""/>
</appSettings>
<system.net>
<defaultProxy enabled ="true" useDefaultCredentials = "true">
<proxy usesystemdefault ="True" bypassonlocal="False"/>
</defaultProxy>
</system.net>
</configuration>
toosensitive, your app.config when built and deployed will be renamed to : name of of your assembly + (.exe or .dll) + ".config". The answer above is valid for web applications, but not for console ones, libraries and windows services. You can't put app.config alongside with any assembly and expect this assembly to start reading the appSettings section, the same way IIS reads web.config files. I think this is why you receive null.
Update 2:
You can read the values like described here but for local app settings configuration file:
var proxy = System.Configuration.ConfigurationManager.GetSection("system.net/defaultProxy") as System.Net.Configuration.DefaultProxySection
if (proxy != null)
{ /* Check Values Here */ }
For custom sections you can use the following steps:
You have define a custom configsection class derived from ConfigurationSection:
public class ProxyConfiguration : ConfigurationSection
{
private static readonly ProxyConfiguration Config = ConfigurationManager.GetSection("proxy") as ProxyConfiguration;
public static ProxyConfiguration Instance
{
get
{
return Config;
}
}
[ConfigurationProperty("autoDetect", IsRequired = true, DefaultValue = true)]
public bool AutoDetect
{
get { return (bool)this["autoDetect"]; }
}
// all other properties
}
After that you can use the class instance to access the values:
ProxyConfiguration.Instance.AutoDetect
You can find an example in MSDN

Modify SmtpSection in web.config in c# code in asp.net?

I have set up the following in my web.config to have multiple smtp settings defined:
<sectionGroup name="mailSettings">
<section name="smtp_1" type="System.Net.Configuration.SmtpSection" requirePermission="false"/>
<section name="smtp_2" type="System.Net.Configuration.SmtpSection" requirePermission="false"/>
</sectionGroup>
</configSections>
<mailSettings>
<smtp_1 deliveryMethod="Network" from="xxx#hotmail.com">
<network host="smtp.live.com" port="587" userName="xxx#hotmail.com" password="xxx" defaultCredentials="false"/>
</smtp_1>
<smtp_2 deliveryMethod="Network" from="yyy#gmail.com">
<network host="smtp.gmail.com" port="465" userName="yyy#gmail.com" password="yyy" defaultCredentials="false"/>
</smtp_2>
</mailSettings>
I have been able to retrieve any of the settings using code and I have set up a function to iterate through the config file and pull out each smtp setting and add to a dropdownlist.
The only thing that doesn't want to work is actually writing back to the web.config (either adding a new smtp or modifying an existing one). I have used the following C# code:
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
smtpSection.From = "zzz#hotmail.com";
smtpSection.Network.Port = 25;
smtpSection.Network.UserName = "xxx";
smtpSection.Network.Password = "xxx";
webConfig.Save();
But this returns the error:
The configuration is read only.
This code works perfectly fine, but of course it modifies the primary smtp settings in the system.net (where you cannot have multiple smtp settings).
System.Net.Configuration.MailSettingsSectionGroup mailSection = webConfig.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup;
mailSection.Smtp.From = "xxx#hotmail.com";
mailSection.Smtp.Network.Host = "smtp.live.com";
mailSection.Smtp.Network.Port = 25;
webConfig.Save();
Been racking my brain over this and can't seem to find the answer. Feels like it's going to be something so simple (or just not possible). If not, will probably need to encrypt settings and store in the DB.
Thanks! :)

How to set proxy settings for my application in .NET

I have an application in C# which uses a service reference to send SMS through a web service. The user's internet connection needs to pass through a proxy server in order to reach the world.
So my question is how to tell .NET to call web service through the proxy? Or how to set proxy settings for internet connection of my application just like what you can do in YMahoo Messenger?
Also I want to let user to choose proxy settings.
I believe what you are looking for is defaultProxy in your config file.
Here's an example from the link:
<configuration>
<system.net>
<defaultProxy>
<proxy
usesystemdefault="true"
proxyaddress="http://192.168.1.10:3128"
bypassonlocal="true"
/>
<bypasslist>
<add address="[a-z]+\.contoso\.com" />
</bypasslist>
</defaultProxy>
</system.net>
</configuration>
Please try below code hope this will help you
tring targetUrl = "http://www.google.com";
string proxyUrlFormat = "http://zend2.com/bro.php?u={0}&b=12&f=norefer";
string actualUrl = string.Format(proxyUrlFormat, HttpUtility.UrlEncode(targetUrl));
// Do something with the proxy-ed url
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(actualUrl));
HttpWebResponse resp = req.GetResponse();
string content = null;
using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
content = sr.ReadToEnd();
}
Console.WriteLine(content);

Logon failure: unknown user name or bad password? But I am using the right username and password

I want to connect xml file in remote server. I wrote my code like this:
string XMLPATH = #"\\10.222.54.141\c$\Data\CL\Casinolink30\BuildFiles\Logging\980\NoLog4NetFile.UnitTest.Tests.nunit-results.xml";
FileWebRequest request = (FileWebRequest)FileWebRequest.Create(XMLPATH);
request.Credentials = new NetworkCredential("administrator", "Igtcorp123");
FileWebResponse response = request.GetResponse() as FileWebResponse;
Stream stReader = response.GetResponseStream();
XmlTextReader reader = new XmlTextReader(stReader);
int count = 100;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "test-case")
{
//Console.WriteLine("testcase name:" + reader.GetAttribute("name"));
Console.WriteLine("testcase info");
Console.WriteLine("name: " + reader.GetAttribute("name").ToString());
//Console.WriteLine("success: " + reader.GetAttribute("success").ToString());
Console.WriteLine("------------------------------------");
}
}
}
I got a error: "logon failure: unknown user name or bad".
and I try to do this:
input the address (10.222.54.141\c$\Data\CL\Casinolink30\BuildFiles\Logging\980\NoLog4NetFile.UnitTest.Tests.nunit-results.xml) to the address bar,and open. A dialog show up let me add user name and password. I typed in right word, and I successfully accessed the file.
I run the code above. I successfully got the data.
I try this program in another computer. They can access the address, but the program does not work.
I am confused about this? Why does this happen?
Now I deployed my project to the server, I can successfully get my data in localhost address(http://localhost:61547/) on server. But I can not get data in my computer remotely through addr: http://10.222.54.140:8080/. What happen? Can any one help me? Much appreciate.
Try changing the app.config file a bit:
<system.net>
<defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true"/>
</defaultProxy>
</system.net>
This might solve the problem.
You can add this as below in the Web.config file:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.net>
<defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="True"/>
</defaultProxy>
</system.net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>

Categories

Resources