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);
        }
        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);
        }
Exemple #5
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())
                }));
            }
        }
        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())
                }));
            }
        }
        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())
                }));
            }
        }
Exemple #9
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())
                }));
            }
        }
Exemple #10
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())
                }));
            }
        }
        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())
                }));
            }
        }
Exemple #12
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())
                }));
            }
        }
Exemple #13
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())
                }));
            }
        }
Exemple #14
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())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteReadOnlyRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }
                if (string.IsNullOrWhiteSpace(request.Owner))
                {
                    throw new ArgumentException("Parameter cannot be null", "Owner");
                }

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

                var web = clientContext.Web;

                var associatedVisitorGroup = web.AssociatedVisitorGroup;
                var associatedMemberGroup  = web.AssociatedMemberGroup;
                var associatedOwnerGroup   = web.AssociatedOwnerGroup;

                clientContext.Load(web, w => w.AllProperties, w => w.SiteUsers);
                clientContext.Load(associatedVisitorGroup, g => g.Title, g => g.Users);
                clientContext.Load(associatedMemberGroup, g => g.Title, g => g.Users);
                clientContext.Load(associatedOwnerGroup, g => g.Title, g => g.Users);
                clientContext.ExecuteQueryRetry();

                var addToVisitorsGroup = new List <User>();
                addToVisitorsGroup.AddRange(associatedMemberGroup.Users);
                addToVisitorsGroup.AddRange(associatedOwnerGroup.Users);

                foreach (var user in associatedVisitorGroup.Users)
                {
                    if (request.RemoveVisitors)
                    {
                        log.Info($"Removing {user.LoginName} from {associatedVisitorGroup.Title}");
                        associatedVisitorGroup.Users.RemoveByLoginName(user.LoginName);
                    }
                }

                foreach (var user in associatedMemberGroup.Users)
                {
                    if (request.RemoveMembers)
                    {
                        log.Info($"Removing {user.LoginName} from {associatedMemberGroup.Title}");
                        associatedMemberGroup.Users.RemoveByLoginName(user.LoginName);
                    }
                }

                foreach (var user in associatedOwnerGroup.Users)
                {
                    if (request.RemoveOwners)
                    {
                        log.Info($"Removing {user.LoginName} from {associatedOwnerGroup.Title}");
                        associatedOwnerGroup.Users.RemoveByLoginName(user.LoginName);
                    }
                }

                clientContext.ExecuteQueryRetry();

                log.Info($"Adding {request.Owner} to {associatedOwnerGroup.Title}");
                web.AddUserToGroup(associatedOwnerGroup, request.Owner);


                if (web.AllProperties.FieldValues.ContainsKey("GroupType") && web.AllProperties.FieldValues["GroupType"].ToString().Equals("Private"))
                {
                    log.Info($"The site is connected to a private group. Adding existing members/owners to {associatedVisitorGroup.Title}.");
                    foreach (var user in addToVisitorsGroup)
                    {
                        if (user.LoginName.Contains("#ext#") && request.RemoveExternalUsers)
                        {
                            log.Info($"{user.LoginName} is an external user and will not be added to visitors.");
                        }
                        else
                        {
                            log.Info($"Adding {user.LoginName} to {associatedVisitorGroup.Title}.");
                            associatedVisitorGroup.Users.AddUser(user);
                        }
                    }
                }
                else
                {
                    try
                    {
                        var user = web.SiteUsers.First(u => u.LoginName.Contains("spo-grid-all-users"));
                        log.Info($"Adding {user.LoginName} to {associatedVisitorGroup.Title}");
                        web.AddUserToGroup(associatedVisitorGroup, user);
                    } catch (Exception)
                    {
                    }
                }

                clientContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteReadOnlyResponse>(new SetSiteReadOnlyResponse {
                        SetReadOnly = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Info(e.StackTrace);
                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())
                }));
            }
        }
Exemple #16
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteColorRequest request, TraceWriter log)
        {
            if (!request.RGB.StartsWith("#"))
            {
                request.RGB = "#" + request.RGB;
            }
            if (request.RGB.Length != 7 && request.RGB.Length != 4)
            {
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadGateway)
                {
                    Content = new ObjectContent <string>("Color was not in correct format. Use #ccc or #cccccc.", new JsonMediaTypeFormatter())
                }));
            }

            try
            {
                string    siteUrl     = request.SiteURL;
                XDocument colorScheme = GenerateSPColor(request.RGB);

                MemoryStream spcolorStream = new MemoryStream();
                colorScheme.Save(spcolorStream);
                spcolorStream.Position = 0;

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

                var web = clientContext.Web;
                web.Lists.EnsureSiteAssetsLibrary();
                const string fileName        = "theme.spcolor";
                string       relativeSiteUrl = UrlUtility.MakeRelativeUrl(siteUrl);
                string       siteAssetsUrl   = UrlUtility.Combine(relativeSiteUrl, "SiteAssets");
                var          folder          = web.GetFolderByServerRelativeUrl(siteAssetsUrl);

                var file    = folder.UploadFile(fileName, spcolorStream, true);
                var fileUrl = UrlUtility.Combine(siteAssetsUrl, fileName);

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

                try
                {
                    file.DeleteObject();
                    clientContext.ExecuteQueryRetry();
                }
                catch (Exception)
                {
                    //Don't worry if deleting file fails
                }

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteColorResponse>(new SetSiteColorResponse {
                        ColorSet = 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")] SetGroupPermissionsRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            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;
                var associatedOwnerGroup   = web.AssociatedOwnerGroup;
                var associatedMemberGroup  = web.AssociatedMemberGroup;
                var associatedVisitorGroup = web.AssociatedVisitorGroup;
                var webRoleDefinitions     = web.RoleDefinitions;
                var webRoleAssignments     = web.RoleAssignments;
                web.Context.Load(associatedOwnerGroup);
                web.Context.Load(associatedMemberGroup);
                web.Context.Load(associatedVisitorGroup);
                web.Context.Load(webRoleDefinitions);
                web.Context.Load(webRoleAssignments);
                web.Context.ExecuteQueryRetry();

                var associatedOwnerGroupRoleAss   = webRoleAssignments.Where(roleAss => roleAss.PrincipalId == associatedOwnerGroup.Id).ToList();
                var associatedMemberGroupRoleAss  = webRoleAssignments.Where(roleAss => roleAss.PrincipalId == associatedMemberGroup.Id).ToList();
                var associatedVisitorGroupRoleAss = webRoleAssignments.Where(roleAss => roleAss.PrincipalId == associatedVisitorGroup.Id).ToList();

                for (var i = 0; i < associatedOwnerGroupRoleAss.Count; i++)
                {
                    associatedOwnerGroupRoleAss[i].DeleteObject();
                }

                for (var i = 0; i < associatedMemberGroupRoleAss.Count; i++)
                {
                    associatedMemberGroupRoleAss[i].DeleteObject();
                }

                for (var i = 0; i < associatedVisitorGroupRoleAss.Count; i++)
                {
                    associatedVisitorGroupRoleAss[i].DeleteObject();
                }

                web.Update();
                web.Context.ExecuteQueryRetry();

                var associatedOwnerGroupRdb = new RoleDefinitionBindingCollection(clientContext)
                {
                    webRoleDefinitions.GetByType(request.OwnersPermissionLevel)
                };
                webRoleAssignments.Add(associatedOwnerGroup, associatedOwnerGroupRdb);

                var associatedMemberGroupRdp = new RoleDefinitionBindingCollection(clientContext)
                {
                    webRoleDefinitions.GetByType(request.MembersPermissionLevel)
                };
                webRoleAssignments.Add(associatedMemberGroup, associatedMemberGroupRdp);

                var associatedVisitorGroupRdb = new RoleDefinitionBindingCollection(clientContext)
                {
                    webRoleDefinitions.GetByType(request.VisitorsPermissionLevel)
                };
                webRoleAssignments.Add(associatedVisitorGroup, associatedVisitorGroupRdb);

                web.Update();
                web.Context.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetGroupPermissionsResponse>(new SetGroupPermissionsResponse {
                        PermissionsModified = 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 <SetGroupPermissionsResponse>(new SetGroupPermissionsResponse {
                        PermissionsModified = false
                    }, new JsonMediaTypeFormatter())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] ApplyTemplateRequest request, TraceWriter log)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            string siteUrl = request.SiteURL;

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

                string templateUrl   = request.TemplateURL.Trim(); // remove potential spaces/line breaks
                var    clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                var web = clientContext.Web;
                web.Lists.EnsureSiteAssetsLibrary();
                clientContext.ExecuteQueryRetry();

                Uri templateFileUri = new Uri(templateUrl);
                var webUrl          = Web.WebUrlFromFolderUrlDirect(clientContext, templateFileUri);
                var templateContext = clientContext.Clone(webUrl.ToString());

                var library = templateUrl.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/');
                var idx     = library.IndexOf("/", StringComparison.Ordinal);
                library = library.Substring(0, idx);

                // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not
                var    fileConnector         = new SharePointConnector(templateContext, templateContext.Url, library);
                string templateFileName      = Path.GetFileName(templateUrl);
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector));
                templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
                var provisioningTemplate = provider.GetTemplate(templateFileName, new ITemplateProviderExtension[0]);

                if (request.Parameters != null)
                {
                    foreach (var parameter in request.Parameters)
                    {
                        provisioningTemplate.Parameters[parameter.Key] = parameter.Value;
                    }
                }

                provisioningTemplate.Connector = provider.Connector;

                TokenReplaceCustomAction(provisioningTemplate, clientContext.Web);

                ProvisioningTemplateApplyingInformation applyingInformation = new ProvisioningTemplateApplyingInformation()
                {
                    ProgressDelegate = (message, progress, total) =>
                    {
                        log.Info(String.Format("{0:00}/{1:00} - {2}", progress, total, message));
                    },
                    MessagesDelegate = (message, messageType) =>
                    {
                        log.Info(String.Format("{0} - {1}", messageType, message));
                    }
                };

                clientContext.Web.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);
                stopWatch.Stop();

                var applyTemplateResponse = new ApplyTemplateResponse
                {
                    TemplateApplied     = true,
                    ElapsedMilliseconds = stopWatch.ElapsedMilliseconds
                };
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <ApplyTemplateResponse>(applyTemplateResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                stopWatch.Stop();
                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")] PublishFileRequest request, TraceWriter log)
        {
            string fileName = System.IO.Path.GetFileName(request.FileURL);

            if (string.IsNullOrWhiteSpace(fileName))
            {
                log.Error("Error: filename is missing");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>("Filename is missing", new JsonMediaTypeFormatter())
                }));
            }
            Uri    fileUri = new Uri(request.FileURL.Replace(fileName, ""));
            string rootUrl = $"{fileUri.Scheme}://{fileUri.Authority}";

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

            var webUrl      = Web.WebUrlFromFolderUrlDirect(clientContext, fileUri);
            var fileContext = clientContext.Clone(webUrl.ToString());
            var web         = fileContext.Web;

            fileContext.Load(web, w => w.ServerRelativeUrl);

            bool published = false;

            try
            {
                var file = fileContext.Web.GetFileByUrl(request.FileURL);
                fileContext.Load(file);
                fileContext.ExecuteQueryRetry();

                if (file.CheckOutType != CheckOutType.None)
                {
                    file.UndoCheckOut();
                }
                if (file.MinorVersion != 0)
                {
                    published = true;
                    file.CheckOut();

                    PatchListUrls(file, fileContext, web);

                    file.CheckIn("Publish major version", CheckinType.MajorCheckIn);
                }
                fileContext.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <PublishFileResponse>(new PublishFileResponse {
                        Published = published
                    }, 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())
                }));
            }
        }
Exemple #20
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AddUserToGroupRequest 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;
                var user = web.EnsureUser(request.Title);
                Microsoft.SharePoint.Client.Group siteGroup = null;

                switch (request.AssociatedGroup)
                {
                case AssociatedGroup.Member:
                {
                    siteGroup = web.AssociatedMemberGroup;
                }
                break;

                case AssociatedGroup.Owner:
                {
                    siteGroup = web.AssociatedOwnerGroup;
                }
                break;

                case AssociatedGroup.Visitor:
                {
                    siteGroup = web.AssociatedVisitorGroup;
                }
                break;
                }


                if (siteGroup != null)
                {
                    web.Context.Load(siteGroup);
                    web.Context.Load(user);
                    web.Context.ExecuteQueryRetry();

                    siteGroup.Users.AddUser(user);
                    web.Context.ExecuteQueryRetry();

                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <AddUserToGroupResponse>(new AddUserToGroupResponse {
                            UserAdded = true
                        }, new JsonMediaTypeFormatter())
                    }));
                }
                else
                {
                    return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <AddUserToGroupResponse>(new AddUserToGroupResponse {
                            UserAdded = false
                        }, 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 <AddUserToGroupResponse>(new AddUserToGroupResponse {
                        UserAdded = false
                    }, new JsonMediaTypeFormatter())
                }));
            }
        }
        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())
                }));
            }
        }
Exemple #22
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] SetSiteLanguageRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

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

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

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

                var isDirty = false;

                foreach (var lcid in web.SupportedUILanguageIds)
                {
                    var found = request.LanguageIds.Contains(lcid);

                    if (!found)
                    {
                        web.RemoveSupportedUILanguage(lcid);
                        isDirty = true;
                    }
                }
                if (isDirty)
                {
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                foreach (var lcid in request.LanguageIds)
                {
                    web.AddSupportedUILanguage(lcid);
                }
                web.Update();
                web.Context.ExecuteQueryRetry();

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <SetSiteLanguageResponse>(new SetSiteLanguageResponse {
                        LanguagesModified = 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())
                }));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetTermPropertyRequest 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.TermGUID))
                {
                    throw new ArgumentException("Parameter cannot be null", "TermGUID");
                }
                if (string.IsNullOrWhiteSpace(request.PropertyName))
                {
                    throw new ArgumentException("Parameter cannot be null", "PropertyName");
                }
                if (string.IsNullOrWhiteSpace(request.FallbackValue))
                {
                    request.FallbackValue = "";
                }
                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                clientContext.Load(taxonomySession);
                clientContext.ExecuteQueryRetry();
                TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                var       term      = termStore.GetTerm(new Guid(request.TermGUID));
                clientContext.Load(term, t => t.LocalCustomProperties);
                clientContext.ExecuteQueryRetry();
                var propertyValue = string.Empty;
                do
                {
                    if (term.LocalCustomProperties.Keys.Contains(request.PropertyName))
                    {
                        propertyValue = term.LocalCustomProperties[request.PropertyName];
                    }
                    else
                    {
                        term = term.Parent;
                        clientContext.Load(term, t => t.LocalCustomProperties);
                        clientContext.ExecuteQueryRetry();
                    }
                } while (string.IsNullOrWhiteSpace(propertyValue));

                var getTermPropertyResponse = new GetTermPropertyResponse
                {
                    PropertyValue = propertyValue
                };
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception)
            {
                var getTermPropertyResponse = new GetTermPropertyResponse
                {
                    PropertyValue = request.FallbackValue
                };
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter())
                }));
            }
        }