This is part two of the series. Please read first post at http://blog.mmasood.com/2015/04/from-sharepoint-on-premise-to-office365.html of series "From SharePoint On-Prem to Office365"
I will be using SharePoint Timer Service to send an email to newly registered customers/users for this demo. The newly registered customers/users are stored in SharePoint list with a status field capturing whether an email has been sent or not.
There are some implementation choices when developing a SharePoint Timer service:
- Azure Web Job
- Azure Worker Role
- Windows Service (can be hosted on premise or vm on Cloud)
- Task Scheduler (hosted on premise)
Azure web job does not live it its own. It sits under Azure Web Apps. For this purpose I am going to create a dummy web app and host my Azure web job. I will be hosting all my CSOM code in this web job.
There are two types of web job:
- Continuous best fit for queuing application where it keeps receiving messages from queue.
- On Demand can be scheduled for hourly, weekly and monthly etc.
Querying SharePoint using CSOM and CAML Query:
Sends Email using Office365 Web Exchange:
Composing email using Razor Engine templating engine:
And finally update SharePoint list item using CSOM:
You can download full source code from Codeplex: https://webjobforsptimer.codeplex.com/
When writing a Web Job, the following points should be considered to make your web job diagnosable and reusable:
- Do not absorbs exceptions. Handle it first throw it to let web job know something went wrong.
- Try to use interfaces so that it can be mocked for unit testings
- Always log major steps and errors using Console.WriteLine etc
- Make your code like it can be used as console application so that it can be used in Task scheduler
- Try to avoid hardcoding. Maximise the use of configuration. It can be plugged from Azure portal as well.
That’s it. Happy SharePointing :)