How to connect with TcpClient in C# from behind a proxy? - c#

I'm behind a proxy and can't connect with TcpClient to GMail's POP3. I get the following error:
System.Net.Sockets.SocketException (0x80004005): No such host is known
Any clues?
Code:
var tcpClient = new TcpClient();
try
{
tcpClient.ReceiveTimeout = 60000;
tcpClient.SendTimeout = 60000;
tcpClient.Connect("pop.gmail.com", 995);
output.AppendLine("Connection OK!");
}
catch (SocketException e)
{
output.AppendLine(e.ToString());
}
finally
{
tcpClient.Close();
}
app.config (proxy is set up in Internet Explorer):
<?xml version="1.0"?>
<configuration>
<system.net>
<defaultProxy>
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

Nothing. Not possible. It looks like:
Your company DNS does not include public DNS information.
So your comptuers ask a proxy which asks an outside DNS.
This heavily implies you also have no possible routing
Without Routing no TCP Connection is possible anyway. By design.
Possible workarounds:
Use a SOCKS proxy. Unlikely to exist.
Ask your IT Department - the proper way to solve this inot to bypass the firwewall, but to send the emails using the proper channel (internal SMTP Service).
If the proper way is using gmail, some not too smart person (i.e. a manager) put you into a corner. Then they have to open a TCP connection possibiltiy for you and make the public DNS information available for your computer.
At the end, you can have it both ways - either you force all clients through a proxy, or you have outgiong direct TCP connections.

Related

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>

Unable to connect to SQL Server in a C# program but system is able to connect

I am attempting to connect to a SQL Server 2014. A week or so ago it seemed to work, now it does not. The systems team did upgrade recently to 2014. What's weird is that I'm able to use SQL Server Management Studio to connect, ODBC, and telnet. It's just an issue with C#. Additionally, this exact program runs on another server as compiled/release. It's just not running on my system using debug (or fully compiled/release).
I checked through the documentation -- disabled all the firewalls, had STP check the server... nada
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
My C# code:
namespace SQLTest
{
class Program
{
static void Main(string[] args)
{
string connectionString = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;
string OrganizationSqlStr = #"SELECT * FROM school";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(OrganizationSqlStr, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.Write(reader["School_ID"] + " | ");
Console.Write(reader["title"] + "\n\r");
}
Console.ReadKey();
}
}
}
app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="SQLConn"
connectionString="server=SERVER;database=DATABASE;uid=USERNAME;password=PASSWORD"/>
</connectionStrings>
</configuration>
I would try to force the .net program to use tcp
http://www.connectionstrings.com/sqlconnection/
find the section labeled
Connect via an IP address
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;
Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Network Library=DBMSSOCN is the magic sugar.
see also:
What does DBMSSOCN stand for?
APPEND:
If that still produces an error, then something is probably blocking your access.
Here is the in-general tool to determine.
https://www.microsoft.com/en-us/download/details.aspx?id=24009
Specify the IP and Port Number, and it'll tell you it the port is blocked or filtered.
My personal history is that we had a new router installed that was filtering the port number and stopping my sql server access. The portqueryui revealed the issue. PortQry works "outside" of sql server, so the network guys can't blame sql-server for the lack of connectivity.
APPEND
The OP posted this in the comments of this answer
portqry.exe -n db-alexandrite.domain.edu -e 1433 -p TCP exits with return code 0x00000000
This is your problem. "db-alexandrite.domain.edu" is not resolving.
You can fix it by either changing "db-alexandrite.domain.edu" to be the actual IP address of that machine.
OR figuring out why "db-alexandrite.domain.edu" does not resolve.
Ask your team to check whether they have enabled all network protocols the server. Either tcp or named pipe protocol should be enabled.
This error is helpful:
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
It seems that your connection string, or SqlConnection by default, wants to use the named pipe provider to connect to the SQL server.
Given that your server was recently changed/upgraded, it's certainly possible that the named pipe provider was disabled. It's a common mistake.
You can force your connection to use simple TCP instead of named pipe by altering your connection string:
server=tcp:mysqlserver.domain.com;...
I recently set up a new test server with sql and went through the usual checklist.
Make sure remote connections are allowed.
Make sure you select integrated mode is using both Windows and Sql Server logins.
Make sure port 1440/your port and tcp/your protocol is enabled in sql configuration manager.
Make sure your firewall allows incoming and outgoing.
Make sure your connection string is valid.
These 4 steps will eliminate most connection issues. However, on new servers, the Windows Defender will block by default. I had to disable private and public profiles in defender as it was blocking. Since we do not use windows defender this was ok. However, if you rely on it then you need to create a rule.
<add name="SQLConn" connectionString="Data Source=SERVER;Integrated Security=False;User ID=USER;Password=PASSWORD;Initial Catalog=DATABASE" providerName="System.Data.SqlClient" />

Connect to TFS from C# via HTTP proxy

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.

Entity framework 4 Underlaying provider failed on Open

I am trying to connect to the database but I am getting this exception:
A network-related or instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify that the instance name
is correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I've googled a lot, but I could not find the answer.
Here's my configuration:
I use MS SQL Server 2008 Express. Both Sql Server and Sql Server Browser use my account (I am an administrator). I've also used local system and local service. Without success.
Here is my connectionstring in app.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="EventManagerEntities" connectionString="metadata=res://*/Entities.RelationModel.csdl|res://*/Entities.RelationModel.ssdl|res://*/Entities.RelationModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=martijn-laptop\sql2008;Initial Catalog=EventManager;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
I've also tried to use the sql server username and password, also without success.
I am using winforms. What else can I try?
When I check netstat -an I get this:
TCP 0.0.0.0:1433 0.0.0.0:0 LISTENING
TCP [::]:1433 [::]:0 LISTENING
I don't think this is correct, right? But how do I set it right?
It cannot find instance/server. Telnet the 1433th or the configured port of martijn-laptop\sql2008 to verify its accessible
Go into the SQL Server Configuration Manager and make sure you have the protocols you want to use enabled under "SQL Server Network Configuration" > "Protocols for Sql2008"
From the error it seem like there is connectivity to database issue. Assuming this solution has been working elsewhere have you setup and connected to a different database?
Is so validate that the code generated with edmx has the correct default database connection name or that you are overriding it:
var context = new EventManagerContext("EventManagerEntities");
Or whatever the correct systax for EF is.

How to send mail using IIS 5.1 in WinXP?

I have this code to send mail:
public bool SendMail(MailMessage message)
{
message.From = new MailAddress(AppProperties.FromMailAddress, AppProperties.FromDisplayName);
SmtpClient smtp = new SmtpClient { EnableSsl = AppProperties.EnableSsl };
try
{
smtp.Send(message);
return true;
}
catch (Exception)
{
return false;
}
}
and have configured web.config to send mail using IIS 5.1 in localhost with this (as suggested by the answers):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="localhost"
userName=""
password=""
defaultCredentials="false"
port="25" />
</smtp>
</mailSettings>
</system.net>
What do I have to do to send mail with my IIS 5.1 in Windows XP? Is possible to do it? I guess yes, as you say, since I don't get any exception, but I don't receive it on destination. If I should put an user and a password, wich must be?
You should first install SMTP server (Windows Components > IIS > SMTP Service) and then configure it to enable relaying.
IIS > Default SMTP Server > Properties
Access > Authentication
Access Control > Anonymous Access - Checked
Relay Restrictions > Relay > Select - Only the list below > Add > 127.0.0.1
Sure it's possible, you will no longer need to use SSL however. In the config file, your port will probably be 25, you may or may not need username/password, and of course your hostname will change.
Also make sure you install the SMTP components along with IIS.
yes you can send it this way :D (but i think you need to use port 25) smtp class is part of .net

Categories