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.
Related
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();
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.
I'm sending the contents of a few textboxes to my website using the HttpClient. My PHP script inserts the data in a database.
But after clicking the btnSubmit-button, it runs the code but nothing is added to my database and no exceptions are thrown. What's wrong with my code?
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Net.Http;
namespace PhoneApp2
{
public partial class Submit2 : PhoneApplicationPage
{
public Submit2()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("barcode", out parameter))
{
Barcode.Text = parameter;
}
}
public static int typeConnection()
{
switch (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType)
{
default:
return 0;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
return 2;
}
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
try
{
if (typeConnection() < 2)
{
string URI = "http://cocktailpws.net23.net/requests/add_contribution.php";
string myParameters = "barcode=" + Barcode.Text + "&booze=" + Name.Text + "&email=" + Email.Text;
sendData(URI, myParameters);
}
else
{
MessageBox.Show("No database connection could be established. Please check your internet connection and try again.");
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
public async void sendData(string URI, string myParameters)
{
using (HttpClient hc = new HttpClient())
{
var response = await hc.PostAsync(URI, new StringContent(myParameters));
}
}
}
}
PHP:
if(isset($_POST['barcode']) && isset($_POST['booze']) && isset($_POST['email'])){
include_once "../inc/inc_db.php";
$booze = sqlesc($_POST['booze']);
$barcode = sqlesc($_POST['barcode']);
$email = sqlesc($_POST['email']);
date_default_timezone_set('Europe/Amsterdam');
$date = date("Y-m-d H:i:s");
$query = "INSERT INTO contr_barcode(booze,barcode,email,datum) VALUES ('$booze','$barcode','$email',$date')";
if(mysqli_query($con,$query)){
echo "1";
}else{
echo "0";
}
}
You are sending the values formatted as if you are sending application/x-www-form-urlencoded however, by default StringContent will declare the content-type as text/plain. It is possible that the PHP framework is not parsing the content correctly because it thinks you are just sending unformatted plain text.
You could either change the content-type of the StringContent object, or you could use the UrlEncodedFormContent class. e.g.
var content = new StringContent(myParameters);
content.Headers.Content-Type = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await hc.PostAsync(URI, content);
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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError