Azure Active Directory Archives - Thrive https://thrivenextgen.com/category/azure-active-directory/ NextGen Managed Services Provider Fri, 11 Mar 2022 18:57:32 +0000 en-US hourly 1 Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 2 https://thrivenextgen.com/balancing-security-and-productivity-in-microsoft-365-during-times-of-crisis-part-2/ Mon, 13 Apr 2020 19:31:21 +0000 https://www.timlinenterprises.com/?p=1611 In our first blog of this series, we discussed how entitlement management in Azure Active Directory (Azure AD) Identity Governance creates Access Packages to control the scope and duration of access to groups, applications, and…

The post Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 2 appeared first on Thrive.

]]>
In our first blog of this series, we discussed how entitlement management in Azure Active Directory (Azure AD) Identity Governance creates Access Packages to control the scope and duration of access to groups, applications, and SharePoint sites. The two additional primary tools designed to control and audit access to company resources include Access Reviews and Privileged Identity Management. These three functions work synergistically to help keep a watchful eye on the collaboration space without impeding productivity.

In Part 2, we’ll discuss Access Reviews in detail. These are about auditing access to ensure previously-granted permissions are still appropriate and necessary.

Access Reviews

Setting up an Access Review

An Access Review is a scheduled, guided review of a group of Microsoft 365 users to help determine if their continued access to tenant resources is required. The review can be performed by multiple users and can be set to report on dispositions and, in some cases, automatically take action based on the dispositions set.

The first step of creating an Access Review is naming and describing its purpose. You will also set a start date and frequency if the intention is to perform the review periodically. Frequencies include weekly, monthly, quarterly, semi-annually, and annually. Occurrences can run indefinitely or can end by a specified date or after a number of occurrences. The review will also have an end date, after which the review will close and the “upon completion settings” will be applied.

Create an Access Review

Next, you determine who will be reviewed and who will be performing the review. The users to review can be Members of a Group or users Assigned to an Application on the tenant. Additionally, you can scope the review to include Guest users only or include all users. For Reviewers, you can select the Group’s owners, specific tenant users, or allow for self-review by the users. You can also associate the review with a Program (similar in concept to a Catalog for Access Packages) or choose the Default Program.

Select Users And Reviewers

Next, we’ll set the “Upon completion settings,” which determine the action to take when the end date of the review is reached. The first choice is whether or not you’d like to auto-apply the results. With this setting enabled, any user whose disposition is to Deny access will automatically have their access removed upon the completion of the review. The second option is to determine what actions to take if reviewers don’t respond. These options include “No change,” “Remove access,” “Approve access,” or “Take recommendations.” The last option is based on Azure AD’s auto-set recommendations, which are primarily based on the last time the reviewed user utilized the system.

The final settings, under Advanced, include options to Show recommendations, Require a reason on approval, Mail notifications, and send Reminders to reviewers. All are currently enabled by default.

Settings

At this point, we are ready to start the review process. After pressing the Start button, the new Access Review will be added to the Access Reviews section within the Identity Governance module. The listing will include the name, the resource being reviewed, the status, and when it was created. 

Starting the Access Review

Clicking on the review will show an overview of the settings as well as a chart showing the status of the resources being reviewed. There are also pages to view the Results and the Reviewers. You can even send automated reminders for individual reviewers with the press of a button.

Performing a User Access Review

If the Mail Notifications option was set to Enabled, reviewers should receive an email with a link to begin their review. The email will have a hyperlinked button to take the user directly to the review page.

Review Request

The Review page will show all relevant information, including who requested the review, when it is due by, the names of any other reviewers, and the progress made so far. It will also list each Resource being reviewed with their name, email address, Access Info (statement about whether they have recently logged in), and a recommended Action.

Team Review

This list of users can be filtered based on Status (Reviewed, Not Yet Reviewed, All), Recommendation (Approve, Deny, All), or Action (Approved, Denied, Don’t Know, All). The reviewer can click on a single source to review or multi-select resources using the checkboxes, then press the “Review n user(s)” button. Reviewing resources opens a dialog with options for the disposition and comments. Actions can be Approve, Deny, or Don’t Know. The recommended action will be highlighted already. Don’t Know is useful if there are other reviewers who may have more insight or knowledge of the resource being reviewed. 

Approve or Deny

Although all Resources may have been reviewed, the Access Review will stay open until its end date has been reached to allow for changes or other reviewers to provide input. If desired, a review can be manually stopped so action can be taken. This can be done by the user who originally set up the review using the Access Review overview screen. At that time, the actions will be automatically applied if the “Upon completion” setting’s “auto apply results to resource” is enabled, or the Apply Results button can be pressed if not. 

The results of the review can be reviewed in the Results section of the Access Review.

Results Section

Summary

Access Reviews in Azure AD Identity Governance provide a simple, consistent, and governed method of reviewing and controlling access to company tenant resources. By combining Access Reviews with Access Packages, administrators can tightly control who has access to which resources and ensure they retain the appropriate access only as long as required, all while maintaining agility and simplicity for users.    

Next up: Privileged Identity Management. Configure just-in-time role escalation to implement a least-privileged security model for day-to-day operations while providing a rapid but governed path to escalated roles as required. Stay tuned!

The post Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 2 appeared first on Thrive.

]]>
Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 1 https://thrivenextgen.com/balancing-security-and-productivity-in-microsoft-365-during-times-of-crisis-part-1/ Thu, 02 Apr 2020 21:21:01 +0000 https://www.timlinenterprises.com/?p=1588 How Azure Active Directory (Azure AD) Identity Governance can assist your organization in responding quickly to new collaboration needs while maintaining security and governance.  The sudden onset of the COVID-19 pandemic sent much of the world into…

The post Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 1 appeared first on Thrive.

]]>
How Azure Active Directory (Azure AD) Identity Governance can assist your organization in responding quickly to new collaboration needs while maintaining security and governance. 

The sudden onset of the COVID-19 pandemic sent much of the world into a frenzy. With businesses concerned for the safety and wellbeing of their employees and customers, and many governments strongly advising social distancing, the need to ramp-up the remote workforce went from a distant goal to a top priority almost overnight. One of the many groups greatly impacted by this new priority is the group of people responsible for collaboration platforms such as Microsoft 365. The need to quickly enable remote workers has made it seem necessary for many groups to ignore or postpone best practices and security considerations in favor of business continuityAzure AD’s Identity Governance is one set of tools designed to help strike the balance between security and productivity, enabling quick turnaround on required resources while providing checks and balances to mitigate risk.

What is Azure AD Identity Governance? 

Simply put, Azure AD Identity Governance is about “ensuring the right people have the right access at the right time.” More specifically, it is a set of 3 primary tools designed to control and audit access to company resources.   

Entitlement Management is about creating Access Packages to control the scope and duration of access to groups, applications, and SharePoint sites.    

Access Reviews are about auditing access to ensure previously granted permissions are still appropriate and necessary. 

Privileged Identity Management covers the just-in-time elevation of tightly scoped roles to allow users to perform privileged operations when needed while maintaining lower permission levels during their day-to-day job functions.   

These three functions work synergistically to help keep a watchful eye on the collaboration space without impeding productivity. Part 1 of this series will cover Entitlement Management in detail.   

Entitlement Management 

Setting up an Access Package 

The key component of Entitlement Management is the creation of “Access Packages”.  An Access Package is a collection of resources that users can be granted or request access to. Unlike simply adding users directly to Groups, these packages can control the duration, approval process, and periodic reviews of those assignments.   

The first step of creating an Access Package is naming and describing its purpose.  You can also create “Catalogs” to group multiple packages and delegate the administration of them to the appropriate users.

First steps of setting up Access Package.

 

Next, you determine the Resource Roles that will be part of this package. It can be a combination of Groups/Teams, Applications, and SharePoint sites. In this case, we will grant access to the “COVID-19 Response Team” team in the Member role.

Determining Resource Roles

We’ll then move onto the Request process. Since this team may be made up of external collaborators who are unknown at this time, we’ll select “For users not in your directory”, and we’ll allow “All users (All connected organizations + any new external users)” to request access. 

Request Process

Since we are allowing as of yet unknown external users, we must require approval (other settings allow you to disable approval). We will set a specific user to provide approval, ensure a decision is made within 2 days, and force both the requestor and the approver to provide a justification for the access. We’ll enable this access request when we are ready to start requesting access.

Approval Process

Next, we will set the lifecycle of the access being provided. In this case, we will allow for 30 days of access, with the ability to request an extension (which also requires approval). If this was a longer duration or did not expire, we could also tie access to an Access Review, which we’ll cover later.

Expiration Settings

The last page will show a summary of all the choices to allow you to make any desired changes before creating the package.  

Once the package is created, the browser will display a list of all Access Packages the current user has access to. From here, you can use the ellipsis to copy the link used to request access. This link can be emailed, put on a public site, or shared in any other traditional way.

Final Review

Requesting Access

To request access via an Access Package, a user can use the link generated during the creation process. Once they sign in to the 365 tenant, they will be presented details of the access being requested. The user would then select the package and push the “request access” button. 

Requesting Access

From there, because we require justification, the user will be presented an area to provide the reason they are requesting access.

Justification Requirement

They will receive confirmation that their request was submitted.

Request Confirmation

Approving Access

After requesting access, the Approver will receive an Email with actions to Approve or Deny the request, and a summary of the information about the request. 

Approval Process

Pressing the Approve or deny request button takes you to an Approvals page where you can approve or deny and provide the required justification. 

Approve or Deny

Now that the request has been approved, the user should have access to the Team as a Member.  When the expiration date is reached in 30 days, that access will be revoked unless an extension is requested. 

Summary

Entitlement Management using Access Packages is a great way to govern access to resources such as Teams, SharePoint sites, and Applications, especially when external users are involved or the context of the access is limited to a specific timeframe. Users can request access as needed, owners can be empowered to grant access on demand, and removal of access can be automated to prevent lingering exposure of company information.  

Next up: Access Reviews

Configure periodic, guided reviews of access to resources with suggestions based on login activity and automated resolution based on dispositions. 

 

The post Balancing Security and Productivity in Microsoft 365 During Times of Crisis – Part 1 appeared first on Thrive.

]]>
How To Invite External Users Using Microsoft Flow and Microsoft Graph API https://thrivenextgen.com/how-to-invite-external-users-using-microsoft-flow-and-microsoft-graph-api/ https://thrivenextgen.com/how-to-invite-external-users-using-microsoft-flow-and-microsoft-graph-api/#respond Wed, 20 Nov 2019 00:39:50 +0000 https://www.timlinenterprises.com/?p=1411 Timlin recently helped a customer automate the creation of new SharePoint site collections designed for external sharing. Prior to our work, the client had a number of manual steps that included completing a PDF form,…

The post How To Invite External Users Using Microsoft Flow and Microsoft Graph API appeared first on Thrive.

]]>

Timlin recently helped a customer automate the creation of new SharePoint site collections designed for external sharing. Prior to our work, the client had a number of manual steps that included completing a PDF form, manually logging and tracking the request, spinning up the site and associated security, and manually inviting the external users.  With the new automated process, the client simply fills out a Power Apps form that allows them to specify email addresses for the external access, and all the remaining steps are fully automated.

When looking for the underlying solution to automate this process, we decided on Microsoft Graph API.  We needed to be able to authenticate with Microsoft Graph API and execute actions against it via Microsoft Flow.  We have used this for many of our solutions, and in this post, we will detail just what is needed to authenticate with Microsoft Graph API and how to use its Invite API to invite guest users to your tenant.

Setting Up an Azure AD App Registration

The main requirement for this process to work is the Azure Active Directory App Registration. This App Registration serves as the authentication handshake between Microsoft Flow and Microsoft Graph API. You will need an elevated level of privilege to create the app registration and assign it the permissions we need in this example.

First, navigate to your Azure Portal (https://portal.azure.com) and click on Azure Active Directory.

If Azure Active Directory is not present in your quick links section, simply search for it and click on it from there. Next, navigate to “App Registrations” on the left-hand navigation menu and then “New Registration”.

You can name this Registration whatever you’d like, leave the rest of the settings as they stand and click “Register”.

Authentication and Permissions for our Azure AD App Registration

Now that we have our App Registration created, we need to setup two things: our App Secret and the required App Permissions.

First, navigate to “Certificates & secrets” and click on “New Client Secret”.

We can call our Secret anything we’d like. In this instance, we’ll just name it “Secret”. The expiration date is up to you but keep in mind if you select an expiration date other than “Never” that you will need to update this Secret key down the line in order for your functionality to continue working.

You should now have a Secret key appear. Make sure to copy and save the key somewhere safe as you will only see it this one time.

Next, we need to give our App Registration a single permission called “User.Invite.All”. This gives the App Registration access to invite guest users to our tenant. To do so, navigate to “API Permissions” and click on “Add a Permission”.

In the now visible pop-up menu, click on “Microsoft Graph” followed by “Application permissions”.

If we now search for “User.Invite”, we will see our required permission. Check it off and click “Add permissions”.

Lastly, we need to grant the permission itself to the Application. To do so, click on the “Grant admin consent” button found at the bottom of the screen. If this is greyed out for you, it means that you do not have admin permission on your tenant to execute this action.

Setting Up Our Microsoft Flow

Now that we have our App Registration setup, we can create our Flow that will invite external users to our tenant. Be sure to keep our App Registration up in a separate window/tab as we will need some information from this shortly.

Our Flow consists of only two actions and a trigger. For now, we’ve set this up to be on a manual trigger, but you can always alter this for your needs. The two actions are an “Initialize Variable” action and an “HTTP” action (the HTTP action does appear as a Premium action but is available with appropriate licensing). The Initialize action will simply hold the Graph API invitation’s URL.

Next, our HTTP action will consume our GraphURL variable and build the JSON Body that we will send to the Graph Invite API.

Each property we specified in the Body is detailed below:

  1. Invited User Email Address – The email address of the external user we will be inviting
  2. Invite Redirect URL – The URL the external user will be redirected to once accepting the invitation
  3. Send Invitation Message – If set to false, the user will not receive their invitation email, but they will still be added into Azure AD. If set to true and no Customized Message Body is sent, the default invitation email will be sent to the external user.
  4. Invited User Message Info and Customized Message Body – This allows for you to send a customized invite message to the user. This object is optional.

Next, we need to take care of authentication on this HTTP call. Click on “Show advanced options” to reveal the authentication options.

In your example, replace the first part of the tenant URL with your tenant name. For Client ID, this can be found in your newly created App Registration on the Overview page.

Next, select “Secret” for “Credential Type” and paste in the Secret you saved from earlier in the field labeled “Secret”.

You’re Finished!

With this, the Flow should be fully configured and ready to go. If you run the Flow, you should be presented with the following email upon completion in the inbox you specified. The user will have a guest user profile generated in your tenant’s Azure Active Directory. Within 5 to 10 minutes after this invitation, the user will also have a SharePoint User Profile created as well.

 

Let us know if you have any questions on this process or would like us to help you set it up.  

The post How To Invite External Users Using Microsoft Flow and Microsoft Graph API appeared first on Thrive.

]]>
https://thrivenextgen.com/how-to-invite-external-users-using-microsoft-flow-and-microsoft-graph-api/feed/ 0
Top Takeaways, Announcements, and Moments from Microsoft Ignite 2019 https://thrivenextgen.com/microsoft-ignite-2019-recap/ https://thrivenextgen.com/microsoft-ignite-2019-recap/#respond Mon, 11 Nov 2019 12:00:38 +0000 https://www.timlinenterprises.com/?p=1431 Microsoft Ignite 2019 has come to a close, but we’re recapping all the fun that was had with a round-up of the top takeaways, announcements, and moments at this year’s event in Orlando.  This year’s…

The post Top Takeaways, Announcements, and Moments from Microsoft Ignite 2019 appeared first on Thrive.

]]>

Microsoft Ignite 2019 has come to a close, but we’re recapping all the fun that was had with a round-up of the top takeaways, announcements, and moments at this year’s event in Orlando. 

This year’s attendees were lucky enough to experience first-hand new Microsoft feature announcements, compelling sessions, and inspiring keynote speakers. 

Top Announcements from Microsoft Ignite

  • Autonomous Systems – You can now design and manage autonomous systems across their lifecycle with a comprehensive portfolio of leading-edge technology that you can apply to your real business scenarios. 
  • Microsoft Endpoint ManagerProvides transformative, modern management and security that meets customers where they are and helps them move to the cloud.
  • Microsoft Flow Becomes ‘Power Automate’UI flows bring together the rich feature set of API-based digital process automation (DPA) that is available today, with RPA UI-based automation to create a truly end-to-end automation platform.
  • Power Platform CertificationIn addition to the existing fundamentals and role-based certification types, Microsoft has added a third certification type—specialty. Specialty certifications validate deep technical skills and the ability to manage industry solutions, including third-party solutions, on or with Microsoft platforms. 
  • Teams Announcements – At Ignite, Microsoft announced a variety of new capabilities in Teams to help customers in all industries work in new ways and better respond to the evolving needs of their business.
  • Project Cortex – A new service that uses AI to create a knowledge network that reasons over your organization’s data and automatically organizes it into shared topics like projects and customers. 
  • Teams for Virtual ConsultationHealthcare providers can now schedule and conduct B2C virtual consultations through Teams with new Virtual Consults capabilities, and new features like SMS Sign-In and Global Sign-Out make it quick and easy for Firstline workers to securely access Teams from their mobile devices.
  • Edge AnnouncementThe new Microsoft Edge is built on the Chromium engine, providing best-in-class compatibility with extensions and web sites, providing great support for the latest rendering capabilities, modern web applications, and powerful developer tools across all supported platforms.
  • Updates to Azure Product and Service Offerings – A host of exciting updates about Azure Arc, Azure Stack, Azure Quantam, and Azure Synapse.

Top Takeaways from Microsoft Ignite

  • The Microsoft community is stronger than ever:  Community Central proved to be a popular place for the Microsoft community to gather and connect at this year’s event.
  • The tech industry is truly investing in women in business:  Female power and investment was a huge focus during the 2019 event, with daily sessions regarding women in business and technology, and a successful lunch & learn panel event. In addition, Microsoft is keeping the investment going after the conference — for every Ignite conference evaluation submitted, they are donating $1 to Girls Who Code.

 

View this post on Instagram

 

A post shared by Blair Niederhauser (@kcbrunetteintech) on

  • Microsoft Azure and the future of cloud computing:  From the Community Central day dedicated to Azure topics to the community whiteboard wall which encouraged people to talk about what Azure means to them, there sure was a lot of buzz about the future of cloud computing.

Top Moments from Microsoft Ignite 2019

Attendees of Microsoft Ignite know how to get social! Here are a few of our favorite photos shared during the week through the #MSIgnite hashtag. 

 

View this post on Instagram

 

A post shared by Daniel Rubino (@daniel_rubino) on

 

 

View this post on Instagram

 

A post shared by ShareGate (@sharegatetools) on

 

View this post on Instagram

 

A post shared by Bexar County IT (@bexarcountyit) on

 

View this post on Instagram

 

A post shared by Scott Duffy – Azure Trainer (@softwarearchitect.ca) on

 

View this post on Instagram

 

A post shared by Kyla Mitsunaga (@withwarriors) on

 

View this post on Instagram

 

A post shared by jon (@jonmedel) on

 

View this post on Instagram

 

A post shared by Danny (@dannycire) on

 

View this post on Instagram

 

A post shared by Veritas Technologies LLC (@veritastechllc) on

 

View this post on Instagram

 

A post shared by BindTuning (@bindtuningcom) on

What were your favorite moments from MS Ignite? Let us know by following us on LinkedIn and starting a conversation with a comment on this post! 

The post Top Takeaways, Announcements, and Moments from Microsoft Ignite 2019 appeared first on Thrive.

]]>
https://thrivenextgen.com/microsoft-ignite-2019-recap/feed/ 0
Timer Trigger Function Apps in Azure https://thrivenextgen.com/timer-trigger-function-apps-azure/ https://thrivenextgen.com/timer-trigger-function-apps-azure/#respond Wed, 31 Jan 2018 15:47:22 +0000 https://www.timlinenterprises.com/?p=665 Introduction In the not too distant past, if you wanted to run code at regular intervals you had a few go-to options to choose from.  If you wanted a “down and dirty” solution, a quick…

The post Timer Trigger Function Apps in Azure appeared first on Thrive.

]]>
Introduction

In the not too distant past, if you wanted to run code at regular intervals you had a few go-to options to choose from.  If you wanted a “down and dirty” solution, a quick PowerShell script could be scheduled using the Task Scheduler.  If you needed anything more advanced or formal, you could write a Windows Service to house both the logic and the scheduling for unattended execution.  In the age of cloud computing you may think of firing up an Azure Virtual Machine to accomplish the same tasks, but without needing an on-premise server always running.  But why maintain an entire machine for code that needs to run once a day, or even once an hour?  Fortunately, Microsoft has provided a flexible, easy to use solution for this type of task in the form of Timer Trigger functions within Azure Function Apps.

Azure Functions let you write the code to perform your task, without worrying about the infrastructure that runs it.  Depending on the trigger type, there are different languages available to code your logic, including C#, PowerShell, TypeScript, and others.  Regardless of which you choose, you get a powerful browser-based user interface with which to write, configure, and monitor your code.

In my case I was looking to create an automated daily check to see who didn’t complete their timesheets for the prior business day, sending an email with the list of offenders should any exist.  We use Project Online to track daily hours, so I wanted to directly pull from that data using the OData reporting interface to make the determination.  Before running through these steps in your own environment, be sure you understand Azure pricing models.  The solution described here costs pennies per month, but that could change based on total usage, subscription plans, or future changes to the pricing models.

Getting started

To get started, navigate to portal.azure.com.  In the portal, click on the “All resource” navigation link where you will see everything associated with your instance.  To create a new Function App, click on the Add button in the ribbon.  This will bring up a list of everything available in the Azure Marketplace.  In the search box, search for and select “Function App”, which should bring up the description, publisher, pricing, and documentation panel for the app.

Azure Function App

 

 

 

 

 

 

Press the Create button to get started.  You will first be presented with a list of general options for your function app.

 

 

 

 

 

 

 

 

 

 

 

 

Notes:

  • The app name must be globally unique, so you may want to preface it with your company or product name
  • Be sure to read up and understand Resource Groups, Storage accounts, Locations, and the difference between Consumption Plan and App Service plan, as they can have a drastic impact on the charges incurred

Once you have setup the basics of the Function App, it is time to add an actual function.  As of this writing, there are 33 different triggers to choose from!  For our case we will use the Timer Trigger.

Timer Trigger

 

 

 

 

 

 

Add the Timer Trigger by finding the Timer trigger card and clicking on a language choice, such as C#.  You will then be prompted for a name and a Timer trigger schedule.  Don’t worry if you don’t understand cron expressions; there are plenty of examples and documentation within the designer.  For our daily job, we use the expression “0 30 14 * * 1-5”, to specify Monday through Friday at 2:30 PM UTC (9:30 AM Eastern).

Setting up

You should now be in the designer, with the file “run.csx” open.  This will be the main entry point for your function.  The default template will provice a Run method that passes in the time and a TraceWriter for logging purposes.  Before we get too far along here, we need to think about what other libraries we want to use in order to gain access to SharePoint Online and the Project OData endpoints.  To do this, expand the “View Files” pane on the right and select the “project.json” file.  This is the “package reference” used to tell NuGet which packages to retrieve for your project.  A reference can be found at https://docs.microsoft.com/en-us/nuget/archive/project-json.  For this project, we are using the SharePoint Online CSOM library and the Newtonsoft Json library.  Our library file will look like this:

 

 

 

 

 

This will implicitly create a project.lock.json file with all of the details regarding the individual assemblies brought into our application.

We’ll also want to add a few application settings for our mail configuration, rather than having them directly within the code.  Application Settings can be configured by going to the top-level node of your function in the tree view, and selecting the “Application settings” tab.  You can add, edit, or delete your settings in the Application settings section of that page, to be referenced within your code as needed.

On to the code!

Our code will start with our using statements, as well as some configuration data we’ll pull from application settings and/or hard code as desired.

using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using Microsoft.SharePoint.Client;
using Newtonsoft.Json;

// Mail server configuration
private static string mailHost = ConfigurationManager.AppSettings[“MailHost”];
private static int mailPort = Convert.ToInt32(ConfigurationManager.AppSettings[“MailPort”]);
private static string username = ConfigurationManager.AppSettings[“EmailUsername”];
private static string password = ConfigurationManager.AppSettings[“EmailPassword”];
private static string toAddress = ConfigurationManager.AppSettings[“ToAddress”];

// Mail message constants
private const string mailSubjectTemplate = @”Missing Hours for {0}”; // {0} = Date
private const string mailBodyTemplate = @”<h3>The following people were missing hours yesterday…</h3>{0}”; // {0} = List of users

// API constants
private const string pwaPath = @”https://timlin.sharepoint.com/teams/projects/PWA/”;
private const string pwaApiPath = @”_api/ProjectData/”;

Next up, we construct a Url to use to retrieve the prior day’s time.  This call will use the TimesheetLineActualDataSet data, selecting just the columns we need and filtering to a specific day.  The date value will be a string template that we format in at runtime.  I would recommend working the exact syntax out in your own environment via a browser to make sure you have it right.

// Templates for REST OData calls

private const string getHoursPwaRequestPathTemplate = @”TimesheetLineActualDataSet?$filter=TimeByDay%20eq%20datetime%27{0}%27&$select=ResourceName,ActualWorkBillable&$format=json”;

Next we create and initialize a dictionary to store the list of users we want to track.

// Dictionary of users to report on
private static Dictionary<string, double> userHours = new Dictionary<string, double>() {
{ “John Doe”, 0.0 },
{ “Jane Smith”, 0.0 },
{ “Hapie Goluky”, 0.0 },
{ “Joe Piccirilli”, 0.0 }
};

We also have a few “helper” functions to keep our main code clean.

// Get the prior business date
private static DateTime GetYesterday() {
var date = DateTime.Today;
switch (date.DayOfWeek) {
case DayOfWeek.Sunday:
date = date.AddDays(-2);
break;
case DayOfWeek.Monday:
date = date.AddDays(-3);
break;
default:
date = date.AddDays(-1);
break;
}
return date;
}

private static dynamic DeserializeJsonObject(string content) {
return JsonConvert.DeserializeObject<dynamic>(content);
}

private static void SendMessage(string subject, string body) {
var smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
smtpClient.Port = mailPort;
smtpClient.Host = mailHost;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(username);
mailMessage.To.Add(new MailAddress(toAddress));
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
}

Reading the Project Online data uses .Net’s HttpWebRequest object, with SharePointOnlineCredentials providing the authentication mechanism.  We encapsulate the credentials and the web GET calls with other helper properties and functions.

private static SharePointOnlineCredentials _creds;
private static SharePointOnlineCredentials Credentials {
get {
if (_creds == null) {
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
_creds = new SharePointOnlineCredentials(username, securePassword);
}
return _creds;
}
}

private static string WebGet(string requestUrl) {
var req = (HttpWebRequest)WebRequest.Create(requestUrl);
req.Credentials = Credentials;
req.Headers[“X-FORMS_BASED_AUTH_ACCEPTED”] = “f”;

var resp = (HttpWebResponse)req.GetResponse();
var receiveStream = resp.GetResponseStream();

var readStream = new StreamReader(receiveStream, Encoding.UTF8);

return readStream.ReadToEnd();
}

One final helper method constructs the call to WebGet.

// Get hours from PWA OData service for the prior business day
private static string GetHoursPwa(string date) {
return WebGet(pwaPath + pwaApiPath + string.Format(getHoursPwaRequestPathTemplate, date));
}

Within our main Run method, we orchestrate the overall logic.  First, we get the date and log a message to know what date we ran for.  These messages are visible in the Logs panel below the code window, and in the Monitor page accessible from the tree view navigation for all execution.

public static void Run(TimerInfo myTimer, TraceWriter log)
{
_log = log;

// Get yesterday’s date
var date = GetYesterday().ToString(“yyyy-MM-dd”);
_log.Info($”Running for {date}”);

Next we get and deserialize the data into a “dynamic” object.

// Get the PWA OData
var data = GetHoursPwa(date);

// Deserialize to a dynamic object
var dynamicObject = DeserializeJsonObject(data);

We’ll then iterate over the data in the dynamic object and aggregate the hours for each resource’s time entries into our dictionary.

// Populate our userHours dictionary based on hours in timesheet
foreach (var user in dynamicObject.value) {
if (userHours.ContainsKey(user.ResourceName.ToString())) {
userHours[user.ResourceName.ToString()] += Double.Parse(user.ActualWorkBillable.ToString());
}
}

We only need to deal with users with no hours, so we’ll use a quick Linq statement to extract them.

// Extract the names of users with 0 hours

var usersWithNoHours = userHours.Where(x => x.Value == 0.0).Select(x => x.Key);

Finally, we’ll send an email message out to our distribution list if there are any offenders or log the fact that all is clear if not.

  // Send the message, if there are any users without hours
if (usersWithNoHours.Any()) {
var subject = string.Format(mailSubjectTemplate, date);
var body = string.Format(mailBodyTemplate, string.Join(“<br />”, usersWithNoHours));
_log.Info(body);
SendMessage(subject, body);
}
else
{
_log.Info(“No offenders found!”);
}

Wrapping up

Once the code is in place, the App is running, and the timer function is enabled, the code will wake up every day, run through the logic, and go back to sleep until needed again.  As we have this configured, using a Consumption pricing tier, this once-daily execution costs less than $0.10 per month beyond any standard subscription costs.  As stated before, your mileage may vary based on the specifics of your plan, number of calls, disk / data usage, etc., so be sure to research these items first and monitor your application within Azure to ensure your costs are in line with expectations.

The post Timer Trigger Function Apps in Azure appeared first on Thrive.

]]>
https://thrivenextgen.com/timer-trigger-function-apps-azure/feed/ 0