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. :)
Related
I have a connection with TCP / IP. I want a multiple connection. I'm using SimpleTcp. It is very simple and useful for single connection. Unfortunately, I don't know how to make multiple connections with SimpleTcp.
The code below is the one used for single connection.
public void EthernetConnect()
{
try
{
string IpAddress = Ip.Text;
int Port = Convert.ToInt32(PortName.Text);
SimpleTcpClient client = new SimpleTcpClient(IpAddress, Port, false, null, null);
if (!client.IsConnected)
{
client.Connect();
if (client != null)
{
if (client.IsConnected)
{
Console.WriteLine("Connected");
client.Events.DataReceived += EthernetDataReceived;
client.Events.Connected += EthernetConnected;
client.Events.Disconnected += EthernetDisconnected;
timer.Start();
}
else
{
Console.WriteLine("Not Connected");
}
}
}
else
{
client.Events.DataReceived -= EthernetDataReceived;
}
}
catch
{
}
}
EthernetDataReceived
private void EthernetDataReceived(object sender, DataReceivedFromServerEventArgs e)
{
try
{
var Data = e.Data;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
How can the EthernetDataReceived function in single connection be used in multiple connections? Creating a separate function for each link sounds ridiculous.
I can use different structures other than SimpleTcp. But I'm a beginner please help?
EthernetDataReceived is just an event handler that can be used to handle the DataReceived event from any SimpleTcpClient object. You can think of it as a method that may be called by any object from any thread.
Isn't there a problem if data comes from all of them at the same time?
Then the method will be called once per event that gets raised. This isn't an issue as long as you don't read or modify any shared data in the event handler. If you do this, you need to make the method thread-safe which is a topic of its own.
Also, how do I know which server data is coming from?
You should be able to cast the sender argument and check the properties of the SimpleTcpClient:
private void EthernetDataReceived(object sender, DataReceivedFromServerEventArgs e)
{
SimpleTcpClient client = (SimpleTcpClient)sender;
//...
}
Or check the DataReceivedFromServerEventArgs whatever that is.
Overview of Problem:
I need to connect to an IRC Server. Once connected, the program will send a message to the channel, and a response will occur over multiple lines back. I need to read these lines and store in a variable for later use. A special character at the end of the message (]) will define the end of the message over multiple lines. Once we have received this character, the IRC session should disconnect and processing should continue.
Situation:
I am using the Smartirc4net library. Calling irc.Disconnect() takes about 40 seconds to disconnect the session. Once we've received the ] character, the session should be disconnected, Listen() should not be blocking, and the rest of the program should continue to run.
Research:
I have found this: smartirc4net listens forever, can't exit thread, and I think it might be the same issue, however, I am unsure of what I need to do to resolve the problem.
Code:
public class IrcCommunicator
{
public IrcClient irc = new IrcClient();
string data;
public string Data { get { return data; } }
// this method we will use to analyse queries (also known as private messages)
public void OnQueryMessage(object sender, IrcEventArgs e)
{
data += e.Data.Message;
if (e.Data.Message.Contains("]"))
{
irc.Disconnect(); //THIS TAKES 40 SECONDS!!!
}
}
public void RunCommand()
{
irc.OnQueryMessage += new IrcEventHandler(OnQueryMessage);
string[] serverlist;
serverlist = new string[] { "127.0.0.1" };
int port = 6667;
string channel = "#test";
try
{
irc.Connect(serverlist, port);
}
catch (ConnectionException e)
{
// something went wrong, the reason will be shown
System.Console.WriteLine("couldn't connect! Reason: " + e.Message);
}
try
{
// here we logon and register our nickname and so on
irc.Login("test", "test");
// join the channel
irc.RfcJoin(channel);
irc.SendMessage(SendType.Message, "test", "!query");
// here we tell the IRC API to go into a receive mode, all events
// will be triggered by _this_ thread (main thread in this case)
// Listen() blocks by default, you can also use ListenOnce() if you
// need that does one IRC operation and then returns, so you need then
// an own loop
irc.Listen();
// when Listen() returns our IRC session is over, to be sure we call
// disconnect manually
irc.Disconnect();
}
catch (Exception e)
{
// this should not happen by just in case we handle it nicely
System.Console.WriteLine("Error occurred! Message: " + e.Message);
System.Console.WriteLine("Exception: " + e.StackTrace);
}
}
}
IrcBot bot = new IrcBot();
bot.RunCommand();
ViewBag.IRC = bot.Data;
As you can see, once this
Thank you for your time to look at this code and read my problem description. If you have any thoughts, or other suggestions, please let me know.
Mike
I was able to successfully disconnect straight away by calling RfcQuit() within OnQueryMessage(), before irc.Disconnect();
I am developing software for landline phones and full-duplex voice modems using C# and TAPI 3 library. Call answering is working fine but call hangup is throwing an exception. I did a lot of search to find solution but I could not. Following are the errors:
Exception is occurring on calling method ici.ReleaseUserUserInfo();
{"This implementation doesn't take advises (Exception from HRESULT:
0x80040003 (OLE_E_ADVISENOTSUPPORTED))"} System.Exception
{System.Runtime.InteropServices.COMException}"
My goal is to save recorded calls. One interesting thing is that if, before call hangup, I close the application, it successfully saves the recorded call.
My code:
private void BtnAnswer_Click(object sender, EventArgs e)
{
IEnumCall ec = ia[line].EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
ITTerminal recordTerminal;//NY test record
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
recordTerminal = bc.RequestTerminal(TapiConstants.CLSID_String_FileRecordingTerminal,
TapiConstants.TAPIMEDIATYPE_MULTITRACK,
TAPI3Lib.TERMINAL_DIRECTION.TD_RENDER);
ITMediaControl mediacontrol = (ITMediaControl)recordTerminal;
ITMediaRecord mediarecord = (ITMediaRecord)recordTerminal;
mediarecord.FileName = "a.wav";
bc.SelectTerminalOnCall(recordTerminal);
bc.Answer();
mediacontrol.Start();
}
catch (Exception exp)
{
MessageBox.Show("There may not be any calls to answer! \n\n" + exp.ToString(), "TAPI3");
}
}
private void BtnHang_Click(object sender, EventArgs e)
{
IEnumCall ec = ia[line].EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl bc = (ITBasicCallControl)ici;
bc.Disconnect(DISCONNECT_CODE.DC_NORMAL);
ici.ReleaseUserUserInfo();
}
catch (Exception exp)
{
MessageBox.Show("No call to disconnect!", "TAPI3");
}
}
I believe that the error code you're seeing is actually TAPI_E_NOTSUPPORTED!
According to the MSDN documentation for ITCallInfo::ReleaseUserUserInfo:
The ReleaseUserUserInfo method informs the service provider that the application has processed the user-user information obtained from the ITCallInfo::GetCallInfoBuffer method, called with the CIB_USERUSERINFO member of CALLINFO_BUFFER, and subsequently received user-user information can now be written.
Hwoever, User-user information is specific to the ISDN Q.931 standard and not all service providers support it.
Unless you specifically want to exchange this information between your client and the remote end, it is probably sufficient to simply delete the offending line of code, as it is otherwise both unused and unsupported.
I'm trying to write bot for irc channel, which will read messages from channel, recognize if they are commands to him and do some actions depends on command which was send.
I've choose ircDotNet because it was the only library that contains some examples how to use it, but they are actually very outdated, only half of them works. My lack of experience in C# and in programming at all don't allows me to understand stuff without good examples :(
So what my program does now:
logs in to server using password
joins channel
log-outs (very buggy)
I cant capture and send any messages from and to a channel and i cant log-out instantly.
Global classes that used for login and IrcClient class exemplar used everywhere in events
public IrcRegistrationInfo irc_iri
{
get
{
return new IrcUserRegistrationInfo()
{
NickName = "jsBot",
UserName = "jsBot",
RealName = "jsBot",
Password = "oauth:p4$$w0rdH3Re48324729214812489"
};
}
}
public IrcClient gIrcClient = new IrcClient();
Also all current events:
private void Form1_Load(object sender, EventArgs e)
{
try
{
gIrcClient.Connected += ircClient_Connected;
gIrcClient.Disconnected += gIrcClient_Disconnected;
gIrcClient.FloodPreventer = new IrcStandardFloodPreventer(1, 10000);
}
catch (Exception ex) { MessageBox.Show(ex.ToString());}
}
Login button code:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
if (!gIrcClient.IsConnected)
{
button1.Text = "Connecting...";
gIrcClient.Connect("irc.twitch.tv", 6667, false, irc_iri);
}
else
{
button1.Text = "Disconnecting...";
gIrcClient.Quit(5000, "bye");
}
}
Logic is: program checks if ircClient connected or not, and do some action. Then after that action appropriate event will raise, enable that button again. But that Quit function works very slow or don't works at all, bot will stay at channel until i don't close my program (maybe i need to dispose ircclient?)
Connect and disconnect events. In connect event, bot will join channel. Bot appears at channel after ~30 seconds after i press connect button, but connected event raised after 2-3 seconds. And same for disconnect - disconnect event raises quickly, but bot stays on channel for much longer time (about 120 seconds).
void ircClient_Connected(object sender, EventArgs e)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate {
button1.Text = "Disconnect";
button1.Enabled = true; };
button1.Invoke(del);
}
else
{
button1.Text = "Disconnect";
button1.Enabled = true;
}
gIrcClient.Channels.Join("#my_channel");
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void gIrcClient_Disconnected(object sender, EventArgs e)
{
if (!gIrcClient.IsConnected)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate
{
button1.Text = "Connect";
button1.Enabled = true;
};
button1.Invoke(del);
}
else
{
button1.Text = "Connect";
button1.Enabled = true;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
else gIrcClient.Disconnect();
}
Join channel and message received events. They are never raising, have no idea why.
void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
{
try
{
gIrcClient.Channels[0].MessageReceived += Form1_MessageReceived;
gIrcClient.LocalUser.SendMessage(e.Channel, "test");
MessageBox.Show(gIrcClient.Channels[0].Users[0].User.NickName);
MessageBox.Show("bot_join_channel_event_raised");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void Form1_MessageReceived(object sender, IrcMessageEventArgs e)
{
try
{
if (e.Text.Equals("asd"))
gIrcClient.LocalUser.SendMessage(e.Targets, "received");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
So main question is: how do i catch messages from channel and how do i send message to channel? I would appreciate any examples. You can find all code in one piece here: http://pastebin.com/TBkfL3Vq
Thanks
You try to join channel before adding an event.
gIrcClient.Channels.Join("#my_channel");
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
My suggestion is try adding event first like this:
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
gIrcClient.Channels.Join("#my_channel");
There is a bug in the IRC.NET library and twitch.tv is using a non-standard message reply that is tripping up IRC.NET.
I have created a bug here describing it. But basically twitch sends "Welcome, GLHF!" as the RPL_WELCOME message. The IRC RFC describes the format of the message to be "Welcome to the Internet Relay Network !#".
IRC.NET parses GLHF out of the welcome message as your nick name, which is used for things like firing the JoinedChannel and MessageRecieved events.
My solution is to download the source code and to comment out where it sets the nick name when receiving the RPL_WELCOME message. It sets the Nickname correctly from the IrcRegistrationInfo passed into the IrcClient constructor and doesn't need to be parsed from the welcome message from twitch. Not sure if this is the case for other IRC servers.
The function is called ProcessMessageReplyWelcome in IrcClientMessageProcessing.cs:
/// <summary>
/// Process RPL_WELCOME responses from the server.
/// </summary>
/// <param name="message">The message received from the server.</param>
[MessageProcessor("001")]
protected void ProcessMessageReplyWelcome(IrcMessage message)
{
Debug.Assert(message.Parameters[0] != null);
Debug.Assert(message.Parameters[1] != null);
this.WelcomeMessage = message.Parameters[1];
// Extract nick name, user name, and host name from welcome message. Use fallback info if not present.
var nickNameIdMatch = Regex.Match(this.WelcomeMessage.Split(' ').Last(), regexNickNameId);
//this.localUser.NickName = nickNameIdMatch.Groups["nick"].GetValue() ?? this.localUser.NickName;
this.localUser.UserName = nickNameIdMatch.Groups["user"].GetValue() ?? this.localUser.UserName;
this.localUser.HostName = nickNameIdMatch.Groups["host"].GetValue() ?? this.localUser.HostName;
this.isRegistered = true;
OnRegistered(new EventArgs());
}
A more involved solution might be to refine the nick name Regex so it does not match on GLHF!, which I think is not a valid nickname.
IRC.NET uses case sensitive string comparisons for finding users by nickname. So the value you pass into the IrcRegistrationInfo for the nickname must match the casing that twitch uses in messages pertaining to you. Which is all lowercase.
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(!)