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);
Related
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);
It seems to be pretty simple question but not for me. I am trying to read connection string from web.config file.
I have WCF service application which have web.config file. In web.config file I defined connection strings.
Then I deployed wcf application on IIS7 under default web site(One template which comes when you install IIS7).
Now when we read connection string then it is not giving me connection strings which define in wcf web.config file. Somehow I am not able to access it. And while debugging when I found a connection string which is actually not connection string which I defined in wcf web.config but it is default web site connection string which I don't want.
I want to access connection string which I defined WCF web.config file only. I am stuck in it. I tried all but with no luck. For reference I am putting code which I tried and web.config code also.
Web.Config code.
<configuration>
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<appSettings>
<add key="ConnString" value=""/>
<!--<add key="ConnString" value=""/>-->
</appSettings>
<connectionStrings/>
<system.web>
<httpRuntime maxRequestLength="2097151"
useFullyQualifiedRedirectUrl="true"
executionTimeout="14400" />
<compilation debug="true" />
</system.web>
Code to read connstring
string connString = string.Empty;
string svcDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
DirectoryInfo rootDir = Directory.GetParent(svcDir);
string root = rootDir.FullName;
string webConfigFilePath = root + "\\Web.config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = webConfigFilePath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var test = configuration.ConnectionStrings.ConnectionStrings;
string connectionString = "";
if (configuration.ConnectionStrings.ConnectionStrings["ConnString"].ConnectionString.Length > 0)
{
connectionString = configuration.ConnectionStrings.ConnectionStrings["ConnString"].ConnectionString;
}
//var connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnString"];
//if (connectionString != null)
//{
//}
return connString;
I am using .net framework 4.0, IIS 7, apppool is .net framework 4.0 and windows 7 machine.
Thanks,
Awadhendra
The web.config has a dedicated section for connection strings, and the code you are using is using the configuration manager to access the connection strings section in the web.config. The problem you have is that you haven't put the connection string in the connection strings section, you have put it in the app settings. Move the connection string out of app settings and put into the connection strings section, or change your code to read it from app settings. Now storing a connection string in app settings was the way it was done in .NET 2.0, but since then (.NET 3.5) there has been a dedicated section made for connection strings.
please refer here
e.g.
<connectionStrings>
<add name="ConnString" connectionString="xxxwhateveritisxxx" />
</connectionStrings>
or code to read it from app settings (if you must have it in app settings, although I wouldn't recommend):
string connectionString = ConfigurationManager.AppSettings["ConnString"];
Can u give a try to this :-
string connString = ConfigurationManager.AppSettings["ConnString"].ToString()
return connString;
It will read the app setting section of your web.config.
I have two ASP.NET vNext Web Applications running with CoreCLR on Azure WebSites, published by the lates Visual Studio 2015 CTP.
When I'm trying to make a call from one application to the second with standard HttpClient code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_webUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent contentPost = new StringContent(request.ToJson(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, contentPost);//.PostAsJsonAsync("api/products", request);
if (response.IsSuccessStatusCode)
{
...
}
}
I get following exception:
WinHttpException: An attempt was made to access a socket in a way forbidden by its access permissions.
System.Net.Http.WinInetProxyHelper.GetProxyForUrl(SafeInternetHandle sessionHandle, Uri uri, WINHTTP_PROXY_INFO& proxyInfo)
HttpRequestException: An error occurred while sending the request.
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
my web.config on the azure websites ftp:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="kpm-package-path" value="..\approot\packages" />
<add key="bootstrapper-version" value="1.0.0-beta2" />
<add key="kre-package-path" value="..\approot\packages" />
<add key="kre-version" value="1.0.0-beta2" />
<add key="kre-clr" value="CoreCLR" />
<add key="kre-app-base" value="..\approot\src\Ingrid.Web" />
</appSettings>
</configuration>
Solution which I found on: https://github.com/sendgrid/sendgrid-csharp/issues/18
it's better to go with RestSharp than HttpClient, and it is indeed working: http://restsharp.org/
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.
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>