public void Execute(ClientContext ctx, string title, Uri url, BasePermissions visibleTo)
        {
            Logger.Verbose($"Started executing {nameof(AddItemToSiteActionsMenu)} for item '{title}'");

            // inspired by https://github.com/OfficeDev/PnP/tree/master/Scenarios/Provisioning.SiteModifier
            var web = ctx.Web;
            ctx.Load(web, w => w.UserCustomActions);
            ctx.ExecuteQuery();

            var existingItem = web.UserCustomActions.SingleOrDefault(a => a.Title == title);
            if (existingItem != null)
            {
                Logger.Warning($"Menu item '{title}' already exists");
                return;
            }

            var uca = web.UserCustomActions.Add();
            uca.Location = "Microsoft.SharePoint.StandardMenu";
            uca.Group = "SiteActions";
            uca.Rights = visibleTo;
            uca.Sequence = 100;
            uca.Title = title;
            uca.Url = url.ToString();
            uca.Update();
            ctx.ExecuteQuery();
        }
Beispiel #2
0
        public void SetUpCustomPermissionLevels(ClientContext context, List<ShPermissionLevel> permissionLevels)
        {
            foreach (var permissionLevel in permissionLevels)
            {
                context.Load(context.Site.RootWeb.RoleDefinitions);
                context.ExecuteQuery();

                var existingPermissionLevel = context.Site.RootWeb.RoleDefinitions.FirstOrDefault(x => x.Name.Equals(permissionLevel.Name));
                if (existingPermissionLevel == null)
                {
                    Log.Info("Creating permission level " + permissionLevel.Name);
                    BasePermissions permissions = new BasePermissions();
                    foreach (var basePermission in permissionLevel.BasePermissions)
                    {
                        permissions.Set(basePermission);
                    }
                    RoleDefinitionCreationInformation roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
                    roleDefinitionCreationInfo.BasePermissions = permissions;
                    roleDefinitionCreationInfo.Name = permissionLevel.Name;
                    roleDefinitionCreationInfo.Description = permissionLevel.Description;
                    RoleDefinition roleDefinition = context.Site.RootWeb.RoleDefinitions.Add(roleDefinitionCreationInfo);
                    context.ExecuteQuery();
                }
            }
        }
Beispiel #3
0
 protected bool DoesUserHavePermission()
 {
     BasePermissions perms = new BasePermissions();
     perms.Set(PermissionKind.ManageWeb);
     ClientResult<bool> _permResult = _ctx.Web.DoesUserHavePermissions(perms);
     _ctx.ExecuteQuery();
     return _permResult.Value;
 }
Beispiel #4
0
 protected override void ExecuteCmdlet()
 {
     BasePermissions permissions = new BasePermissions();
     foreach (PermissionKind kind in Rights)
     {
         permissions.Set(kind);
     }
     SPOnline.Core.SPOWeb.AddCustomAction(this.SelectedWeb, Title, Group, Location, Name, Sequence, Url, permissions, ClientContext);
 }
        public void SetBasePermissionsTest()
        {
            CustomAction ca = new CustomAction();
            BasePermissions bp = new BasePermissions();
            bp.Set(PermissionKind.ApplyStyleSheets);
            bp.Set(PermissionKind.BrowseUserInfo);

            ca.Rights = bp;

            ca.RightsValue = 29;
        }
Beispiel #6
0
 private bool DoesUserHavePermission()
 {
     var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
     using (var ctx = spContext.CreateUserClientContextForSPHost())
     {
         BasePermissions perms = new BasePermissions();
         perms.Set(PermissionKind.ManageLists);
         ClientResult<bool> _permResult = ctx.Web.DoesUserHavePermissions(perms);
         ctx.ExecuteQuery();
         return _permResult.Value;
     }
 }
Beispiel #7
0
        private void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx)
        {

            Web web = ctx.Web;
            ctx.Load(web, w => w.UserCustomActions);
            ctx.ExecuteQuery();

            ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId);
            ctx.ExecuteQuery();

            UserCustomAction userCustomAction = web.UserCustomActions.Add();
            userCustomAction.Location = "Microsoft.SharePoint.StandardMenu";
            userCustomAction.Group = "SiteActions";
            BasePermissions perms = new BasePermissions();
            perms.Set(PermissionKind.ManageWeb);
            userCustomAction.Rights = perms;
            userCustomAction.Sequence = 100;
            userCustomAction.Title = "Modify Site";

            string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(ctx.Url));
            string issuerId = WebConfigurationManager.AppSettings.Get("ClientId");

            var modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", Request.Url.Authority);
            string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});";
            url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl);

            userCustomAction.Url = url;
            userCustomAction.Update();
            ctx.ExecuteQuery();

            // Remove the entry from the 'Recents' node
            NavigationNodeCollection nodes = web.Navigation.QuickLaunch;
            ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children));
            ctx.ExecuteQuery();
            var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault();
            if (recent != null)
            {
                var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault();
                if (appLink != null) appLink.DeleteObject();
                ctx.ExecuteQuery();
            }
        }
        protected override void ExecuteCmdlet()
        {
            var permissions = new BasePermissions();
            if (Rights != null)
            {
                foreach (var kind in Rights)
                {
                    permissions.Set(kind);
                }
            }

            var ca = new CustomActionEntity
            {
                Name = Name,
                ImageUrl = ImageUrl,
                CommandUIExtension = CommandUIExtension,
                RegistrationId = RegistrationId,
                RegistrationType = RegistrationType,
                Description = Description,
                Location = Location,
                Group = Group,
                Sequence = Sequence,
                Title = Title,
                Url = Url,
                Rights = permissions
            };

            switch (Scope)
            {
                case CustomActionScope.Web:
                    SelectedWeb.AddCustomAction(ca);
                    break;

                case CustomActionScope.Site:
                    ClientContext.Site.AddCustomAction(ca);
                    break;

                case CustomActionScope.All:
                    WriteWarning("CustomActionScope 'All' is not supported for adding CustomActions");
                    break;
            }
        }
Beispiel #9
0
        public static UserCustomAction AddCustomAction(Web web, string title, string group, string location, string name, int sequence, string url, BasePermissions rights, ClientContext clientContext)
        {
            UserCustomAction customAction = null;

            // Add site settings link, if it doesn't already exist
            if (!CustomActionAlreadyExists(clientContext, name))
            {
                // Add site settings link
                customAction = clientContext.Web.UserCustomActions.Add();
                customAction.Group = group;
                customAction.Location = location;
                customAction.Name = name;
                customAction.Sequence = sequence;
                customAction.Url = url;
                customAction.Rights = rights;
                customAction.Title = title;
                customAction.Update();
                clientContext.Load(customAction);
                clientContext.ExecuteQuery();
            }
            return customAction;
        }
Beispiel #10
0
        protected override void ExecuteCmdlet()
        {
            var permissions = new BasePermissions();
            foreach (var kind in Rights)
            {
                permissions.Set(kind);
            }
            var ca = new CustomActionEntity { Description = Description, Location = Location, Group = Group, Sequence = Sequence, Title = Title, Url = Url, Rights = new BasePermissions() };

            foreach (var permission in Rights)
            {
                ca.Rights.Set(permission);
            }

            if (Scope == CustomActionScope.Web)
            {
                SelectedWeb.AddCustomAction(ca);
            }
            else
            {
                ClientContext.Site.AddCustomAction(ca);
            }
        }
Beispiel #11
0
        protected override void ExecuteCmdlet()
        {
            BasePermissions permissions = new BasePermissions();
            foreach (PermissionKind kind in Rights)
            {
                permissions.Set(kind);
            }
            CustomActionEntity ca = new CustomActionEntity();
            ca.Description = Description;
            ca.Location = Location;
            ca.Group = Group;
            ca.Sequence = Sequence;
            ca.Title = Title;
            ca.Url = Url;
            ca.Rights = new BasePermissions();

            foreach(var permission in Rights)
            {
                ca.Rights.Set(permission);
            }

            this.SelectedWeb.AddCustomAction(ca);
        }
        public void Execute(ClientContext ctx, string permissionLevelName, string permissionLevelDescription, BasePermissions permissions)
        {
            Logger.Verbose($"About to execute {nameof(CreatePermissionLevel)} for level '{permissionLevelName}' on web '{ctx.Url}'");

            var roleDefinitions = ctx.Web.RoleDefinitions;
            ctx.Load(roleDefinitions);
            ctx.ExecuteQuery();

            var roleDefinition = roleDefinitions.SingleOrDefault(rd => rd.Name == permissionLevelName);
            if (roleDefinition != null)
            {
                Logger.Warning($"Permission level '{permissionLevelName}' already exists");
                return;
            }

            ctx.Web.RoleDefinitions.Add(
                new RoleDefinitionCreationInformation
                {
                    BasePermissions = permissions,
                    Name = permissionLevelName,
                    Description = permissionLevelDescription
                });
            ctx.ExecuteQuery();
        }
        protected override void ExecuteCmdlet()
        {
            var permissions = new BasePermissions();
            if (Rights != null)
            {
                foreach (var kind in Rights)
                {
                    permissions.Set(kind);
                }
            }

            var ca = new CustomActionEntity
            {
                Name = Name,
                ImageUrl = ImageUrl,
                CommandUIExtension = CommandUIExtension,
                RegistrationId = RegistrationId,
                RegistrationType = RegistrationType,
                Description = Description,
                Location = Location,
                Group = Group,
                Sequence = Sequence,
                Title = Title,
                Url = Url,
                Rights = permissions
            };

            if (Scope == CustomActionScope.Web)
            {
                SelectedWeb.AddCustomAction(ca);
            }
            else
            {
                ClientContext.Site.AddCustomAction(ca);
            }
        }
        private void MapCustomAction(UserCustomAction existringAction, UserCustomActionDefinition customAction)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Updating user custom action properties.");

            existringAction.Sequence    = customAction.Sequence;
            existringAction.Group       = customAction.Group;
            existringAction.Location    = customAction.Location;
            existringAction.Name        = customAction.Name;
            existringAction.ScriptBlock = customAction.ScriptBlock;
            existringAction.ScriptSrc   = customAction.ScriptSrc;

            // fallback for old models
            // fill out Title/Description with Name if NULLs
            // that needs for SP2016 to work well with translation exports

            // UserCustomAction without Title/Description breaks Translation Export #937
            // https://github.com/SubPointSolutions/spmeta2/issues/937

            if (!string.IsNullOrEmpty(customAction.Title))
            {
                existringAction.Title = customAction.Title;
            }
            else
            {
                existringAction.Title = customAction.Name;
            }

            if (!string.IsNullOrEmpty(customAction.Description))
            {
                existringAction.Description = customAction.Description;
            }
            else
            {
                existringAction.Description = customAction.Name;
            }

            existringAction.Url = customAction.Url;

            if (!string.IsNullOrEmpty(customAction.CommandUIExtension))
            {
                existringAction.CommandUIExtension = customAction.CommandUIExtension;
            }

            if (!string.IsNullOrEmpty(customAction.RegistrationId))
            {
                existringAction.RegistrationId = customAction.RegistrationId;
            }

            if (!string.IsNullOrEmpty(customAction.RegistrationType))
            {
                // skipping setup for List script
                // System.NotSupportedException: Setting this property is not supported.  A value of List has already been set and cannot be changed.
                if (customAction.RegistrationType != BuiltInRegistrationTypes.List)
                {
                    existringAction.RegistrationType =
                        (UserCustomActionRegistrationType)
                        Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType, true);
                }
            }

            var permissions = new BasePermissions();

            if (customAction.Rights != null && customAction.Rights.Count > 0)
            {
                foreach (var permissionString in customAction.Rights)
                {
                    permissions.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), permissionString));
                }
            }

            existringAction.Rights = permissions;


            ProcessLocalization(existringAction, customAction);
        }
        private void GetAllSiteCollections(string url)
        {
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(url + "/_api/search/query?querytext='contentclass:sts_site'&trimduplicates=false&rowlimit=100");

            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json;odata=verbose";
            NetworkCredential cred = new NetworkCredential(Login, Mdp, DomaineUser);

            endpointRequest.Credentials = cred;
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();

            try
            {
                WebResponse  webResponse    = endpointRequest.GetResponse();
                Stream       webStream      = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string       response       = responseReader.ReadToEnd();

                JObject jobj = JObject.Parse(response);

                for (int ind = 0; ind < jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"].Count(); ind++)
                {
                    string urlCollection = jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"][ind]["Cells"]["results"][6]["Value"].ToString();
                    string nomCollection = jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"][ind]["Cells"]["results"][3]["Value"].ToString();
                    if (urlCollection.Contains("loca-fcn-sp16/sites/") == true)
                    {
                        string[] split = urlCollection.Split('/');
                        ClientCtx = new ClientContext(Domaine + "/sites/" + split[4]);
                        using (ClientCtx = new ClientContext(ClientCtx.Url))
                        {
                            ClientCtx.Credentials = new NetworkCredential(Login, Mdp, DomaineUser);
                            Web rootWeb = ClientCtx.Site.RootWeb;
                            ClientCtx.Load(rootWeb);

                            BasePermissions bp = new BasePermissions();
                            bp.Set(PermissionKind.AddListItems);
                            //
                            ClientResult <bool> viewListItems = rootWeb.DoesUserHavePermissions(bp);
                            try
                            {
                                ClientCtx.ExecuteQuery();
                                if (viewListItems.Value)
                                {
                                    ListDesSiteCollections.Add(nomCollection, split[4]);
                                }
                            }
                            catch
                            {
                                Console.WriteLine("\n ---> You don't have access to site {0}\n   -- Exception: ");
                            }
                        }
                    }
                }

                responseReader.Close();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message); Console.ReadLine();
            }
        }
        public static BasePermissions ToBasePermissions(this string basePermissionString)
        {
            BasePermissions bp = new BasePermissions();

            // Is it an int value (for backwards compability)?
            int permissionInt = 0;
            if (int.TryParse(basePermissionString, out permissionInt))
            {
                bp.Set((PermissionKind)permissionInt);
            }
            else {
                foreach (var pk in basePermissionString.Split(new char[] { ',' }))
                {
                    PermissionKind permissionKind = PermissionKind.AddAndCustomizePages;
                    if (Enum.TryParse<PermissionKind>(basePermissionString, out permissionKind))
                    {
                        bp.Set(permissionKind);
                    }
                }
            }
            return bp;
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {

                // if this is a sub site then we're not provisioning security as by default security is inherited from the root site
                if (web.IsSubSite())
                {
                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning);
                    return parser;
                }

                var siteSecurity = template.Security;

                var ownerGroup = web.AssociatedOwnerGroup;
                var memberGroup = web.AssociatedMemberGroup;
                var visitorGroup = web.AssociatedVisitorGroup;

                web.Context.Load(ownerGroup, o => o.Title, o => o.Users);
                web.Context.Load(memberGroup, o => o.Title, o => o.Users);
                web.Context.Load(visitorGroup, o => o.Title, o => o.Users);

                web.Context.ExecuteQueryRetry();

                if (!ownerGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope);
                }
                if (!memberGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope);
                }
                if (!visitorGroup.ServerObjectIsNull.Value)
                {
                    AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope);
                }

                foreach (var siteGroup in siteSecurity.SiteGroups)
                {
                    Group group = null;
                    var allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName));
                    web.Context.ExecuteQueryRetry();

                    if (!web.GroupExists(siteGroup.Title))
                    {
                        scope.LogDebug("Creating group {0}", siteGroup.Title);
                        group = web.AddGroup(
                            parser.ParseString(siteGroup.Title),
                            parser.ParseString(siteGroup.Description),
                            parser.ParseString(siteGroup.Title) == parser.ParseString(siteGroup.Owner));
                        group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                        group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                        group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;

                        if (parser.ParseString(siteGroup.Title) != parser.ParseString(siteGroup.Owner))
                        {
                            Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parser.ParseString(siteGroup.Owner));
                            if (ownerPrincipal == null)
                            {
                                ownerPrincipal = web.EnsureUser(parser.ParseString(siteGroup.Owner));
                            }
                            group.Owner = ownerPrincipal;

                        }
                        group.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    else
                    {
                        group = web.SiteGroups.GetByName(parser.ParseString(siteGroup.Title));
                        web.Context.Load(group,
                            g => g.Title,
                            g => g.Description,
                            g => g.AllowMembersEditMembership,
                            g => g.AllowRequestToJoinLeave,
                            g => g.AutoAcceptRequestToJoinLeave,
                            g => g.Owner.LoginName);
                        web.Context.ExecuteQueryRetry();
                        var isDirty = false;
                        if (group.Description != parser.ParseString(siteGroup.Description))
                        {
                            group.Description = parser.ParseString(siteGroup.Description);
                            isDirty = true;
                        }
                        if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership)
                        {
                            group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                            isDirty = true;
                        }
                        if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave)
                        {
                            group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave)
                        {
                            group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.Owner.LoginName != parser.ParseString(siteGroup.Owner))
                        {
                            if (parser.ParseString(siteGroup.Title) != parser.ParseString(siteGroup.Owner))
                            {
                                Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parser.ParseString(siteGroup.Owner));
                                if (ownerPrincipal == null)
                                {
                                    ownerPrincipal = web.EnsureUser(parser.ParseString(siteGroup.Owner));
                                }
                                group.Owner = ownerPrincipal;
                            }
                            else
                            {
                                group.Owner = group;
                            }
                            isDirty = true;
                        }
                        if (isDirty)
                        {
                            scope.LogDebug("Updating existing group {0}", group.Title);
                            group.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                    if (group != null && siteGroup.Members.Any())
                    {
                        AddUserToGroup(web, group, siteGroup.Members, scope);
                    }
                }

                foreach (var admin in siteSecurity.AdditionalAdministrators)
                {
                    var user = web.EnsureUser(admin.Name);
                    user.IsSiteAdmin = true;
                    user.Update();
                    web.Context.ExecuteQueryRetry();
                }

                if (siteSecurity.SiteSecurityPermissions != null)
                {
                    var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any())
                    {
                        foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions)
                        {
                            var siteRoleDefinition = existingRoleDefinitions.FirstOrDefault(erd => erd.Name == parser.ParseString(templateRoleDefinition.Name));
                            if (siteRoleDefinition == null)
                            {
                                scope.LogDebug("Creation role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                var roleDefinitionCI = new RoleDefinitionCreationInformation();
                                roleDefinitionCI.Name = parser.ParseString(templateRoleDefinition.Name);
                                roleDefinitionCI.Description = parser.ParseString(templateRoleDefinition.Description);
                                BasePermissions basePermissions = new BasePermissions();

                                foreach (var permission in templateRoleDefinition.Permissions)
                                {
                                    basePermissions.Set(permission);
                                }

                                roleDefinitionCI.BasePermissions = basePermissions;

                                web.RoleDefinitions.Add(roleDefinitionCI);
                                web.Context.ExecuteQueryRetry();
                            }
                            else
                            {
                                var isDirty = false;
                                if (siteRoleDefinition.Description != parser.ParseString(templateRoleDefinition.Description))
                                {
                                    siteRoleDefinition.Description = parser.ParseString(templateRoleDefinition.Description);
                                    isDirty = true;
                                }
                                var templateBasePermissions = new BasePermissions();
                                templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p));
                                if (siteRoleDefinition.BasePermissions != templateBasePermissions)
                                {
                                    isDirty = true;
                                    foreach (var permission in templateRoleDefinition.Permissions)
                                    {
                                        siteRoleDefinition.BasePermissions.Set(permission);
                                    }
                                }
                                if (isDirty)
                                {
                                    scope.LogDebug("Updating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                    siteRoleDefinition.Update();
                                    web.Context.ExecuteQueryRetry();
                                }
                            }
                        }
                    }

                    var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions);
                    var groups = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any())
                    {
                        foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments)
                        {
                            Principal principal = groups.FirstOrDefault(g => g.LoginName == parser.ParseString(roleAssignment.Principal));
                            if (principal == null)
                            {
                                principal = web.EnsureUser(parser.ParseString(roleAssignment.Principal));
                            }

                            var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context);

                            var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == roleAssignment.RoleDefinition);

                            if (roleDefinition != null)
                            {
                                roleDefinitionBindingCollection.Add(roleDefinition);
                            }
                            web.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                }
            }
            return parser;
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Changed by Paolo Pialorsi to embrace the new sub-site attributes to break role inheritance and copy role assignments
                // if this is a sub site then we're not provisioning security as by default security is inherited from the root site
                //if (web.IsSubSite() && !template.Security.BreakRoleInheritance)
                //{
                //    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning);
                //    return parser;
                //}

                if (web.IsSubSite() && template.Security.BreakRoleInheritance)
                {
                    web.BreakRoleInheritance(template.Security.CopyRoleAssignments, template.Security.ClearSubscopes);
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                var siteSecurity = template.Security;

                var ownerGroup   = web.AssociatedOwnerGroup;
                var memberGroup  = web.AssociatedMemberGroup;
                var visitorGroup = web.AssociatedVisitorGroup;

                web.Context.Load(ownerGroup, o => o.Title, o => o.Users);
                web.Context.Load(memberGroup, o => o.Title, o => o.Users);
                web.Context.Load(visitorGroup, o => o.Title, o => o.Users);
                web.Context.Load(web.SiteUsers);

                web.Context.ExecuteQueryRetry();

                if (!ownerGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope, parser);
                }
                if (!memberGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope, parser);
                }
                if (!visitorGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope, parser);
                }

                foreach (var siteGroup in siteSecurity.SiteGroups)
                {
                    Group group;
                    var   allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName));
                    web.Context.ExecuteQueryRetry();

                    string parsedGroupTitle       = parser.ParseString(siteGroup.Title);
                    string parsedGroupOwner       = parser.ParseString(siteGroup.Owner);
                    string parsedGroupDescription = parser.ParseString(siteGroup.Description);

                    if (!web.GroupExists(parsedGroupTitle))
                    {
                        scope.LogDebug("Creating group {0}", parsedGroupTitle);
                        group = web.AddGroup(
                            parsedGroupTitle,
                            parsedGroupDescription,
                            parsedGroupTitle == parsedGroupOwner);
                        group.AllowMembersEditMembership   = siteGroup.AllowMembersEditMembership;
                        group.AllowRequestToJoinLeave      = siteGroup.AllowRequestToJoinLeave;
                        group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;

                        if (parsedGroupTitle != parsedGroupOwner)
                        {
                            Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                            if (ownerPrincipal == null)
                            {
                                ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                            }
                            group.Owner = ownerPrincipal;
                        }
                        group.Update();
                        web.Context.Load(group, g => g.Id, g => g.Title);
                        web.Context.ExecuteQueryRetry();
                        parser.AddToken(new GroupIdToken(web, group.Title, group.Id));
                    }
                    else
                    {
                        group = web.SiteGroups.GetByName(parsedGroupTitle);
                        web.Context.Load(group,
                                         g => g.Title,
                                         g => g.Description,
                                         g => g.AllowMembersEditMembership,
                                         g => g.AllowRequestToJoinLeave,
                                         g => g.AutoAcceptRequestToJoinLeave,
                                         g => g.Owner.LoginName);
                        web.Context.ExecuteQueryRetry();
                        var isDirty = false;
                        if (!String.IsNullOrEmpty(group.Description) && group.Description != parsedGroupDescription)
                        {
                            group.Description = parsedGroupDescription;
                            isDirty           = true;
                        }
                        if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership)
                        {
                            group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                            isDirty = true;
                        }
                        if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave)
                        {
                            group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave)
                        {
                            group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.Owner.LoginName != parsedGroupOwner)
                        {
                            if (parsedGroupTitle != parsedGroupOwner)
                            {
                                Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                                if (ownerPrincipal == null)
                                {
                                    ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                                }
                                group.Owner = ownerPrincipal;
                            }
                            else
                            {
                                group.Owner = group;
                            }
                            isDirty = true;
                        }
                        if (isDirty)
                        {
                            scope.LogDebug("Updating existing group {0}", group.Title);
                            group.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                    if (group != null && siteGroup.Members.Any())
                    {
                        AddUserToGroup(web, group, siteGroup.Members, scope, parser);
                    }
                }

                foreach (var admin in siteSecurity.AdditionalAdministrators)
                {
                    var parsedAdminName = parser.ParseString(admin.Name);
                    try
                    {
                        var user = web.EnsureUser(parsedAdminName);
                        user.IsSiteAdmin = true;
                        user.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        scope.LogWarning(ex, "Failed to add AdditionalAdministrator {0}", parsedAdminName);
                    }
                }

                // With the change from october, manage permission levels on subsites as well
                if (siteSecurity.SiteSecurityPermissions != null)
                {
                    var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any())
                    {
                        foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions)
                        {
                            var roleDefinitions    = existingRoleDefinitions as RoleDefinition[] ?? existingRoleDefinitions.ToArray();
                            var siteRoleDefinition = roleDefinitions.FirstOrDefault(erd => erd.Name == parser.ParseString(templateRoleDefinition.Name));
                            if (siteRoleDefinition == null)
                            {
                                scope.LogDebug("Creating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                var roleDefinitionCI = new RoleDefinitionCreationInformation();
                                roleDefinitionCI.Name        = parser.ParseString(templateRoleDefinition.Name);
                                roleDefinitionCI.Description = parser.ParseString(templateRoleDefinition.Description);
                                BasePermissions basePermissions = new BasePermissions();

                                foreach (var permission in templateRoleDefinition.Permissions)
                                {
                                    basePermissions.Set(permission);
                                }

                                roleDefinitionCI.BasePermissions = basePermissions;

                                web.RoleDefinitions.Add(roleDefinitionCI);
                                web.Context.ExecuteQueryRetry();
                            }
                            else
                            {
                                var isDirty = false;
                                if (siteRoleDefinition.Description != parser.ParseString(templateRoleDefinition.Description))
                                {
                                    siteRoleDefinition.Description = parser.ParseString(templateRoleDefinition.Description);
                                    isDirty = true;
                                }
                                var templateBasePermissions = new BasePermissions();
                                templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p));
                                if (siteRoleDefinition.BasePermissions != templateBasePermissions)
                                {
                                    isDirty = true;
                                    foreach (var permission in templateRoleDefinition.Permissions)
                                    {
                                        siteRoleDefinition.BasePermissions.Set(permission);
                                    }
                                }
                                if (isDirty)
                                {
                                    scope.LogDebug("Updating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                    siteRoleDefinition.Update();
                                    web.Context.ExecuteQueryRetry();
                                }
                            }
                        }
                    }

                    var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions);
                    var groups             = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any())
                    {
                        foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments)
                        {
                            var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == parser.ParseString(roleAssignment.RoleDefinition));
                            if (roleDefinition != null)
                            {
                                Principal principal = groups.FirstOrDefault(g => g.LoginName == parser.ParseString(roleAssignment.Principal));

                                if (principal == null)
                                {
                                    var parsedUser = parser.ParseString(roleAssignment.Principal);
                                    if (parsedUser.Contains("#ext#"))
                                    {
                                        principal = web.SiteUsers.FirstOrDefault(u => u.LoginName.Equals(parsedUser));

                                        if (principal == null)
                                        {
                                            scope.LogInfo($"Skipping external user {parsedUser}");
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            principal = web.EnsureUser(parsedUser);
                                            web.Context.ExecuteQueryRetry();
                                        }
                                        catch (Exception ex)
                                        {
                                            scope.LogWarning(ex, "Failed to EnsureUser {0}", parsedUser);
                                        }
                                    }
                                }

                                if (principal != null)
                                {
                                    var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context);
                                    roleDefinitionBindingCollection.Add(roleDefinition);
                                    web.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                                    web.Context.ExecuteQueryRetry();
                                }
                            }
                            else
                            {
                                scope.LogWarning("Role assignment {0} not found in web", roleAssignment.RoleDefinition);
                            }
                        }
                    }
                }
            }
            return(parser);
        }
Beispiel #19
0
        public bool DoesUserHavePermissions()
        {
            bool _returnResult = false;                
            UsingContext(ctx =>
            {                        
                var _web = ctx.Web;
                ctx.Load(_web);
                BasePermissions perms = new BasePermissions();
                perms.Set(PermissionKind.ManageWeb);
                ClientResult<bool> _permResult = ctx.Web.DoesUserHavePermissions(perms);
                ctx.ExecuteQuery();

                _returnResult = _permResult.Value;
            });

            return _returnResult;
        }                
Beispiel #20
0
        /// <summary>
        /// Creates a new permission level in specified web context
        /// </summary>
        /// <param name="context">Client Context</param>
        /// <param name="permissionLevelName">Name of permission level to be created</param>
        /// <param name="description">Description of permission level to be created</param>
        /// <returns>Boolean value whether permission level created or not</returns>
        private static bool CreateNewPermissionLevel(ClientContext context, string permissionLevelName, string description)
        {
            bool isPermissionLevelCreated = false;
            try
            {
                RemovePermissionLevelIfExists(context, permissionLevelName);
                BasePermissions permissions = new BasePermissions();

                // List Permissions
                permissions.Set(PermissionKind.AddListItems);
                permissions.Set(PermissionKind.EditListItems);
                permissions.Set(PermissionKind.DeleteListItems);
                permissions.Set(PermissionKind.ViewListItems);
                permissions.Set(PermissionKind.OpenItems);
                permissions.Set(PermissionKind.ViewVersions);
                permissions.Set(PermissionKind.DeleteVersions);
                permissions.Set(PermissionKind.CreateAlerts);

                // Site Permissions
                permissions.Set(PermissionKind.BrowseDirectories);
                permissions.Set(PermissionKind.CreateSSCSite);
                permissions.Set(PermissionKind.BrowseDirectories);
                permissions.Set(PermissionKind.ViewPages);
                permissions.Set(PermissionKind.BrowseUserInfo);
                permissions.Set(PermissionKind.UseRemoteAPIs);
                permissions.Set(PermissionKind.UseClientIntegration);
                permissions.Set(PermissionKind.Open);
                permissions.Set(PermissionKind.EditMyUserInfo);

                // Personal Permissions
                permissions.Set(PermissionKind.ManagePersonalViews);
                permissions.Set(PermissionKind.AddDelPrivateWebParts);
                permissions.Set(PermissionKind.UpdatePersonalWebParts);

                // Extra Permissions
                permissions.Set(PermissionKind.ManagePermissions);
                permissions.Set(PermissionKind.EnumeratePermissions);

                RoleDefinitionCreationInformation roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
                roleDefinitionCreationInfo.BasePermissions = permissions;
                roleDefinitionCreationInfo.Name = permissionLevelName;
                roleDefinitionCreationInfo.Description = description;
                context.Web.RoleDefinitions.Add(roleDefinitionCreationInfo);
                context.Web.Update();
                context.ExecuteQuery();
                isPermissionLevelCreated = true;
                Console.WriteLine();
                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["NewPermission"], permissionLevelName), ErrorMessage.MessageType.Success);
            }
            catch (Exception exception)
            {
                isPermissionLevelCreated = false;
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                RemovePermissionLevelIfExists(context, permissionLevelName);
            }
            return isPermissionLevelCreated;
        }
Beispiel #21
0
        /// <summary>
        /// Assign permission to the group
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="collSite">Site object</param>
        /// <param name="site">Web object</param>
        /// <param name="currentGrp">Group object</param>
        private static void AssignPermissionToGroup(ClientContext clientContext, Site collSite, Web site, Group currentGrp)
        {
            //Create permission role and assign group to the role
            RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(clientContext);
            RoleDefinition roleDef = site.RoleDefinitions.FirstOrDefault(roles => roles.Name == ConfigurationManager.AppSettings["restrictedAccessRoleName"]);
            if (roleDef == null)
            {
                BasePermissions permissions = new BasePermissions();
                permissions.Set(PermissionKind.UseRemoteAPIs);
                permissions.Set(PermissionKind.Open);

                RoleDefinitionCreationInformation rdcInfo = new RoleDefinitionCreationInformation();
                rdcInfo.Name = ConfigurationManager.AppSettings["restrictedAccessRoleName"];
                rdcInfo.Description = ConfigurationManager.AppSettings["restrictedAccessRoleDescription"];
                rdcInfo.BasePermissions = permissions;
                roleDef = collSite.RootWeb.RoleDefinitions.Add(rdcInfo);
            }
            collRDB.Add(roleDef);
            site.RoleAssignments.Add(currentGrp, collRDB);
            clientContext.Load(currentGrp);
            clientContext.Load(collRDB);
            clientContext.ExecuteQuery();
        }
        protected override void OnLoad(EventArgs e)
        {
            bool hasManageWebPerms = false;

            //get SharePoint context
            var spContext = Util.ContextUtil.Current;

            using (var clientContext = TokenHelper.GetClientContextWithContextToken(spContext.ContextDetails.AppWebUrl, spContext.ContextDetails.ContextTokenString, Request.Url.Authority))
            {
                //check if the user has ManageWeb permissions from app web
                BasePermissions perms = new BasePermissions();
                perms.Set(PermissionKind.ManageWeb);
                ClientResult <bool> result = clientContext.Web.DoesUserHavePermissions(perms);
                clientContext.ExecuteQuery();
                hasManageWebPerms = result.Value;
            }

            //define initial script
            string script = @"
            function chromeLoaded() {
                $('body').show();
            }
            //function callback to render chrome after SP.UI.Controls.js loads
            function renderSPChrome() {
                //Get the host site logo url from the SPHostLogoUrl parameter
                var hostlogourl = decodeURIComponent(getQueryStringParameter('SPHostLogoUrl'));

                var links = [{
                    'linkUrl': 'mailto:[email protected]',
                    'displayName': 'Contact us'
                }];
                ";

            //add link to settings if the current user has ManageWeb permissions
            if (hasManageWebPerms)
            {
                script += @"links.push({
                        'linkUrl': '" + spContext.ContextDetails.AppWebUrl + @"/SSConfig',
                        'displayName': 'Settings'
                    });";
            }

            //add remainder of script
            script += @"
                //Set the chrome options for launching Help, Account, and Contact pages
                var options = {
                    'appIconUrl': hostlogourl,
                    'appTitle': document.title,
                    'settingsLinks': links,
                    'onCssLoaded': 'chromeLoaded()'
                };

                //Load the Chrome Control in the divSPChrome element of the page
                var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
                chromeNavigation.setVisible(true);

            }";

            //register script in page
            Page.ClientScript.RegisterClientScriptBlock(typeof(BasePage), "BasePageScript", script, true);

            //call base onload
            base.OnLoad(e);
        }
Beispiel #23
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Changed by Paolo Pialorsi to embrace the new sub-site attributes to break role inheritance and copy role assignments
                // if this is a sub site then we're not provisioning security as by default security is inherited from the root site
                //if (web.IsSubSite() && !template.Security.BreakRoleInheritance)
                //{
                //    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning);
                //    return parser;
                //}

                if (web.IsSubSite() && template.Security.BreakRoleInheritance)
                {
                    web.BreakRoleInheritance(template.Security.CopyRoleAssignments, template.Security.ClearSubscopes);
                    web.Update();
                    web.Context.ExecuteQueryRetry();
                }

                var siteSecurity = template.Security;

                var ownerGroup   = web.AssociatedOwnerGroup;
                var memberGroup  = web.AssociatedMemberGroup;
                var visitorGroup = web.AssociatedVisitorGroup;

                web.Context.Load(ownerGroup, o => o.Title, o => o.Users);
                web.Context.Load(memberGroup, o => o.Title, o => o.Users);
                web.Context.Load(visitorGroup, o => o.Title, o => o.Users);
                web.Context.Load(web.SiteUsers);

                web.Context.ExecuteQueryRetry();

                if (!ownerGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope, parser);
                }
                if (!memberGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope, parser);
                }
                if (!visitorGroup.ServerObjectIsNull())
                {
                    AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope, parser);
                }

                //sorting groups with respect to possible dependency through Owner property. Groups that are owners of other groups must be processed prior owned groups.
                for (int i = 0; i < siteSecurity.SiteGroups.Count; i++)
                {
                    var    currentGroup      = siteSecurity.SiteGroups[i];
                    string currentGroupOwner = currentGroup.Owner;
                    string currentGroupTitle = parser.ParseString(currentGroup.Title);

                    if (currentGroupOwner != "SHAREPOINT\\system" && currentGroupOwner != currentGroupTitle && !(currentGroupOwner.StartsWith("{{associated") && currentGroupOwner.EndsWith("group}}")))
                    {
                        for (int j = i + 1; j < siteSecurity.SiteGroups.Count; j++)
                        {
                            if (siteSecurity.SiteGroups[j].Title == currentGroupOwner)
                            {
                                siteSecurity.SiteGroups.Insert(i, siteSecurity.SiteGroups[j]);
                                siteSecurity.SiteGroups.RemoveAt(j);
                                i--;
                                break;
                            }
                        }
                    }
                }

                foreach (var siteGroup in siteSecurity.SiteGroups)
                {
                    Group group;
                    var   allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName));
                    web.Context.ExecuteQueryRetry();

                    string parsedGroupTitle       = parser.ParseString(siteGroup.Title);
                    string parsedGroupOwner       = parser.ParseString(siteGroup.Owner);
                    string parsedGroupDescription = parser.ParseString(siteGroup.Description);
                    bool   descriptionHasHtml     = HttpUtility.HtmlEncode(parsedGroupDescription) != parsedGroupDescription;

                    if (!web.GroupExists(parsedGroupTitle))
                    {
                        scope.LogDebug("Creating group {0}", parsedGroupTitle);
                        group = web.AddGroup(
                            parsedGroupTitle,
                            parsedGroupDescription,
                            parsedGroupTitle == parsedGroupOwner);
                        group.AllowMembersEditMembership     = siteGroup.AllowMembersEditMembership;
                        group.AllowRequestToJoinLeave        = siteGroup.AllowRequestToJoinLeave;
                        group.AutoAcceptRequestToJoinLeave   = siteGroup.AutoAcceptRequestToJoinLeave;
                        group.OnlyAllowMembersViewMembership = siteGroup.OnlyAllowMembersViewMembership;
                        group.RequestToJoinLeaveEmailSetting = siteGroup.RequestToJoinLeaveEmailSetting;

                        if (parsedGroupTitle != parsedGroupOwner)
                        {
                            Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                            if (ownerPrincipal == null)
                            {
                                ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                            }
                            group.Owner = ownerPrincipal;
                        }
                        group.Update();
                        web.Context.Load(group, g => g.Id, g => g.Title);
                        web.Context.ExecuteQueryRetry();
                        parser.AddToken(new GroupIdToken(web, group.Title, group.Id));

                        if (descriptionHasHtml)
                        {
                            var groupItem = web.SiteUserInfoList.GetItemById(group.Id);
                            groupItem["Notes"] = parsedGroupDescription;
                            groupItem.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                    else
                    {
                        group = web.SiteGroups.GetByName(parsedGroupTitle);
                        web.Context.Load(group,
                                         g => g.Id,
                                         g => g.Title,
                                         g => g.Description,
                                         g => g.AllowMembersEditMembership,
                                         g => g.AllowRequestToJoinLeave,
                                         g => g.AutoAcceptRequestToJoinLeave,
                                         g => g.OnlyAllowMembersViewMembership,
                                         g => g.RequestToJoinLeaveEmailSetting,
                                         g => g.Owner.LoginName);
                        web.Context.ExecuteQueryRetry();

                        var isDirty = false;
                        if (descriptionHasHtml)
                        {
                            var groupItem = web.SiteUserInfoList.GetItemById(group.Id);
                            web.Context.Load(groupItem, g => g["Notes"]);
                            web.Context.ExecuteQueryRetry();
                            var description = groupItem["Notes"]?.ToString();

                            if (description != parsedGroupDescription)
                            {
                                groupItem["Notes"] = parsedGroupDescription;
                                groupItem.Update();
                                isDirty = true;
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(group.Description) && group.Description != parsedGroupDescription)
                            {
                                group.Description = parsedGroupDescription;
                                isDirty           = true;
                            }
                        }
                        if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership)
                        {
                            group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership;
                            isDirty = true;
                        }
                        if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave)
                        {
                            group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave)
                        {
                            group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave;
                            isDirty = true;
                        }
                        if (group.OnlyAllowMembersViewMembership != siteGroup.OnlyAllowMembersViewMembership)
                        {
                            group.OnlyAllowMembersViewMembership = siteGroup.OnlyAllowMembersViewMembership;
                            isDirty = true;
                        }
                        if (!String.IsNullOrEmpty(group.RequestToJoinLeaveEmailSetting) && group.RequestToJoinLeaveEmailSetting != siteGroup.RequestToJoinLeaveEmailSetting)
                        {
                            group.RequestToJoinLeaveEmailSetting = siteGroup.RequestToJoinLeaveEmailSetting;
                            isDirty = true;
                        }
                        if (group.Owner.LoginName != parsedGroupOwner)
                        {
                            if (parsedGroupTitle != parsedGroupOwner)
                            {
                                Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner);
                                if (ownerPrincipal == null)
                                {
                                    ownerPrincipal = web.EnsureUser(parsedGroupOwner);
                                }
                                group.Owner = ownerPrincipal;
                            }
                            else
                            {
                                group.Owner = group;
                            }
                            isDirty = true;
                        }
                        if (isDirty)
                        {
                            scope.LogDebug("Updating existing group {0}", group.Title);
                            group.Update();
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                    if (group != null && siteGroup.Members.Any())
                    {
                        AddUserToGroup(web, group, siteGroup.Members, scope, parser);
                    }
                }

                foreach (var admin in siteSecurity.AdditionalAdministrators)
                {
                    var parsedAdminName = parser.ParseString(admin.Name);
                    try
                    {
                        var user = web.EnsureUser(parsedAdminName);
                        user.IsSiteAdmin = true;
                        user.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        scope.LogWarning(ex, "Failed to add AdditionalAdministrator {0}", parsedAdminName);
                    }
                }

                // With the change from october, manage permission levels on subsites as well
                if (siteSecurity.SiteSecurityPermissions != null)
                {
                    var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any())
                    {
                        foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions)
                        {
                            var roleDefinitions    = existingRoleDefinitions as RoleDefinition[] ?? existingRoleDefinitions.ToArray();
                            var siteRoleDefinition = roleDefinitions.FirstOrDefault(erd => erd.Name == parser.ParseString(templateRoleDefinition.Name));
                            if (siteRoleDefinition == null)
                            {
                                scope.LogDebug("Creating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                var roleDefinitionCI = new RoleDefinitionCreationInformation();
                                roleDefinitionCI.Name        = parser.ParseString(templateRoleDefinition.Name);
                                roleDefinitionCI.Description = parser.ParseString(templateRoleDefinition.Description);
                                BasePermissions basePermissions = new BasePermissions();

                                foreach (var permission in templateRoleDefinition.Permissions)
                                {
                                    basePermissions.Set(permission);
                                }

                                roleDefinitionCI.BasePermissions = basePermissions;

                                var newRoleDefinition = web.RoleDefinitions.Add(roleDefinitionCI);
                                web.Context.Load(newRoleDefinition, nrd => nrd.Name, nrd => nrd.Id);
                                web.Context.ExecuteQueryRetry();
                                parser.AddToken(new RoleDefinitionIdToken(web, newRoleDefinition.Name, newRoleDefinition.Id));
                            }
                            else
                            {
                                var isDirty = false;
                                if (siteRoleDefinition.Description != parser.ParseString(templateRoleDefinition.Description))
                                {
                                    siteRoleDefinition.Description = parser.ParseString(templateRoleDefinition.Description);
                                    isDirty = true;
                                }
                                var templateBasePermissions = new BasePermissions();
                                templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p));
                                if (siteRoleDefinition.BasePermissions != templateBasePermissions)
                                {
                                    isDirty = true;
                                    foreach (var permission in templateRoleDefinition.Permissions)
                                    {
                                        siteRoleDefinition.BasePermissions.Set(permission);
                                    }
                                }
                                if (isDirty)
                                {
                                    scope.LogDebug("Updating role definition {0}", parser.ParseString(templateRoleDefinition.Name));
                                    siteRoleDefinition.Update();
                                    web.Context.ExecuteQueryRetry();
                                }
                            }
                        }
                    }

                    var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions);
                    var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments);
                    var groups             = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName));
                    web.Context.ExecuteQueryRetry();

                    if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any())
                    {
                        foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments)
                        {
                            if (!roleAssignment.Remove)
                            {
                                var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == parser.ParseString(roleAssignment.RoleDefinition));
                                if (roleDefinition != null)
                                {
                                    Principal principal = GetPrincipal(web, parser, scope, groups, roleAssignment);

                                    if (principal != null)
                                    {
                                        var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context);
                                        roleDefinitionBindingCollection.Add(roleDefinition);
                                        web.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                                        web.Context.ExecuteQueryRetry();
                                    }
                                }
                                else
                                {
                                    scope.LogWarning("Role assignment {0} not found in web", roleAssignment.RoleDefinition);
                                }
                            }
                            else
                            {
                                var principal = GetPrincipal(web, parser, scope, groups, roleAssignment);
                                var assignmentsForPrincipal = webRoleAssignments.Where(t => t.PrincipalId == principal.Id);
                                foreach (var assignmentForPrincipal in assignmentsForPrincipal)
                                {
                                    var binding = assignmentForPrincipal.EnsureProperty(r => r.RoleDefinitionBindings).FirstOrDefault(b => b.Name == roleAssignment.RoleDefinition);
                                    if (binding != null)
                                    {
                                        assignmentForPrincipal.DeleteObject();
                                        web.Context.ExecuteQueryRetry();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(parser);
        }
        protected override void ExecuteCmdlet()
        {
            var permissions = new BasePermissions();

            if (Rights != null)
            {
                foreach (var kind in Rights)
                {
                    permissions.Set(kind);
                }
            }
            CustomActionEntity ca = null;

            if (ParameterSetName == ParameterSet_DEFAULT)
            {
                ca = new CustomActionEntity
                {
                    Name               = Name,
                    ImageUrl           = ImageUrl,
                    CommandUIExtension = CommandUIExtension,
                    RegistrationId     = RegistrationId,
                    RegistrationType   = RegistrationType,
                    Description        = Description,
                    Location           = Location,
                    Group              = Group,
                    Sequence           = Sequence,
                    Title              = Title,
                    Url    = Url,
                    Rights = permissions,
                };
            }
            else
            {
#if !SP2013 && !SP2016
                ca = new CustomActionEntity()
                {
                    Name     = Name,
                    Title    = Title,
                    Location = Location,
                    Sequence = Sequence,
                    ClientSideComponentId         = ClientSideComponentId.Id,
                    ClientSideComponentProperties = ClientSideComponentProperties,
#if !ONPREMISES
                    ClientSideHostProperties = ClientSideHostProperties
#endif
                };

                if (ParameterSpecified(nameof(RegistrationId)))
                {
                    ca.RegistrationId = RegistrationId;
                }

                if (ParameterSpecified(nameof(RegistrationType)))
                {
                    ca.RegistrationType = RegistrationType;
                }
#endif
            }

            switch (Scope)
            {
            case CustomActionScope.Web:
                SelectedWeb.AddCustomAction(ca);
                break;

            case CustomActionScope.Site:
                ClientContext.Site.AddCustomAction(ca);
                break;

            case CustomActionScope.All:
                WriteWarning("CustomActionScope 'All' is not supported for adding CustomActions");
                break;
            }
        }
Beispiel #25
0
        /// <summary>
        /// Iterates the row from the CSV file
        /// </summary>
        /// <param name="entries">The collection values per row.</param>
        /// <param name="logger">The logger.</param>
        public override void IterateCollection(Collection<string> entries, LogHelper logger)
        {
            Stopwatch IterationSW = new Stopwatch();
            IterationSW.Start();

            logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "Establishing context object to: '{0}'", entries[this.SiteIndex]));

            try
            {
                // Use context of current iteration URL for current user item
                using (ClientContext context = new ClientContext(entries[this.SiteIndex]))
                {
                    using (SecureString password = new SecureString())
                    {
                        foreach (char c in this.Password.ToCharArray())
                        {
                            password.AppendChar(c);
                        }

                        context.Credentials = new SharePointOnlineCredentials(this.UserName, password);

                        // Get file to upload from directory
                        FileInfo theFileToUpload = new FileInfo(Path.Combine(this.DirectoryLocation + "\\", entries[this.FileIndex] + ".xlsx"));

                        logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "Attempting to {0} file {1}", this.DocumentAction, theFileToUpload));

                        // Ensure account has permissions to access
                        BasePermissions perm = new BasePermissions();
                        perm.Set(PermissionKind.AddListItems);

                        ConditionalScope scope = new ConditionalScope(context, () => context.Web.DoesUserHavePermissions(perm).Value);

                        using(scope.StartScope())
                        {
                            Stopwatch tempSW = new Stopwatch();
                            tempSW.Start();

                            int success = 0;

                            while(tempSW.Elapsed.TotalSeconds < 20)
                            {
                                var digest = context.GetFormDigestDirect();

                                string cookie = ((SharePointOnlineCredentials)context.Credentials).GetAuthenticationCookie(new Uri(entries[this.SiteIndex])).TrimStart("SPOIDCRL=".ToCharArray());

                                using (Stream s = theFileToUpload.OpenRead())
                                {
                                    // Define REST string request to upload document to context
                                    string theTargetUri = string.Format(CultureInfo.CurrentCulture, "{0}/_api/web/lists/getByTitle('Documents')/RootFolder/Files/add(url='{1}',overwrite='true')?", entries[this.SiteIndex], this.FileUploadName);

                                    // Define REST HTTP request obkect
                                    HttpWebRequest SPORequest = (HttpWebRequest)HttpWebRequest.Create(theTargetUri);

                                    // Define HTTP request action method
                                    if (this.DocumentAction == "Upload")
                                    {
                                        SPORequest.Method = "POST";
                                    }
                                    else if (this.DocumentAction == "Delete")
                                    {
                                        SPORequest.Method = "DELETE";
                                    }
                                    else
                                    {
                                        logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "There was a problem with the HTTP request in DocumentAction attribute of XML file"));
                                        throw new Exception("The HTTP Request operation is not supported, please check the value of DocumentAction in the XML file");
                                    }

                                    // Build out additional HTTP request details
                                    SPORequest.Accept = "application/json;odata=verbose";
                                    SPORequest.Headers.Add("X-RequestDigest", digest.DigestValue);
                                    SPORequest.ContentLength = s.Length;
                                    SPORequest.ContentType = "application/octet-stream";

                                    // Handle authentication to context through cookie
                                    SPORequest.CookieContainer = new CookieContainer();
                                    SPORequest.CookieContainer.Add(new Cookie("SPOIDCRL", cookie, string.Empty, new Uri(entries[this.SiteIndex]).Authority));

                                    // Perform file upload/deletion
                                    using (Stream requestStream = SPORequest.GetRequestStream())
                                    {
                                        s.CopyTo(requestStream);
                                    }

                                    // Get HTTP response to determine success of operation
                                    HttpWebResponse SPOResponse = (HttpWebResponse)SPORequest.GetResponse();

                                    logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "Successfully '{0}' file {1}", this.DocumentAction, theFileToUpload));
                                    logger.LogOutcome(entries[this.SiteIndex], "SUCCCESS");

                                    success = 1;

                                    // Dispose of the HTTP response
                                    SPOResponse.Close();

                                    break;
                                }
                                                       
                            }

                            tempSW.Stop();

                            if (success != 1)
                            {
                                throw new Exception("The HTTP Request operation exceeded the timeout of 20 seconds");
                            }

                        }
                    }
                }

            }
            catch(Exception ex)
            {
                logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "There was an issue performing '{0}' on to the URL '{1}' with exception: {2}", this.DocumentAction, entries[this.SiteIndex], ex.Message));
                logger.LogOutcome(entries[this.SiteIndex], "FAILURE");
            }
            finally
            {
                IterationSW.Stop();
                logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, "Completed processing URL:'{0}' in {1} seconds", entries[this.SiteIndex], IterationSW.ElapsedMilliseconds/1000));
            }
        }
Beispiel #26
0
        public static void CrearNivel(ClientContext c)
        {
            //try
            //{
            c.Load(
                c.Web,
                website => website.Title,
                website => website.HasUniqueRoleAssignments);

            c.ExecuteQuery();
            Console.WriteLine("Creando nivel de permiso");
            if (!c.Web.HasUniqueRoleAssignments)
            {
                c.Web.BreakRoleInheritance(false, true);
                c.ExecuteQuery();
            }
            BasePermissions permisoBuffet = new BasePermissions();

            permisoBuffet.Set(PermissionKind.EmptyMask);
            permisoBuffet.Set(PermissionKind.AddListItems);
            permisoBuffet.Set(PermissionKind.EditListItems);
            permisoBuffet.Set(PermissionKind.ViewListItems);
            permisoBuffet.Set(PermissionKind.ViewVersions);
            permisoBuffet.Set(PermissionKind.DeleteVersions);
            permisoBuffet.Set(PermissionKind.CreateAlerts);
            permisoBuffet.Set(PermissionKind.ViewFormPages);
            permisoBuffet.Set(PermissionKind.OpenItems);
            permisoBuffet.Set(PermissionKind.BrowseDirectories);
            permisoBuffet.Set(PermissionKind.ViewPages);
            permisoBuffet.Set(PermissionKind.UseRemoteAPIs);
            permisoBuffet.Set(PermissionKind.BrowseUserInfo);
            permisoBuffet.Set(PermissionKind.UseClientIntegration);
            permisoBuffet.Set(PermissionKind.Open);
            permisoBuffet.Set(PermissionKind.EditMyUserInfo);
            permisoBuffet.Set(PermissionKind.ManagePersonalViews);
            permisoBuffet.Set(PermissionKind.AddDelPrivateWebParts);
            permisoBuffet.Set(PermissionKind.UpdatePersonalWebParts);
            permisoBuffet.Set(PermissionKind.CreateSSCSite);
            permisoBuffet.Set(PermissionKind.CreateAlerts);

            RoleDefinitionCreationInformation creationInfo = new RoleDefinitionCreationInformation();

            creationInfo.BasePermissions = permisoBuffet;
            creationInfo.Description     = "Colaborar sin eliminar";
            creationInfo.Name            = "Colaborar sin eliminar";
            creationInfo.Order           = 0;
            RoleDefinition rd = c.Web.RoleDefinitions.Add(creationInfo);

            c.ExecuteQuery();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("--- NIVEL DE PERMISO CREADO --");
            Console.ResetColor();
            //}
            //catch (Exception ex)
            //{
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("--- ERROR AL CREAR EL NIVEL DE PERMISO --");
            Console.ResetColor();
            //}
            c.ExecuteQuery();
        }
Beispiel #27
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());

            var web = webModelHost.HostSite.RootWeb;
            var securityRoleModel = model.WithAssertAndCast <SecurityRoleDefinition>("model", value => value.RequireNotNull());

            var context = web.Context;

            var roleDefinitions = web.RoleDefinitions;

            context.Load(roleDefinitions);
            context.ExecuteQueryWithTrace();

            var currentRoleDefinition = FindRoleDefinition(roleDefinitions, securityRoleModel.Name);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentRoleDefinition,
                ObjectType       = typeof(RoleDefinition),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            var basePermissions = new BasePermissions();

            foreach (var permissionString in securityRoleModel.BasePermissions)
            {
                basePermissions.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), permissionString));
            }

            if (currentRoleDefinition == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security role");

                currentRoleDefinition = roleDefinitions.Add(new RoleDefinitionCreationInformation
                {
                    Name            = securityRoleModel.Name,
                    BasePermissions = basePermissions,
                    Description     = securityRoleModel.Description ?? string.Empty
                });
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security role");
            }

            // SPBug,
            // something wrong with setting up BasePermissions.Set() method up
            // so, a new object has to be assigned every time
            currentRoleDefinition.BasePermissions = basePermissions;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentRoleDefinition,
                ObjectType       = typeof(RoleDefinition),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            currentRoleDefinition.Update();

            context.ExecuteQueryWithTrace();
        }
Beispiel #28
0
        /// <summary>
        /// Creates a new permission level in specified web context
        /// </summary>
        /// <param name="context">Client Context</param>
        /// <param name="permissionLevelName">Name of permission level to be created</param>
        /// <param name="description">Description of permission level to be created</param>
        /// <returns>Boolean value indicating success of permission level creation</returns>
        private static bool CreateNewPermissionLevel(ClientContext context, string permissionLevelName, string description)
        {
            string errorFilePath = Directory.GetParent(Directory.GetCurrentDirectory()) + "/" + "ErrorLog.txt";
            bool isPermissionLevelCreated = false;
            try
            {
                RemovePermissionLevelIfExists(context, permissionLevelName);

                BasePermissions permissions = new BasePermissions();

                // List Permissions
                permissions.Set(PermissionKind.AddListItems);
                permissions.Set(PermissionKind.EditListItems);
                permissions.Set(PermissionKind.DeleteListItems);
                permissions.Set(PermissionKind.ViewListItems);
                permissions.Set(PermissionKind.OpenItems);
                permissions.Set(PermissionKind.ViewVersions);
                permissions.Set(PermissionKind.DeleteVersions);
                permissions.Set(PermissionKind.CreateAlerts);

                // Site Permissions
                permissions.Set(PermissionKind.BrowseDirectories);
                permissions.Set(PermissionKind.CreateSSCSite);
                permissions.Set(PermissionKind.BrowseDirectories);
                permissions.Set(PermissionKind.ViewPages);
                permissions.Set(PermissionKind.BrowseUserInfo);
                permissions.Set(PermissionKind.UseRemoteAPIs);
                permissions.Set(PermissionKind.UseClientIntegration);
                permissions.Set(PermissionKind.Open);
                permissions.Set(PermissionKind.EditMyUserInfo);

                // Personal Permissions
                permissions.Set(PermissionKind.ManagePersonalViews);
                permissions.Set(PermissionKind.AddDelPrivateWebParts);
                permissions.Set(PermissionKind.UpdatePersonalWebParts);

                // Extra Permissions
                permissions.Set(PermissionKind.ManagePermissions);
                permissions.Set(PermissionKind.EnumeratePermissions);

                RoleDefinitionCreationInformation roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
                roleDefinitionCreationInfo.BasePermissions = permissions;
                roleDefinitionCreationInfo.Name = permissionLevelName;
                roleDefinitionCreationInfo.Description = description;
                context.Web.RoleDefinitions.Add(roleDefinitionCreationInfo);
                context.Web.Update();
                context.ExecuteQuery();
                isPermissionLevelCreated = true;
                Console.WriteLine("New permission level created [{0}]", permissionLevelName);
            }
            catch (Exception exception)
            {
                isPermissionLevelCreated = false;
                ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                RemovePermissionLevelIfExists(context, permissionLevelName);
            }
            return isPermissionLevelCreated;
        }
        private void MapCustomAction(UserCustomAction existringAction, UserCustomActionDefinition customAction)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Updating user custom action properties.");

            existringAction.Sequence = customAction.Sequence;
            existringAction.Description = customAction.Description;
            existringAction.Group = customAction.Group;
            existringAction.Location = customAction.Location;
            existringAction.Name = customAction.Name;
            existringAction.ScriptBlock = customAction.ScriptBlock;
            existringAction.ScriptSrc = customAction.ScriptSrc;
            existringAction.Title = customAction.Title;
            existringAction.Url = customAction.Url;

            if (!string.IsNullOrEmpty(customAction.CommandUIExtension))
                existringAction.CommandUIExtension = customAction.CommandUIExtension;

            if (!string.IsNullOrEmpty(customAction.RegistrationId))
                existringAction.RegistrationId = customAction.RegistrationId;

            if (!string.IsNullOrEmpty(customAction.RegistrationType))
            {
                // skipping setup for List script 
                // System.NotSupportedException: Setting this property is not supported.  A value of List has already been set and cannot be changed.
                if (customAction.RegistrationType != BuiltInRegistrationTypes.List)
                {
                    existringAction.RegistrationType =
                        (UserCustomActionRegistrationType)
                            Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType, true);
                }
            }

            var permissions = new BasePermissions();

            if (customAction.Rights != null && customAction.Rights.Count > 0)
            {
                foreach (var permissionString in customAction.Rights)
                    permissions.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), permissionString));
            }

            existringAction.Rights = permissions;
        }
Beispiel #30
0
        private void AddSiteInformationJsLink(Microsoft.SharePoint.Client.ClientContext clientContext)
        {
            Web web = clientContext.Web;
            clientContext.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId);
            clientContext.ExecuteQuery();

            string issuerId = ConfigurationManager.AppSettings.Get("ClientId");

            DeleteExistingActions(clientContext, web);

            UserCustomAction userCustomAction = web.UserCustomActions.Add();
            userCustomAction.Location = "Microsoft.SharePoint.StandardMenu";
            userCustomAction.Group = "SiteActions";
            BasePermissions perms = new BasePermissions();
            perms.Set(PermissionKind.ManageWeb);
            userCustomAction.Rights = perms;
            userCustomAction.Sequence = 100;
            userCustomAction.Title = "Site Information";
            userCustomAction.Name = "SiteInformationApp";

            string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(clientContext.Url));

            string host = "";
            foreach (Uri u in OperationContext.Current.Host.BaseAddresses)
            {
                if (u.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase))
                {
                    host = u.Authority;
                }
            }

            var appPageUrl = string.Format("https://{0}/Pages/Default.aspx?{{StandardTokens}}", host);
            string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}', {{width:600,height:400,title:'Site Information'}});";
            url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, appPageUrl);

            userCustomAction.Url = url;
            userCustomAction.Update();
            clientContext.ExecuteQuery();
        }
Beispiel #31
0
        /// <summary>
        /// Adds a custom Action to a Site Collection
        /// </summary>
        /// <param name="ctx">The Authenticaed client context.</param>
        /// <param name="hostUrl">The Provider hosted URL for the Application</param>
        static void AddCustomAction(ClientContext ctx, string hostUrl)
        {
            var _web = ctx.Web;
            ctx.Load(_web);
            ctx.ExecuteQuery();

            //we only want the action to show up if you have manage web permissions
            BasePermissions _manageWebPermission = new BasePermissions();
            _manageWebPermission.Set(PermissionKind.ManageWeb);

            CustomActionEntity _entity = new CustomActionEntity()
            {
                Group = "SiteTasks",
                Location = "Microsoft.SharePoint.SiteSettings",
                Title = "Site Classification",
                Sequence = 1000,
                Url = string.Format(hostUrl, ctx.Url),
                Rights = _manageWebPermission,
            };

            CustomActionEntity _siteActionSC = new CustomActionEntity()
            {
                Group = "SiteActions",
                Location = "Microsoft.SharePoint.StandardMenu",
                Title = "Site Classification",
                Sequence = 1000,
                Url = string.Format(hostUrl, ctx.Url),
                Rights = _manageWebPermission
            };
            _web.AddCustomAction(_entity);
            _web.AddCustomAction(_siteActionSC);
        }
        protected override void DeployModelInternal(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast<SiteModelHost>("modelHost", value => value.RequireNotNull());

            var web = webModelHost.HostSite.RootWeb;
            var securityRoleModel = model.WithAssertAndCast<SecurityRoleDefinition>("model", value => value.RequireNotNull());

            var context = web.Context;

            var roleDefinitions = web.RoleDefinitions;

            context.Load(roleDefinitions);
            context.ExecuteQuery();

            var currentRoleDefinition = FindRoleDefinition(roleDefinitions, securityRoleModel.Name);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentRoleDefinition,
                ObjectType = typeof(RoleDefinition),
                ObjectDefinition = model,
                ModelHost = modelHost
            });

            var basePermissions = new BasePermissions();

            foreach (var permissionString in securityRoleModel.BasePermissions)
                basePermissions.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), permissionString));

            if (currentRoleDefinition == null)
            {
                currentRoleDefinition = roleDefinitions.Add(new RoleDefinitionCreationInformation
                {
                    Name = securityRoleModel.Name,
                    BasePermissions = basePermissions,
                    Description = securityRoleModel.Description ?? string.Empty
                });
            }

            // SPBug,
            // something wrong with setting up BasePermissions.Set() method up
            // so, a new object has to be assigned every time
            currentRoleDefinition.BasePermissions = basePermissions;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = currentRoleDefinition,
                ObjectType = typeof(RoleDefinition),
                ObjectDefinition = model,
                ModelHost = modelHost
            });

            currentRoleDefinition.Update();

            context.ExecuteQuery();
        }
        public static BasePermissions ToBasePermissionsV201612(this string basePermissionString)
        {
            BasePermissions bp = new BasePermissions();

            // Is it an int value (for backwards compability)?
            int permissionInt;
            if (int.TryParse(basePermissionString, out permissionInt))
            {
                bp.Set((PermissionKind)permissionInt);
            }
            else if (!string.IsNullOrEmpty(basePermissionString))
            {
                foreach (var pk in basePermissionString.Split(','))
                {
                    PermissionKind permissionKind;
                    if (Enum.TryParse<PermissionKind>(pk, out permissionKind))
                    {
                        bp.Set(permissionKind);
                    }
                }
            }
            return bp;
        }
 private void BuildRoleDefinitionAdd(string name, RoleType roleTypeKind, PermissionKind[] permissions, string description, bool hidden, int order, out RoleDefinition newRoleDefinition, out BasePermissions basePermissions)
 {
     newRoleDefinition              = CreateNewAndAdd() as RoleDefinition;
     newRoleDefinition.Name         = name;
     newRoleDefinition.Description  = description;
     newRoleDefinition.Hidden       = hidden;
     newRoleDefinition.Order        = order;
     newRoleDefinition.RoleTypeKind = roleTypeKind;
     basePermissions = new BasePermissions();
     basePermissions.Set(PermissionKind.EmptyMask);
     foreach (var permission in permissions)
     {
         basePermissions.Set(permission);
     }
 }