|
To pass the value which has been typed into the form, you must submit the form. If you use an <a> to navigate to the "forgot password" action, none of the values in the form will be sent.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi all. I've tried for days now (quite literally) to get a simple web service to work, however it's like nothing in the $Ajax section is run at all. Can anyone help me with this, please?
There are two methods I've been trying, with an img with an OnClick or a button.
Both alerts work ("This button was clicked") but nothing else..
<form id="form1" runat="server">
<p>Click on this paragraph.</p>
<div>
<img id="imgMediabtn" src="media/login.gif" onmouseover="this.style.cursor = 'pointer';" />
<asp:Button ID="Button4" runat="server" Text="Button" OnClientClick="BindTreeview()"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
<script>
$(document).ready(function () {
$("p").click(function () {
alert("The paragraph was clicked.");
});
$("#imgMediabtn").click(function () {
alert("The image was clicked.");
$.ajax({
type: "POST",
url: "MyWebService1.asmx/HelloWorld",
data: '{name: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function OnSuccess(response) {
alert("Hello");
},
failure: function (response) {
alert("Goodbye");
}
});
});
});
function BindTreeview() {
alert("The button was clicked.");
$.ajax({
type: "POST",
url: "TestWebService.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function OnSuccess(response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
})
}
}
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class MyWebService1
Inherits System.Web.Services.WebService
<WebMethod()>
Public Function HelloWorld(ByVal name As String) As String
Return "Hello " & name & Environment.NewLine & "The Current Time is: " &
DateTime.Now.ToString()
End Function
End Class
|
|
|
|
|
Clicking the button will submit the form. You need to prevent that from happening to give your AJAX code a chance to run.
Either:
OnClientClick="BindTreeview();return false;" Or:
OnClientClick="BindTreeview(event);"
function BindTreeview(event){
event.preventDefault();
... Event.preventDefault() - Web APIs | MDN[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks, Richard, however still no luck.
Also, clicking on an image (IMG) doesn't have a postback or 'usual' thing for the ajax code not to run and it still won't call the webservice file.
Can't even get a failure response to my ajax call. Could I be missing an ajax exension or something? I'm using visual studio 2019 and loaded this all in a new webforms project. I would think Ajax is built in, right?
|
|
|
|
|
"Ajax" is just calling xmlhttprequest, which is an object that the browser exposes. What you're using to interface to that, though, is JQuery (as per the $ bit) and that isn't "built in" to either ASP.Net nor to the browser. You'll need to include a SCRIPT reference to JQuery, either via a CDN or on your own server.
|
|
|
|
|
Greetings again,
Sorry that I have to come back for help for this script.
Each time this script runs, it sends email notifications to our Executive team advising them of whether any or all of the apps are either down or up.
The script works very well thanks entirely to the great Richard Deeming.
However, management has asked that I modify the script to add foreground color of red and background color of yellow to any URL of the app that is down along with the text indicating down.
For instance, when app sends out email notifications, it lists the apps and their status as follows:
Please find the status of the DMZ servers below:
https://www.link1: WORKING
https://www.link2.com WORKING
https://www.link3.com DOWN
https://www.link4.com WORKING
They would like any app that is down to display as follows:
Please find the status of the DMZ servers below:
link 1: https://www.link1 WORKING
Link 2 https://www.link2.com WORKING
Link 3 https://www.link3.com DOWN
Link 4 https://www.link4.com WORKING
In this example, Link 3 https://www.link3.com DOWN
They would like the entire row of the URL that is down to be color coded, background color of yellow and text color of red.
Link 1 corresponds to the first URL, Link 2 to second URL, etc.
If it is only possible to just color code just the URL and the DOWN text without the link #, that would be fine too.
I am not sure if this is possible.
I could not figure a way to do this.
Any thought on how I could get this to work?
I recognize the send mail bit has body (IsBodyHtml) set to false but I can change this to true if I can the color thing to work.
Below is the working code.
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System.Linq;
namespace showserverstatus
{
class Program
{
static async Task<int> Main(string[] args)
{
System.Collections.Concurrent.ConcurrentDictionary<string, string> urlToStatus = new();
IEnumerable < Task<bool> > tasks = args.Select(async url =>
{
bool result = await ServerStatusByAsync(url);
return urlToStatus.TryAdd(url, result ? "WORKING" : "DOWN");
});
bool[] results = await Task.WhenAll(tasks);
StringBuilder body = new("Please find the status of the DMZ servers below:");
foreach (var kvp in urlToStatus)
{
body.AppendLine();
body.AppendFormat("{0}: {1}", kvp.Key, kvp.Value);
}
await SendEmailAsync("DMZ Server Status", body.ToString());
await Task.Delay(3000);
return results.Count(result => !result);
}
static async Task<bool> ServerStatusByAsync(string url)
{
HttpClient http = new();
using (HttpResponseMessage response = await http.GetAsync(url))
{
Console.WriteLine("GET {0}: {1}", url, response.StatusCode);
if (response.IsSuccessStatusCode)
{
await SendEmailAsync($"{url} WORKING", $"GET {url} returned {response.StatusCode}");
return true;
}
await SendEmailAsync($"{url} DOWN", $"GET {url} returned {response.StatusCode}");
return false;
}
}
static async Task SendEmailAsync(string subject, string body)
{
using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com");
mm.To.Add("janeblow@yahoo.com");
mm.CC.Add("kevin.bruiner@hotmail.com");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
SmtpClient smtp = new()
{
Host = ConfigurationManager.AppSettings["Host"],
Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
};
await smtp.SendMailAsync(mm);
}
}
}
As always, many thanks in advance
|
|
|
|
|
You would need to format the message body as HTML.
static async Task SendEmailAsync(string subject, string body, bool isBodyHtml = false)
{
using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com");
mm.To.Add("janeblow@yahoo.com");
mm.CC.Add("kevin.bruiner@hotmail.com");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = isBodyHtml;
SmtpClient smtp = new()
{
Host = ConfigurationManager.AppSettings["Host"],
Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
};
await smtp.SendMailAsync(mm);
}
static async Task<int> Main(string[] args)
{
System.Collections.Concurrent.ConcurrentDictionary<string, bool> urlToStatus = new();
IEnumerable<Task<bool>> tasks = args.Select(async url =>
{
bool result = await ServerStatusByAsync(url);
return urlToStatus.TryAdd(url, result);
});
bool[] results = await Task.WhenAll(tasks);
StringBuilder body = new("<p>Please find the status of the DMZ servers below:</p>");
body.Append("<ul>");
foreach (var kvp in urlToStatus)
{
string encodedLink = System.Net.WebUtility.HtmlEncode(kvp.Key);
body.Append(kvp.Value ? "<li>" : "<li style=\"color:red;background-color:yellow;\">");
body.Append(kvp.Value ? "<a href=\"" : "<a style=\"color:red;\" href=\"");
body.Append(encodedLink);
body.Append("\">");
body.Append(encodedLink);
body.Append("</a> - ");
body.Append(kvp.Value ? "WORKING" : "DOWN");
body.Append("</li>");
}
body.Append("</ul>");
await SendEmailAsync("DMZ Server Status", body.ToString(), true);
await Task.Delay(3000);
return results.Count(result => !result);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Oh wow, this is so incredible.
Just too good.
Many, many THANK YOU sir.
I truly do appreciate your help.
You are the nicest, most generous individual that I never met.
Sir, do you know why they keep getting two different emails?
Let's say for instance that they just wanted to get the status of one link, https://www.link1.com
When they receive email, it displays like this:
DMZ Server Status. Please find the status of the DMZ servers below.
https://www.link1.com WORKING GET https://www.link1.com" returned OK
Is there a way to remove the second email so they always get the bolded one with subject DMZ Server Status and when they open the email, they get details about the link or links?
UPDATE: I *THINK* I got it!
This is the part of the script that is sending the GET email ( the second email)
static async Task<bool> ServerStatusByAsync(string url)
{
HttpClient http = new();
using (HttpResponseMessage response = await http.GetAsync(url))
{
Console.WriteLine("GET {0}: {1}", url, response.StatusCode);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
}
So by commenting out
await SendEmailAsync(...)
for both WORKING and DOWN, allows only one email:
DMZ Server Status... to come through.
I hope it is correct.
If so, all I would need help on now is to create another copy of this same script but this time, to send email to certain group ONLY when any or all of the apps is(are) down and I swear no more changes will be needed.
modified 1-Sep-21 14:57pm.
|
|
|
|
|
That's the correct change to remove the other email.
If you only want to send the main email if any site is down, you'll need to check before sending it:
bool[] results = await Task.WhenAll(tasks);
if (results.Any(up => !up))
{
StringBuilder body = ...
...
await SendEmailAsync("DMZ Server Status", body.ToString(), true);
await Task.Delay(3000);
} If you only want to send the message if all sites are down, use:
if (results.All(up => !up))
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you so so so much sir.
Your complete grasp of technology is truly amazing.
No way I get this solution without your unflinching support and incredible patiences.
May God continue to bless more.
|
|
|
|
|
i need code for bank transaction when i simply give coustermer id
|
|
|
|
|
First you need to design your banking system. You cannot create a transaction until you know what inputs it takes, what outputs it needs to produce, and what rules it must follow.
|
|
|
|
|
|
Hello experts,
I have five (5) public facing REST servers and I have been tasked with coming up with a script that will monitor the status of the servers (whether up or down) and send email notifications three times a day, at &30am, 12:30pm, and 3:30pm.
The email notification should either indicate whether the servers are up or down.
I have had issues thinking up a solution.
However, while googling, I found this article:
Repeat Task every N interval using Windows Service in C# and VB.Net[^]
I am trying to follow it and I have made some minor changes.
For instance, in appSettings, I changed the configuration to this:
<appSettings>
<add key ="Mode" value ="Daily"/>
<add key ="ScheduledTime" value ="24:00"/>
</appSettings>
I am not entirely sure that it is completely correct.
Then, I made this change:
if (mode == "DAILY")
{
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if(DateTime.Now().ToString("HH:mm") = "07:30" || DateTime.Now().ToString("HH:mm") = "12:30" || DateTime.Now().ToString("HH:mm") = "3:30"))
{
scheduledTime = scheduledTime.AddDays(1);
}
}
Do I still need the WriteToFile(...) which saves the server status to a text file?
Here is the complete script from that link:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(SchedularCallback));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if(DateTime.Now().ToString("HH:mm") = "07:30" || DateTime.Now().ToString("HH:mm") = "12:30" || DateTime.Now().ToString("HH:mm") = "3:30"))
{
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
Schedular.Change(dueTime, Timeout.Infinite);
}
catch(Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
{
serviceController.Stop();
}
}
}
private void SchedularCallback(object e)
{
this.WriteToFile("Simple Service Log: {0}");
this.ScheduleService();
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
}
Assistance, as always, is greatly appreciated.
|
|
|
|
|
Rather than trying to write your own task scheduler, use the built-in Windows task scheduler.
Task Scheduler for developers - Win32 apps | Microsoft Docs[^]
Create a simple console application which checks your servers, sends the email, and exits. Schedule it to run at whatever time(s) you want.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard,
As always, thank you sir for your continued assistance.
I *think* this console app will do the trick:
using System.Net.NetworkInformation;
public static void ServerStatusBy(string url)
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(url);
Console.WriteLine("Status of Host: {0}", url);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
Console.WriteLine(reply.Status);
}
Then this will be the call:
Console.Write("Enter server url:");
var url = Console.ReadLine();
Console.Clear();
ServerStatusBy(url);
Console.ReadLine();
I have some questions please.
1, There are 5 API servers as indicated and I can schedule this to run on each server, fine.
However, can you help with not having to interact with the app?
We don't want to have to enter server url in order to get the status.
We just want the app to contact the URL automatically.
So could that mean something like this:
public static void ServerStatusBy(string url)
url = "https://www.something.com/REST" for example?
The second question that I have is that I can essentially write something like:
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Server APP One is running");
}
else
{
Console.WriteLine("Server APP One is running");
}
Once again, thank you very much sir for your help.
|
|
|
|
|
Just a thought; what if you pass the URL as a command line argument ? This way the program is agnostic to which server it is checking. You could also pass the email addresses on the command line.
|
|
|
|
|
Hi David and thanks a lot for your response.
When you say to pass the URL as command line argument, do you mean when scheduling the app to run?
This is all new for me unfortunately and I ask that you guys forgive me for the questions if they appear silly as probably are.
//UPDATE:
I tried changing the code to the one below so user doesn't have to be prompted to enter URL:
using System;
using System.Net.NetworkInformation;
using System.Text;
namespace showserverstatus
{
class Program
{
static void Main(string[] args)
{
}
public static void ServerStatusBy()
{
Ping pingSender = new Ping();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 10000;
PingOptions options = new PingOptions(64, true);
PingReply reply = pingSender.Send("www.yahoo.com", timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
Console.WriteLine(reply.Status);
}
}
I got the following:
Press any key to continue...
When I do, the console closes.
No records shows.
modified 24-Aug-21 23:19pm.
|
|
|
|
|
Any help with this please?
I know this is not your issue but I am being pressured for completion of this task.
Many thanks in advance.
|
|
|
|
|
I see a few problems with your code:
1) Looks like your main() does not call your ServerStatusBy() function
2) You are not reading any values from the command line.
Here is a VB example:
Sub Main()
Dim args() As String = System.Environment.GetCommandLineArgs()
Dim s As String
For i As Integer = 0 To args.Length - 1
Console.WriteLine(String.Format("Arg {0}): {1} ", i, args(i)))
Next
s = Console.ReadLine
End Sub
When you run the program from a command prompt like HellowWorld.exe www.google.com jdoe@companyabc.com
The output is as follows:
Arg 0): C:\_WorkingCopies\HelloWorld\HelloWorld\bin\Debug\HelloWorld.vshost.exe
Arg 1): www.google.com
Arg 2): jdoe@companyabc.com
You can see that you want to grab Arg(1) as the URL and Arg(2) as the email address you want to send the report.
|
|
|
|
|
David,
Thank you so much for your help.
I converted your VB to C# and this is my code after integrating yours but still doesn't work.
I am also getting this: Unnecessary assignment of a value to 's'
Just so you know, I am not limited to using only C# for this task.
I can use VB if that's available.
Thank you again for your help.
using System;
using System.Net.NetworkInformation;
using System.Text;
namespace showserverstatus
{
class Program
{
static void Main()
{
string[] args = System.Environment.GetCommandLineArgs();
string s;
for (int i = 0; i <= args.Length - 1; i++)
Console.WriteLine(string.Format("Arg {0}): {1} ", i, args[i]));
s = Console.ReadLine();
}
public static void ServerStatusBy()
{
Ping pingSender = new Ping();
int timeout = 10000;
PingReply reply = pingSender.Send("www.yahoo.com", timeout);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
Console.WriteLine(reply.Status);
}
}
}
|
|
|
|
|
You can get the command-line arguments by changing the declaration of your Main method to Main(string[] args) .
You don't want to call Console.ReadLine if you're going to schedule your application to run in the background. There won't be a user to press a key and end the application. Instead, return an exit code indicating the status of your application - 0 generally indicates success, and anything else indicates an error.
You'll want to pass each command-line argument to your status function, and use that as the site to test - for example:
static int Main(string[] args)
{
int result = 0;
foreach (string site in args)
{
if (!ServerStatusBy(site))
{
result++;
}
}
return result;
}
static bool ServerStatusBy(string site)
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(site, 10000);
if (reply.Status != IPStatus.Success)
{
Console.WriteLine("{0}: {1}", site, reply.Status);
return false;
}
...
return true;
}
YourApp.exe site1.local codeproject.com google.com
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
WOW, thank you very much sir.
You remind me so much of this super guru called Bill Wilkinson of classic ASP and JavaScript way back when I was learning classic ASP.
Just when I felt stuck and in trouble, he would come out of nowhere to help me out.
God bless you sir.
Please forgive me for additional questions.
1, does this ... (the dot dot dot) mean there is more code to go in there?
2, I use this -> YourApp.exe site1.local codeproject.com google.com for scheduling the run times, correct?
3, This -> YourApp.exe site1.local codeproject.com google.com means that I can add the five links all at once correct?
Many thanks again. I really appreciate your help.
I feel a bit better now.
UPDATE: I think I answered question #1.
This is how I *THINK* the code should look like now.
I added the email component since users will be getting emails with the status of the servers whether up or down.
Email subject should indicate Server Up or Down bases on what happens on ServerStatusBy() method
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Text;
using System.Configuration;
namespace showserverstatus
{
class Program
{
private string statusMessage;
static int Main(string[] args)
{
int result = 0;
foreach (string site in args)
{
if (!ServerStatusBy(site))
{
result++;
}
}
return result;
}
static bool ServerStatusBy(string site)
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(site, 10000);
if (reply.Status != IPStatus.Success)
{
Console.WriteLine("{0}: {1}", site, reply.Status);
string statusMessage = "Shw message that Server is down";
SendEmail();
return false;
}
else
statusMessage = "Shw message that Server is up";
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
SendEmail();
return true;
}
public static void SendEmail()
{
using (MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"],"joe.bloew@yahoo.com"))
{
mm.To.Add("joesixpack@gmail.com");
mm.CC.Add("janeDoe@gmail.com");
mm.Subject = statusMessage;
mm.Body = "Test";
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
Console.WriteLine("Sending Email......");
smtp.Send(mm);
Console.WriteLine("Email Sent.");
System.Threading.Thread.Sleep(3000);
Environment.Exit(0);
}
}
}
}
modified 25-Aug-21 19:11pm.
|
|
|
|
|
1. It looks like you've already answered that one.
2. Yes, you'd set the application to be the full path to your .exe file, and the command-line arguments to be the list of domains you want to test.
3. You can pass as many domains to test as you want as command-line arguments.
samflex wrote:
if (reply.Status != IPStatus.Success)
{
Console.WriteLine("{0}: {1}", site, reply.Status);
string statusMessage = "Shw message that Server is down";
SendEmail();
return false;
}
else
statusMessage = "Shw message that Server is up"; A couple of problems there:
Within the if block, you've created a local variable called statusMessage , which hides the static field of the same name. The value you store in the local variable won't be visible to the SendEmail function.
You don't need the else , since you've got a return within the if block.
samflex wrote:
Console.WriteLine("Email Sent.");
System.Threading.Thread.Sleep(3000);
Environment.Exit(0); You shouldn't call Environment.Exit within the SendEmail function, since that will terminate your app after the first message is sent.
I'd avoid using a field, and pass the message subject and body as parameters to the SendEmail function instead.
public static void SendEmail(string subject, string body)
{
using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joe.blow@yahoo.com");
mm.To.Add("joesixpack@gmail.com");
mm.CC.Add("jandoe@gmail.com");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
SmtpClient smtp = new()
{
Host = ConfigurationManager.AppSettings["Host"],
Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
};
Console.WriteLine("Sending email...");
smtp.Send(mm);
Console.WriteLine("Email sent.");
System.Threading.Thread.Sleep(3000);
}
static bool ServerStatusBy(string site)
{
Ping pingSender = new();
PingReply reply = pingSender.Send(site, 10000);
if (reply.Status != IPStatus.Success)
{
Console.WriteLine("{0}: {1}", site, reply.Status);
SendEmail($"{site} DOWN", $"Ping {site} returned {reply.Status}.");
return false;
}
Console.WriteLine("IP Address: {0}", reply.Address);
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
SendEmail($"{site} Up", $@"Ping {site}
IP Address: {reply.Address}
RoundTrip time: {reply.RoundtripTime}
Time to live: {reply.Options.Ttl}
Don't fragment: {reply.Options.DontFragment}
Buffer size: {reply.Buffer.Length}");
return true;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Man, looks like you were born with this
I work hard and spend a lot of time learning this but still struggle mightily.
Many, many thanks sir.
I am so grateful as this solution comes in handy as they are demanding demo by 10am togay.
Just need one more clarification, is this right?
YourApp.exe site1.local codeproject.com google.com
|
|
|
|
|