This is my code that i try to connect to a telegram bot
namespace telegramUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TelegramBotClient bot = new TelegramBotClient("xxxxxxxxx");
int offset = 23;
Update temp = null;
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
try
{
var m = Task.Run(async()=> bot.GetUpdatesAsync(offset,50)).Result;
foreach (var x in m.Result)
{
switch (x.Type)
{
case UpdateType.MessageUpdate:
temp = x;
backgroundWorker1.ReportProgress(0);
bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").ConfigureAwait(false);
break;
}
offset = x.Id+1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = temp.Message.From.FirstName;
}
}
}
after ruining message box show "One or more errors occurred." what is the problem? telegram bot should reply ":)" but it don't. I can not find out if m receive any updates or not.
try this:
bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").GetAwaiter().GetResult();
you didn't execute the task. just it
to me this same error happen recently (the code was working on Feb 2020 but did not work later) when making bot.SendTextMessageAsync i received same exception. After some research i found this topic [Telegram Bot stops with An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
that actually solved my problem.
using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Related
I am trying to write a program that communicates with a controller. The controller is supposed to send a "welcome" message when a connection is successfully established and, in fact, it does when I connect using a communications software. However, using the .NET code below, I never see the welcome message. Beyond that, it works. How can I capture this message. It seems to be sent the moment the connection is established.
Again, I am able to communicate fine with the controller after connection but I simply cannot seem to get the welcome message that is sent a the moment the connection is opened.
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
SerialPort sp;
public Form1()
{
InitializeComponent();
}
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort(comboBox1.SelectedItem.ToString(),Int32.Parse(comboBox2.SelectedItem.ToString()));
sp.DataReceived += SerialPort_OnDataReceived;
sp.Close();
sp.Open();
richTextBox1.AppendText("open\n");
button2.Enabled = true;
button3.Enabled = true;
}
catch (Exception ex)
{
richTextBox1.AppendText(ex.Message);
}
}
void SerialPort_OnDataReceived(object sender,SerialDataReceivedEventArgs args)
{
SerialPort sp = sender as SerialPort;
string s = sp.ReadExisting();
richTextBox1.Invoke(this.myDelegate, new Object[] { s });
}
private void button2_Click(object sender, EventArgs e)
{
sp.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
sp.Close();
richTextBox1.AppendText("\nclosed\n");
}
private void Form1_Load_1(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
string[] Ports = SerialPort.GetPortNames();
comboBox2.SelectedIndex = comboBox2.Items.Count - 1;
Array.Sort(Ports, (a, b) => string.Compare(a.Substring(3).PadLeft(3, '0'), b.Substring(3).PadLeft(3, '0')));
foreach (string port in Ports)
{
comboBox1.Items.Add(port);
}
comboBox1.SelectedIndex = 0;
}
}
}
I worked it out. Required a slight delay between connection and trying to pull data from the port.
I am facing trouble in calling events in Zkemkeeper.dll. I have succesfully established the connection however on putting the finger on sensor no event is fired. Infact no realtime event is being triggered.
Any help would be appreciated following is my code;
private void button2_Click(object sender, EventArgs e)
{
string s = "";
int Val = 0;
bool bIsConnected = false;
try {
//zkemkeeper.CZKEMClass axczkem1 = new zkemkeeper.CZKEMClass();
// bIsConnected = axczkem1.Connect_USB(1);
bIsConnected = axczkem1.Connect_Com(6,1,115200);
if(bIsConnected==true){
Cursor = Cursors.Default;
bool asa= axczkem1.EnableDevice(1, true);
if (axczkem1.RegEvent(1, 65535))
{
axczkem1.OnFinger += new zkemkeeper._IZKEMEvents_OnFingerEventHandler(axczkem1_OnFinger);
axczkem1.OnKeyPress += new zkemkeeper._IZKEMEvents_OnKeyPressEventHandler(axczkem1_OnKeyPress);
axczkem1.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(axCZKEM1_OnConnected);
axczkem1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
}
MessageBox.Show("Connection established!!!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
And following are the event methods:
private void axCZKEM1_OnVerify(int UserID)
{
label2.Text = "Verify";
}
private void axCZKEM1_OnConnected()
{
label1.Text = "Connected";
}
private void axczkem1_OnKeyPress(int Key)
{
MessageBox.Show(Key.ToString());
}
private void axczkem1_OnFinger()
{
MessageBox.Show("Connection");
}
if this is a windows form application . If program have long running process event doesn't work . For example loop (while,for) . And also Thread.sleep() .
If you want to trigger work your program do nothing .
If this is not a windows form see this link enter link description here
I have a problem with WPF MessageBox,its due to when internet connection is not available. I need the message to displays once only, but it shows multiple times.
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(cc);
}
void cc(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.Message, "Uncaught", MessageBoxButton.OK);
}
Simple.
You should confirm before you show message box.
// message box flag.
bool canIShowMessageBox = true;
// for thread lock.
object exLocker = new object();
void cc(object sender, UnhandledExceptionEventArgs e)
{
lock(exLocker)
{
if (canIShowMessageBox)
canIShowMessageBox = false;
else
return;
}
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.Message, "Uncaught", MessageBoxButton.OK);
lock(exLocker)
canIShowMessageBox = true;
}
I have just started to learn about threads and methodinvoking in c#, but I have come across a problem which I couldn't find the solution of.
I made a basic C# form program which keeps updating and displaying a number, by starting a thread and invoke delegate.
Starting new thread on Form1_load:
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Threading.Thread(DoThisAllTheTime);
t.Start();
}
Public void DoThisAllTheTime (which keeps updating the number) :
public void DoThisAllTheTime()
{
while(true)
{
if (!this.IsDisposed)
{
number += 1;
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
this.Invoke(yolo);
}
}
}
Now when I click the X button of the form, I get the following exception:
'An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll
Can't update a deleted object'
While I actually did check if the form was disposed or not.
EDIT: I added catch (ObjectDisposedException ex) to the code which fixed the problem.
Working code:
public void DoThisAllTheTime()
{
while(true)
{
number += 1;
try {
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
this.Invoke(yolo);
}
catch (ObjectDisposedException ex)
{
t.Abort();
}
}
}
Your call to this.IsDisposed is always out of date. You need to intercept your form closing event and stop the thread explicitly. Then you won't have to do that IsDisposed test at all.
There are many ways you can do this. Personally, I would use the System.Threading.Tasks namespace, but if you want to keep your use of System.Threading, you should define a member variable _updateThread, and launch it in your load event:
_updateThread = new System.Threading.Thread(DoThisAllTheTime);
_updateThread.Start();
Then in your closing event:
private void Form1_Closing(object sender, CancelEventArgs e)
{
_stopCounting = true;
_updateThread.Join();
}
Finally, replace the IsDisposed test with a check on the value of your new _stopCounting member variable:
public void DoThisAllTheTime()
{
MethodInvoker yolo = delegate() { label1.Text = number.ToString(); };
while(!_stopCounting)
{
number += 1;
this.Invoke(yolo);
}
}
Just put this override in your form class:
protected override void OnClosing(CancelEventArgs e) {
t.Abort();
base.OnClosing(e);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Thread.CurrentThread.Abort();
}
I have made a simple windows form with a ComboBox, TextBox and two Buttons to setup a serial protocol with my hardware.
However, whenever I send something I do get reply from hardware but C# doesn't display it. Instead it gives an exception saying that the operation has timed out. I even used an oscilloscope to check if I received something and it was positive. But C# doesn't display the code as stated before.
I am attaching my code below. Anyhelp would be welcome. Thanks in advance.
public partial class Form3 : Form
{
string buffer;
public SerialPort myComPort = new SerialPort();
delegate void setTextCallback(string text);
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Caption"].ToString().Contains("(COM"))
{
comboBox1.Items.Add(queryObj["Caption"]);
}
}
comboBox1.Text = comboBox1.Items[0].ToString();
}
catch (ManagementException ex)
{
MessageBox.Show(ex.Message);
}
}
private void setText(string text)
{
if (textBox1.InvokeRequired)
{
setTextCallback tcb = new setTextCallback(setText);
this.Invoke(tcb, new object[] { text });
}
else
{
textBox1.Text = text;
}
}
void myComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string myString = myComPort.ReadLine();
setText(myString);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void button1_Click(object sender, EventArgs e)
{
myComPort.Close();
// button1.Enabled = false;
string name = comboBox1.Text;
string[] words = name.Split('(', ')');
myComPort.PortName = words[1];
myComPort.ReadTimeout = 5000;
// myComPort.WriteTimeout = 500;
myComPort.BaudRate = 9600;
myComPort.DataBits = 8;
myComPort.StopBits = StopBits.One;
myComPort.Parity = Parity.None;
myComPort.DataReceived += new SerialDataReceivedEventHandler(myComPort_DataReceived);
myComPort.Open();
}
private void button2_Click(object sender, EventArgs e)
{
myComPort.WriteLine("?GV1\r");
}
}
It say
...The DataReceived event is not guaranteed to be raised for every byte received...
Try something like:
private static void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// prevent error with closed port to appears
if (!_port.IsOpen)
return;
// read data
if (_port.BytesToRead >= 1)
{
// ...
// read data into a buffer _port.ReadByte()
DataReceived(sender, e);
}
// ...
// if buffer contains data, process them
}
Have a look at this url:
http://csharp.simpleserial.com/
And this url for WMI:
http://www.codeproject.com/Articles/32330/A-Useful-WMI-Tool-How-To-Find-USB-to-Serial-Adapto