Connect to TFS from C# via HTTP proxy - c#

I'm writing a small C# reporting application for TFS 2012.
TFS server is remote and can be accessed only via HTTP proxy server in the network, as firewalls block direct access.
The proxy is configured in Internet Explorer, so I can open TFS URL in IE, and also it's automatically used by Visual Studio when working with TFS.
The problem is that my application ignores IE proxy settings and tries to connect to TFS server directly (I see this in Wireshark), so it fails after a timeout due to firewalls.
Here is the code I use:
Uri TfsCollectionURL = new Uri("...");
NetworkCredential credential = new System.Net.NetworkCredential(Username, Password, Domain);
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(TfsCollectionURL, credential);
collection.EnsureAuthenticated();
ICommonStructureService projectService = collection.GetService<ICommonStructureService>();
foreach (ProjectInfo project in projectService.ListProjects())
{
...
}
Application fails at .EnsureAuthenticated() with exception:
TF400324: Team Foundation services are not available from server ...
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond ...
It does work from another subnet where direct access to the TFS server is allowed.
QUESTION:
How can I use HTTP proxy in my C# application for connection to TFS?

Try adding an App.config file to set the default proxy with the following code:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>
</system.net>
</configuration>

You can directly set credentials to pass the proxy:
WebProxy p = new WebProxy("proxyserver.domain.com:8080", true);
p.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = p;
In my scenario we have a subnet for development and those accounts/machines are not allowed to access the internet. Therefore we need to enter the upper domain proxy and those domain credentials to get access to internet.

Related

Call HttpListener from external IP

I have a very simple API in C# for test purposes. The API is created in a Windows Forms project
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
LogUtils.appendInfo("Listening for connections on: " + url);
//Handle requests
Task listenTask = HandleIncomingConnections();
listenTask.GetAwaiter().GetResult();
If I call http://localhost:8080/ I get response from API.
The problem is that if I call the API from another PC using the external IP address http://ExternalIp:8080/
I get this error:
Bad Request - Invalid Hostname HTTP Error 400. The request hostname is
invalid
What I have tried:
I have put in the firewall a rule for port 8080 in incoming connections.
I have tested with the ISS server that brings Windows Server 2019 off and on.
I have created a 'applicationhost.config 'file in 'C:\Users\myUser\source\repos\myProyect.vs\proyectname\config' for <'binding protocol="http" bindingInformation=":8080:" /> because my project not have applicationhost.config file.
As #PanagiotisKanavos commented I can not use "localhost" in "listener.Prefixes.Add" for external request.
Solved by:
http://*:8080/
And run Visual Studio as administrator.

Unable to connect to Azure DevOps Repo from C#

I have a web api which connects to azure devops repo and retrieves some files to do some operations. Problem is, I am unable to connect from the web service. I get the error "SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond". However, the same code runs perfectly fine in a console application.
VssConnection connection = new VssConnection(new Uri("https://dev.azure.com/org"), new VssBasicCredential(string.Empty, "psa"));
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>(); //error here
string projectName = "Project";
string scopePath = $"$/{projectName}/";
List<TfvcItem> items = tfvcClient.GetItemsAsync(scopePath: scopePath, recursionLevel: VersionControlRecursionType.OneLevel).Result;
Console.WriteLine("Connection Established");
Strangely, once I establish connection through the console application, if I run the same code through the web service, it works. I turned off firewall and checked but nothing works. Been stuck for so long!
After struggling to make it work for few days, it worked fine after enabling the default proxy in web.config:
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>

How to set certificate in C# Win Application

Im using a webservice in my program.
this is the web service : "https://X.Y.Z.W/ib/ws/openbill.asmx?wsdl"
It works as local. when I write this on Internet Explorer, I can see the proper page after selecting "Continue to this website (not recommended)" in this attachment :
but when I want to access to this, in my c# code, I get this exception :
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
So how can I access this in my c# program?
I think you should first acquire a certificate file, and then use it in your code. For example, to set it for a SMTPClient object:
string certificate = "Certificate.cer";
X509Certificate cert = new X509Certificate2(certificate);
MailMessage message = new MailMessage(from, to);
SmtpClient client = new SmtpClient(server);
client.ClientCertificates.Add(cert);
client.Send(message);
The web service that you are trying to connect to is using SSL/TLS. When you open the web service via internet explorer, it is giving you a warning that it cannot validate the certificate of the web service.
This has many reasons, and I guess in your case it is that the certificate that the web service is using is not for X.Y.Z.W.
Another reason could be that your machine does not trust the root issuer of the web service certificate. But from the error message that you have, I don't think this is the case.
You can view the certificate in IE by click on "Continue on this web site..", and the clicking on "Certificate Error", and the "View certificates".
From there, you will view the certificate. Go to details, and look for DNS Name inside Subject Alternative Name.
The DNS name is the name of the machine that the web service certificate was given for.
I guess in your case it will not be X.Y.Z.W.
Is the web service yours? can you obtain a different certificate for it? If so, can make sure you create a certificate that has the correct DNS name.
As a last resort, you can skip certificate validation from your code (this is not recommended). Take a look at this question.

Credentialed Service Receives 401 Unauthorized from EWS

I have written a windows service in C# to automatically poll an exchange mailbox using EWS.
On my development machine, which is connected to the exchange server network via VPN, it works perfectly.
On the target server the EWS is returning:
Request failed. The remote server returned an error: (401) Unauthorized.(The remote server returned an error: (401) Unauthorized.)
On the same server, I can connect to the EWS URL via a browser using the same credentials as are being provided to the service.
The credentials are provided in the app.config file, and I have triple checked that they are the same on the target server as my development machine.
What could be causing this?
Well as it turned out the issue was that this
_ews.Credentials = new NetworkCredential(Settings.Username, Settings.Password); // Username in the form "domainname\username"
should have been this
_ews.Credentials = new NetworkCredential(Settings.Username, Settings.Password, Settings.Domain); // Domainname and username separate
For some reason the first line worked externally over a VPN but not internally on the domain network itself.

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I am using the following code which is working on local machine, but when i tried the same code on server it throws me error
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection
failed because connected host has failed to respond
Here is my code:
WebClient client = new WebClient();
// Add a user agent header in case the
// requested URI contains a query.
//client.Headers.Add ("ID", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead("http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
Console.WriteLine(s);
data.Close();
reader.Close();
I am getting error on
Stream data = client.OpenRead("http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID);
is it due any firewall setting?
I had a similar problem and had to convert the URL from string to Uri object using:
Uri myUri = new Uri(URLInStringFormat, UriKind.Absolute);
(URLInStringFormat is your URL)
Try to connect using the Uri instead of the string as:
WebClient client = new WebClient();
client.OpenRead(myUri);
setting the proxy address explicitly in web.config solved my problem
<system.net>
<defaultProxy>
<proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false"/>
</defaultProxy>
</system.net>
Resolving the “TCP error code 10060: A connection attempt failed…” while consuming a web service
I know this ticket is old, but I just ran into this issue and I thought I would post what was happening to me and how I resolved it:
In my service I was calling there was a call to another web service. Like a goof, I forgot to make sure that the DNS settings were correct when I published the web service, thus my web service, when published, was trying to call from api.myproductionserver.local, rather than api.myproductionserver.com. It was the backend web service that was causing the timeout.
Anyways, I thought I would pass this along.
I know this post was posted 5 years ago, but I had this problem recently. It may be cause by corporate network limitations. So my solution is letting WebClient go through proxy server to make the call. Here is the code which worked for me. Hope it helps.
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
WebProxy proxy = new WebProxy("your proxy host IP", port);
client.Proxy = proxy;
string sourceUrl = "xxxxxx";
try
{
using (Stream stream = client.OpenRead(new Uri(noaaSourceUrl)))
{
//......
}
}
catch (Exception ex)
{
throw;
}
}
Adding the following block of code in web.config solves my problem
<system.net>
<defaultProxy enabled="false" >
</defaultProxy>
</system.net>
In my case I got this error because my domain was not listed in Hosts file on Server.
If in future anyone else is facing the same issue, try making entry in Host file and check.
Path : C:\Windows\System32\drivers\etc
FileName: hosts
Is the URL that this code is making accessible in the browser?
http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID
First thing you need to verify is that the URL you are making is correct. Then check in the browser to see if it is browsing. then use Fiddler tool to check what is passing over the network. It may be that URL that is being called through code is wrongly escaped.
Then check for firewall related issues.
I had this problem. Code worked fine when running locally but not when on server.
Using psPing (https://technet.microsoft.com/en-us/sysinternals/psping.aspx) I realised the applications port wasn't returning anything.
Turned out to be a firewall issue. I hadn't enabled my applications port in the Windows Firewall.
Administrative Tools > Windows Firewall with Advanced Security
added my applications port to the Inbound Rules and it started working.
Somehow the application port number had got changed, so took a while to figure out what was going on - so thought I'd share this possibility in case it saves someone else time...
I have resolved this below issue
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
Solution
We need to configured proxy setting in code. my scenario using Web.config file
Added Proxy address as below
<system.net>
<defaultProxy>
<proxy proxyaddress="http://XXXXX:XXXX" bypassonlocal="True"/>
</defaultProxy>
</system.net>
Also added proxy credential using below code NetworkCredential - I have used my local credential here.
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Credentials = new NetworkCredential("XXXX", "XXXXX");
webReq.Proxy.Credentials = new NetworkCredential("XXXX", "XXXX");
It works for me!
First Possibility: The encrypted string in the Related Web.config File should be same as entered in the connection string (which is shown above)
And also, when you change anything in the "Registry Editor" or regedit.exe (as written at Run), then after any change, close the registry editor and reset your Internet Information Services by typing IISRESET at Run. And then login to your environment.
Type Services.msc on run and check:
Status of ASP.NET State Services is started. If not, then right click on it, through Properties, change its Startup type to automatic.
Iris ReportManager Service of that particular bank is Listed as Started or not. If its Running, It will show "IRIS REPORT MANAGER SERVICE" as started in the list. If not, then run it by clicking IRIS.REPORTMANAGER.EXE
Then Again RESET IIS
I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.
It might be issue by proxy settings in server. You can try by disabling proxy setting,
<defaultProxy enabled="false" />
Íf above solutions don't work for your case. May be your request drop by firewall. Check firewall settings.

Categories