public static ChangeToken GetChangeToken(string listID)
 {
     using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
     {
         List     announcementsList = cc.Web.Lists.GetByTitle("Webhook");
         ListItem item = announcementsList.GetItemById(1);
         cc.Load(item);
         cc.ExecuteQuery();
         string oldValue = (string)item["Title"];
         string newValue = string.Format("1;3;{0};{1};-1", listID, DateTime.Now.AddSeconds(-2).ToUniversalTime().Ticks.ToString());
         item["Title"] = newValue;
         item.Update();
         cc.ExecuteQuery();
         ChangeToken newChangeToken = new ChangeToken();
         newChangeToken.StringValue = oldValue;
         return(newChangeToken);
     };
 }
        public static void CopyFile(
            [ActivityTrigger] ApprovalStartInfo approvalStartInfo,
            ILogger log,
            ExecutionContext context)
        {
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
            {
                List     docLib = cc.Web.Lists.GetByTitle("Drafts");
                ListItem item   = docLib.GetItemById(approvalStartInfo.itemId);
                Microsoft.SharePoint.Client.File file = item.File;

                cc.Load(file);
                cc.Load(item);

                cc.ExecuteQuery();
                string dest = ConfigurationManager.AppSettings["siteUrl"] + "Published/" + file.Name;
                file.CopyTo(dest, true);
                cc.ExecuteQuery();
            };
        }
        public static ListItemData GetListItemData(
            [ActivityTrigger] ApprovalStartInfo approvalStartInfo,
            ILogger log,
            ExecutionContext context)
        {
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))

            {
                List     docLib = cc.Web.Lists.GetByTitle("Drafts");
                ListItem item   = docLib.GetItemById(approvalStartInfo.itemId);
                cc.Load(item);
                cc.ExecuteQuery();
                var listItemData = new ListItemData();
                listItemData.DocumentOwner = ((FieldUserValue)item["DocumentOwner"]).LookupId;
                listItemData.StakeHolders  = new List <int>();
                foreach (FieldUserValue sh in (FieldUserValue[])item["StakeHolders"])
                {
                    listItemData.StakeHolders.Add(sh.LookupId);
                }
                return(listItemData);
            };
        }
 public static void ScheduleStakeholderApproval(
     [ActivityTrigger] ScheduleStakeHolderApprovalParams parms, // lokuupID of the user
     TraceWriter log,
     ExecutionContext context
     )
 {
     using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
     {
         List taskList = cc.Web.Lists.GetByTitle("Tasks");
         ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
         ListItem taskItem = taskList.AddItem(itemCreateInfo);
         taskItem["Title"]      = "StakeHolder Approval required";
         taskItem["AssignedTo"] = new FieldUserValue()
         {
             LookupId = parms.stakeHolderId
         };
         taskItem["workflowId"] = parms.instanceId;
         taskItem["Action"]     = "StakeHolderApproval";
         taskItem.Update();
         cc.ExecuteQuery();
         var results = new ListItemData();
     }
 }
        public static void DocownerRejected(
            [ActivityTrigger] ApprovalStartInfo approvalStartInfo,
            TraceWriter log,
            ExecutionContext context
            )
        {
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
            {
                var emailp = new EmailProperties();
                emailp.BCC = new List <string> {
                    approvalStartInfo.startedByEmail
                };
                emailp.To = new List <string> {
                    approvalStartInfo.startedByEmail
                };
                emailp.From    = "*****@*****.**";
                emailp.Body    = "<b>rejected</b>";
                emailp.Subject = "rejected";

                Utility.SendEmail(cc, emailp);
                cc.ExecuteQuery();
            };
        }
Esempio n. 6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,

            ExecutionContext context,
            ILogger log)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         // This gives you access to your application settings in your local development environment
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         // This is what actually gets you the application settings in Azure
                         .AddEnvironmentVariables()
                         .Build();

            log.LogInformation("C# HTTP trigger function processed a request.");

            string KeyVault_Name = config["KeyVault_Name"];
            string Cert_Name     = config["Cert_Name"];
            string appOnlyId     = config["AppOnlyID"];
            string tenant_URL    = config["Tenant_URL"];
            string siteURL       = "https://" + tenant_URL + ".sharepoint.com/teams/scw";

            // // parse query parameter
            string key      = req.Query["key"];
            string comments = req.Query["comments"];
            string status   = req.Query["status"];


            // // Get request body
            //dynamic data = await req.Content.ReadAsAsync<object>();
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // // Set name to query string or body data
            key      = key ?? data?.name.key;
            comments = comments ?? data?.name.comments;
            status   = status ?? data?.name.status;

            log.LogInformation("get info" + key);
            int id = Int32.Parse(key);

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteURL, appOnlyId, tenant_URL + ".onmicrosoft.com", KeyVaultAccess.GetKeyVaultCertificate(KeyVault_Name, Cert_Name)))

            {
                Web  web  = cc.Web;
                List list = cc.Web.Lists.GetByTitle("Space Requests");

                ListItem oItem = list.GetItemById(id);

                oItem["Approved_x0020_Date"]     = DateTime.Now;
                oItem["Reviewer_x0020_Comments"] = comments;
                oItem["_Status"] = status;

                oItem.Update();
                cc.ExecuteQuery();
                string responseMessage = "Create item successfully ";

                return(new OkObjectResult(responseMessage));
            }
        }
Esempio n. 7
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "AddExternalUser")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                // Gets data from request body.
                log.Info("Starting...");
                dynamic data = await req.Content.ReadAsAsync <object>();

                string siteUrl      = data.SiteUrl;
                string currentEmail = data.CurrentUser_EmailAddress;
                string groupName    = data.GroupName;
                log.Info(siteUrl);
                log.Info(currentEmail);
                log.Info(groupName);
                if (String.IsNullOrEmpty(siteUrl) || String.IsNullOrEmpty(currentEmail))
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass parametes site URL and Email Address in request body!"));
                }

                // Fetches client id and client secret from app settings.
                string clientId     = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process);
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
                string urlAdminSite = Environment.GetEnvironmentVariable("UrlAdminSite", EnvironmentVariableTarget.Process);

                // Obtains client context using the client id and client secret.
                //var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(urlAdminSite, clientId, clientSecret);

                //Tenant tenant = new Tenant(ctx);
                //SiteProperties siteProps = tenant.GetSitePropertiesByUrl(siteUrl, true);
                //log.Info("a");
                //ctx.Load(siteProps);
                //log.Info("after tenant:" + siteUrl);
                //ctx.ExecuteQuery();
                //log.Info("after line " + siteUrl);

                var newctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret);

                Site site = newctx.Site;
                Web  web  = site.RootWeb;
                log.Info("get web");
                Group group = null;
                RoleDefinitionCollection permissionLevels = web.RoleDefinitions;

                log.Info("permissionLevels");

                newctx.Load(web);
                newctx.Load(web.SiteGroups);

                newctx.Load(permissionLevels);
                log.Info("execute query");
                newctx.ExecuteQuery();

                log.Info("after newctx");

                //if (CheckUserDomainFrom(siteProps, currentEmail))
                //{
                // If group doesn't exist in web, add it
                if (!GroupExistsInWebSite(web, groupName))
                {
                    if (groupName == "SCJ External Contribute")
                    {
                        //var permissionLevelExist = permissionLevels.Select(p => p.Name == "SCJ External Contribute").Count();
                        // Create Custom Permission Level
                        //if (permissionLevelExist!=0)
                        CreateContributePermissionLevel(web);
                        // Create new Group
                        group = AddGroup(web, groupName);
                        // Add Custom Pemission Level to Group
                        web.AddPermissionLevelToGroup(groupName, "SCJ External Contribute", true);
                    }

                    if (groupName == "SCJ External Read")
                    {
                        // Create Custom Permission Level
                        CreateReadPermissionLevel(web);
                        // Create new Group
                        group = AddGroup(web, groupName);
                        // Add Custom Pemission Level to Group
                        web.AddPermissionLevelToGroup(groupName, "SCJ External Read", true);
                    }
                }
                else     // Just Add the user to group
                {
                    group = web.SiteGroups.GetByName(groupName);
                }
                newctx.ExecuteQuery();
                return(req.CreateResponse(HttpStatusCode.OK, true));
                //}

                // return req.CreateResponse(HttpStatusCode.OK, false);
            }
            catch (Exception e)
            {
                return(req.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "havePermission")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                // Gets data from request body.
                dynamic data = await req.Content.ReadAsAsync <object>();

                string siteUrl = data.SiteUrl;
                //test comment
                string currentEmail = data.CurrentUser_EmailAddress;
                if (String.IsNullOrEmpty(siteUrl) || String.IsNullOrEmpty(currentEmail))
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass parametes site URL and Email Address in request body!"));
                }

                // Fetches client id and client secret from app settings.
                string clientId     = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process);
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
                string urlAdminSite = Environment.GetEnvironmentVariable("UrlAdminSite", EnvironmentVariableTarget.Process);

                // Obtains client context using the client id and client secret.
                var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(urlAdminSite, clientId, clientSecret);

                Tenant                   tenant          = new Tenant(ctx);
                SiteProperties           siteProp        = tenant.GetSitePropertiesByUrl(siteUrl, true);
                Site                     site            = tenant.GetSiteByUrl(siteUrl);
                Web                      web             = site.RootWeb;
                RoleAssignmentCollection roleAssignments = web.RoleAssignments;

                //Get the current user by email address.
                User currentUser = web.EnsureUser(currentEmail);

                ctx.Load(site, s => s.RootWeb, s => s.RootWeb.CurrentUser);
                ctx.Load(siteProp);
                ctx.Load(currentUser);
                ctx.Load(web, w => w.CurrentUser, w => w.SiteGroups, w => w.Url, w => w.Title);
                ctx.Load(roleAssignments, roleAssignement => roleAssignement.Include(r => r.Member, r => r.RoleDefinitionBindings));
                ctx.ExecuteQuery();

                var allowedListDomainFromSite = siteProp.SharingAllowedDomainList.Split(',').Select(x => x.Trim().ToUpper()).ToList();

                if (!siteProp.SharingCapability.ToString().Equals("Disabled"))
                {
                    if (allowedListDomainFromSite.Count() != 0)
                    {
                        if (currentUser.IsSiteAdmin || CheckUserInAdminGroups(ctx, web, roleAssignments, currentUser)) // check if the current user have full control
                        {
                            return(req.CreateResponse(HttpStatusCode.OK, true));
                        }
                    }
                }
                else
                {
                    return(req.CreateResponse(HttpStatusCode.OK, false));
                }

                return(req.CreateResponse(HttpStatusCode.OK, false));
            }
            catch (Exception e)
            {
                return(req.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
        public static void ProcessChanges(string listID, ChangeToken lastChangeToken, DurableOrchestrationClient client, ILogger log)
        {
            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["siteUrl"], ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]))
            {
                ChangeQuery changeQuery = new ChangeQuery(false, false);
                changeQuery.Item             = true;
                changeQuery.Update           = true; // could handle deletes too. Just need to know if approve or reject is assumed
                changeQuery.ChangeTokenStart = lastChangeToken;
                List changedList = cc.Web.GetListById(new Guid(listID));
                var  changes     = changedList.GetChanges(changeQuery);
                cc.Load(changes);
                cc.ExecuteQuery();
                foreach (Change change in changes)
                {
                    if (change is ChangeItem)
                    {
                        ListItem task = changedList.GetItemById((change as ChangeItem).ItemId);
                        ListItemVersionCollection taskVersions = task.Versions;
                        cc.Load(taskVersions);
                        cc.Load(task);
                        cc.ExecuteQuery();
                        if (taskVersions.Count < 2)
                        {
                            return;
                        }
                        var    currentStatus = (string)taskVersions[0]["Status"];
                        var    priorStatus   = (string)taskVersions[1]["Status"];
                        string wfid          = (string)task["workflowId"];
                        Console.WriteLine($"Item # ${task.Id} current status is ${currentStatus} Prior status is ${priorStatus}");
                        switch ((string)task["Action"])
                        {
                        case "DocOwnerApproval":
                            if (currentStatus != priorStatus)
                            {
                                if (currentStatus == "Approve")
                                {
                                    log.LogInformation("Sending event DocOwnerApproved");
                                    client.RaiseEventAsync(wfid, "DocOwnerApproved");
                                }
                                else
                                {
                                    log.LogInformation("Sending event DocOwnerRejected");
                                    client.RaiseEventAsync(wfid, "DocOwnerRejected");
                                }
                            }
                            break;

                        case "StakeHolderApproval":
                            if (currentStatus != priorStatus)
                            {
                                if (currentStatus == "Approve")
                                {
                                    var eventName = "StakeHolderApproval:" + ((FieldUserValue)task["AssignedTo"]).LookupId;
                                    log.LogInformation($"Sending event '${eventName}'");
                                    client.RaiseEventAsync(wfid, eventName, true);
                                }
                                else
                                {
                                    log.LogInformation($"Sending event 'StakeHolderRejection'");
                                    client.RaiseEventAsync(wfid, "StakeHolderRejection");
                                }
                            }
                            break;
                        }
                    }
                }
            };
        }