Why example not work? Even SMTP server is OK.
I setup Outlook just to test SMTP server. Everything is OK. I am able to send and receive mails.
The problem is with C# code. It is always return timeout exception. Even if i set Timeout to max int.
The SMTP server port is fine due to Outlook client is used without any problem. Just check link on the top to see configuration of the SMT server. The same options are used from the same network.
public void SendAbvBg(string message)
{
var Smtp = new SmtpClient("smtp.abv.bg", 465);
Smtp.UseDefaultCredentials = false;
Smtp.EnableSsl = true;
Smtp.Timeout = 80000;
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.Credentials = new System.Net.NetworkCredential("mail#abv.bg", "pass");
MailMessage msg = new MailMessage();
msg.Body = message;
msg.From = new MailAddress("mail#abv.bg", "name");
msg.To.Add("mail#abv.bg");
msg.HeadersEncoding = Encoding.UTF8;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Subject = "Form";
msg.SubjectEncoding = Encoding.UTF8;
msg.Headers.Add("MIME-Version", "1.0");
msg.Headers.Add("Content-Language", "en-us");
try
{
Smtp.Send(message);
}
catch(Exception e)
{
// timeout exception
}
}
How is this possible? Standard Outlook pop/smtp work. The code - no! Why?
Apart of that, Outlook configuration timeout is 2 minutes.
I have try 5 minutes Timeout = 300000 and still receive error:
Message = "The operation has timed out."
The SMT server is owned by ABV.BG. It is a UNIX smtp very old server.
The client code and Outlook client is in the same office company network. The network not restrict any ports or policy. The Outlook work perfectly with the same configuration and options as code example. This is the prove that problem is not related with network, firewall or any other restriction. It is bug in the code.
Can it be the problem with default TargetName = "SMTPSVC/smtp.abv.bg"?
https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.targetname?view=net-5.0
The GMAIL is OK and it is not part of the current topic.
https://passport.abv.bg/app/profiles/sendtosupport/form?from=abv.bg
https://passport.abv.bg
Test from https://www.smtper.net/
I've made a class to test SMTP access. Simple test call the SmtpSeverProbe(...) method with your data. You will receive the Email on success. Will test the normal ports 25,465,587 will test SSL.
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace CommonCore.Tests
{
// Based in:
// https://gist.github.com/xamlmonkey/4737291
//Normal port 25 text,465 SSL,587 text then STARTSSL
/// <summary>
/// For Testing access to SMTP server.
/// </summary>
public static class SmtpTests
{
static int connectionTimeout = 1300;
/// <summary>
/// Tests RELAY, Try to send email port 25 with and without StartSSl, port 465 with SSL, Port 587 with StartSSL.
/// Returns a resume Log, but you have a 'out string log' variable with details.
/// </summary>
/// <param name="login"></param>
/// <param name="password"></param>
/// <param name="server">To test SSL use a name that exists in the Server Certificate, For SSL avoid a IP</param>
/// <param name="to">Accepts all formats: ...#... or "......." <....#....></param>
/// <param name="msg">Message in the body</param>
/// <param name="log">very detailed Log</param>
/// <param name="error">Only Errors Log</param>
/// <param name="from"></param>
/// <returns></returns>
public static string SmtpServerProbe(string login, string password, string server,
string to, string msg, out string log, out string error, string from = null)
{
//Normal port 25 text,465 SSL,587 text then STARTSSL
string resume = "";
error = "";
log = Environment.NewLine;
string _resume = "";
string _error = "";
int port;
bool forceSsl;
from = from ?? "\"Test Email\" <test#email.com>";
bool _sendok = false;
System.Net.Mail.MailAddress addr = null;
try
{
addr = new System.Net.Mail.MailAddress(from);
}
catch
{
error = "'from' email address is incorrect.";
log += "!! Error : " + error;
resume = Environment.NewLine + $"[FAIL] 'from' incorrect format > '{from}'" + Environment.NewLine;
return resume;
}
try
{
addr = new System.Net.Mail.MailAddress(to);
}
catch
{
error = "'to' email address is incorrect.";
log += "!! Error : " + error;
resume = Environment.NewLine + $"[FAIL] 'to' incorrect format > '{to}'" + Environment.NewLine;
return resume;
}
//Test Relay
port = 25;
forceSsl = false;
log += "----------------------------------" + Environment.NewLine +
"Testing RELAY." + Environment.NewLine +
"(user is not authenticated, email is sento to 'test#gmail.com')" + Environment.NewLine;
_sendok = Tests.SmtpTests.ScanSMTP("", "", server, port, forceSsl, "\"Test Email\" <test#email.com>", "test#gmail.com", "Relay Test", out string _log, out _resume, out _error);
if (_sendok)
{
resume += "SERVER IS ACCEPTING RELAY THAT'S VERY BAD IDEIA";
resume += Environment.NewLine + $" (maybe it has an exception to this Host or IP '{System.Net.Dns.GetHostName()}')";
log += _log + Environment.NewLine;
log += "----------------------------------" + Environment.NewLine + " SERVER IS ACCEPTING RELAY THAT'S VERY BAD IDEIA" + Environment.NewLine + Environment.NewLine;
}
else
{
log += "----------------------------------" + Environment.NewLine + " SERVER is not accepting Relay, that's good." + Environment.NewLine + Environment.NewLine;
}
//TEST SMTPS
port = 465;
forceSsl = true;
log += Environment.NewLine + "__________________________________" + Environment.NewLine +
$"Testing port {port} / force SSL={forceSsl}";
_sendok = Tests.SmtpTests.ScanSMTP(login, password, server, port, forceSsl, from, to, msg, out _log, out _resume, out _error);
log += _log;
error += Environment.NewLine + _error;
resume += _resume;
//TEST SMTP with STARTSSL
port = 25;
forceSsl = false;
log += Environment.NewLine + "__________________________________" + Environment.NewLine +
$"Testing port {port} / try STARTSSL=true";
_sendok = Tests.SmtpTests.ScanSMTP(login, password, server, port, forceSsl, from, to, msg, out _log, out _resume, out _error);
log += _log;
error += Environment.NewLine + _error;
resume += _resume;
//TEST SMTP no STARTSSL
port = 25;
forceSsl = false;
log += Environment.NewLine + "__________________________________" + Environment.NewLine +
$"Testing port {port} / try STARTSSL=false";
_sendok = Tests.SmtpTests.ScanSMTP(login, password, server, port, forceSsl, from, to, msg,
out _log, out _resume, out _error,
true, false);
log += _log;
error += Environment.NewLine + _error;
resume += _resume;
//Test port 587 with STARTSSL
port = 587;
forceSsl = false;
log += Environment.NewLine + "__________________________________" + Environment.NewLine +
$"Testing port {port} / try STARTSSL=true";
_sendok = Tests.SmtpTests.ScanSMTP(login, password, server, port, forceSsl, from, to, msg, out _log, out _resume, out _error);
log += _log;
error += Environment.NewLine + _error;
resume += _resume;
return resume;
}
/// <summary>
/// Tests the SMTP server and try to send a test Email
/// </summary>
/// <param name="login"></param>
/// <param name="password"></param>
/// <param name="server">Server DNS name</param>
/// <param name="port"></param>
/// <param name="forceSsl"></param>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="msg">Message to send to the body</param>
/// <param name="log">Detailed Log</param>
/// <param name="resume">Resumed Log</param>
/// <param name="error">Erro Log</param>
/// <param name="checkcertificate">Check if SSL Certificate in the Server is acceptable</param>
/// <param name="trystartssl">try to send the command STARTTLS</param>
/// <returns></returns>
public static bool ScanSMTP(string login, string password, string server, int port, bool forceSsl,
string from, string to, string msg,
out string log, out string resume, out string error,
bool checkcertificate = true, bool trystartssl = true)
{
#region check parameters
log = Environment.NewLine;
error = "";
resume = "";
string _fromaddrstr = "";
string _toaddrstr = "";
string _errorResume = $"[FAIL] Port={port}, Force SSL={forceSsl}, try STARTSSL={trystartssl}";
System.Net.Mail.MailAddress addr = null;
if (!String.IsNullOrEmpty(login))
{
if (String.IsNullOrEmpty(password))
{
error = "If login is not empty than the password cannot be empty";
log += "!! Error : " + error;
resume = Environment.NewLine + $"[FAIL] 'password' is missing" + Environment.NewLine;
return false;
}
}
try
{
addr = new System.Net.Mail.MailAddress(from);
_fromaddrstr = addr.Address;
}
catch
{
error = "'from' email address is incorrect.";
log += "!! Error : " + error;
resume = Environment.NewLine + $"[FAIL] 'from' incorrect format > '{from}'" + Environment.NewLine;
return false;
}
try
{
addr = new System.Net.Mail.MailAddress(to);
_toaddrstr = addr.Address;
}
catch
{
error = "'to' email address is incorrect.";
log += "!! Error : " + error;
resume = Environment.NewLine + $"[FAIL] 'to' incorrect format > '{to}'" + Environment.NewLine;
return false;
}
#endregion
try
{
#region support variables
string _response = "";
string _msgfotter = "";
StreamReader clearTextReader = null;
StreamWriter clearTextWriter = null;
StreamReader sslreader = null;
StreamWriter sslwriter = null;
SslStream sslStream = null;
// Depending on checkcertificate value stream may ignore Certificate Errors
// like: Hostname not in the certificate and Certificate Chain Errors
SslStream GetSslStream(Stream innerstream)
{
if (checkcertificate)
return new SslStream(innerstream);
else
return new SslStream(
innerstream,
false,
new RemoteCertificateValidationCallback((s, c, h, e) => true),
null
);
}
#endregion
#region support internal methods
void ExitError(string str, ref string _log, ref string _error)
{
_error = str;
_log += "!! Error : " + str + Environment.NewLine + Environment.NewLine;
if (sslStream == null)
{
clearTextWriter.WriteLine("QUIT");
}
else
{
sslwriter.WriteLine("QUIT");
}
}
string AskReceive(string commandline, ref string _log)
{
if (sslStream == null)
{
_log += "> " + commandline + Environment.NewLine;
clearTextWriter.WriteLine(commandline);
string _str;
System.Threading.Thread.Sleep(200);
//while (!clearTextReader.EndOfStream)
//while (!String.IsNullOrEmpty(_str))
// {
// System.Threading.Thread.Sleep(200);
// //yield return _str;
// _str = clearTextReader.ReadLine();
// _log += "< " + _str + Environment.NewLine;
//}
_str = clearTextReader.ReadLine();
_log += "< " + _str + Environment.NewLine;
return _str;
}
else
{
_log += "> " + commandline + Environment.NewLine;
sslwriter.WriteLine(commandline);
System.Threading.Thread.Sleep(200);
string _str = sslreader.ReadLine();
_log += "< " + _str + Environment.NewLine;
return _str;
}
}
bool Login(ref string _log, ref string _error)
{
if (!(_response = AskReceive($"AUTH LOGIN", ref _log)).StartsWith("334"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
if (!(_response = AskReceive(Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}")), ref _log)).StartsWith("334"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
if (!(_response = AskReceive(Convert.ToBase64String(Encoding.UTF8.GetBytes($"{password}")), ref _log)).StartsWith("235"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
return true;
}
bool SendMsg(ref string _log, ref string _error)
{
// HELO JakesDominoApp
// MAIL FROM: jake#jakehowlett.com
// RCPT To: jhowlett#EITS
// DATA
// From: My Self <me#you.com>
// To: A secret list <you#me.com>
// Subject: A simple test
// Mime-Version: 1.0;
// Content-Type: text/html; charset="ISO-8859-1";
// Content-Transfer-Encoding: 7bit;
//
// <html>
// <body>
// <h2>An important link to look at!</h2>
// Here's an important link
// </body>
// </html>
// .
// QUIT
if (!String.IsNullOrEmpty(login))
if (!Login(ref _log, ref _error))
return false;
if (!(_response = AskReceive($"MAIL FROM: <{_fromaddrstr}>", ref _log)).StartsWith("250"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
if (!(_response = AskReceive($"RCPT TO: <{_toaddrstr}>", ref _log)).StartsWith("250"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
string _return = AskReceive($"DATA", ref _log);
if (_return.Substring(0, 1) == "5")
{
ExitError(_return, ref _log, ref _log);
return false;
}
string _details = $"Server:'{server}' | Login:'{login}' | port:{port} | try STARTTSL:{trystartssl} | Force SSL:{forceSsl}";
if (!AskReceive(
$"From: {from}" + Environment.NewLine +
$"To: {to}" + Environment.NewLine +
$"Subject: " + _details +
Environment.NewLine + Environment.NewLine +
msg + Environment.NewLine + Environment.NewLine +
"__________________________________________________" + Environment.NewLine + Environment.NewLine +
_details + " " + _msgfotter + Environment.NewLine +
Environment.NewLine + Environment.NewLine + ".", ref _log).StartsWith("250"))
{
ExitError(_response, ref _log, ref _error);
return false;
}
AskReceive($"QUIT", ref _log);
return true;
}
#endregion
#region method body
TcpClient client = new TcpClient();
//Make the connection with timeout
if (!client.ConnectAsync(server, port).Wait(connectionTimeout))
{
//log = ex.ExceptionToString();
error = $"Could not connect '{server}' at port '{port}'";
log += Environment.NewLine + error + Environment.NewLine;
resume = Environment.NewLine + $"[FAIL] Port={port}. Could not connect '{server}' at port '{port}'" + Environment.NewLine;
return false;
}
using (client)
{
if (forceSsl)
{
using (NetworkStream stream = client.GetStream())
using (sslStream = GetSslStream(stream)) // new SslStream(stream))
{
sslStream.AuthenticateAsClient(server);
using (sslreader = new StreamReader(sslStream))
using (sslwriter = new StreamWriter(sslStream) { AutoFlush = true })
{
log += Environment.NewLine + Environment.NewLine + "## SSL connection (safe)" + Environment.NewLine;
string connectResponse = sslreader.ReadLine();
log += "< " + connectResponse + Environment.NewLine;
if (!connectResponse.StartsWith("220"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"[FAIL] Port={port}, Force SSL={forceSsl} (encrypted)";
return false;
}
if (!(_response = AskReceive($"HELO {Dns.GetHostName()}", ref log)).StartsWith("250"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"[FAIL] Port={port}, Force SSL={forceSsl} (encrypted)";
return false;
}
_msgfotter = $"Encrypted MSG using SMTP/S on port: {port}";
if (SendMsg(ref log, ref error))
{ resume = Environment.NewLine + $"[SUCCESS] Port={port}, Force SSL={forceSsl} (encrypted)"; return true; }
else
{ resume = Environment.NewLine + $"[FAIL] Port={port}, Force SSL={forceSsl} (encrypted)"; return false; }
}
}
}
else //Not SMTP/S (SSL)
{
using (NetworkStream stream = client.GetStream())
using (clearTextReader = new StreamReader(stream))
using (clearTextWriter = new StreamWriter(stream) { AutoFlush = true })
{
log += Environment.NewLine + Environment.NewLine + "## Plain text connection (UNSAFE)" + Environment.NewLine;
string connectResponse = clearTextReader.ReadLine();
log += "< " + connectResponse + Environment.NewLine;
if (!connectResponse.StartsWith("220"))
{
ExitError(connectResponse, ref log, ref error);
resume = Environment.NewLine + $"[FAIL] Port={port}, Force SSL={forceSsl} (unsafe, plain text)";
return false;
}
if (!(_response = AskReceive($"HELO {Dns.GetHostName()}", ref log)).StartsWith("250"))
{
ExitError(_response, ref log, ref error);
resume = Environment.NewLine + $"[FAIL] Port={port}, Force SSL={forceSsl} (unsafe, plain text)";
return false;
}
if (trystartssl)
{
if ((_response = AskReceive("STARTTLS", ref log)).StartsWith("220"))
{
clearTextReader = null;
clearTextWriter = null;
using (sslStream = GetSslStream(stream)) // new SslStream(stream))
{
//TLS Start
sslStream.AuthenticateAsClient(server);
log += Environment.NewLine + Environment.NewLine + "## TLS connection (safe)" + Environment.NewLine;
using (sslreader = new StreamReader(sslStream))
using (sslwriter = new StreamWriter(sslStream) { AutoFlush = true })
{
if (!AskReceive($"HELO {Dns.GetHostName()}", ref log).StartsWith("250"))
{ ExitError(_response, ref log, ref error); resume = $"[FAIL] Port={port}, Force SSL={forceSsl} (encrypted)"; return false; }
_msgfotter = "Encrypted MSG using STARTSSL on port: " + port.ToString();
if (SendMsg(ref log, ref error))
{
resume = Environment.NewLine +
$"[SUCCESS] Port={port}, Force SSL={forceSsl}, try STARTSSL={trystartssl} (encrypted)";
return true;
}
else
{
resume = Environment.NewLine +
$"[FAIL] Port={port}, Force SSL={forceSsl}, try STARTSSL={trystartssl} (encrypted)";
return false;
}
}
}
}
}
if ((trystartssl && !_response.StartsWith("220")) || !trystartssl)
{
if (trystartssl)
log += "## Does not accept StartSSL" + Environment.NewLine;
_msgfotter = "Unsafe MSG using plain text on port: " + port.ToString();
if (SendMsg(ref log, ref error))
{
resume = Environment.NewLine +
$"[SUCCESS] Port={port}, Force SSL={forceSsl}, try STARTSSL={trystartssl} (unsafe, plain text)";
return true;
}
else
{
resume = Environment.NewLine +
$"[FAIL] Port={port}, Force SSL={forceSsl}, try STARTSSL={trystartssl} (unsafe, plain text)";
return false;
}
}
return false;
}
}
}
#endregion
}
catch (Exception ex)
{
if (ex.Message == #"The remote certificate is invalid according to the validation procedure.")
{
log += $"The host name '{server}' must exist in the server SSL certificate. Don't use IP or host names not in the Certificate" + Environment.NewLine;
}
error = ex.Message;
log += "!! Error : " + ex.Message + Environment.NewLine;
resume += Environment.NewLine + _errorResume;
return false;
}
}
}
}
The following method calls Ping.Send(). When I pass an invalid URL, Send() dies and an unhandled exception happens. What is the cause of this?
private void ping()
{
comboBox3.Visible = false;
listBox2.Items.Clear();
// check the url if it is null
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
{
listBox2.Items.Add("Please use valid IP or web address!!");
comboBox3.Visible = false;
coloring_red_tab4();
}
else
{
// do the ping
coloring_green_tab4();
for (int i = 0; i < numericUpDown1.Value; i++)
{
string s;
s = textBox1.Text;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
Ping p = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
//pingexception was unhalded (if the url wrong here is the error)
PingReply r = p.Send(s, timeout, buffer, options);
// if it's true url
if (r.Status == IPStatus.Success)
{
listBox2.Items.Add("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n");
label91.Text = r.Address.ToString();
}
else
{
// just to know the ip for the website if they block the icmp protocol
listBox2.Items.Add(r.Status);
IPAddress[] ips;
ips = Dns.GetHostAddresses(textBox1.Text);
foreach (IPAddress ip in ips)
{
label91.Text = ip.ToString();
}
}
}
}
}
The exception is unhandled because you do not handle it. Whenever you call a .Net library method, you need to check its documentation to see what exceptions it throws, and decide which, if any, you want to handle at that level of code. Here is the relevant portion of the documentation for Ping.Send(), which I am including as an image so you will be able to recognize these sections going forward:
Notice that the documentation states that a PingException can occur if
An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.
Thus it's clear from the documentation that many errors from Ping() will be reported as thrown exceptions rather than reported by setting PingReply.Status != IPStatus.Success. So you need to modify your code to be something like the following:
public static bool TryPing(string hostNameOrAddress, out string pingStatusMessage, out string pingAddressMessage)
{
if (String.IsNullOrWhiteSpace(hostNameOrAddress))
{
pingStatusMessage = "Missing host name";
pingAddressMessage = "";
return false;
}
var data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
var buffer = Encoding.ASCII.GetBytes(data);
var timeout = 120;
using (var p = new Ping())
{
var options = new PingOptions();
options.DontFragment = true;
try
{
var r = p.Send(hostNameOrAddress, timeout, buffer, options);
if (r.Status == IPStatus.Success)
{
pingStatusMessage = "Ping to " + hostNameOrAddress.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n";
pingAddressMessage = r.Address.ToString();
return true;
}
else
{
// just to know the ip for the website if they block the icmp protocol
pingStatusMessage = r.Status.ToString();
var ips = Dns.GetHostAddresses(hostNameOrAddress);
pingAddressMessage = String.Join(",", ips.Select(ip => ip.ToString()));
return false;
}
}
catch (PingException ex)
{
pingStatusMessage = string.Format("Error pinging {0}: {1}", hostNameOrAddress, (ex.InnerException ?? ex).Message);
pingAddressMessage = hostNameOrAddress;
return false;
}
}
}
Here I have extracted a utility method from the user interface code and also properly disposed of the Ping instance after it is no longer needed.
Then
TryPing(#"www.google.com", out pingStatusMessage, out pingAddressMessage);
Gives
Ping to www.google.com[146.115.8.83] (Successful) Bytes =32 TTL=62 Response delay = 8 ms
While
TryPing(#"www.kdjf98rglkfgjldkfjgdl;fge8org.com", out pingStatusMessage, out pingAddressMessage);
Gives
Error pinging www.kdjf98rglkfgjldkfjgdl;fge8org.com: No such host is known
We are developing a winforms client with C#, for sending SSH commands using plink.exe. We have got the following method. But we execute it, standard error gives "FATAL ERROR : Server unexpectedly closed network connection".
The same command (plink.exe + arguments) is executed successfully in the command line.
Any idea?
Thanks.
public string SendSSHCommand(string host, string userName, string password, string commandFile, string logPath, int maxRetryCount)
{
string result = String.Empty;
string commandText = "plink.exe";
Process sshProcess = new Process();
sshProcess.StartInfo = new ProcessStartInfo(commandText);
sshProcess.StartInfo.Arguments = String.Format("{0} -P 22 -ssh -l {1} -pw {2} <\"{3}\"> \"{4}\"", host, userName, password, commandFile, logPath);
sshProcess.StartInfo.WorkingDirectory = Parameters.RootDirectory;
sshProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
sshProcess.StartInfo.CreateNoWindow = true;
sshProcess.StartInfo.UseShellExecute = false;
sshProcess.StartInfo.RedirectStandardInput = true;
sshProcess.StartInfo.RedirectStandardError = true;
sshProcess.StartInfo.RedirectStandardOutput = true;
//sshProcess.EnableRaisingEvents = true;
_logger.Log("SSH Command : " + commandText + " " + sshProcess.StartInfo.Arguments);
int iteration = 0;
while (iteration <= maxRetryCount)
{
iteration++;
sshProcess.Start();
//Thread.Sleep(2000); // wait for two seconds.
sshProcess.StandardInput.WriteLine("y");
sshProcess.WaitForExit();
string output = sshProcess.StandardOutput.ReadToEnd();
string error = sshProcess.StandardError.ReadToEnd();
_logger.Log("STANDARD OUTPUT : " + output);
_logger.Log("STANDARD ERROR : " + error);
if (File.Exists(logPath))
{
using (StreamReader sr = new StreamReader(logPath))
{
result = sr.ReadToEnd();
}
File.Delete(logPath);
}
else
{
result = "NO RESULT FILE";
}
if (String.IsNullOrEmpty(result)) // retry needed.
{
_logger.Log("SSH command failed. Retrying after 5 seconds...");
Thread.Sleep(5000);
}
else
{
break; // command executed. no retry needed.
}
}
if (iteration >= maxRetryCount)
{
_logger.Log("Max retry count is reached.");
throw new Exception("SSH command failed after " + maxRetryCount.ToString() + " attempts.\nFailed command :\n" + commandText + " " + sshProcess.StartInfo.Arguments);
}
return result;
}
Hey I'm new to coding C# and I'm trying to code a C# IRC Bot and I want to make a GUI for it so I can send chat from the GUI but I'm having problems doing so.
First off I'm opening two things, the Console app and a winform.
This code is executed within another class:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Here is the main code (I did not code it all):
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.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace IRCBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
class IrcBot
{
// Irc server to connect
public static string SERVER = File.ReadAllText("server.txt");
// Irc server's port (6667 is default port)
private static int PORT = 6667;
// User information defined in RFC 2812 (Internet Relay Chat: Client Protocol) is sent to irc server
private static string USER = "USER LeeSharp Bot v1 * :I'm a C# IRC bot made by LeeIzaZombie";
// Bot's nickname
private static string NICK = File.ReadAllText("nickname.txt");
// Channel to join
private static string CHANNEL = File.ReadAllText("channel.txt");
// StreamWriter is declared here so that PingSender can access it
public static StreamWriter writer;
static void Main(string[] args)
{
NetworkStream stream;
TcpClient irc;
string inputLine;
StreamReader reader;
string nickname;
try
{
irc = new TcpClient(SERVER, PORT);
stream = irc.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
// Start PingSender thread
PingSender ping = new PingSender();
ping.Start();
Console.WriteLine("Connecting to " + SERVER);
Console.WriteLine("Port: " + PORT);
writer.WriteLine(USER);
writer.Flush();
Console.WriteLine("Nickname: " + NICK + ".");
writer.WriteLine("NICK " + NICK);
writer.Flush();
Console.WriteLine("Now joining " + CHANNEL);
writer.WriteLine("JOIN " + CHANNEL);
writer.Flush();
while (true)
{
while ((inputLine = reader.ReadLine()) != null)
{
if (inputLine.EndsWith("JOIN :" + CHANNEL))
{
nickname = inputLine.Substring(1, inputLine.IndexOf("!") - 1);
writer.WriteLine("PRIVMSG " + CHANNEL + " :" + "Hi " + nickname +
" and welcome to " + CHANNEL + " !");
writer.Flush();
// Sleep to prevent flooding :P
Thread.Sleep(2000);
}
if (inputLine.Contains(" is no longer AFK"))
{
writer.WriteLine("PRIVMSG " + CHANNEL + " :Welcome back! :D");
writer.Flush();
// Sleep to prevent excess flood
Thread.Sleep(2000);
}
if (inputLine.Contains("leebot go away"))
{
nickname = inputLine.Substring(1, inputLine.IndexOf("!") - 1);
if (nickname == "LeeIzaZombie")
{
writer.WriteLine("QUIT");
writer.Flush();
}
// Sleep to prevent excess flood
Thread.Sleep(2000);
}
/* if (inputLine.EndsWith(" joined the game."))
{
nickname = inputLine.Substring(1, inputLine.IndexOf(" joined") - 1);
nickname2 = nickname.Substring(1, nickname.IndexOf("PRIVMSG") - 1);
writer.WriteLine("PRIVMSG " + CHANNEL + " :Hey, " + nickname2 + " welcome to $server!");
writer.Flush();
// Sleep to prevent excess flood
Thread.Sleep(2000);
}*/
if (inputLine.Contains("Hey LeeBot"))
{
writer.WriteLine("PRIVMSG " + CHANNEL + " :Hey, what up?");
writer.Flush();
// Sleep to prevent excess flood
Thread.Sleep(2000);
}
Thread.Sleep(5);
if (inputLine.EndsWith("JOIN :" + CHANNEL))
{
nickname = inputLine.Substring(1, inputLine.IndexOf("!") - 1);
inputLine = nickname + " joined " + CHANNEL;
}
Console.WriteLine(inputLine);
}
// Close all streams
writer.Close();
reader.Close();
irc.Close();
}
}
catch (Exception e)
{
// Show the exception, sleep for a while and try to establish a new connection to irc server
Console.WriteLine(e.ToString());
Thread.Sleep(5000);
string[] argv = { };
Main(argv);
}
}
}
}
What I've tried to do was make a button in the Form and a Textbox and I wanted to make the button add the text into the writer in the IrcBot class like:
writer.WriteLine("PRIVMSG " + CHANNEL + " :" + textbox.Text);
writer.Flush();
But I can't get the variable "CHANNEL" from the Form, but I manualy changed it to test the writer and the writer did not work.
Basicaly I want the Form to use the console's writer, and I have no idea how to do it.
You can't access it because it's private. Change it to public and you should be able to access it from your Form1 class.
As CHANNEL is static you should access it with the class name, like this:
IrcBot.writer.WriteLine("PRIVMSG " + IrcBot.CHANNEL + " :" + textbox.Text);
IrcBot.writer.Flush();
I am using vs 2010 for developing a winform application using c#.
For dowloading email attachments from mailbox i have used pop3.dll
my code download attachment when i use it on my machine which is direclty connected to internet but when i use it inside a domain where ISA server 2004 is used as a firewall my code only shows me how many message the mailbox box has and then goes for waiting
please can anybody tell me why and what should i do to resolve this problem..
here is the code
public bool DownloadEmailWithAttachment(string Type)
{
try
{
EventLog.WriteEntry("Service", "Attachment Path :> " + AttachmentDir);
long count = 0;
Pop3Client email = new Pop3Client(UserName, Password, IncomingPopAddress);
email.OpenInbox();
//LogEntry();
EventLog.WriteEntry("Service", "Counter :> " + email.MessageCount);
while (email.NextEmail())
{
count = email.MessageCount;
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)enumerator.Current;
string checkIfFile = multipart.Filename;
if (checkIfFile != null)
{
//Console.WriteLine("checkIfFile.Contains('Leave') =" + checkIfFile.ToString());
EventLog.WriteEntry("Service", "checkIfFile.Contains('"+Type+"') =" + checkIfFile.ToString());
if (checkIfFile.Contains(""+Type))
{
EventLog.WriteEntry("Service", "Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Encoding.ASCII.GetBytes(multipart.Data);
//Search FileName
int fileLength = checkIfFile.Length;
EventLog.WriteEntry("Service", "fileLength=" + fileLength);
//int Begin = multipart.ContentType.IndexOf("name="+checkIfFile.ToString());
string leFileNale = checkIfFile.ToString();
EventLog.WriteEntry("Service", leFileNale);
FileStream LeFS = new FileStream(AttachmentDir + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
string DeleteMailContainingSubject = email.Subject.ToString();
if (email.Subject.Contains(DeleteMailContainingSubject))
{
email.DeleteEmail();
EventLog.WriteEntry("Service", "Email with Subject " + DeleteMailContainingSubject);
}
}
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException ex)
{
EventLog.WriteEntry("Service","Exception :" + ex.ToString());
}
return true;
}
This is my code for downloading email attachments.