Good Sample .Net Windows service to report an error - c#

I am writing a windows service that will be doing a lot of network communication (copy many many files in shared folders and modify database).
I need a way to notify a user (if logged on) of any exceptions/errors. My issue is do group to errors for send it (by email) to administrator address.
I am aware of event logging neither notification bubble from system tray, but the administrator not views that log, he prefers email.
The ideal component is ASP.NET Health Monitoring, but only works for IIS, and it is required a component similar for Windows Services.
Any sample application Windows Service in C# or another language in .net (with source code) about this issue ??

If you're just needing a way to send an email notification, .Net has SMTP and mail types to take care of this. Email notifications are common in software anymore and that's why the commonly used functionality has been incorporated into the base class lib.
You could use SmtpClient, MailAddress, and MailMessage objects to accomplish what you need to simply send an email notification. Of course you need to have access to an SMTP server to transmit the mail, so find out what its host address is to properly configure your application. Here are a few examples:
SmtpClient mailClient = new SmtpClient("smtp.fu.bar");
MailAddress senderAddr = new MailAddress("you#fu.bar");
MailAddress recipAddr = new MailAddress("admin#fu.bar");
MailMessage emailMsg = new MailMessage( senderAddr, recipAddr );
emailMsg.Subject = "Test email.";
emailMsg.Body = "Here is my email string which serves as the body.\n\nSincerely,\nMe";
mailClient.Send( emailMsg );
That example is just straight code, but it would be better to put it into a reusable method like this:
public void SendNotification( string smtpHost, string recipientAddress, string senderAddress, string message, string subject )
{
SmtpClient mailClient = new SmtpClient(smtpHost);
MailMessage emailMsg = new MailMessage( new MailAddress(senderAddress), new MailAddress(recipientAddress) );
emailMsg.Subject = subject;
emailMsg.Body = message;
mailClient.Send( emailMsg );
}

check this : http://www.codeproject.com/Articles/16335/Simple-Windows-Service-which-sends-auto-Email-aler
my advice if it's first time to work with windows service (because Windows Service is very hard to debug)
first make it Command Line application with c#
when you be certain with all functionality of your project move it to Windows Service

Related

What are possible reasons a recipient doesn't receive email some of the time, but CC receives it 100% of the time?

We have an internal web application that sends email notifications when a form is submitted. It sends using an internal exchange server that is connected to Office 365.
The notifications go to a distribution group, and for years this has worked fine, but some weeks ago they started not getting some of the emails, roughly 50% of them. To try and troubleshoot this issue, I added myself to the CC on the test version of this internal site, and while the distro group still only receives roughly 50% of the notifications they should be receiving, I get 100% of them. If they submit 10 forms, they'll only receive 5 or so while I receive all 10.
Looking in the exchange trace logs, I can see most of the emails that send successfully to both the distro group and me, but not all of them. Also mysteriously, I cannot locate the emails that only send to myself at all.
To further complicate this, this all started when some users were errantly added to the distro group, and subsequently removed. Those users happened to be in a different domain than the others that were already in and still are in the group.
Here is the relevant code that sends the emails upon submission of the form, from a controller action in a .NET Core project.
var mailSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("Mail");
var clientHost = mailSettings.GetValue<string>("clienthost");
var clientPort = mailSettings.GetValue<int>("clientport");
if (account.Status.Equals("Submitted"))
{
using (var mail = new MailMessage())
{
string body = "body here";
mail.Subject = "subject here";
#if DEBUG
mail.Subject = "TEST - " + mail.Subject;
#endif
mail.Body = body;
mail.From = new MailAddress(account.Email);
mail.To.Add("distrogroup#mycompany.fake");
#if DEBUG
mail.CC.Add("myemail#mycompany.fake");
#endif
mail.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Host = clientHost;
smtp.Port = clientPort;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
}
}
The inconsistent behavior and missing log information is really making me scratch my head, so I'm looking for ideas on what I can do to continue troubleshooting. What steps would you take to narrow this issue down? Is there any additional information that I should provide?
Thank you in advance.
EDIT:
If I replace the distribution group with the individual email addresses that belong to it, they all get them 100% of the time. I'm really sure what would cause the distro group to fail some of the time, but I thought that was interesting.

Windows Phone 8 sendGridMessage Compile error

private async void sendMail(string from,string to, string subject,string text)
{
// Create network credentials to access your SendGrid account
string username = "xx";
string pswd = "xx";
MailMessage msg = new MailMessage();
NetworkCredential credentials = new NetworkCredential(username, pswd);
// Create the email object first, then add the properties.
// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("xx");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
myMessage.From = new MailAddress(from);
// Create an Web transport for sending email.
var transportWeb = new SendGrid.Web(credentials );
// Send the email.
await transportWeb.DeliverAsync(myMessage);
}
My application is Windows Phone 8.1, I try to send mail via sendGrid I created an account and include libraries to code but it gives 3 error:
error CS0570: 'SendGrid.SendGridMessage.From' is not supported by the language
error CS1502: The best overloaded method match for 'SendGrid.Web.Web(string)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'System.Net.NetworkCredential' to 'string'
I have used this site"https://azure.microsoft.com/tr-tr/documentation/articles/sendgrid-dotnet-how-to-send-email/" as reference.
Do errors stem from because app is a Windows Phone app or what?
And is there any other way to send an email by declaring "from" within code?
This isn't really an answer to your question, but it's important enough I made it an answer and not a comment.
This is not a secure way to send email from a mobile device, because you are giving the code that contains the credentials to users that install. All they need to do is inspect the traffic from your app and your SendGrid API key or account is compromised.
You need to make a request to some secure backend server (or provider, e.g. Parse or Azure), and then send the email from that server rather than the client app.
If you want to debug the code though, check out the readme and example on Github. Microsoft's docs go out of date rather quickly. https://github.com/sendgrid/sendgrid-csharp

How to send mails to multiple reciepients from web application?

I have developed a asp.net Mvc 4 project and now i am planing to integrate a Mail system in my application.Initially i taught like integrating mail System in my existing web application but later i moved it to a console application using Scheduler to send mail at some time interval.
My scenario is like i have a list of mail ids and i need to send mail to all these mail ids . I have checked System.Web.Mail and i found i can only give one email address at a time. Is it possible in System.Web.Mail or is there any other library available to achieve my scenario.
To in System.Net.Mail is a MailAddressCollection,so you can add how many addresses you need.
MailMessage msg = new MailMessage();
msg.To.Add(...);
msg.To.Add(...);
Chris's answer is correct but you may want to also consider using a mail service. Here are some you could try - they all have a free tier to get started on.
http://sendgrid.com/
http://www.mailgun.com/
https://mandrill.com/
http://aws.amazon.com/ses/
You can easily sent emails to more than one recipient. Here is a sample that uses a SMTP server to send an email to multiple addreses:
//using System.Net.Mail;
public void SendEmail(){
MailMessage email = new MailMessage();
email.To.Add("first#email.com");
email.To.Add("second#email.com");
email.To.Add("third#email.com");
email.From = new MailAddress("me#email.com");
string smtpHost = "your.SMTP.host";
int smtpPort = 25;
using(SmtpClient mailClient = new SmtpClient(smtpHost, smtpPort)){
mailClient.Send(email);
}
}
Just a note: if you go with SMTP, you should probably have a look also on MSDN for the SmtpClient.Send method, just to be sure you are catching any related exceptions.

Is it possible to send an email programmatically without using any actual email account

I'm thinking of implementing "Report a bug/Suggestions" option to my game, however I am not quite sure how I could get that working. I do not have my own server or anything, so I can't just send the text that user has written to there.
The only way I came up with is that the client would write a message and I would send it to an email account where I could read them. However, I do not want that users would need to send the reports through their personal accounts. I am not quite sure how I could implement this and googling didn't bring up any good suggestions.
I haven't done a lot of network stuff, so I'd really appreciate it if you could explain ( possibly even in code ) the process step-by-step.
I am using C# and the game is being programmed for Windows Phone 7.
Yes, it is absolutely possible to do that. From a relatively low-level perspective, you need to:
Resolve the MX (mail-exchanger) server for the e-mail account you want to send to.
Open a socket to the MX server.
Send the appropriate SMTP commands to cause the e-mail message to be delivered to your recipient account. You essentially have the freedom to set the "from" address to be any arbitrary thing you want.
SMTP is a very simple/human-friendly protocol, so it's not a massive effort to do all of that by hand. At the same time, there are prebuilt libraries that will handle all of that for you (except possibly the resolution of the recipient's MX server).
Note that emails sent this way are more likely to be filtered out as spam (generally because the sender's IP/hostname is not going to match whatever domain you put on the outgoing e-mail address you decide to use).
Also note that since you can set the "from" address to anything, you have the option of asking the user if they want to provide their actual contact address, and if they do you can make that the "from" address so that you can actually get back in touch with them if necessary.
You don't need to use email at all. Consider using an error reporting service like sentry or airbrake.
These services have clients that you embed in your program; which automatically log your errors, including any debugging information/stacktrace; and notify you by email when your application reports a problem.
Usually you integrate the app's API into your own error handling mechanism. At the point of an error, the client will capture your debugging information, you can popup a modal asking user for information like "what were you doing when this error happened?", save that as part of your error response that is sent back to the service.
Since the app works over HTTP, you don't need any special ports to be open. It is easier and more helpful than having users send you emails with "it doesn't work!!", and you don't have to deal with email sending headaches.
I recently wrote an article on this: Sending email with C#
You basically have two choices, either you send it using an SMTP-client, this means that you have to have a SMTP-server and be able to connect to port 25 (if you're not using an external SMTP, then you have to manage that by yourself). Or you can use an external email provider, such as:
AlphaMail
SendGrid
Mandrill
If you're using AlphaMail you can send emails in the following way:
IEmailService emailService = new AlphaMailEmailService()
.SetServiceUrl("http://api.amail.io/v1/")
.SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
var person = new Person()
{
Id = 1234,
UserName = "jdoe78",
FirstName = "John",
LastName = "Doe",
DateOfBirth = 1978
};
var response = emailService.Queue(new EmailMessagePayload()
.SetProjectId(12345) // ID of AlphaMail project (determines options, template, etc)
.SetSender(new EmailContact("support#company.com", "from#example.com"))
.SetReceiver(new EmailContact("Joe E. Receiver", "to#example.org"))
.SetBodyObject(person) // Any serializable object
);
Another thing that differs from just building HTML and sending it with an SMTP-client is that with AlphaMail you have the ability to edit your emails outside your code directly in a GUI. You can also easily create highly dynamic templates using AlphaMail's templating language Comlang.
<html>
<body>
<b>Name:</b> <# payload.FirstName " " payload.LastName #><br>
<b>Date of Birth:</b> <# payload.DateOfBirth #><br>
<# if (payload.Id != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
So this is my thought, why don't you have the email sent to you...as you?
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name"); //Both the email addresses would be yours
var toAddress = new MailAddress("to#example.com", "To Name"); //Both the email addresses would be yours
const string fromPassword = "fromPassword";
const string subject = "There name or whatever";
const string body = "Errors ect....";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
code from here
All they would see would be the submit button so they wouldn't have all your personal username/password, also you should prolly set up a dummy account to have them sent to even if it just then forwards them to your real email account.
Another way to achieve this would be to host a WCF Service which takes in your Message and stores in db or /sends email. One downside of this is you'll need a web server to do this.
Try following code this might help you :
Dim objCDOMail
Set objCDOMail = Server.CreateObject("CDONTS.NewMail")
objCDOMail.From = "sender#domain.com"
objCDOMail.To = "receiver#domain.com"
objCDOMail.Subject = "Test Mail Script"
objCDOMail.BodyFormat = 0
objCDOMail.MailFormat = 0
objCDOMail.Body = "Testing Mail from Test Script"
objCDOMail.Importance = 1
objCDOMail.Send
Set objCDOMail = Nothing

Email Sender App with Images on Local Machine

I have a small email application that lets a user build a message from checkboxes and then send the message as an email. I am trying to add an image to the email, i.e. a logo or signature. The application worked fine but as I was reseaching getting the images into the email, I found that I should be using System.Net.Mail instead of Interop. So I changed my email class to the code below. Now I'm not recieving the emails. I'm assumeing this is because the code is set-up for a server and I just want to run this on my local machine. This is just something I'm playing with to help me understand some concepts so real world use is not going to be a factor. I just want to be able to test my little program on my Outlook email account locally. My code is as follows...
using System;
using System.Net.Mail;
using System.Net.Mime;
namespace Email_Notifier
{
public class EmailSender:Notification
{
string emailRecipient = System.Configuration.ConfigurationManager.AppSettings ["emailRecipient"];
public void SendMail(string message)
{
try
{
string strMailContent = message;
string fromAddress = "MyApp#gmail.com";
string toAddress = emailRecipient;
string contentId = "image1";
string path = (#"C:Libraries/Pictures/Logo.gif");
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Email Notification";
LinkedResource logo = new LinkedResource( path , MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
// HTML formatting for logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:Logo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("localhost");
mailSender.Send(mailMessage);
}
catch (Exception e)
{
Console.WriteLine("Problem with email execution. Exception caught: ", e);
}
return;
}
}
}
You specify mailSender = new SmtpClient("localhost");.
Have you set up an SMTP server on your local machine? If not, you will need to do so to use SmtpClient. Otherwise, specify a hostname other than localhost, perhaps using your Gmail account as specified here, bearing in mind you will need to configure it for authentication and SSL.
See also the documentation for SmtpClient.
There are also one or two other issues I can see with your code - but let's deal with these after getting simple mail sending working.
if your problem is that you don't have a smtp server you are talking to on your machine, you will see an exception rather than just silently not having your email delivered (which i believe is what you are seeing given that you did not list an exception, but not completely sure). it could be that you are successfully delivering to your local smtp server, but it is failing to send the mail on. if you have the iis smtp server installed and that is what you are trying to use to send the mail, you can see failed email messages in the subdirectories of C:\Inetpub\mailroot. there is a badmail subdirectory that should have failed deliveries.
if you are on windows 7, it doesn't support the iis smtp server. an alternative for having an smtp server on your machine that doesn't actually deliver the email but does show you everything that has come through for any email address is http://smtp4dev.codeplex.com/. even if i do have the iis smtp server available in my operating system, i prefer this for development needs.

Categories

Resources