IRC Bot GUI crash? - c#

Ok so, The bot connects just fine, but when I create the bot, the form crashes. The bot stays connected but also the !about commands doesnt work. If i use this same exact code with a console application everything works fine. The problem is just the UI form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
namespace cIRCBot
{
public partial class bSetup : Form
{
public bSetup()
{
InitializeComponent();
}
private void createbotbtn_Click(object sender, EventArgs e)
{
string buf, nick, owner, server, chan;
int port;
TcpClient sock = new TcpClient();
TextReader input;
TextWriter output;
//Get nick, owner, server, port, and channel from user
nick = botnick.Text;
owner = botname.Text;
server = servername.Text;
bool isNumber = int.TryParse(portnum.Text, out port);
chan = channelname.Text;
if (isNumber == false)
{
MessageBox.Show("Failed to connect. Make sure the server address and port number are correct.", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//Connect to irc server and get input and output text streams from TcpClient.
sock.Connect(server, port);
if (!sock.Connected)
{
//Console.WriteLine("Failed to connect!");
return;
}
else
{
this.Close();
input = new StreamReader(sock.GetStream());
output = new StreamWriter(sock.GetStream());
//Starting USER and NICK login commands
output.Write(
"USER " + nick + " 0 * :" + owner + "\r\n" +
"NICK " + nick + "\r\n"
);
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine())
{
//Display received irc message
//Console.WriteLine(buf);
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) { output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush(); }
if (buf[0] != ':') continue;
/* IRC commands come in one of these formats:
* :NICK!USER#HOST COMMAND ARGS ... :DATA\r\n
* :SERVER COMAND ARGS ... :DATA\r\n
*/
//After server sends 001 command, we can set mode to bot and join a channel
if (buf.Split(' ')[1] == "001")
{
output.Write("MODE " + nick + " +B\r\n" + "JOIN " + chan + "\r\n");
output.Flush();
if (buf.Contains("!about"))
{
output.WriteLine("PRIVMSG {0} :" + "I'm a shitty little bot coded by " + botname, channelname);
output.Flush();
}
}
}
}
}
}
}
This is the Main window, I have the other form which you use to setup
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cIRCBot
{
public partial class mWin : Form
{
public mWin()
{
InitializeComponent();
}
private void newBotToolStripMenuItem_Click(object sender, EventArgs e)
{
bSetup bSetup = new bSetup();
bSetup.Show();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
This is the setup window

I suspect that what causes the problem is the fact that You're doing this.Close() and it gets disposed. After calling Close() You go into for() and try to operate on possibly disposed resources.

Related

How to use android phone for SMS Sending app in C#?

I am trying to develop a C# application that will be able to send SMS only through GSM Modem. When we connect a GSM Modem to our laptop/PC then we have to check the Port of that modem from Device manager > Modem > Port. But in this case, I want to connect my android phone as a GSM Modem with my laptop and trying to use the port number of my connected mobile phone but it is not connecting as a modem. Please help me if you have any idea or any possibility to connect the android phone as a GSM Modem to laptop. Here is my mode.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TextmagicRest;
using TextmagicRest.Model;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.IO.Ports;
using System.Threading;
namespace SMS_Sending_App_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SerialPort sp = new SerialPort();
sp.PortName = textBox3.Text;
sp.Open();
sp.WriteLine("AT" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CMGF=1" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CSCS=\"GSM\"" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CMGS=\"" + textBox1.Text + "\"" + Environment.NewLine);
Thread.Sleep(100);
sp.Write(new byte[] { 26 }, 0, 1);
Thread.Sleep(100);
var response = sp.ReadExisting();
if (response.Contains("ERROR"))
{
MessageBox.Show("SMS failed!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("SMS Sent!!!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
sp.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
}
}
Is there a reason for not using a modem? I've seen info that ppl are using their phones but I don't know how they do it. It would be a big risk if the phone offered the modem interface just by connecting to the PC.
For better modem communication look at this project : SMSTerminal

How can I take direct data form Ardruino server and upload to PC another ( installed SQL )

I wrote 2 winforms as follows
Check the connection of the Ardruino to PC 1 and write the received information to log.txt file
Read selected information in log files and send them to PC 2 (SQL installed)
Note: PC 1 has 2 network cards (network card 1 receives the signals of the Arduino over the range: 192.168.1.2; Network card 2 connects to PC 2 via the range: 110.110.1.2)
How do I get the information I need from PC 1 and transfer them to PC 2 (with SQL installed) with only 1 program
My code Winform received form Arduino:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
namespace TCPIPSeverMutilClient
{
public partial class Form1 : Form
{
const int MAX_CONNECTION = 30;
const int PORT_NUMBER =1989;
int currentconnect = 0;
delegate void SetTextCallback(string text);
static TcpListener listener;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress address = IPAddress.Parse(IPText.Text);
listener = new TcpListener(address, PORT_NUMBER);
AddMsg("Creat Sever with IP :"+ IPText.Text);
AddMsg("Waiting for connection...");
button1.Hide();
listener.Start();
for (int i = 0; i < MAX_CONNECTION; i++)
{
// new Thread(DoWork).Start();
Thread aThread = new Thread(DoWork);
aThread.IsBackground = true; //<-- Set the thread to work in background
aThread.Start();
}
}
private void DoWork()
{
while (true)
{
Socket soc = listener.AcceptSocket();
currentconnect = currentconnect + 1;
SetText("Numbers Connection " + currentconnect.ToString());
Console.WriteLine("Connection received from: {0}", soc.RemoteEndPoint);
try
{
var stream = new NetworkStream(soc);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
//writer.WriteLine("Welcome to Student TCP Server");
// writer.WriteLine("Please enter the student id");
while (true)
{
string id = reader.ReadLine();
SetText(id);
// writer.WriteLine("END");
if (String.IsNullOrEmpty(id))
break; // disconnect
//if (_data.ContainsKey(id))
// writer.WriteLine("Student's name: '{0}'", _data[id]);
else
{
writer.WriteLine("END");
// writer.WriteLine("Can't find name for student id '{0}'", id);
}
}
stream.Close();
}
catch (Exception ex)
{
SetText("Error: " + ex);
}
// Console.WriteLine("Client disconnected: {0}",soc.RemoteEndPoint);
soc.Close();
currentconnect = currentconnect - 1;
SetText("Numbers Connection " + currentconnect.ToString());
}
}
private void SetText(string text)
{
if (this.rtbText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText); // khởi tạo 1 delegate mới gọi đến SetText
this.Invoke(d, new object[] { text });
}
else
{
this.AddMsg(text);
}
}
private void SaveText(string text)
{
const string textFileName = "Log.txt";
const int insertAtLineNumber = 0;
List<string> fileContent = File.ReadAllLines(textFileName).ToList();
// AddMsg(fileContent.Count.ToString());
//fileContent.InsertRange(insertAtLineNumber, text);
fileContent.Insert(insertAtLineNumber, text);
File.WriteAllLines(textFileName, fileContent);
}
private void AddMsg(string msg)
{
rtbText.Items.Add(DateTime.Now + " : " + msg);
SaveText(DateTime.Now + " : " + msg);
if (rtbText.Items.Count >= 150)
{ rtbText.Items.RemoveAt(0); }
}
}
}
As the Arduino card attached to PC 1 cannot be accessed from the PC 2.
You need to pass the Arduino data to the MSSQL Database. Then Retrieve the data in PC 2 by accessing it from PC 1. You can use this Reference for How to access Database over network
Up to now, when I returned this case I had a solution.
In PC1, there are 2 network cards, you just need to use the Network class to find the IP with the IP with IP in PC2
Instead of reading from the log file I was inspired directly from Arduino returned and transmitted to PC2
string hostname = Dns.GetHostName();
System.Net.IPHostEntry ip = new IPHostEntry();
ip = Dns.GetHostByName(hostname);
foreach (IPAddress listip in ip.AddressList)
{
if (listip.ToString().StartsWith("110."))
{
ipMay = listip.ToString();
macPairIp = GetMacByIP(ipMay);
try
{
//Do work here
}
catch (...)
{}
}
}

How to C# send AT command to GSM modem and get response

I want to get AT command response.
I want to read SMS from my GSM modem.
I fount some code on google, This script send AT commands but not get response.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CSharp_SMS
{
public partial class Form_SMS_Sender : Form
{
private SerialPort _serialPort;
public Form_SMS_Sender()
{
InitializeComponent();
}
private void buttonSend_Click(object sender, EventArgs e)
{
string number = textBoxNumber.Text;
string message = textBoxMessage.Text;
_serialPort = new SerialPort("COM6", 115200);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.WriteLine("AT" + "\r");
Thread.Sleep(1000);
string status = _serialPort.ReadLine();
labelStatus.Text = "|-"+ status + "-|";
_serialPort.Close();
}
}
}
This code is not work.
not get response, but send AT commands.
How to get response?
Thanks
if ECHO is off on your modem, you won't get any response to your AT commands.
Ensure echo is enabled by sending ATE1 first
Thread.Sleep(1000);
_serialPort.WriteLine("ATE1" + "\r");
Thread.Sleep(1000);
_serialPort.WriteLine("AT" + "\r");
celu.RtsEnable = true;
celu.DtrEnable = true;
celu.WriteBufferSize = 3000;
celu.BaudRate = 9600;
celu.PortName = "COM26"; // You have check what port your phone is using here, and replace it
celu.Open();
//string cmd = "AT+CLIP=1"; // Here you put your AT command
//celu.WriteLine(cmd);
celu.WriteLine ("AT+CLIP=1"+"\r");
Thread.Sleep(500);
//celu.Open();
string ss = celu.ReadExisting();

C# UDP Chat receive no message

I try to write a UDP-Chat in C#.
I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them.
I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving.
is there a error in my code or is it a desing error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;
namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
string name = "testuser";
UdpClient receiveClient = new UdpClient(1800);
IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
public Chat_window(string name)
{
this.name = name;
fileWriter("Chat started", false); // write the initial start date in the errorfile
InitializeComponent();
Message_Load(); // starts the listen server theread
}
private void Message_Load()
{
lb_chat.Items.Add(name + " Joined the room...");
Thread rec = new Thread(ReceiveMessageFn);
rec.Start();
}
private void ReceiveMessageFn()
{
try
{
while (true)
{
Byte[] receve = receiveClient.Receive(ref receiveEndPint);
string message = Encoding.UTF8.GetString(receve);
if (message == name + " logged out...")
{
break;
}
else
{
if (message.Contains(name + " says >>"))
{
message = message.Replace(name + " says >>", "Me says >>");
}
ShowMessage(message);
}
}
//Thread.CurrentThread.Abort();
//Application.Current.Shutdown();
}
catch (Exception e)
{
//errorHandler(e);
}
}
private void ShowMessage(string message)
{
if (lb_chat.Dispatcher.CheckAccess())
{
lb_chat.Items.Add(message);// add Item to list-box
lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
lb_chat.UpdateLayout();
}
else {
lb_chat.Dispatcher.BeginInvoke(
new Action<string>(ShowMessage), message); // if list-box is not access able get access
return;
}
}
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
{
tb_eingabe.Text = "";
}
private void btn_submit_Click(object sender, RoutedEventArgs e)
{
submit_message();
}
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
submit_message();
}
}
void submit_message()
{
if (tb_eingabe.Text != "")
{
string data = name + " says >> " + tb_eingabe.Text;
SendMessage(data);
tb_eingabe.Clear(); // clear the textbox-values
tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
}
}
private void SendMessage(string data)
{
try{
UdpClient sendClient = new UdpClient();
Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
sendClient.Send(message, message.Length, endPoint);
sendClient.Close();
}
catch (Exception e)
{
errorHandler(e);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string data = name + " logged out...";
SendMessage(data); // send a logout message to the other chat peers
}
// debugging functions
static void errorHandler(Exception errorMsg)
{
MessageBox.Show(errorMsg.ToString()); // create a error-message-box
fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
}
static void fileWriter(string fileText, bool append)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
file.Close();
}
public static String GetTime(DateTime val)
{
return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
}
}
}
Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. See the example below:
IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);
IPAddress.Broadcast doesn't work in some network.

C# Program stops responding after second WebClient.DownloadString()

I am working on a program for proof of concept that does a webrequest using WebClient.DownloadString("http://website/members/login.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);
to get the boolean value of wether or not the user is a valid login and then if it is it gives a success notification if it isn't ten it gives a fail notification.
The problem is when i press the button to try and login the first time it works fine but when i press it again the second tine the program freezes and gets stuck at the Webclient.download string.
If anyone can spot and tell me whats wrong that would be great. I am providing the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public static WebClient webclient = new WebClient();
HttpWebResponse wResp;
WebRequest wReq;
bool isConnected = false;
private String Session = "";
public Form1()
{
InitializeComponent();
}
public Boolean checkUser(String username, String password)
{
String login = `webclient.DownloadString("http://connorbp.info/members/auth.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);`
Boolean bLogin = Boolean.Parse(login);
if (bLogin)
{
Session = username + "-" + password;
}
return bLogin;
}
public int CanConnect(string dUrl)
{
wReq = WebRequest.Create(dUrl);
int cnt = Connect();
return cnt;
}
private int Connect()
{
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
isConnected = true;
return 1;
}
catch (Exception)
{
return 0;
}
}
private void button1_Click(object sender, EventArgs e)
{
int init = CanConnect("http://connorbp.info/members/auth.php");
if (init == 0)
{
notifyIcon1.ShowBalloonTip(200, "CBP Login", "Failed to connect to server! Try again later.", ToolTipIcon.Error);
}
else
{
if(checkUser(textBox1.Text, textBox2.Text))
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Logged In!", ToolTipIcon.Info);
}
else
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Invalid Username/Password!", ToolTipIcon.Error);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
notifyIcon1.ShowBalloonTip(20, "CBP Login", "for more cool things go to http://connorbp.info", ToolTipIcon.Info);
}
}
}
You are not closing the response.
The second call is trying to open something that is already open, therefore it hangs.

Categories