RabbitMQ Connection Error " None of the specified endpoints were reachable" - c#

I installed rabbitmq service on the server and on my system.
I want to use RPC pattern:
var factory = new ConnectionFactory() {
HostName = "158.2.14.42",
Port = Protocols.DefaultProtocol.DefaultPort,
UserName = "Administrator",
Password = "#server#",
VirtualHost = "/"
ContinuationTimeout = new TimeSpan(10, 0, 0, 0)
};
connection = factory.CreateConnection();
I have an error on creating connection with this message:
None of the specified endpoints were reachable
When I use it on localhost instance of the server it works, but when I create the connection from local to that server,it returned the error.
It not work with local ip and username and password of the my local computer.
Can anyone help me?

Thank you all.
As this :
https://stackoverflow.com/questions/4987438/rabbitmq-c-sharp-connection-trouble-when-using-a-username-and-password
After I installed RabbitMQ, I enabled management tools at the server and on my local computer with this:
rabbitmq-plugins enable rabbitmq_management
Then I restarted RabbitMQ service from services.msc
I could see the rabbitmq management at http://localhost:15672
I loginned to rabbit management with user:guest and pass:guest
I added my favorite user pass with administrator access, so it worked.

I was also facing the same issue and later realized I have to open both ports i.e. 15672 and 5672.
The below command works for me in the docker container model.
docker run -it --rm --name mymq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
Code snippet:
var factory = new RabbitMQ.Client.ConnectionFactory
{
Uri = new Uri("amqp://guest:guest#localhost:5672/")
};
or
var factory = new ConnectionFactory() { HostName = "localhost" };

Do not use guest. Create your own account and password, and in http://localhost:15672/#/users , ensure "can access virtual hosts " is "/"
var factory = new ConnectionFactory() {
HostName = "192.168.1.121",
Port = 5672,
UserName = "fancky",
Password = "123456"
};

In our case it was an assembly binding failure of System.Threading.Tasks.Extensions, our exception logger was not logging the InnerException
Exception information:
Exception type: FileLoadException
Exception message: Could not load file or assembly 'System.Threading.Channels, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at RabbitMQ.Client.Framing.Impl.AutorecoveringConnection..ctor(ConnectionFactory factory, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) in /_/projects/RabbitMQ.Client/client/api/ConnectionFactory.cs:line 494
Very poor misleading error message.

it means that the client can't reach the server 158.2.14.42 and default vhost /.
Maybe a firewall configuration

By default as you say RabbitMQ will listen on 5672 but this can be changed, if you have a look at your config (on the MQ server) you should find a section:
rabbit.tcp_listeners
which will detail the port being used. Check it's what you think it is.
Also, are you using IPv4 or IPv6? you may need to have additional config to support both.
Have a read of this:
https://www.rabbitmq.com/networking.html

1) Open RabbitMQ Command Promp
2) Change path to "C:\Program Files\RabbitMQ Server\rabbitmq_server-3.6.10\sbin" where rabbitmq_server installed.
3) Run following commamd :
rabbitmq-plugins enable rabbitmq_management
If Firewall has blocked it, then popup display. Allow Firewall for this.
now you can access in browser.

I've been experiencing this very issue, and in the end it was just about having provided the URI as lowercase, while the name of the machine was uppercase.
As it took a couple of hours to figure it out, I thought it might help someone else.

I created a small application using .netcore and rabbitmq and created the image in docker for both of them using below docker-compose code -
version: '3'
services:
rabbitmq:
container_name: rabbitmq
hostname: "rabbitmq"
image: rabbitmq:3-management
ports:
- "5672:5672"
- "15672:15672"
volumes:
- rabbitmq:/rabbitmq
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 30s
timeout: 10s
retries: 5
isp_hub:
depends_on:
- rabbitmq
build:
context: .
dockerfile: Dockerfile
ports:
- "9090:80"
volumes:
rabbitmq:
after running the cmd docker-compose up the image is created and container is started and i am using Jmeter client to hit the container .net code is working but while trying to pass the data in queue getting below exception -
"log":"info: Microsoft.Hosting.Lifetime[0]\r\n","stream":"stdout","time":"2022-04-04T08:25:22.6109672Z"}
{"log":" Application is shutting down...\r\n","stream":"stdout","time":"2022-04-04T08:25:22.6109672Z"}
{"log":"info: Microsoft.Hosting.Lifetime[0]\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4488984Z"}
{"log":" Now listening on: http://[::]:80\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4488984Z"}
{"log":"info: Microsoft.Hosting.Lifetime[0]\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":" Application started. Press Ctrl+C to shut down.\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":"info: Microsoft.Hosting.Lifetime[0]\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":" Hosting environment: Production\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":"info: Microsoft.Hosting.Lifetime[0]\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":" Content root path: C:\app\r\n","stream":"stdout","time":"2022-04-04T08:25:38.4498991Z"}
{"log":"fail: Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher[8]\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" Failed to invoke hub method 'SendToMessageBroker'.\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" ---\u003e System.AggregateException: One or more errors occurred. (Connection failed)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" ---\u003e RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" ---\u003e System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.\u003c\u003ec.\u003c.cctor\u003eb__4_0(Object state)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" --- End of stack trace from previous location ---\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.TcpClientAdapter.ConnectAsync(String host, Int32 port)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" --- End of inner exception stack trace ---\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func2 socketFactory, TimeSpan timeout, AddressFamily family)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"} {"log":" at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Func2 socketFactory, TimeSpan timeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"} {"log":" at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, Func2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func2 selector)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"} {"log":" --- End of inner exception stack trace ---\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"} {"log":" at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func2 selector)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.Framing.Impl.AutorecoveringConnection.Init(IEndpointResolver endpoints)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" --- End of inner exception stack trace ---\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.ConnectionFactory.CreateConnection(String clientProvidedName)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at RabbitMQ.Client.ConnectionFactory.CreateConnection()\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at ISP_Hub.HubConfig.CenterHub.SendToMessageBroker(String requestData) in C:\src\ISP_Hub\HubConfig\CenterHub.cs:line 38\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at Microsoft.Extensions.Internal.ObjectMethodExecutor.\u003c\u003ec__DisplayClass33_0.\u003cWrapVoidMethod\u003eb__0(Object target, Object[] parameters)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
{"log":" at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher1.ExecuteMethod(ObjectMethodExecutor methodExecutor, Hub hub, Object[] arguments)\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"} {"log":" at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher1.\u003c\u003ec__DisplayClass16_0.\u003c\u003cInvoke\u003eg__ExecuteInvocation|0\u003ed.MoveNext()\r\n","stream":"stdout","time":"2022-04-04T08:26:55.7889752Z"}
rabbitmq connection code -
public void SendToMessageBroker(string requestData)
{
var trace = JsonConvert.DeserializeObject(requestData);
// string rabbitMqUrl = "127.0.0.1";
// var factory = new ConnectionFactory() { HostName = "172.24.17.225", Port = 5672 };
//var factory = new ConnectionFactory
//{
// HostName = rabbitMqUrl,
// UserName = "guest",
// Password = "guest",
// Port = AmqpTcpEndpoint.UseDefaultPort,
// VirtualHost = "/",
// RequestedHeartbeat = new TimeSpan(60),
// Ssl = { ServerName = rabbitMqUrl, Enabled = false }
//};
var factory = new RabbitMQ.Client.ConnectionFactory
{
Uri = new Uri("amqp://guest:guest#localhost:5672/")
};
using var conn = factory.CreateConnection();
using var channel = conn.CreateModel();
RabbitMQPublisher.Publish(channel, trace);
Clients.All.SendAsync("test");
channel.Close();
conn.Close();
Debug.WriteLine("Show Message: " + requestData);
}
i am new to docker . please help me to understand the issue and how to resolve it

Don't know if it helps you but it happen after update RabbitMQ.Client from 5.1.2 to 5.2.0 for .net 4.6.1.
If you rise target framework to 4.8 it goes through.

Misleading error. The local version works ok but the remote server didn't. Turned out I did not supply the credentials i.e. username and password which are mandatory for remote server. Local server happily connects without them.

Related

Blazor connect to service with external database

I am currently trying with Blazor server to get a list. But when the list is called via the service I just get an error:
Error: System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call.
---> MySqlConnector.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, MySqlConnection connection, Int32 startTickCount, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in //src/MySqlConnector/Core/ServerSession.cs:line 433
at MySqlConnector.Core.ConnectionPool.ConnectSessionAsync(MySqlConnection connection, String logMessage, Int32 startTickCount, IOBehavior ioBehavior, CancellationToken cancellationToken) in //src/MySqlConnector/Core/ConnectionPool.cs:line 363
i am currently calling in the Program.cs:
builder.Services.AddScoped<Organization>().AddDbContext<OrganizationDbContext>().AddEntityFrameworkMySql();
then i try to inject the Organization.
in the Organization there is:
public Organization()
{
this.organizationDBContext = new OrganizationDbContext();
}
so the funny part about all that is in the unit test the external project works just perfect(also if i call new Organization in the OnInitializedAsync sometime it works sometime it doesn't idk why).
My unit test which works perfectly fine:
Organization org = new Organization();
var customers = org.Customers.GetCustomers().ToList();
i get a list with the customers, how should i do this in blazor server?
Thanks!
For all of you who have the same error, this is the right way, keep an eye on your docker environment^^

Unable to fetch azure key vault secret from dapr as daprClient.GetSecretAsync function returning error

Expected Behavior
Working fine when access with dapr API using postman to access key vault secret.
Should fetch the secret from azure key vault using c sharp dapr client SDK.
Actual Behavior
Azure key vault with service principal YAML:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: azuresecretstore
namespace: default
spec:
type: secretstores.azure.keyvault
version: v1
metadata:
- name: vaultName
value: "kv-xxxx-dev-xxx"
- name: azureTenantId
value: "5xxxxaf-bxx8-4xxe4-xxxc-a0fxxxxc36"
- name: azureClientId
value: "e01xxxxf-8xxx-xxxx-9axx-3f12xxxxce5"
- name: azureClientSecret
value : "aCK8Q~xxxxxxxxxxxxxxLixFKe1ZD__u6a_v"
When executing daprClient.GetSecretAsync function in c# web api code getting below error
Dapr.DaprException
HResult=0x80131500
Message=Secret operation failed: the Dapr endpoint indicated a failure. See InnerException for details.
Source=Dapr.Client
StackTrace:
at Dapr.Client.DaprClientGrpc.d__48.MoveNext()
at Program.<$>d__0.MoveNext() in C:\Users\DmonteN\source\repos\touchstone-svc-template\src\Touchstone.Api\Program.cs:line 120
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
RpcException: Status(StatusCode="Unavailable", Detail="Error connecting to subchannel.", DebugException="System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at Grpc.Net.Client.Balancer.Internal.SocketConnectivitySubchannelTransport.TryConnectAsync(CancellationToken cancellationToken)")
Steps to Reproduce the Problem
Install dapr, configure azure key vault yaml file.
Run dapr side car engine
Verify if you are able to fetch the secret using dapr secret API in postman
If yes, then execute below code in c sharp
// Create Dapr Client
var daprClient = new DaprClientBuilder().UseHttpEndpoint("http://127.0.0.1:50001/").UseJsonSerializationOptions(default).Build();
// Add the DaprClient to DI.
builder.Services.AddSingleton(daprClient);
var noProxy = Environment.GetEnvironmentVariable("no_proxy");
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken cancellationToken = source.Token;
//Using Dapr SDK to invoke a method
var metadata = new Dictionary<string, string> { ["version_id"] = "3" };
var secret = await daprClient.GetSecretAsync("azuresecretstore", "appcs-id-Primary", metadata, cancellationToken); <= Getting error at this line
Console.WriteLine($"Result: {string.Join(", ", secret)}");
Have you set up Key Vault access policies to allow your Web app to read secrets from KV?
Looks like no access policies have been set in KV which is why connection was actively refused.
Check this link on how to setup access policies in KV to allow access from a Web app : https://learn.microsoft.com/en-us/azure/key-vault/general/tutorial-net-create-vault-azure-web-app#configure-the-web-app-to-connect-to-key-vault

Siemens OPC UA and .NET C# client can not connect to server?

I tryed to connect to OPC UA server using the client provided on this page: https://support.industry.siemens.com/cs/document/42014088/programming-an-opc-ua-net-client-with-c%23-for-the-simatic-net-opc-ua-server?dti=0&lc=en-US . Connection to OPC UA server using the Siemens OPC Scount v10 works fine. When connecting to the OPC UA server using client provided in the article, I get this message:
Could not open UA TCP request channel.
Stack trace of the exception is this:
Server stack trace:
at Opc.Ua.Bindings.UaTcpRequestChannel.OnEndOpen(IAsyncResult result)
at Opc.Ua.Bindings.UaTcpRequestChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Opc.Ua.ISessionChannel.CreateSession(CreateSessionMessage request)
at Opc.Ua.SessionChannel.CreateSession(CreateSessionMessage request)
at Opc.Ua.SessionClient.CreateSession(RequestHeader requestHeader, ApplicationDescription clientDescription, String serverUri, String endpointUrl, String sessionName, Byte[] clientNonce, Byte[] clientCertificate, Double requestedSessionTimeout, UInt32 maxResponseMessageSize, NodeId& sessionId, NodeId& authenticationToken, Double& revisedSessionTimeout, Byte[]& serverNonce, Byte[]& serverCertificate, EndpointDescriptionCollection& serverEndpoints, SignedSoftwareCertificateCollection& serverSoftwareCertificates, SignatureData& serverSignature, UInt32& maxRequestMessageSize)
at Opc.Ua.Client.Session.Open(String sessionName, UInt32 sessionTimeout, IUserIdentity identity, IList`1 preferredLocales)
at Opc.Ua.Client.Session.Open(String sessionName, IUserIdentity identity)
Any help would be appreciated. OPC UA server runs on Siemens Simatic HMI TP700 Comfort. Configuration on the OPC UA server is default.
After andrewcullen tip, we are getting the below log in the tracelog.txt file and error when catching the exception that says
An unexpected error occurred while connecting to the server.
PID:4196 ************************* Logging started at 02/03/2016 07:41:34 *************************
4196 - 07:41:38.742 GetEndpoints Called. RequestHandle=1, PendingRequestCount=1
4196 - 07:41:38.992 SECURE CHANNEL CREATED [TcpClientChannel UA-TCP 1.00.238.1] [ID=12752] Connected To: opc.tcp://xxx.xxx.xxx.xxx:4870/
4196 - 07:41:39.008 TCPCLIENTCHANNEL SOCKET CONNECTED: 00000698, ChannelId=12752
4196 - 07:41:39.008 SECURE CHANNEL CREATED [Opc.Ua.ChannelBase WCF Client 1.00.238.1] [ID=] Connected To: opc.tcp://xxx.xxx.xxx.xxx:4870/
4196 - 07:41:39.101 GetEndpoints Completed. RequestHandle=1, PendingRequestCount=0
4196 - 07:41:39.132 TCPCLIENTCHANNEL SOCKET CLOSED: 00000698, ChannelId=12752
4196 - 07:41:44.230 Writing rejected certificate to directory:
4196 - 07:41:59.694 CreateSession Called. RequestHandle=1, PendingRequestCount=1
4196 - 07:42:13.672 TCPCLIENTCHANNEL SOCKET CLOSED: 000007C0, ChannelId=0
4196 - 07:42:13.750 CreateSession Completed. RequestHandle=1, PendingRequestCount=0
I got the answer from the Siemens official support:
The application was not tested with Comfort Panel. The code e.g. contains Block Read and Block Write which is not supported from the Panel Server.
So this application will not work.
This Siemens UaClient uses a library 'ClientAPI' which extends the OPC Foundation's Opc.Ua.Core and Opc.Ua.Client. ClientAPI has a lot of nice Helper functions to simplify connecting and subscribing. However, I see in the code for Connect(string Url) that it is using the original WCF-style channel. And your stack trace is showing the WCF types are throwing an exception that is hard to diagnose. I would change two things:
First configure tracing to write to a file. In ClientAPI, find Helpers.CreateClientConfiguration() and add
// add trace config before calling validate
configuration.TraceConfiguration = new TraceConfiguration {
OutputFilePath="tracelog.txt",
DeleteOnLoad = true,
TraceMasks = Utils.TraceMasks.All };
configuration.Validate(ApplicationType.Client);
Second, upgrade the channel type used to connect. In ClientAPI, find Server.Connect(string url) and modify the middle as shown:
// Initialize the channel which will be created with the server.
// SessionChannel channel = SessionChannel.Create(
// configuration,
// endpointDescription,
// endpointConfiguration,
// bindingFactory,
// clientCertificate,
// null);
ITransportChannel channel = WcfChannelBase.CreateUaBinaryChannel(
configuration,
endpointDescription,
endpointConfiguration,
clientCertificate,
configuration.CreateMessageContext());
// Wrap the channel with the session object.
// This call will fail if the server does not trust the client certificate.
// m_Session = new Session(channel, configuration, endpoint);
m_Session = new Session(channel, configuration, endpoint, clientCertificate);
Edit 2/4:
From the tracelog you might find certificate errors. When creating a new session, the client and server both provide and validate each others certificate. By default, UaClient is retrieving it's cert from the windows store LocalMachine\My (aka Personal). The api generates this cert during it's first run, (which requires the first run as administrator) ( to see this cert, run 'certlm.msc').
On the server machine, the server will validate the client's cert, by checking if it matches the certs in its 'TrustedPeerList'. Servers usually use a directory to store the trusted certs. If the client cert is not trusted, the server will copy the client's cert to a 'RejectedCertificates' directory. You are required to copy the cert you find in 'RejectedCertificates' to the trusted cert directory.
Back on the client machine, the client will validate the server's cert. This client uses a windows store for validation 'LocalMachine\My' (aka Personal).
Instead of using a 'Rejected' directory, the client registers an event handler that opens a message box, asking if you wish to accept the server's cert. If you choose to accept, the client sets the eventArg e.Accept = true; To suppress the message box, the server's cert should be imported into the client's 'LocalMachine\My' (aka Personal) using the tool 'certlm.msc'.
Try to ping the server with DNS name. If the server is not accessible the Hosts file in C:\Windows\System32\drivers\etc... must be edited. Open the notepad as administrator, then open the Hosts file and enter the mapping of IP Address to the host name as follows:
xxx.xxx.xxx.xxx host name

WCF SslStreamSecurity DNS Identity Check failing for just 4.6 framework

I am working on developing a new binding for a Wcf service that is hosted in IIS, I thought I got everything working, but it turns out that the client only works when it is targetting .Net framework 4.5, if I change it to target 4.6 then I get the following error when I try to open a connection:
System.ServiceModel.Security.MessageSecurityException occurred
HResult=-2146233087
Message=The Identity check failed for the outgoing message. The remote endpoint did not provide a domain name system (DNS) claim and therefore did not satisfied DNS identity 'xxx.domain.local'. This may be caused by lack of DNS or CN name in the remote endpoint X.509 certificate's distinguished name.
Source=System.ServiceModel
StackTrace:
at System.ServiceModel.Security.IdentityVerifier.EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
If I do nothing other than change the target framework in my test code back to 4.5, then it works fine. This makes me think that it could be a bug in .Net 4.6, I know there were Wcf ssl changes made in 4.6
With first chance exceptions turned on I see the following exception that is raised internally in System.ServiceModel
System.ArgumentNullException occurred
HResult=-2147467261
Message=Value cannot be null.
Parameter name: value
ParamName=value
Source=mscorlib
StackTrace:
at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult)
InnerException:
System.ServiceModel.dll!System.ServiceModel.Security.IssuanceTokenProviderBase<System.ServiceModel.Security.Tokens.IssuedSecurityTokenProvider.FederatedTokenProviderState>.DoNegotiation(System.TimeSpan timeout) Unknown System.ServiceModel.dll!System.ServiceModel.Security.IssuanceTokenProviderBase<System.ServiceModel.Security.Tokens.IssuedSecurityTokenProvider.FederatedTokenProviderState>.GetTokenCore(System.TimeSpan timeout) Unknown
System.IdentityModel.dll!System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Security.Tokens.IssuedSecurityTokenProvider.GetTokenCore(System.TimeSpan timeout) Unknown
System.IdentityModel.dll!System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Security.SecurityProtocol.TryGetSupportingTokens(System.ServiceModel.Security.SecurityProtocolFactory factory, System.ServiceModel.EndpointAddress target, System.Uri via, System.ServiceModel.Channels.Message message, System.TimeSpan timeout, bool isBlockingCall, out System.Collections.Generic.IList<System.ServiceModel.Security.SupportingTokenSpecification> supportingTokens) Unknown
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.SecureOutgoingMessageAtInitiator(ref System.ServiceModel.Channels.Message message, string actor, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.SecureOutgoingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Security.SecurityProtocol.SecureOutgoingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout, System.ServiceModel.Security.SecurityProtocolCorrelationState correlationState) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.SecurityChannelFactory<System.ServiceModel.Channels.IRequestChannel>.SecurityRequestChannel.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.TransactionRequestChannelGeneric<System.ServiceModel.Channels.IRequestChannel>.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Dispatcher.RequestChannelBinder.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannel.Call(string action, bool oneway, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, object[] outs, System.TimeSpan timeout) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(System.Runtime.Remoting.Messaging.IMethodCallMessage methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.Invoke(System.Runtime.Remoting.Messaging.IMessage message) Unknown
mscorlib.dll!System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref System.Runtime.Remoting.Proxies.MessageData msgData, int type) Unknown
The wcf service being communicated to is targeting 4.6, and as far as I can tell I am specifying the dns identity, which does exist as a CN= in the cert subject. The binding is a custom binding so that I can do federated net.tcp, the client creates everything in code and I don't use the Add Service Reference feature in visual studio, the client code that is creating the binding:
var binding = new CustomBinding(new BindingElement[] {
new TransactionFlowBindingElement(),
security,
new SslStreamSecurityBindingElement(),
new BinaryMessageEncodingBindingElement() {
ReaderQuotas = { MaxDepth = maxReceivedSizeBytes, MaxStringContentLength = maxReceivedSizeBytes, MaxArrayLength = maxReceivedSizeBytes, MaxBytesPerRead = maxReceivedSizeBytes, MaxNameTableCharCount = maxReceivedSizeBytes },
},
new TcpTransportBindingElement {
TransferMode = TransferMode.StreamedResponse,
MaxReceivedMessageSize = maxReceivedSizeBytes,
},
}) {
SendTimeout = sendTimeout,
};
var channelFactory = new ChannelFactory<T>(binding, new EndpointAddress(new Uri(url), EndpointIdentity.CreateDnsIdentity("xxx.domain.local"), new AddressHeader[0]));
Could this be a bug in the 4.6 framework causing different behavior? Would the next steps only be trying to step through and debug framework code to try and find why 4.6 is behaving differently?
EDIT -
I created a small sample project that demonstrates the error, the repro steps are:
(Using VS 2015) Open the WcfSelfHostedServer solution
Add the IdentityFail.pfx cert to your Local Computer, Personal store using mmc
Run the WcfSelfHostedServer project (likely clicking firewall yes allow port 30000)
Open the WcfClient solution
Right click on project > properties, note that it is targetting 4.6.1
Run the project, it will throw the exception described above
Now switch the client to target 4.5.2, it will run fine with no errors
Update -
I found the following that appear related:
https://support.microsoft.com/en-us/kb/3069494
https://msdn.microsoft.com/en-us/library/mt298998(v=vs.110).aspx
But specifying Tls12 at the server and client didn't fix the issue, and even adding the DontEnableSchUseStrongCrypto=true flag didn't affect the DNS Identity Check error even though it got around the Enum.Parse internal error that was being thrown from this line
I needed to look at Retargetting Changes in the .NET Framework 4.6.1, as certificate validation logic changed in that release. (change in behavior for X509CertificateClaimSet.FindClaims that was causing my issue)
The fix is editing my app.config to add:
<runtime>
<AppContextSwitchOverrides value="Switch.System.IdentityModel.DisableMultipleDNSEntriesInSANCertificate=true" />
</runtime>
You can see the changed code on referencesource, and naturally makecert.exe doesn't appear to support generating certificates with "Subject Alternative Name" fields
You can fix in code adding one line.
like this.
AppContext.SetSwitch("Switch.System.IdentityModel.DisableMultipleDNSEntriesInSANCertificate",true);
Installing .net 4.7 on the server solved the problem for me.
Brandon.
It appears that if the flag is 'false' AND a cert does NOT contain SAN entries, we don't add the dns entry.

Cannot access website from the same server

I have a website on http://SomeDomain.com. when I go to that domain from any computer I am able to access the website. If I then go to that same domain but from the server that is hosting that website I will not be able to access the site. It looks like if a firewall will not be enabling the connection.
I know I can go to http://localhost from within that server in order to access the website.
Anyways the problem is that I cannot send emails from that server I have the following code to send an email:
public static void SendEmail(string toEmailAddress, string subject, string body)
{
var fromAddress = new MailAddress("sales#domainName.com", "domainName");
var toAddress = new MailAddress(toEmailAddress);
string fromPassword = "MY_PASSWORD";
var smtp = new SmtpClient
{
Host = "mail.toglcloud.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("v040\\sales.domainName", fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(message);
}
}
when I run that code from any computer (I already tried 5 different ones) it works! But if I run that exact code on the server (computer hosting website and that contains mail server) it does not work. I get the following exception:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.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 206.155.112.15:587 at
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress) at
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
Exception& exception) --- End of inner exception stack trace ---
I think it has to do with the same reason why I cannot find the endpoint http://SomeDomain.com
The difference between 5 other computers and the server:
1. Which user are you logged in as? What are permissions for the user.
2. Firewall permissions (biggest chance since the mail server is totally not accessible)
3. For the website - is it IE permissions (often on the server this could be an issue)
For me, I added an entry in the host file and it works well.

Categories