Real time console app that triggers everytime it receives new email? - c#

I have an email parser application in C# that uses Exchange Web Service where it retrieves incoming emails from the exchange account. Is it possible to have it run real time in the background? Whenever an email arrives, it automatically does its job without me having to click it every time or using a task scheduler. The first plan is task scheduler which I set to run every 5 minutes but I need a more efficient way as this app will receive heaps of emails which will then send a reply back to the sender.
Let me know if I missed some information or if my question is too vague.
Edit:
I did what L-Three suggested but... (please read my reply to BugFinder). The program must only trigger if there is an incoming email. Looping is consuming too much of CPU usage. Is it possible to do this?

I think you are looking for EWS Push Notifications (see https://msdn.microsoft.com/en-us/library/office/dn458791(v=exchg.150).aspx)
If you google for this term, you will find some sample programs, eg http://www.codeproject.com/Articles/73834/EWS-Mail-Notifier.

Related

Bot Framework - Prevent GatewayTimeout for Long Operation

I've built a bot using botframework V4 for .Net that replies to user for both email and directline channels.
However, some of the request takes more than 15 seconds to complete, therefore I'd receive a GatewayTimeout error:
These requests are heavy (fetch some data from the database, fetch other data from another server via API calls, process the data, generate HTML and send them back to the user...) therefore nothing can be done to shorten the process.
I am aware that the gateway timeout delay is by design (the 15 seconds), but the problem is that the channel automatically retries the request after a small period of time and I end up receiving multiple emails for the same query (approx. 1 minute apart each).
I noticed as well that the directline replies are much faster than email ones (websocket vs SMTP), therefore this is mainly occurring with the email channel only. Noting that the emails are kept under 300KB as per this comment but can easily have a size close to this limit.
Therefore, is there a way to:
Increase the timeout delay?
Disable the automatic retries?
Or perhaps a certain workaround to prevent this issue?
Remember that your bot is a web app that exposes an HTTP endpoint, and every activity sent to your bot is an API call. Long-running API calls should be designed to return a response immediately and do their processing asynchronously. For example, consider the Recognize Text Computer Vision API. It just returns an Operation-Location where the actual result will become available later.
For bot Framework bots, all you have to do to send a message to the channel after the turn already ended is to send a proactive message. It's often also a good idea to design your bot to give the user an indication that the result is coming, such as by sending a preliminary "processing" message or a typing indicator, but that's probably unwanted in the case of the email channel. Eric Dahlvang explained this in the issue you linked to:
If the developer knows the response will take longer than 15 seconds, it is possible, depending on the channel, to start a separate thread to handle the long running process, return a valid status code on the receiving thread, and when the process finishes, send a proactive message from the background thread.

How to wait 24hrs before completing an async task?

I'm making an MVC app with the .NET Framework and in one of my controllers I call an async task that sends an e-mail to the signed in user.
This task is called upon when the user clicks a specific checkbox and the e-mail is meant to work as sort of reminder.
The entire task works as intended (the user gets an e-mail when the checkbox is checked), but I need it to wait 24 hours before actually sending the e-mail, as it is a reminder.
Currently the e-mail is sent right away, how can I delay the completion of my "e-mail task", while the code continues?
Use a library like Hangfire which lets you schedule background jobs and backs them with persistent storage.
You can then easily schedule a job like:
BackgroundJob.Schedule(
() => SendEmail("user#domain"),
TimeSpan.FromDays(1));
This is a classic X Y Problem. While it may be possible to make your system wait 24 hours you are creating a very fragile system that can be affected by app pool resets and server reboots.
Putting aside the possibility of an unexpected reboot, what happens when your maintenance cycle comes around and a scheduled reboot is going to happen? How many queued email reminders will you have that you can't do anything with?
The best approach for systems that don't immediately use their data is to buffer it through some form of storage scheme. It could be as simple as writing queued emails to files on the system, or something more robust like a database with a dedicated email sending service.
I have used a LOT of email sending systems over the years, and even for immediate sends we have used a database intermediary, with one dedicated email sending Windows service to produce and send the actual email. By centralizing the email production you not only get one place to maintain your email sending code, but you can also increase the durability of the whole system.
Bonus points if your database is part of a high availability cluster, as in this kind of system the database becomes the critical point. If it is then you're protected from any form of downtime other than a total network outage.
Let the Task wait for 24 hours before sending the mail.
await Task.delay(TimeSpan.FromHours(24));
Add this line in your async function bfore sending the email

Polling asp.net MVC server from an Android client

After much research and bumping into the wall a couple of times, it's time to ask some questions.
I'm developing a project which is going to send a message from a web client to a server, then the server should notify multiple clients about the update, which should be done in seconds.
First I thought of using GCM notifications, but the user then have to push the notification in order for some code to run on the client (turning on gps and stuff) but my clients don't have time for clicking the notification when it arrives. So it has to be done without user interaction.
Next thing I thought about was if the android client could listen to the c# server and run code when the server had a new message, but I haven't found a working torturial yet. I was looking into GCM again without push, just messages back and forward, but it's getting difficult to get to work. Also sockets was a option, but it also seems really difficult to get to work and I'm not sure if those options are the way to go.
So I was thinking to just let the android have a background service which is polling either a database or a method on my c# server.
Can anybody give me an idea of what is the right option and maybe a link to a tutorial which is a nice step by step thing.
It could be nice if I had the option to also use it on IOS at a later point.
If i understand correctly, what you are trying to do can be easily done by one of the following or more ways:
1)Use GCM messages with a Payload! When the mobile client receives the Notification it gets the Payload and proceeds on specific actions. http://developer.android.com/google/gcm/adv.html - http://developer.android.com/training/cloudsync/gcm.html#react
2)Use a SyncAdapter and make your app use an AlarmManager which will periodically tell to the app to poll the server through the SyncAdapter and check for new content. Another way of triggering the SyncAdapter is sending a GCM notification like in the first step. http://developer.android.com/training/sync-adapters/creating-sync-adapter.html

Schedule an email to be sent

Is there a way for me, with a WPF browser application, to schedule an email to be sent? What I will have is a date, date of user subscription, and then I would like it to send the user an email 5 days before their membership expires. How can I achieve this?
The easiest way to do this is to write a record to a database table (say a email task table) then write a Windows service that polls this table say every minute, checks for any emails that need to be sent and then sends them.
Seems to be you'll have to do something on the server side with a scheduled job/task checking daily for who needs to get an email sent to them.
AFAIK the SMTP server sends the emails immediately so you have to persist this queue in your application (or use MSMQ as queue storage) and have some part of your application executing the delivery at required time.
At this point my question is, if you can send when you know is the time to send, can't you send directly later without using the queue or do you have any logic in your application so that the email you would generate today can't be generated at later time?
I would probably create a Windows Service or, even better, have a scheduled task calling my application every day at midnight then the application verifies to whom the email should be sent right now, creates it and sends it out.

Sending emails with ASP.NET

I am building a web site, and the client wants a newsletter "system" on it.
How do I send this kinds of mass (>1000) emails?
I read somewhere that using sendasync method of the smtpclient does the trick.
But it constantly gives me an "Email faliure" exception. And, I don't know what to do with that right there...
So, basically my question is, is it ok to send the emails using the SEND method of the smtpclient, but each mail in it's own thread.
for eg.
NewsletterEmail newsletterEmail = new NewsletterEmail(emailAdress[i], mailSubject, mailBody);
Thread t = new Thread(new ThreadStart(newsletterEmail.MakeAndSendEmail));
t.IsBackground = true;
t.Start();
i think , you should rethink about your startegey for sending bulk emails
Creating > 1000 threads is not a good idea , it may even crash your server or it may make your server respond very slow.
Tell your client about Constant Contact. They are going to handle this much better than you ever could. It's also cheaper than your time.
In the event that fails you have a couple options.
If they already have an email server, leverage that to do the email broadcasting. In other words, relay the mail through that server.
If you can't do that, go download a free email server. I've been using hMailserver. Set it up and relay through it.
If you can't do that, write your own SMTP processing engine. Don't attempt to send the emails directly from ASP.Net. Queue them up in a database and write a windows service to handle the mail broadcasting.
Sending emails can sometimes take several seconds per email. This could completely hose your website while it's trying to handle sending 1000 emails.
A number of mail servers are configured with grey listing, meaning that they require you to send the same email twice in order to prove you aren't a spammer.
Next, getting the DNS appropriately set up can be a PITA. Which is why I suggest constant contact. I have one client that took nearly 5 years to finally get their DNS configured; and yes, I gave them explicit instructions once a year on what to do. Reverse DNS is critical.
Another thing is that some recipient servers have a limit on the number of threads they will accept from you at once. Most mail servers are built to take this into consideration. If you cross that boundary, then the recipient servers will consider you a spammer and take appropriate action.
Another problem area is in sending to a bad address, over and over again. AOL and others will consider you a spammer just for this one thing.
Point is, you really don't want to write this yourself.
Your best bet would be to have a separate process send the emails. Either have it run on a schedule to check for emails that need to be sent (maybe store the emails in a table?), or, if you don't like the scheduled process idea, then you can have a console application that is started by your website.
Something else to keep in mind is that if you are sending too many emails in a short period of time, it becomes very easy to get black-listed and then none of the emails from your domain will make it to any servers that have you black-listed.
I've taken two approaches:
1) Lazy, sloppy approach of configuring the asp.net process timeout long enough to complete via Send
2) Create a console app that is spawned by the web app.
I built a similar system a year or two ago. There's so many things that can go wrong when you send an email programmatically. For this reason, do yourself a favor and seperate the messages from the process of sending them. This way, you can "teach" your system that "badEmail#goodDomian.com" should be ignored or other similar situations.
You can store the message, subject, or whatever level of seperation of data you desire in the database along with a flag for meta-data like "SentOn", "FailedOn", etc. I sent my message one at a time to allow for individual errors to be stored and/or handled. I used SmtpMail.Send(), but whatever method you choose should work as long as you built something smart and recoverable.
Have a look at the MailChimp API: http://www.mailchimp.com/api/gettingstarted/

Categories