Call WCF service remotely - wcf

I have a WCF service that is hosted in IIS and remote database in a location.
I have a client that is working in B location. Each location is away from each other.
The remote database doesn't accept 1433 sql port for remote requests.
I added a WCF service to my web app:
//// WCF Method ////
public SqlDataReader DataReader(string query)
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(RemoteConnection());
con.Open();
cmd = new SqlCommand(query, con);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public string RemoteConnection()
{
var con = new SqlConnection("Data Source=.;Initial Catalog=DBNAME;User ID=sa;Password=abc123abc;");
return con.ConnectionString;
}
I am calling the WCF from remote side like below
WcfWebService srv = new WcfWebService();
GridView1.DataSource = srv.DataReader("SELECT * FROM TABLE);
but I get an error:
The underlying connection was closed: An unexpected error occurred on a receive.
I just want to query remote database via WCF service from remote side. Which methods do I have in this case?

Related

RabbitMQ Java Client Connection Timeout

I am using the same client connection properties for Producer and Consumer. But while I am able to Produce messages to RabbitMQ, getting following error for Consumer side. I have read many solutions all say check out connection properties, firewall etc. But I have working producer.
Consumer side connection codes:
String userName = "myuser"; // not guest
String password = "mypassword"; // not guest
String virtualHost = "/";
String hostName = "one_of_rbmq_ip";
Integer portNumber = 5672;
ConnectionFactory factory = new ConnectionFactory();
// "guest"/"guest" by default, limited to localhost connections
factory.setUsername(userName);
factory.setPassword(password);
factory.setVirtualHost(virtualHost);
factory.setHost(hostName);
factory.setPort(portNumber);
Connection conn = factory.newConnection();
Error gives at last line (conn)
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:81)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:162)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:160)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1216)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1173)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1131)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1294)
at Condumer2.main(Condumer2.java:25)
I have changed my code like following it worked
Address[] addrArr = new Address[]{ new Address("10.28.94.117", 5672)
, new Address("10.28.94.118", 5672)
, new Address("10.28.94.119", 5672)
};
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("rabbitmq");
factory.setPassword("qa");
Connection connection = factory.newConnection(addrArr);
Channel channel = connection.createChannel();

Using WCF in .net 2

I've got a method of connecting and use a WCF method, which is on HTTPS and requires a username and password in .net 4.
Now I need to do the same but within .Net 2 and I can't seem to get it to work. I keep on getting the below error. Can anyone help?
Error
{"The underlying connection was closed: An unexpected error occurred on a receive."}
Inner Exception
{"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
.Net 4 Original Code:
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress ea = new EndpointAddress(wcfURL);
var web = new Gateway.GatewayClient(myBinding, ea);
// var web = new Gateway.GatewayClient();
XMLCrypto crypto = new XMLCrypto();
web.ClientCredentials.UserName.UserName = crypto.DecryptString(username);
web.ClientCredentials.UserName.Password = crypto.DecryptString(password);
web.Open();
web.Inbound("HOLog", message.Trim().Replace("\n", "").Replace(#"\\", ""));
web.Close();
.Net 2 Code
XMLCrypto crypto = new XMLCrypto();
url = "http://..../gateway/gateway.svc";
userName = crypto.DecryptString(userName);
password = crypto.DecryptString(password);
var web = new Gateway.Gateway();
var credentials = new NetworkCredential(userName, password);
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", credentials);
web.Credentials = credentials;
string returnMessage = web.Inbound("LSOA", " ");
After a long trolling over the web and testing different ways of talking to a WCF method, I have found the reason why it does not work.
Currently the WCF is set to use wsHttpBinding and now I know that .net 2, does not support it. My work around was to change the Binding from wsHttpBinding to basicHttpBinding within the Web.config of the WCF.
To do this and not effect anything using the WCF, I have to create a seprate Sub domain that will ref a WCF with the config that has the corrected Binding.
"The wsHttpBinding is not compatible with the ASMX-style web references used in .NET 2.0."
How to consume WCF wsHttpBinding Service in application built in 2.0?

A request to send or receive data was disallowed because the socket is not connected

I am trying to connect to a remote external server using TCP sockets in WCF code
My WCF service is the client which has code using sockets to connect to an external server.
This code sends a request to an external server and receives the server response
int byteCount = 0;
Socket m_socClient;
try
{
string query = "My Request String";
m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse("127:0:0:0");
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, 1234);
EVCommon.Log("COnnecting to" + IPSelected + Port);
m_socClient.Connect(remoteEndPoint);
try
{
if (m_socClient.Connected)
{
EVCommon.Log("Connected to" + IPSelected + Port);
var reQuestToSend = string.Format("POST /ZZZZZ HTTP/1.1\r\nContent-Length:{0}\r\n\r\n{1}", query.Length, query);
byte[] bytesToSend = Encoding.ASCII.GetBytes(reQuestToSend);
byteCount = m_socClient.Send(bytesToSend, SocketFlags.None);
byte[] bytesReceived = new byte[1024];
byteCount = m_socClient.Receive(bytesReceived, SocketFlags.None);
Response271 = Encoding.ASCII.GetString(bytesReceived);
m_socClient.Disconnect(false);
m_socClient.Close(5000);
}
}
catch(Exception ex)
{
EVCommon.Log(ex.Message);
}
}
If I make a windows application with the same client code to connect to the remote server, it is successful. I am able to connect, send and receive
This error occurs only when I bring WCF into the picture. The code fails at if(m_socket.Connected). So it is not able to connect successfully.
A request to send or receive data was disallowed because the socket
is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
Thank you
The difference is that the windows applications runs in the identity of the logged in user and the WCF service runs in the identity of the application pool.
What is probably happening is that the application pool is running as NETWORK SERVICE which does not have the right to open a port.
Try changing the identity of the app pool to your user to check if this is the problem.

Accessing SQL Server using Integrated Security from an ASMX run in authenticated user context

I have a Webservice running in Windows Authentication mode.
I have an application to text the asmx connections:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
BasicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress("http://xyzts/Service.asmx");
WS_SPIL.ServiceSoapClient client = new WS_SPIL.ServiceSoapClient(basicHttpBinding, endpoint);
client.ClientCredentials.Windows.AllowedImpersonationLevel = Sytem.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
I execute the folloing code (on the ASMX): User.Identity.Name which returns my windows AD login.
So far so good.
Now i want to connect to the database with the login in user.
But i get the error message that the current user (the IIS user) doesn't have the privilige to connect to the sql server.
try
{
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.DataSource = "sqlservername";
csb.InitialCatalog = "DBName";
csb.IntegratedSecurity = true;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = csb.ToString();
conn.Open();
conn.Close();
return "ok";
}
catch (Exception ex)
{
return ex.ToString();
}
This sounds like a case of the "double-hop problem". Basically, you can't get SQL Server to use the impersonated credentials unless you have Kerberos implemented.

Cassia using impersonation and wcf

I am trying to use Cassia with a WCF web service I keep getting "An existing connection was forcibly closed by the remote host". When I try it on a test console application it works fine. This is the code I am using from a sample I found. Anyone ever do this?
public List<ITerminalServicesSession> getTermminalServerSessions(string serverName)
{
ConnectionDetails connection = new ConnectionDetails();
connection.Domain = "DOMAIN";
connection.Server = serverName;
connection.Username = "USER";
connection.Password = "PASSWORD";
using (ImpersonationHelper.Impersonate(connection))
{
using (var server = GetServer(connection.Server))
{
server.Open();
return server.GetSessions().ToList();
}
}
}