How to keep common name of SSL while changing port wss - c#

I have a problem here. I created a windows app that requires interaction between browser and desktop apps. In the desktop app, I include WebSocket Secure made by [Dave](WebSocket Server in C#).
I have a valid pfx file. While using the default port (443), everything runs smoothly. The URL shows the CN of the SSL. My window app then has to use other port other than default ones (443), when I change in setting it runs not as per CN of the SSL but instead localhost:portnum. how to make it run using CN in ports other than 443? Please help.

I will try to answer this.
I have checked the link that you have pasted and came across the following code snippet:
private static void Main(string[] args){
IWebSocketLogger logger = new WebSocketLogger();
try
{
string webRoot = Settings.Default.WebRoot;
int port = Settings.Default.Port;
// used to decide what to do with incoming connections
ServiceFactory serviceFactory = new ServiceFactory(webRoot, logger);
using (WebServer server = new WebServer(serviceFactory, logger))
{
server.Listen(port);
Thread clientThread = new Thread(new ParameterizedThreadStart(TestClient));
clientThread.IsBackground = false;
clientThread.Start(logger);
Console.ReadKey();
}
}
catch (Exception ex)
{
logger.Error(null, ex);
Console.ReadKey();
}
}
Within the try block there is this code line:
int port = Settings.Default.Port;
Maybe trying setting that to an auto assign port fix your problem.

Related

Trouble Connecting To Known Bluetooth Device

I am using 32Feet.Net's sample (list below) with using statements removed for brevity.
static void Main(string[] args)
{
BluetoothClient client = new BluetoothClient();
BluetoothDeviceInfo device = null;
foreach (var dev in client.DiscoverDevices())
{
if (dev.DeviceName.Contains("moto g(6)"))
{
device = dev;
break;
}
}
client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
client.Close();
}
The line client.Connect(device.DeviceAddress, BluetoothService.SerialPort); blows up with this error {"The requested address is not valid in its context 601D914C50BF:0000110100001000800000805f9b34fb"}.
The only thing I altered in the sample was to find my smart phone, the moto g6. What am I missing?
Before putting a bounty on this question, I need to clarify that I am also looking for documentation or examples of having a desktop computer running Windows 10 be able to receive a file from iOS or Android and without having to use the built-in Bluetooth step by step in Windows 10. I would like to know what to do to correct the error.
I realize there is Command Line Bluetooth, but it would be nice to click a button in a gui and transfer a file using 32Feet.net.
Looks like the issue is because of services that are running on the device https://archive.codeplex.com/?p=32feet
Are you sure that device you are using has SerialPort profile running?
Also, Can you try the following code by using
private void BluetoothClientConnectCallback(IAsyncResult ar)
{
// Write your Call Back Code here
}
static void Main(string[] args)
{
BluetoothClient client = new BluetoothClient();
AllDevices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if (Device.DeviceName.Equals("moto g(6)"))
{
if (!client.Connected)
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
break;
}
}
client.Close();
}
Also, you have to pair your device before connecting. Check here
BluetoothSecurity.PairRequest(Device.DeviceAddress,"123456");

Embedded Nancy not listening

I read a couple of related questions which had an issue with accessing nency from a remote computer. However, I am unable to access nancy from my own pc.
Here is my code:
class Program
{
static void Main(string[] args)
{
HostConfiguration hostConfigs = new HostConfiguration();
//hostConfigs.RewriteLocalhost = true;
hostConfigs.UrlReservations.CreateAutomatically = true;
using (var host = new NancyHost(hostConfigs, new Uri("http://localhost:1234")))
{
host.Start();
Console.WriteLine("Running on http://+:1234");
Console.WriteLine(host.ToString());
}
Console.ReadKey();
}
}
public class HelloModule : NancyModule
{
public HelloModule()
{
Get["/"] = parameters => Response.AsJson("Success");
Get["/nancy"] = parameters => Response.AsJson("Success");
}
}
}
I am administrator on my PC and I do not get any exception. If I type http://localhost:1234 or http://127.0.0.1:1234 to my browser (with /nancy and without) I would expect a response. However, I do net get any reponse. Further, in the list produced with netstat -ano I do not see any process listing on port 1234. I downloaded the latest version of nancy via nuget.
Do you have any idea?
The following line should work as expected:
var host = new NancyHost(hostConfigs, new Uri("http://localhost:1234"))
But what happens with a using statement, is that anything specified between ( and ) (simply put) is disposed after the closing brace (}) of the same using statement. So what is actually happening is, the host gets created, is started, and is disposed right after it printed some lines to the console.
Simply put, move the ReadKey call inside the using statement. There it will wait until a key is pressed, and the host will be disposed after that event has occurred.

Can't establish connection using StreamSocket (universal windows)

Im trying to follow this code sample from microsoft, who is a basic code for sending/receiving data over network from windows 10 computer/phone.
Im on VS2015, i have a phone on W10 and my computer also.
The problem is that my application seems to create packet and send one to establish the connection (i have seen this packet with wireshark), but i never received it on the server side.
Here is code to listen port from the actual internet connection available and wait for a connection :
public static async void StartServer()
{
try
{
StreamSocketListener listener = new StreamSocketListener();
//ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
//await listener.BindServiceNameAsync("5043", SocketProtectionLevel.PlainSocket, internetConnectionProfile.NetworkAdapter);
listener.ConnectionReceived += OnConnection;
await listener.BindServiceNameAsync("5043");
Debug.WriteLine("Server Started !");
}
catch (Exception)
{
Debug.WriteLine("Error StartServer Method !");
}
}
The method "OnConnection" is never reach cause the event "ConnectionReceived" is never called.
Here is the code to establish connection (the string ipDestination contain the internet ip address from my phone for example, that i get from checkip.dyndns.org) :
private static StreamSocket socket;
public static async void Connect(string ipDestination)
{
try
{
//Destination Ip address
HostName host = new HostName(ipDestination);
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
socket = new StreamSocket();
socket.Control.KeepAlive = true;
await socket.ConnectAsync(host, "5043");
//EXCEPTION RAISE HERE after a moment "System.Runtime.InteropServices.COMException, cant join destination.
Debug.WriteLine("Connected !");
}
catch (Exception)
{
Debug.WriteLine("Erreur Connect Method !");
}
}
I think i should miss something but i dont know why and im block at this part since a long and can't continue my project...
I apologize for the bad english I try to make my best :)
Update from comments :
As Jay Zuo suggested, i have try to use local address on private
network and it works, i can establish connection, send and receive
data without problems... So the problem come when i use internet IP
address, and i still can't figure why...
As Kiewic suggested, i have simplify my code and commented the
precedent version.

Programming a distributed application written in C#, Ruby and Java using XML-RPC

I am tasked with writing a distributed event managing tool where each client, either a Ruby, C# or Java Client, synchronises all changes with a list of registered clients. I have to use XML-RPC to achieve the goal. My team and I have written up an XML-RPC client and server in each language and will provide the relevant source code below. If you require more code, please let me know.
The problem is that I can get Java and C# to communicate with each other. Ruby can communicate with the others but C# (and maybe Java, haven't tested yet) have problems addressing the Ruby server. I guess the problem is with the Endpoint. First let me give you some code. When reading please be aware that the code is actually written by a team and naming conventions differ a bit:
C# client
Uri _address = new Uri("http://" + _s + ":8000/xmlrpc/EventManagerService");
ChannelFactory<IEventManagerWCF_XML_RPC> _factory = new ChannelFactory<IEventManagerWCF_XML_RPC>(new WebHttpBinding(WebHttpSecurityMode.None), new EndpointAddress(_address));
_factory.Endpoint.Behaviors.Add(new XmlRpcEndpointBehavior());
IEventManagerWCF_XML_RPC _proxy = _factory.CreateChannel();
_proxy will not hold the client for a given URI. Those are stored in a dictionary and used when the need arises to synchronise events. One such synchronisation would happen in the case of a modification;
foreach(IEventManagerWCF_XML_RPC proxy in this.peers.Values)
proxy.modify(_id, _field, _newValue);
Here is an extract from the IEventManagerWCF_XML_RPC interface;
[OperationContract(Action = "EventManagerService.modify")]
bool modify(int id, string field, string newValue);
C# XML RPC service
Uri _baseAddress = new Uri("http://localhost:8000/xmlrpc");
_eventManagerHost = new ServiceHost(typeof(EventManagerService), _baseAddress);
try
{
ServiceEndpoint epXmlRpc = _eventManagerHost.AddServiceEndpoint(typeof(IEventManagerWCF_XML_RPC), new WebHttpBinding(WebHttpSecurityMode.None), "EventManagerService");
epXmlRpc.Behaviors.Add(new XmlRpcEndpointBehavior());
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
_eventManagerHost.Description.Behaviors.Add(smb);
_eventManagerHost.Open();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
_eventManagerHost.Abort();
}
Nothing special here I guess. Lets move on to the Java code!
Java Client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
try {
config.setServerURL(new URL("http://"+ip+":8000/xmlrpc/EventManagerService"));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
config.setEnabledForExtensions(true);
config.setConnectionTimeout(60 * 1000);
config.setReplyTimeout(60 * 1000);
XmlRpcClient client = new XmlRpcClient();
client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
client.setConfig(config);
xmlRpcPeers.put(ip, client);
xmlRpcPeers now holds the different clients. They are called as follows;
for(XmlRpcClient peer : this.xmlRpcPeers.values())
{
try {
peer.execute("EventManagerService.modify", params);
} catch (Exception e) {
e.printStackTrace();
}
}
The Java Server has it's own class and is instantiated with a simple new call;
public class Server extends Thread{
/**
* Server port
*/
private static final int port = 8000;
/**
* Starts the XML-RPC server
*/
public void run(){
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
try
{
phm.addHandler("EventManagerService", lu.uni.binfo.ds.EventManager_Java.EventManagerService.class);
}
catch (XmlRpcException e1)
{
e1.printStackTrace();
}
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
try
{
webServer.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Up till now everything seemed to work fine. Adding Ruby to the mix is what gives the most trouble. Here is the relevant code;
Ruby Client
Ruby clients are also stored in a dictionary. It is populated as follows;
#devices_XMLRPC[key] = EventManagerClient_XMLRPC.new(tokens[0]).device
The code for the class is:
class EventManagerClient_XMLRPC
#uri
#device
attr_accessor :uri, :device
def initialize(uri)
#uri = uri
#device = XMLRPC::Client.new2(
uri="http://" << #uri.to_s << ":8000/xmlrpc/EventManagerService", proxy=nil, timeout=30)
end
end
A call to synchronise on modifications looks like this:
#devices_XMLRPC.each_value { |client| client.call("EventManagerService.modify", tokens[0], field, value) }
Ruby Server
server = XMLRPC::Server.new(8000, "127.0.0.1")
server.add_handler("xmlrpc/EventManagerService", EventManagerService.instance)
puts "Server ready!"
server.serve
The EventManagerService class:
class EventManagerService
include Singleton
#manager
def initialize()
#manager = EventManager.instance
end
def modify(id, field, newValue)
puts "modify called"
#manager.modify([id, field, newValue], 1)
end
end
EventManager being the class where all the logic resides.
The error when trying to communicate from C# to Ruby is an EndPointNotFoundException that reads:
There was no endpoint listening at http://ip:8000/xmlrpc/EventManagerService that could accept the message.[...]
I tried fiddling around with the endpoint declaration but cannot seem to get it to work. The Ruby documentation does not help either. I am in need of help!
You could try inspecting the traffic that goes over the line with WireShark. With this tool, you would be able to see the actual HTTP data that is transferred between the different applications. Maybe this provides a hint as to why you have problems communicating between Ruby and C#.

Unable to read data from the transport connection: the connection was closed

The exception is Remoting Exception - Authentication Failure. The detailed message says "Unable to read data from the transport connection: the connection was closed."
I'm having trouble with creating two simple servers that can comunicate as remote objects in C#. ServerInfo is just a class I created that holds the IP and Port and can give back the address. It works fine, as I used it before, and I've debugged it. Also the server is starting just fine, no exception is thrown, and the channel is registered without problems. I'm using Forms to do the interfaces, and call some of the methods on the server, but didn't find any problems in passing the parameters from the FormsApplication to the server when debugging. All seems fine in that chapter.
public ChordServerProgram()
{
RemotingServices.Marshal(this, "PADIBook");
nodeInt = 0;
}
public void startServer()
{
try
{
serverChannel = new TcpChannel(serverInfo.Port);
ChannelServices.RegisterChannel(serverChannel, true);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I run two instances of this program. Then startNode is called on one of the instances of the application. The port is fine, the address generated is fine as well. As you can see, I'm using the IP for localhost, since this server is just for testing purposes.
public void startNode(String portStr)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
Int32 port = Int32.Parse(portStr);
serverInfo = new ServerInfo(address, port);
startServer();
//node = new ChordNode(serverInfo,this);
}
Then, in the other istance, through the interface again, I call another startNode method, giving it a seed server to get information from. This is where it goes wrong. When it calls the method on the seedServer proxy it just got, a RemotingException is thrown, due to an authentication failure. (The parameter I'll want to get is the node, I'm just using the int to make sure the ChordNode class has nothing to do with this error.)
public void startNode(String portStr, String seedStr)
{
IPAddress address = IPAddress.Parse("127.0.0.1");
Int32 port = Int32.Parse(portStr);
serverInfo = new ServerInfo(address, port);
IPAddress addressSeed = IPAddress.Parse("127.0.0.1");
Int32 portSeed = Int32.Parse(seedStr);
ServerInfo seedInfo = new ServerInfo(addressSeed, portSeed);
startServer();
ChordServerProgram seedServer = (ChordServerProgram)Activator.GetObject(typeof(ChordServerProgram), seedInfo.GetFullAddress());
// node = new ChordNode(serverInfo,this);
int seedNode = seedServer.nodeInt;
// node.chordJoin(seedNode.self);
}
Try setting the ensureSecurity to false, and it should start working.
ChannelServices.RegisterChannel(serverChannel, false);
You've specified that security is a must on your Remoting server in startServer() with:
ChannelServices.RegisterChannel(serverChannel, true);
Yet the 'client' end does not specify security, hence the authorisation error. You need to specify tcp channel security on both ends unless the server security setting is set to 'false'. In your second startNode method you need to do the following before using Activator.GetObject, note no port specified on the TcpChannel unlike the server end:
TcpChannel ClientChan = new TcpChannel();
ChannelServices.RegisterChannel(ClientChan, true);
Furthermore, unless you're doing it in some code you haven't given us, you also do not seem to have registered a well known service type server side, although you say it's been working in the debugger so maybe that's not necessary in the case. See MSDN on RegisterWellKnownServiceType.

Categories