C# Procedures Do Not Hit - c#

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:

Related

Exception on call hangup for landline phone

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.

IPC Cannot Find the File Specified

using IPC over local TCP to communicate from Client to a Server thread. The connection itself doesn't seem to be throwing any errors, but every time I try to make one of the associated calls, I get this message:
System.Runtime.Remoting.RemotingException: Could not connect to an IPC Port: The System cannot Find the file specified
What I am attempting to figure out is WHY. Because this WAS working correctly, until I transitioned the projects in question (yes, both) from .NET 3.5 to .NET 4.0.
Listen Code
private void ThreadListen()
{
_listenerThread = new Thread(Listen) {Name = "Listener Thread", Priority = ThreadPriority.AboveNormal};
_listenerThread.Start();
}
private void Listen()
{
_listener = new Listener(this);
LifetimeServices.LeaseTime = TimeSpan.FromDays(365);
IDictionary props = new Hashtable();
props["port"] = 63726;
props["name"] = "AGENT";
TcpChannel channel = new TcpChannel(props, null, null);
ChannelServices.RegisterChannel(channel, false);
RemotingServices.Marshal(_listener, "Agent");
Logger.WriteLog(new LogMessage(MethodBase.GetCurrentMethod().Name, "Now Listening for commands..."));
LogEvent("Now Listening for commands...");
}
Selected Client Code
private void InitializeAgent()
{
try
{
_agentController =
(IAgent)RemotingServices.Connect(typeof(IAgent), IPC_URL);
//Note: IPC_URL was originally "ipc://AGENT/AGENT"
// It has been changed to read "tcp://localhost:63726/Agent"
SetAgentPid();
}
catch (Exception ex)
{
HandleError("Unable to initialize the connected agent.", 3850244, ex);
}
}
//This is the method that throws the error
public override void LoadTimer()
{
// first check to see if we have already set the agent process id and set it if not
if (_agentPid < 0)
{
SetAgentPid();
}
try
{
TryStart();
var tries = 0;
while (tries < RUNCHECK_TRYCOUNT)
{
try
{
_agentController.ReloadSettings();//<---Error occurs here
return;
} catch (RemotingException)
{
Thread.Sleep(2000);
tries++;
if (tries == RUNCHECK_TRYCOUNT)
throw;
}
}
}
catch (Exception ex)
{
HandleError("Unable to reload the timer for the connected agent.", 3850243, ex);
}
}
If you need to see something I haven't shown, please ask, I'm pretty much flying blind here.
Edit: I think the issue is the IPC_URL String. It is currently set to "ipc://AGENT/AGENT". The thing is, I have no idea where that came from, why it worked before, or what might be stopping it from working now.
Update
I was able to get the IPC Calls working correctly by changing the IPC_URL String, but I still lack understanding of why what I did worked. Or rather, why the original code stopped working and I needed to change it in the first place.
The string I am using now is "tcp://localhost:63726/Agent"
Can anyone tell me, not why the new string works, I know that...but Why did the original string work before and why did updating the project target to .NET 4.0 break it?

Try Catch Block doesn´t work with Secugen Fingerprint

I'm working on a fingerprint recognition software on c#, WPF Visual Studio 2012, I'm using secugen hamster to take the fingerprints, the software is all done, I can register the fingerprints correctly to the database and succesfull retrieve and compare them for the user access, but sometimes when the software is matching the stored fingerprint with the one just taken of the user, the method MatchIsoTemplate generates an error 'attempt to read or write protected memory. this is often an indication that other memory damaged' and the program stops, I tried to catch this with a try catch but It doesn't work, no matter what the program stops there, this is the code I'm using according to the example of secugen sdk
SGFPMISOTemplateInfo sample_info = new SGFPMISOTemplateInfo();
Int32 err = m_FPM.GetIsoTemplateInfo(customer.Huella, sample_info);
bool matched = false;
for (int i = 0; i < sample_info.TotalSamples; i++)
{
try
{
m_FPM.MatchIsoTemplate(customer.Huella, i, m_VrfMin, 0, m_SecurityLevel, ref matched);
}
catch (Exception)
{
MessageBox.Show("Try Again", "Aviso", MessageBoxButton.OK, MessageBoxImage.Hand);
}
if (matched)
{
//fill data
I answer my own question, finally I discover how to do it, i just need to wrap the method around the [HandleProcessCorruptedStateExceptions] from System.Runtime.ExceptionServices and use a Try Catch in the correct part of the method, like this
[HandleProcessCorruptedStateExceptions]
void myFunction()
{
try
{
switch (sequence)
{
case 0:
sequence++;
m_FPMAux.MatchIsoTemplate(customer.Huella, i, m_VrfMin, 0, m_SecurityLevel, ref matched);
break;
case 1:
sequence++;
m_FPMAux.MatchIsoTemplate(m_VrfMin, 0, customer.Huella, i, m_SecurityLevel, ref matched); .......

ircDotNet bot fails to get messages from IRC channel, long login/logout

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.

IOException I can’t catch

I have an application talking to a USB-GPS. It’s working as a charm if nothing out of the ordinary happnes. But I have a big problem. If the USB gets pulled out, my program (some times) crashes. I have Try/Catch where I need them but this IOExeption doesn’t get caught. I just get "The device does not recognize the command" and the program stops. Here is the code that starts the port:
public LatLongFromGPS(Form1 parent)
{
this.parent = parent;
String port;
this.SPort = new SerialPort(port, 4800);
this.SPort.ReadTimeout = 500;
this.SPort.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
}
public bool checkIfPortsOpen()
{
return (this.SPort.IsOpen);
}
public void openPort()
{
try
{
if (!this.SPort.IsOpen)
{
this.SPort.Open();
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("OPENPORT " + ex.ToString(), Logger.LoggType.Debug);
}
}
public void dataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (SPort.IsOpen)
{
String GPGGAString;
Thread.CurrentThread.Join(200);
buffert = new char[this.SPort.BytesToRead];
this.SPort.Read(buffert, 0, buffert.Length);
GPGGAString = findStringFromGPS();
if (GPGGAString != null)
{
getLatitudefromString(GPGGAString);
getLongitudefromString(GPGGAString);
getTimeFromString(GPGGAString);
this.newData = true;
}
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("GPSERROR " + ex.ToString(), Logger.LoggType.Debug);
}
}
Then I have this in a Timer to check the info
if (this.LatLong.newDataReceived())
{
//DOING STUFF
}
if (!this.LatLong.checkIfPortsOpen())
this.LatLong.openPort();
Anyone have any suggestions how to stop the crashes?
[EDIT] The stack:
at System.IO.Ports.InternalResources.WinIOError(Int32, System.String)
at System.IO.Ports.InternalResources.WinIOError()
at System.IO.Ports.SerialStream.Dispose(Boolean)
at System.IO.Ports.SerialStream.Finalize()
I'm not entirely sure if it applies here, but there are mechanisms to catch overall crashes at the appdomain level -
http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx
(not the section on other events, e.g. ThreadException - these may need their own handlers depending on the situation)
Although not a best practice, top-level exception handling might solve your problem. See http://richnewman.wordpress.com/2007/04/07/top-level-exception-handling-in-windows-forms-applications-%E2%80%93-code-listing-1/ for an example.

Categories