示例#1
0
        private static async Task SetGroupSettings(CreateGroupRequest request, CreateGroupResponse response, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                if (!request.AllowToAddGuests)
                {
                    var groupUnifiedGuestSetting = new GroupSetting()
                    {
                        DisplayName = "Group.Unified.Guest",
                        TemplateId  = "08d542b9-071f-4e16-94b0-74abb372e3d9",
                        Values      = new List <SettingValue> {
                            new SettingValue()
                            {
                                Name = "AllowToAddGuests", Value = "false"
                            }
                        }
                    };
                    log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false");
                    await client.Groups[response.GroupId].Settings.Request().AddAsync(groupUnifiedGuestSetting);
                }
            }
            catch (Exception e)
            {
                log.Error($"Error setting AllowToAddGuests for group {response.GroupId}: {e.Message }\n\n{e.StackTrace}");
            }
        }
示例#2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] IsAppInstalledRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;

                bool isInstalled = false;
                var  instances   = web.GetAppInstances();
                if (instances != null)
                {
                    isInstalled = instances.Any(i => i.Status == AppInstanceStatus.Installed &&
                                                i.Title.Equals(request.Title, StringComparison.InvariantCultureIgnoreCase));
                }

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <IsAppInstalledResponse>(new IsAppInstalledResponse {
                        Installed = isInstalled
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AddNavigationRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;
                if (string.IsNullOrWhiteSpace(request.ParentTitle))
                {
                    request.ParentTitle = string.Empty;
                }
                bool isExternal = !request.NavigationURL.Contains("sharepoint.com");
                var  node       = web.AddNavigationNode(request.Title, new Uri(request.NavigationURL), request.ParentTitle, request.Type, isExternal, !request.AddFirst);

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <AddNavigationResponse>(new AddNavigationResponse {
                        NavigationAdded = node != null
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        private static async Task <bool> MoveEveryoneUser(TraceWriter log, string siteUrl)
        {
            var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

            const string everyoneIdent = "c:0-.f|rolemanager|spo-grid-all-users/";
            bool         moved         = false;

            var web           = clientContext.Web;
            var membersGroup  = web.AssociatedMemberGroup;
            var siteUsers     = web.SiteUsers;
            var visitorsGroup = web.AssociatedVisitorGroup;

            clientContext.Load(siteUsers);
            clientContext.Load(membersGroup);
            clientContext.Load(visitorsGroup);
            clientContext.ExecuteQueryRetry();
            foreach (User user in siteUsers)
            {
                if (!user.LoginName.StartsWith(everyoneIdent))
                {
                    continue;
                }

                if (web.IsUserInGroup(membersGroup.Title, user.LoginName))
                {
                    web.RemoveUserFromGroup(membersGroup, user);
                    web.AddUserToGroup(visitorsGroup, user);
                    moved = true;
                }
                break;
            }
            return(moved);
        }
示例#5
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] ApplySpColorRequest request, TraceWriter log)
        {
            try
            {
                string siteUrl       = request.SiteURL;
                var    clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;
                web.Lists.EnsureSiteAssetsLibrary();
                string relativeSiteUrl = UrlUtility.MakeRelativeUrl(siteUrl);
                string siteAssetsUrl   = UrlUtility.Combine(relativeSiteUrl, "SiteAssets");
                var    fileUrl         = UrlUtility.Combine(siteAssetsUrl, request.Filename);

                web.ApplyTheme(fileUrl, null, null, true);
                web.Update();
                clientContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <ApplySpColorResponse>(new ApplySpColorResponse {
                        Applied = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#6
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SendEmailRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                MailUtility.SendEmail(clientContext, request.Recipient.Split(';'), null, request.Subject, request.Content);

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SendEmailResponse>(new SendEmailResponse {
                        Sent = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetAccessRequestSettingsRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;
            bool   isDirty = false;

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }

                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;
                clientContext.Load(web, w => w.MembersCanShare, w => w.AssociatedMemberGroup.AllowMembersEditMembership, w => w.RequestAccessEmail);
                clientContext.ExecuteQueryRetry();

                if (request.MembersCanShare != web.MembersCanShare)
                {
                    isDirty             = true;
                    web.MembersCanShare = request.MembersCanShare;
                    web.Update();
                }

                if (request.AllowMembersEditMembership != web.AssociatedMemberGroup.AllowMembersEditMembership)
                {
                    isDirty = true;
                    web.AssociatedMemberGroup.AllowMembersEditMembership = request.AllowMembersEditMembership;
                    web.AssociatedMemberGroup.Update();
                }

                if (!string.IsNullOrWhiteSpace(request.RequestAccessEmail) && request.RequestAccessEmail != web.RequestAccessEmail)
                {
                    isDirty = true;
                    web.RequestAccessEmail = request.RequestAccessEmail;
                    web.Update();
                }

                if (isDirty)
                {
                    clientContext.ExecuteQueryRetry();
                }

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetAccessRequestSettingsResponse>(new SetAccessRequestSettingsResponse {
                        AccessRequestSettingsModified = isDirty
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        private static async Task <bool> MakeEveryoneVisitor(TraceWriter log, string siteUrl)
        {
            var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

            const string everyoneIdent = "c:0-.f|rolemanager|spo-grid-all-users/";
            bool         everyOneExceptExternalAddedToVisitors = false;

            var web           = clientContext.Web;
            var visitorsGroup = web.AssociatedVisitorGroup;
            var siteUsers     = web.SiteUsers;

            clientContext.Load(visitorsGroup);
            clientContext.Load(siteUsers);
            clientContext.ExecuteQueryRetry();

            foreach (User user in siteUsers)
            {
                if (user.LoginName.StartsWith(everyoneIdent))
                {
                    if (!web.IsUserInGroup(visitorsGroup.Title, user.LoginName))
                    {
                        web.AddUserToGroup(visitorsGroup, user);
                        everyOneExceptExternalAddedToVisitors = true;
                    }
                }
            }

            return(everyOneExceptExternalAddedToVisitors);
        }
示例#9
0
        private static async Task <List <User> > GetUsers(string[] userEmails)
        {
            List <User> usersList = new List <User>();

            if (userEmails == null || userEmails.Length == 0)
            {
                return(usersList);
            }
            GraphServiceClient client = ConnectADAL.GetGraphClient();
            var users = await client.Users.Request().Top(999).GetAsync();

            while (users.Count > 0)
            {
                foreach (var user in users)
                {
                    if (userEmails.Any(mail => string.Compare(user.UserPrincipalName, mail, true) == 0))
                    {
                        usersList.Add(user);
                    }
                }

                if (users.NextPageRequest != null)
                {
                    users = await users.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
            return(usersList);
        }
示例#10
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] DeleteGroupRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.GroupId))
                {
                    throw new ArgumentException("Parameter cannot be null", "GroupId");
                }

                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.v1);
                await client.Groups[request.GroupId].Request().DeleteAsync();
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeleteGroupResponse>(new DeleteGroupResponse {
                        GroupDeleted = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeleteGroupResponse>(new DeleteGroupResponse {
                        GroupDeleted = false
                    }, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#11
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateSiteRequest request, TraceWriter log)
        {
            string adminUrl = $"https://{request.Tenant}-admin.sharepoint.com";

            try
            {
                if (string.IsNullOrWhiteSpace(request.Title))
                {
                    throw new ArgumentException("Parameter cannot be null", "Title");
                }
                if (string.IsNullOrWhiteSpace(request.Tenant))
                {
                    throw new ArgumentException("Parameter cannot be null", "Tenant");
                }
                if (string.IsNullOrWhiteSpace(request.Url))
                {
                    throw new ArgumentException("Parameter cannot be null", "Url");
                }

                var adminContext = await ConnectADAL.GetClientContext(adminUrl, log);

                Tenant tenant = new Tenant(adminContext);
                adminContext.ExecuteQuery();
                string url = $"https://{request.Tenant}.sharepoint.com/sites/{request.Url}";
                var    siteCreationProperties = new SiteCreationProperties()
                {
                    Title                = request.Title,
                    Url                  = url,
                    Owner                = request.OwnerEmail,
                    Template             = !string.IsNullOrWhiteSpace(request.Template) ? request.Template : "STS#3",
                    StorageMaximumLevel  = 100,
                    UserCodeMaximumLevel = 0,
                    Lcid                 = request.Language != 0 ? request.Language : 1033,
                };
                tenant.CreateSite(siteCreationProperties);
                adminContext.ExecuteQuery();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <CreateSiteResponse>(new CreateSiteResponse {
                        SiteURL = url
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#12
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetGraphMetadataRequest request, TraceWriter log)
        {
            try
            {
                const string extensionName = "techmikael_GenericSchema";

                string schemaKey   = PropertyMapper[request.Key];
                string schemaLabel = schemaKey.Replace("Key", "Label");
                string schemaValue = schemaKey.Replace("Key", "Value");
                string label       = GetLabel(request.Key);

                dynamic property = new ExpandoObject();
                ((IDictionary <string, object>)property).Add(schemaKey, request.Key.ToString());
                ((IDictionary <string, object>)property).Add(schemaLabel, label);
                ((IDictionary <string, object>)property).Add(schemaValue, request.Value);

                dynamic template = new ExpandoObject();
                ((IDictionary <string, object>)template).Add(extensionName, property);

                var    content     = new StringContent(JsonConvert.SerializeObject(template), Encoding.UTF8, "application/json");
                Uri    uri         = new Uri($"https://graph.microsoft.com/v1.0/groups/{request.GroupId}");
                string bearerToken = await ConnectADAL.GetBearerToken();

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var response = await client.PatchAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <SetGraphMetadataResponse>(new SetGraphMetadataResponse {
                            Added = true
                        }, new JsonMediaTypeFormatter())
                    }));
                }
                string responseMsg = await response.Content.ReadAsStringAsync();

                dynamic errorMsg = JsonConvert.DeserializeObject(responseMsg);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <object>(errorMsg, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#13
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateTeamRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.GroupId))
                {
                    throw new ArgumentException("Parameter cannot be null", "GroupId");
                }

                dynamic team    = new ExpandoObject();
                var     content = new StringContent(JsonConvert.SerializeObject(team), Encoding.UTF8, "application/json");
                log.Info(JsonConvert.SerializeObject(team));
                Uri uri = new Uri($"https://graph.microsoft.com/beta/groups/{request.GroupId}/team");
                log.Info(uri.AbsoluteUri);
                string bearerToken = await ConnectADAL.GetBearerToken();

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var response = await client.PutAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    dynamic responseJson = JObject.Parse(responseBody);
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <CreateTeamResponse>(new CreateTeamResponse {
                            Created = true, TeamUrl = responseJson.webUrl
                        }, new JsonMediaTypeFormatter())
                    }));
                }
                string responseMsg = await response.Content.ReadAsStringAsync();

                log.Info(responseMsg);
                dynamic errorMsg = JsonConvert.DeserializeObject(responseMsg);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <CreateTeamResponse>(new CreateTeamResponse {
                        Created = false, ErrorMessage = errorMsg
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#14
0
        public static async Task <AddOwnerResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AddOwnerRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            int idx = request.LoginName.LastIndexOf('|');

            if (idx > 0)
            {
                request.LoginName = request.LoginName.Substring(idx + 1);
            }

            var ownerQuery = await client.Users
                             .Request()
                             .Filter($"userPrincipalName eq '{request.LoginName}'")
                             .GetAsync();

            var  owner = ownerQuery.FirstOrDefault();
            bool added = false;

            if (owner != null)
            {
                try
                {
                    // And if any, add it to the collection of group's owners
                    log.Info($"Adding user {request.LoginName} to Owners group for {request.GroupId}");
                    await client.Groups[request.GroupId].Owners.References.Request().AddAsync(owner);
                    if (request.AddOption == AddOwnerOption.AddAsOwnerAndMember)
                    {
                        log.Info($"Adding user {request.LoginName} to Members group for {request.GroupId}");
                        await client.Groups[request.GroupId].Members.References.Request().AddAsync(owner);
                    }
                    added = true;
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" &&
                        ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing owner
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            return(new AddOwnerResponse()
            {
                Added = added
            });
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetLifecyclePolicyRequest request, TraceWriter log)
        {
            try
            {
                string bearerToken = await ConnectADAL.GetBearerToken(true);

                dynamic template  = new { groupId = request.GroupId };
                var     content   = new StringContent(JsonConvert.SerializeObject(template), Encoding.UTF8, "application/json");
                string  operation = request.Operation == Operation.Add ? "addGroup" : "removeGroup";

                // Get all policies - should return 1
                Uri        policyUri = new Uri("https://graph.microsoft.com/beta/groupLifecyclePolicies");
                HttpClient client    = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                string policyResponse = await client.GetStringAsync(policyUri);

                JObject policies = JsonConvert.DeserializeObject <JObject>(policyResponse);
                var     policyId = policies["value"][0]["id"] + "";

                Uri uri      = new Uri($"https://graph.microsoft.com/beta/groupLifecyclePolicies/{policyId}/{operation}");
                var response = await client.PostAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <SetLifecyclePolicyResponse>(new SetLifecyclePolicyResponse {
                            IsApplied = request.Operation == Operation.Add
                        }, new JsonMediaTypeFormatter())
                    }));
                }

                string responseMsg = await response.Content.ReadAsStringAsync();

                dynamic errorMsg = JsonConvert.DeserializeObject(responseMsg);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <object>(errorMsg, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#16
0
        public static async Task <AllowExternalMembersInGroupResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AllowExternalMembersInGroupRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                const string externalTemplateId    = "08d542b9-071f-4e16-94b0-74abb372e3d9";
                GroupSetting externalMemberSetting = new GroupSetting {
                    TemplateId = externalTemplateId
                };
                SettingValue setVal = new SettingValue
                {
                    Name  = "AllowToAddGuests",
                    Value = request.ExternalAllowed.ToString()
                };
                externalMemberSetting.Values = new List <SettingValue> {
                    setVal
                };

                var existingSettings = await client.Groups[request.GroupId].Settings.Request().GetAsync();

                bool hasExistingSetting = false;
                foreach (GroupSetting groupSetting in existingSettings)
                {
                    if (!groupSetting.TemplateId.Equals(externalTemplateId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    await client.Groups[request.GroupId].Settings[groupSetting.Id].Request().UpdateAsync(externalMemberSetting);
                    hasExistingSetting = true;
                    break;
                }

                if (!hasExistingSetting)
                {
                    await client.Groups[request.GroupId].Settings.Request().AddAsync(externalMemberSetting);
                }

                return(new AllowExternalMembersInGroupResponse {
                    ExternalAllowed = request.ExternalAllowed
                });
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw;
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetSharePointGroupUsersRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }
                if (string.IsNullOrWhiteSpace(request.Group))
                {
                    throw new ArgumentException("Parameter cannot be null", "Title");
                }

                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var regex          = new Regex("[^a-zA-Z0-9 -]");
                var cleanGroupName = regex.Replace(request.Group, "");
                cleanGroupName = Regex.Replace(cleanGroupName, @"\s+", " ");

                var web   = clientContext.Web;
                var group = web.SiteGroups.GetByName(cleanGroupName);
                clientContext.Load(group, g => g.Users);
                web.Context.ExecuteQueryRetry();

                var emails = String.Join(";", group.Users.Where(u => !String.IsNullOrWhiteSpace(u.Email)).Select(u => u.Email).ToArray());


                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <GetSharePointGroupUsersResponse>(new GetSharePointGroupUsersResponse {
                        Group = cleanGroupName, Emails = emails
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#18
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteTitleRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }
                if (string.IsNullOrWhiteSpace(request.Title))
                {
                    throw new ArgumentException("Parameter cannot be null", "Title");
                }

                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;
                web.Context.Load(web, w => w.Title);
                web.Context.ExecuteQueryRetry();

                var oldTitle = web.Title;
                if (oldTitle.Equals(request.Title))
                {
                    web.Title = request.Title;
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteTitleResponse>(new SetSiteTitleResponse {
                        OldTitle = oldTitle, NewTitle = request.Title
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#19
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] TestConnectionSharePointRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }

                var clientContext = await ConnectADAL.GetClientContext(request.SiteURL, log);

                var web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <TestConnectionSharePointResponse>(new TestConnectionSharePointResponse {
                        WebTitle = web.Title
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (ArgumentException ae)
            {
                log.Error($"Error:  {ae.Message }\n\n{ae.StackTrace}");
                var response = new ExpandoObject();
                ((IDictionary <string, object>)response).Add("message", ae.Message);
                ((IDictionary <string, object>)response).Add("statusCode", HttpStatusCode.BadRequest);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new ObjectContent <ExpandoObject>(response, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                var response = new ExpandoObject();
                ((IDictionary <string, object>)response).Add("message", e.Message);
                ((IDictionary <string, object>)response).Add("statusCode", HttpStatusCode.ServiceUnavailable);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <ExpandoObject>(response, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#20
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetNoScriptRequest request, TraceWriter log)
        {
            string siteUrl  = request.SiteURL;
            Uri    uri      = new Uri(siteUrl);
            string adminUrl = uri.Scheme + "://" + uri.Authority;

            if (!adminUrl.Contains("-admin.sharepoint.com"))
            {
                adminUrl = adminUrl.Replace(".sharepoint.com", "-admin.sharepoint.com");
            }

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }

                var clientContext = await ConnectADAL.GetClientContext(adminUrl, log);

                Tenant tenant         = new Tenant(clientContext);
                var    siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, false);
                clientContext.Load(siteProperties, s => s.SharingCapability);
                siteProperties.Context.ExecuteQueryRetry();
                siteProperties.DenyAddAndCustomizePages = (request.NoScript ? DenyAddAndCustomizePagesStatus.Enabled : DenyAddAndCustomizePagesStatus.Disabled);
                siteProperties.Update();
                clientContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetNoScriptResponse>(new SetNoScriptResponse {
                        UpdatedNoScript = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#21
0
        private static async Task SetGroupMembership(CreateGroupResponse response, List <User> owners, List <User> members, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            foreach (var owner in owners)
            {
                try
                {
                    log.Info($"Setting {owner.Mail} as Owner for the group.");
                    await client.Groups[response.GroupId].Owners.References.Request().AddAsync(owner);
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing member
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            foreach (var member in members)
            {
                try
                {
                    log.Info($"Setting {member.Mail} as Member for the group.");
                    await client.Groups[response.GroupId].Owners.References.Request().AddAsync(member);
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing member
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetGraphMetadataBulkRequest request, TraceWriter log)
        {
            try
            {
                const string extensionName = "techmikael_GenericSchema";

                var payload = $"{{\"{extensionName}\": {request.JSON}}}";

                var    content     = new StringContent(payload, Encoding.UTF8, "application/json");
                Uri    uri         = new Uri($"https://graph.microsoft.com/v1.0/groups/{request.GroupId}");
                string bearerToken = await ConnectADAL.GetBearerToken();

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var response = await client.PatchAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <SetGraphMetadataBulkResponse>(new SetGraphMetadataBulkResponse {
                            Added = true
                        }, new JsonMediaTypeFormatter())
                    }));
                }
                string responseMsg = await response.Content.ReadAsStringAsync();

                dynamic errorMsg = JsonConvert.DeserializeObject(responseMsg);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <object>(errorMsg, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetGroupClassificationRequest request, TraceWriter log)
        {
            try
            {
                string bearerToken = await ConnectADAL.GetBearerToken();

                dynamic    template = new { classification = request.Classification };
                var        content  = new StringContent(JsonConvert.SerializeObject(template), Encoding.UTF8, "application/json");
                Uri        uri      = new Uri($"https://graph.microsoft.com/beta/groups/{request.GroupId}");
                HttpClient client   = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var response = await client.PatchAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <SetGroupClassificationResponse>(new SetGroupClassificationResponse {
                            IsUpdated = true
                        }, new JsonMediaTypeFormatter())
                    }));
                }

                string responseMsg = await response.Content.ReadAsStringAsync();

                dynamic errorMsg = JsonConvert.DeserializeObject(responseMsg);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <object>(errorMsg, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#24
0
        public static async Task <GetGroupSiteResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetGroupSiteRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                var rootSite = await client.Groups[request.GroupId].Sites["root"].Request().GetAsync();
                return(string.IsNullOrWhiteSpace(rootSite.WebUrl) ? new GetGroupSiteResponse {
                    SiteURL = "n/a"
                } : new GetGroupSiteResponse {
                    SiteURL = rootSite.WebUrl
                });
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(new GetGroupSiteResponse()
                {
                    SiteURL = e.Message
                });
            }
        }
        public static async Task <GetClassificationValuesResponse> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestMessage req, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                const string groupTemplateId  = "62375ab9-6b52-47ed-826b-58e47e0e304b";
                var          existingSettings = await client.GroupSettings.Request().GetAsync();

                var response = new GetClassificationValuesResponse();
                foreach (GroupSetting groupSetting in existingSettings)
                {
                    if (!groupSetting.TemplateId.Equals(groupTemplateId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }
                    foreach (SettingValue settingValue in groupSetting.Values)
                    {
                        if (settingValue.Name.Equals("ClassificationList"))
                        {
                            response.Classifications = settingValue.Value.Split(',');
                        }
                        else if (settingValue.Name.Equals("DefaultClassification"))
                        {
                            response.DefaultClassification = settingValue.Value;
                        }
                    }
                    break;
                }

                return(response);
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw;
            }
        }
示例#26
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteClassificationRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }
                if (string.IsNullOrWhiteSpace(request.SiteClassification))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteClassification");
                }

                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                //clientContext.Site.SetSiteClassification(request.SiteClassification);
                clientContext.Site.Classification = request.SiteClassification;
                clientContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteClassificationResponse>(new SetSiteClassificationResponse {
                        ClassificationSet = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error: {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#27
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] IsSiteReadyRequest request, TraceWriter log)
        {
            string siteUrl  = request.SiteURL;
            Uri    uri      = new Uri(siteUrl);
            string adminUrl = uri.Scheme + "://" + uri.Authority;

            if (!adminUrl.Contains("-admin.sharepoint.com"))
            {
                adminUrl = adminUrl.Replace(".sharepoint.com", "-admin.sharepoint.com");
            }

            try
            {
                var clientContext = await ConnectADAL.GetClientContext(adminUrl, log);

                Tenant tenant = new Tenant(clientContext);
                var    site   = tenant.GetSitePropertiesByUrl(siteUrl, false);
                clientContext.Load(site, s => s.Status);
                site.Context.ExecuteQueryRetry();
                var status = site.Status;
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <IsSiteReadyResponse>(new IsSiteReadyResponse {
                        IsSiteReady = status == "Active"
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#28
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] DeleteGroupRequest request, TraceWriter log)
        {
            try
            {
                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.Beta);

                // get the group to be deleted
                var delgroup = await client.Groups[request.GroupId].Request().GetAsync();

                // Create a response for the deleted group
                var DelGroupResponse = new DeletedGroupResponse
                {
                    GroupId     = delgroup.Id,
                    DisplayName = delgroup.DisplayName,
                    Mail        = delgroup.Mail
                };

                // delete the group, if the group is deleted the SP Site will be deleted also but take some time.
                await client.Groups[request.GroupId].Request().DeleteAsync();


                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeletedGroupResponse>(DelGroupResponse, new JsonMediaTypeFormatter())
                }));
            }

            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#29
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] RemoveGroupMembersRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.GroupId))
                {
                    throw new ArgumentException("Parameter cannot be null", "GroupId");
                }
                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.v1);
                var group   = client.Groups[request.GroupId];
                var members = await group.Members.Request().Select("displayName, id, mail, userPrincipalName, userType").GetAsync();

                var users = new List <GroupUser>();

                foreach (var u in members.CurrentPage.Where(p => p.GetType() == typeof(User)).Cast <User>().ToList())
                {
                    users.Add(new GroupUser()
                    {
                        Id = u.Id, UserType = u.UserType, Mail = u.Mail
                    });
                }


                // Removing users from group members
                for (int i = 0; i < users.Count; i++)
                {
                    var user = users[i];
                    if (user.UserType != "Guest" && request.GroupMembersRemoval == GroupMembersRemoval.GuestUsersOnly)
                    {
                        continue;
                    }
                    log.Info($"Removing user {user.Id} from group {request.GroupId}");
                    await group.Members[user.Id].Reference.Request().DeleteAsync();
                }


                var removedGuestUsers = new List <GroupUser>();
                if (request.RemoveGuestUsers)
                {
                    var guestUsers = users.Where(u => u.UserType.Equals("Guest")).ToList();
                    for (int i = 0; i < guestUsers.Count; i++)
                    {
                        var guestUser = guestUsers[i];
                        log.Info($"Retrieving unified membership for user {guestUser.Id}");
                        var memberOfPage  = await client.Users[guestUser.Id].MemberOf.Request().GetAsync();
                        var unifiedGroups = memberOfPage.CurrentPage.Where(p => p.GetType() == typeof(Group)).Cast <Group>().ToList().Where(g => g.GroupTypes.Contains("Unified")).ToList();
                        if (unifiedGroups.Count == 0)
                        {
                            log.Info($"Removing guest user {guestUser.Id}");
                            await client.Users[guestUser.Id].Request().DeleteAsync();
                            removedGuestUsers.Add(guestUser);
                        }
                    }
                }

                var removeGroupMembersResponse = new RemoveGroupMembersResponse {
                    RemovedMembers    = users,
                    RemovedGuestUsers = removedGuestUsers
                };

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <RemoveGroupMembersResponse>(removeGroupMembersResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
示例#30
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteSharingRequest request, TraceWriter log)
        {
            string siteUrl  = request.SiteURL;
            Uri    uri      = new Uri(siteUrl);
            string adminUrl = uri.Scheme + "://" + uri.Authority;

            if (!adminUrl.Contains("-admin.sharepoint.com"))
            {
                adminUrl = adminUrl.Replace(".sharepoint.com", "-admin.sharepoint.com");
            }

            try
            {
                var clientContext = await ConnectADAL.GetClientContext(adminUrl, log);

                Tenant tenant         = new Tenant(clientContext);
                var    siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, false);
                clientContext.Load(siteProperties, s => s.SharingCapability);
                siteProperties.Context.ExecuteQueryRetry();

                bool sharingUpdated = false;
                SharingCapabilities externalShareCapabilities;
                switch (request.SharingCapabilities)
                {
                case ExternalSharingCapabilities.Disabled:
                    externalShareCapabilities = SharingCapabilities.Disabled;
                    break;

                case ExternalSharingCapabilities.ExistingExternalUserSharingOnly:
                    externalShareCapabilities = SharingCapabilities.ExistingExternalUserSharingOnly;
                    break;

                case ExternalSharingCapabilities.ExternalUserAndGuestSharing:
                    externalShareCapabilities = SharingCapabilities.ExternalUserAndGuestSharing;
                    break;

                case ExternalSharingCapabilities.ExternalUserSharingOnly:
                    externalShareCapabilities = SharingCapabilities.ExternalUserSharingOnly;
                    break;

                default:
                    externalShareCapabilities = SharingCapabilities.Disabled;
                    break;
                }
                if (siteProperties.SharingCapability != externalShareCapabilities)
                {
                    sharingUpdated = true;
                    siteProperties.SharingCapability = externalShareCapabilities;
                    siteProperties.Update();
                    clientContext.ExecuteQueryRetry();
                }

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteSharingResponse>(new SetSiteSharingResponse {
                        UpdatedSharing = sharingUpdated
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }