XMLRPC c# client to python client - method does not exists - c#

I've searched the web and seen the following question: XML-RPC C# and Python RPC Server
I'm trying for a while to do the same, but I fail. I get the exception "Method "HelloWorld" is not supported..."
[XmlRpcUrl("http://192.168.0.xxx:8000/RPC2")]
public interface HelloWorld : IXmlRpcProxy
{
[XmlRpcMethod]
String HelloWorld();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
HelloWorld proxy = CookComputing.XmlRpc.XmlRpcProxyGen.Create<HelloWorld>();
textBox1.Text = proxy.HelloWorld();
}
catch (Exception ex)
{
HandleException(ex);
}
}
And my Python server is:
class LGERequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def HelloWorld():
return "This is server..."
server = SimpleXMLRPCServer(("192.168.0.xxx", 8000),
requestHandler=LGERequestHandler)
server.register_introspection_functions()
server.register_function("HelloWorld", HelloWorld)
server.register_instance(self)
# Run the server's main loop
server.serve_forever()
The server is up and running, but I still get an exception.

I found the problem:
Syntax problem server.register_function("HelloWorld", HelloWorld) should be server.register_function(HelloWorld, "HelloWorld").
This change also didn't work, so I changed the function name form helloWorld to hello and it worked(!)

Related

websocket sharp library Class OnMessage

I am trying to write a program that can potentially take in multiple websocket connections I am able to create a websocket connection class that will send and manipulate data how I like but I am running into a wall that I do not know how to solve.
class customWebsocket
{
public Websocket ws;
public customWebsocket(string address, int port)
{
string portString = port.ToString();
string webSend = "ws://" + address + ":" + portString;
this.ws = new WebSocket(webSend);
this.ws.Connect();
this.ws.OnMessage += this.Ws_OnMessage;
}
public void Ws_OnMessage(object sender, messageEventArgs e)
{
Console.WriteLine("THIS IS A TEST")
}
}
The initialization works however whenever I get a response from the server the "this is not a test" line does not fire and I cannot figure out why. I want to build the Ws_OnMessage into the class so that I can hopefully use the same class methods for all instances of the WebSocket by referring to the various cases as "this.ws"

C# Procedures Do Not Hit

I'm trying to convert some VB.NET programs to C#. I'm quite familiar with VB and am just now getting started with C#. My first program seems to have been exported well enough. I used the MSDN to take care of a few errors after the conversion. BUT the two procedures below do not hit. The program has 0 errors in Visual Studios, and from what I can tell, they are structured just like the examples on the MSDN website. I'm using Visual Studio 2015.
It’s a simple program that opens a COM port and receives data; very basic. Works perfect in VB, and in C# everything but these 2 procedures fire. Any insight on what I’m doing wrong would be immensely appreciated.
//catches incoming data from serial device.
private void SerialPort1_DataReceived(System.Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
ReceivedText(serialPort1.ReadExisting());
}
catch (Exception ex)
{
MessageBox.Show("Error (4)", "Error", MessageBoxButtons.OK);
}
}
//input from ReadExisting
private void ReceivedText(string text)
{
try
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback x = new SetTextCallback(ReceivedText);
this.Invoke(x, new object[] { (text) });
}
else
{
this.txtOutput.Text += text;
}
//append text
}
catch (Exception ex)
{
MessageBox.Show("Error (5)", "Error", MessageBoxButtons.OK);
}
}
When adding a serial port through the designer, set the call back in the properties window under the events tab:

Exception thrown when I pass the appropriate argument to method

I am reviewing source code of a voice chat application.
Here I want to run server program, so that any client can contact to server for voice chat. To run my server program I have to pass server name , port number and network interface that I am going to use for voice chat, after passing required arguments I have to call ServerStart method which is done by clicking on Start Checkbox in design view.If user has not passed appropriate type of arguments then it shows error by calling method ShowError().
Now, When I pass serverName, port number and Network Interface then serverName variable reference to null instead of the passed serverName argument.
Why An exception is thrown when I run server program that exception is "The source was not found, but some or all events logs could not be searched. Inaccessible logs: Security."
public partial class ServerWindow
{
private ChatServer server;
public delegate void SetListBoxItem(string str, string type);
public ServerWindow()
{
InitializeComponent();
ObtainNetworkInterfaces();
}
private void cbStartStop_Checked(object sender, RoutedEventArgs e)
{
if (cbStartStop.IsChecked == true)
{
// validate the port number
try
{
var port = Int32.Parse(tbPortNumber.Text);
server = new ChatServer(port, cbInterfaces.SelectedItem, tbServerName.Text);
server.ClientConnected += ServerOnClientConnected;
server.ClientDisconnected += ServerOnClientDisconnected;
var serverName = tbServerName.Text;
if (string.IsNullOrWhiteSpace(serverName))
{
ShowError();
}
else
{
server.StartServer();
SetControls(false);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
if (server == null)
return;
server.StopServer();
SetControls(true);
}
}
private void ShowError()
{
MessageBox.Show(#"Please enter valid port number and/or server name");
cbStartStop.IsChecked = false;
}
The problem seems not to be in the code that you posted. After our chat I would suggest to look at this post try the accepted answer. I have the feeling it will solve your problem.
It is usually helpful to use the exception message in the catch clause. :)

WCF+ duplex + Windows Form Application (ButtonClick) Trouble

I have WCF classes and now project to do. My teacher gave as to write app with streaming and duplex (I know that is impossible, but I found backdoor from this situation - I'm sending pics under 60KB).
My code worked well so far as I start wrote my GUI in Windows Form Application.
When I'm testing it via console - everything work well. But, when I want to use buttons in my GUI i have this exception:
An unhandled exception of type 'System.TimeoutException' occurred in
mscorlib.dll Additional information: This request operation sent to
net.tcp://localhost:7756/Przesylanie did not receive a reply within
the configured timeout (00:00:59.9740007). The time allotted to this
operation may have been a portion of a longer timeout. This may be
because the service is still processing the operation or because the
service was unable to send a reply message. Please consider
increasing the operation timeout (by casting the channel/proxy to
IContextChannel and setting the OperationTimeout property) and ensure
that the service is able to connect to the client.
Here bunch of code:
Service + IService (due to limitation of Stack I put it to one file):
public void WyslijstrumienNaSerwer()
{
IPrzesylanieCallback callback = OperationContext.Current.GetCallbackChannel<IPrzesylanieCallback>();
string sciezka = #"E:\5 semestr\Fras\Se płotek\Lab6\WcfServiceContractZadanie2\Host\bin\Pliki\" + "plik_odebrany.jpg";
string filePath = Path.Combine(System.Environment.SystemDirectory, sciezka);
Console.WriteLine("start");
callback.WyslijStrumien(filePath);
Console.WriteLine(filePath);
Console.WriteLine("meta");
}
namespace WcfServiceContractZadanie2
{
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IPrzesylanieCallback))]
public interface IPrzesylanie
{
[OperationContract]
void WyslijstrumienNaSerwer();
}
[ServiceContract]
public interface IPrzesylanieCallback
{
[OperationContract(IsOneWay = true)]
void WyslijStrumien(string filePath);
}
}
Client + callback + form + References.cs:
namespace Aplikacja
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
PrzesylanieClient klient = new PrzesylanieClient(new InstanceContext(new PrzesylanieCallback()), "NetTcpBinding_IPrzesylanie");
klient.WyslijstrumienNaSerwer();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public class PrzesylanieCallback : Referencja1.IPrzesylanieCallback
{
public void WyslijStrumien(string filePath)
{
Form1 o1 = new Form1();
// Pobieranie obrazka od klienta
string sciezka = #"E:\5 semestr\Fras\Se płotek\Lab6\WcfServiceContractZadanie2\Aplikacja\bin\Pliki\" + o1.wybrany();
string filePathZrodla = Path.Combine(System.Environment.SystemDirectory, sciezka);
//Otwieranie obrazka
Stream strumien = null;
try
{
FileStream imageFile = File.OpenRead(filePathZrodla);
strumien = (Stream)imageFile;
}
catch(IOException ioe)
{
Console.WriteLine("Wyjatek otwierania pliku: {0}", ioe.ToString());
Console.ReadKey();
throw ioe;
}
// Zapisywanie obrazka
o1.SaveFile(strumien, filePath);
}
}
}
private void btnPrzeslijPlikNaSerwer_Click(object sender, EventArgs e)
{
PrzesylanieClient klient = new PrzesylanieClient(new InstanceContext(new PrzesylanieCallback()), "NetTcpBinding_IPrzesylanie");
klient.WyslijstrumienNaSerwer();
}
public void WyslijstrumienNaSerwer() {
base.Channel.WyslijstrumienNaSerwer();
}
I wrote methods SaveFile which works correctly.
As you see, I'm testing my code in the begining of Main function in Client and that works well.
But when I'm using the same code in Forms it does not work. Compiler is returnig me to References.cs and gives me exception I mentioned earlier.
Waiting for any respone!
My answer does not solve your exception issue; however, it might prevent you from getting a very bad grade. Streaming AND duplex are both supported in WCF.
Streaming:
https://msdn.microsoft.com/en-us/library/ms733742(v=vs.110).aspx
Duplex:
https://msdn.microsoft.com/en-us/library/ms731064(v=vs.110).aspx

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#.

Categories