Send server running status (Up or Down) email asynchronously using C# in Console Application

simflex
 
on Sep 02, 2021 10:49 PM
700 Views

Greetings again experts,

Send server status email to different groups

The code below checks status of apps whether they are down or up and sends email to certain executive team.

However, I have been tasked with modifying the code to send two different types of emails, one - send email to one group regardless of whether the apps running are DOWN or WORKING. This part works.

The second part is to send email to another group only when any or all of the apps are DOWN.

I have come up with the code to do this but not sure how to handle these two tasks in ONE code.

For instance, by adding this condition:

if (results.Any(up => !up))
{
    --then continue with 
    StringBuilder body = ...
}

How do I combine this condition with the rest of the code so that one group of executives receive emails regardless of whether app is down or not and the other group receives email only when the app is down?

namespace showserverstatus
{
    class Program
    {
        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 the number of servers which were down:
            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, bool isBodyHtml = false)
        {
            using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com");
            mm.To.Add("janedoe@tahoo.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);
        }
    }
}

I hope my concern is clear.

As always, thanks in advance.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 03, 2021 05:22 AM

Hi simflex,

Check with below code.

namespaces

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

Code

class Program
{
    static async Task<int> Main(string[] args)
    {
        ConcurrentDictionary<string, bool> urlToStatus = new ConcurrentDictionary<string, bool>();
        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 bodyWorkingDown = new StringBuilder();
        bodyWorkingDown.Append("<p>Please find the status of the DMZ servers below:</p>");
        bodyWorkingDown.Append("<ul>");
        foreach (var kvp in urlToStatus)
        {
            string encodedLink = WebUtility.HtmlEncode(kvp.Key);
            bodyWorkingDown.Append(kvp.Value ? "<li>" : "<li style=\"color:red;background-color:yellow;\">");
            bodyWorkingDown.Append(kvp.Value ? "<a href=\"" : "<a style=\"color:red;\" href=\"");
            bodyWorkingDown.Append(encodedLink);
            bodyWorkingDown.Append("\">");
            bodyWorkingDown.Append(encodedLink);
            bodyWorkingDown.Append("</a> - ");
            bodyWorkingDown.Append(kvp.Value ? "WORKING" : "DOWN");
            bodyWorkingDown.Append("</li>");
        }
        bodyWorkingDown.Append("</ul>");
        // Sends WORKING or DOWN Email.
        await SendEmailAsync("DMZ Server Status", bodyWorkingDown.ToString(), true);
        await Task.Delay(3000);

        StringBuilder bodyDown = new StringBuilder();
        bodyDown.Append("<p>Please find the Down DMZ servers below:</p>");
        bodyDown.Append("<ul>");
        foreach (var kvp in urlToStatus)
        {
            if (!kvp.Value)
            {
                string encodedLink = WebUtility.HtmlEncode(kvp.Key);
                bodyDown.Append(kvp.Value ? "<li>" : "<li style=\"color:red;background-color:yellow;\">");
                bodyDown.Append(kvp.Value ? "<a href=\"" : "<a style=\"color:red;\" href=\"");
                bodyDown.Append(encodedLink);
                bodyDown.Append("\">");
                bodyDown.Append(encodedLink);
                bodyDown.Append("</a> - ");
                bodyDown.Append("DOWN");
                bodyDown.Append("</li>");
            }
        }
        bodyDown.Append("</ul>");
        // Sends DOWN Email.
        await SendEmailAsync("Down DMZ Servers", bodyDown.ToString(), true);
        await Task.Delay(3000);

        // Return the number of servers which were down:
        return results.Count(result => !result);
    }
    static async Task<bool> ServerStatusByAsync(string url)
    {
        HttpClient http = new HttpClient();
        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, bool isBodyHtml = false)
    {
        using (MailMessage mm = new MailMessage(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com"))
        {
            mm.To.Add("janedoe@tahoo.com");
            mm.Subject = subject;
            mm.Body = body;
            mm.IsBodyHtml = isBodyHtml;

            SmtpClient smtp = new SmtpClient()
            {
                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);
        }
    }
}