public void CreateCustomPermissionLevel(string permissionName)
        {
            try
            {
                context = AuthenticationManager.CreateClientContext(rootUrl, user, password);
                var web = context.Web;
                context.Load(web, w => w.Title, w => w.Description);


                // Set up permissions.
                BasePermissions permissions = new BasePermissions();
                permissions.Set(PermissionKind.ManageLists);
                permissions.Set(PermissionKind.CreateAlerts);
                permissions.Set(PermissionKind.ViewListItems);

                // create
                RoleDefinitionCreationInformation roleDefinitionCreationInformation = new RoleDefinitionCreationInformation();
                roleDefinitionCreationInformation.BasePermissions = permissions;
                roleDefinitionCreationInformation.Name            = permissionName;
                roleDefinitionCreationInformation.Description     = "Custom Permission Level";
                context.Web.RoleDefinitions.Add(roleDefinitionCreationInformation);

                //context.Load(roleDefinitionCreationInformation);
                context.ExecuteQuery();
            }
            catch (Exception)
            {
            }
        }
示例#2
0
        public async Task <IRoleDefinition> AddAsync(string name, RoleType roleTypeKind, PermissionKind[] permissions, string description = null, bool hidden = false, int order = 0)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            var newRoleDefinition = CreateNewAndAdd() as RoleDefinition;

            newRoleDefinition.Name         = name;
            newRoleDefinition.Description  = description;
            newRoleDefinition.Hidden       = hidden;
            newRoleDefinition.Order        = order;
            newRoleDefinition.RoleTypeKind = roleTypeKind;
            var basePermissions = new BasePermissions();

            basePermissions.Set(PermissionKind.EmptyMask);
            foreach (var permission in permissions)
            {
                basePermissions.Set(permission);
            }
            //newRoleDefinition.BasePermissions = basePermissions;
            return(await newRoleDefinition.AddAsync(new System.Collections.Generic.Dictionary <string, object> {
                { "permissions", basePermissions }
            }).ConfigureAwait(false) as RoleDefinition);
        }
        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;
        }
示例#4
0
        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;
        }
 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);
     }
 }
示例#6
0
        protected override void ExecuteCmdlet()
        {
            var permissions = new BasePermissions();

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

            if (ParameterSetName == "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 !ONPREMISES
                ca = new CustomActionEntity()
                {
                    Name     = Name,
                    Title    = Title,
                    Location = Location,
                    ClientSideComponentId         = ClientSideComponentId.Id,
                    ClientSideComponentProperties = ClientSideComponentProperties
                };
#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;
            }
        }
示例#7
0
文件: Program.cs 项目: yangecnu/PnP
        /// <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);
        }
示例#8
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();
                }
            }
        }
        /// <summary>
        /// Validates if the current user is site collection administrator
        /// This will not work if user is not site collection admin
        /// and has been greanted Full Control as part of web application policy
        /// </summary>
        /// <param name="url">Link to site collection</param>
        /// <returns>True if the user is a site collection administrator</returns>
        public static bool IsUserAdmin(string url, ref Exception exception)
        {
            bool isValid = true;

            try
            {
                using (ClientContext context = new ClientContext(url))
                {
                    context.Load(context.Site);
                    context.Load(context.Site.RootWeb);

                    BasePermissions bpFullMask = new BasePermissions();
                    bpFullMask.Set(PermissionKind.FullMask);
                    ClientResult <bool> isAdmin = context.Site.RootWeb.DoesUserHavePermissions(bpFullMask);

                    context.ExecuteQuery();

                    if (isAdmin.Value == false)
                    {
                        isValid = false;
                    }
                }
            }
            catch (Exception ex)
            {
                isValid   = false;
                exception = ex;
            }

            return(isValid);
        }
示例#10
0
        public static void AddCustomAction(List list, string actionUrl)
        {
            ClientContext context = (ClientContext)list.Context;

            context.Load(list.UserCustomActions);
            context.ExecuteQuery();

            foreach (UserCustomAction uca in list.UserCustomActions)
            {
                uca.DeleteObject();
            }

            context.ExecuteQuery();

            UserCustomAction action = list.UserCustomActions.Add();

            action.Location = "EditControlBlock";
            action.Sequence = 10001;
            action.Title    = "Publish this Lessons Learned";
            var permissions = new BasePermissions();

            permissions.Set(PermissionKind.EditListItems);
            action.Rights = permissions;
            action.Url    = actionUrl;

            action.Update();

            context.ExecuteQuery();
        }
示例#11
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);
            }
        }
示例#12
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();
                }
            }
        }
示例#13
0
 protected bool DoesUserHavePermission()
 {
     BasePermissions perms = new BasePermissions();
     perms.Set(PermissionKind.ManageWeb);
     ClientResult<bool> _permResult = _ctx.Web.DoesUserHavePermissions(perms);
     _ctx.ExecuteQuery();
     return _permResult.Value;
 }
示例#14
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);
 }
示例#15
0
        protected bool DoesUserHavePermission()
        {
            BasePermissions perms = new BasePermissions();

            perms.Set(PermissionKind.ManageSubwebs);
            ClientResult <bool> _permResult = _ctx.Web.DoesUserHavePermissions(perms);

            _ctx.ExecuteQuery();
            return(_permResult.Value);
        }
示例#16
0
        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 !ONPREMISES
            if (ClientSideComponentId.Id != Guid.Empty)
            {
                ca.ClientSideComponentId = ClientSideComponentId.Id;
            }
            if (!string.IsNullOrEmpty(ClientSideComponentProperties))
            {
                ca.ClientSideComponentProperties = ClientSideComponentProperties;
            }
#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;
            }
        }
示例#17
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;
     }
 }
示例#18
0
        protected override void ExecuteCmdlet()
        {
            // Validate user inputs
            RoleDefinition roleDefinition = null;

            try
            {
                roleDefinition = ClientContext.Site.RootWeb.RoleDefinitions.GetByName(RoleName);
                ClientContext.Load(roleDefinition);
                ClientContext.ExecuteQuery();
            }
            catch { }
            if (roleDefinition.ServerObjectIsNull == null)
            {
                var spRoleDef  = new RoleDefinitionCreationInformation();
                var spBasePerm = new BasePermissions();

                if (ParameterSpecified(nameof(Clone)))
                {
                    var clonePerm = Clone.GetRoleDefinition(ClientContext.Site);
                    spBasePerm = clonePerm.BasePermissions;
                }

                // Include and Exclude Flags
                if (ParameterSpecified(nameof(Include)))
                {
                    foreach (var flag in Include)
                    {
                        spBasePerm.Set(flag);
                    }
                }
                if (ParameterSpecified(nameof(Exclude)))
                {
                    foreach (var flag in Exclude)
                    {
                        spBasePerm.Clear(flag);
                    }
                }

                // Create Role Definition
                spRoleDef.Name            = RoleName;
                spRoleDef.Description     = Description;
                spRoleDef.BasePermissions = spBasePerm;
                roleDefinition            = ClientContext.Site.RootWeb.RoleDefinitions.Add(spRoleDef);
                ClientContext.Load(roleDefinition);
                ClientContext.ExecuteQueryRetry();
                WriteObject(roleDefinition);
            }
            else
            {
                WriteWarning($"Unable to add Role Definition as there is an existing role definition with the same name. Will be skipped.");
            }
        }
示例#19
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);
            }
        }
示例#20
0
        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;


            ProcessLocalization(existringAction, customAction);
        }
示例#21
0
文件: Default.aspx.cs 项目: vsvr/PnP
        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();
            }
        }
示例#22
0
        public static void CreatePermissions(ClientContext clientContext)
        {
            Console.WriteLine("Adding custom permissions . . . ");

            // add read permissions to a permission collection
            BasePermissions permissions = new BasePermissions();

            permissions.Set(PermissionKind.ViewPages);
            permissions.Set(PermissionKind.ViewListItems);

            RoleDefinitionCreationInformation roleDefinitionCreationInfo;

            Microsoft.SharePoint.Client.RoleDefinition roleDefinition;

            // create custom permission levels - adjust post-provision

            roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
            roleDefinitionCreationInfo.BasePermissions = permissions;
            roleDefinitionCreationInfo.Name            = ContentContributorName;
            roleDefinitionCreationInfo.Description     = ContentContributorName;
            roleDefinition = clientContext.Web.RoleDefinitions.Add(roleDefinitionCreationInfo);

            roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
            roleDefinitionCreationInfo.BasePermissions = permissions;
            roleDefinitionCreationInfo.Name            = ContentManagerName;
            roleDefinitionCreationInfo.Description     = ContentManagerName;
            roleDefinition = clientContext.Web.RoleDefinitions.Add(roleDefinitionCreationInfo);

            roleDefinitionCreationInfo = new RoleDefinitionCreationInformation();
            roleDefinitionCreationInfo.BasePermissions = permissions;
            roleDefinitionCreationInfo.Name            = VisitorName;
            roleDefinitionCreationInfo.Description     = VisitorName;
            roleDefinition = clientContext.Web.RoleDefinitions.Add(roleDefinitionCreationInfo);


            clientContext.ExecuteQuery();
        }
        public object Resolve(object source, object destination, object sourceValue)
        {
            BasePermissions bp = new BasePermissions();
            var             basePermissionString = sourceValue as string;
            // 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);
        }
示例#24
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();
        }
示例#25
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);
        }
        public bool DoesUserHaveAccess(string user)
        {
            Web rootWeb = _ctx.Site.RootWeb;

            _ctx.Load(rootWeb);
            _ctx.ExecuteQuery();

            BasePermissions bp = new BasePermissions();

            bp.Set(PermissionKind.EmptyMask);
            var perm = rootWeb.GetUserEffectivePermissions(user);

            _ctx.ExecuteQuery();

            bool hasAccess = perm.Value.Has(PermissionKind.Open);

            return(hasAccess);
        }
示例#27
0
        public 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    = "Say Hello";

            string url = "javascript:alert('Hello SharePoint Custom Action!!!');";


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

            // Remove the entry from the 'Recents' node
            Microsoft.SharePoint.Client.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();
            }
        }
        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();
        }
        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;
            }
        }
示例#30
0
        public static void AddCustomActionToGearMenu(ClientContext ctx)
        {
            CustomActionEntity caSiteActions = new CustomActionEntity();

            // see https://msdn.microsoft.com/en-us/library/office/bb802730.aspx for locations and groups
            caSiteActions.Location = "Microsoft.SharePoint.StandardMenu";
            caSiteActions.Group    = "SiteActions";
            caSiteActions.Title    = "Press me";
            caSiteActions.Url      = "javascript:alert('yo')";
            // caSiteActions.ScriptBlock = "<script>alert('yo')</script>";
            caSiteActions.Sequence = 50;
            caSiteActions.Name     = "clickmeAction";
            BasePermissions bp = new BasePermissions();

            bp.Set(PermissionKind.ManageWeb); // user can admin site
            caSiteActions.Rights = bp;

            ctx.Web.AddCustomAction(caSiteActions);
        }
示例#31
0
        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;
            }
        }
示例#32
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();
            }
        }
示例#33
0
        public void DCMSetRolePermissions(DCTRoleDefinition role, BaseCollection <DCTPermission> permissions)
        {
            (role.ID <= 0 && string.IsNullOrEmpty(role.Name)).TrueThrow <ArgumentException>("角色中必须包含名称或ID.");


            if (permissions == null || permissions.Count == 0)
            {
                return;
            }

            using (DocLibContext context = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                RoleDefinition roleDef = null;

                if (!string.IsNullOrEmpty(role.Name))
                {
                    roleDef = context.Web.RoleDefinitions.GetByName(role.Name);
                }
                else
                {
                    roleDef = context.Web.RoleDefinitions.GetById(role.ID);
                }

                context.Load(roleDef);
                context.ExecuteQuery();

                BasePermissions basePerm = new BasePermissions();

                foreach (DCTPermission permission in permissions)
                {
                    basePerm.Set((PermissionKind)permission);
                }

                roleDef.BasePermissions = basePerm;
                roleDef.Update();
                context.ExecuteQuery();
            }
        }
示例#34
0
        /// <summary>
        /// Create a test User Custom Action in the site specified by the context configuration
        /// </summary>
        /// <param name="contextId">The number of the context. Default is 0</param>
        /// <param name="customActionName">The name of the custom action. Default is the name of the calling test</param>
        /// <param name="testName">The name of the current test. Default is the name of the calling test</param>
        /// <param name="contextConfig">The name of the context config. Default is the value of TestCommon.TestSite</param>
        /// <param name="addToSiteCollection">A flag indicating if the custom action is created on the Site Collection level, Default is false meaning the custom action will be created at the site level (Web)</param>
        /// <param name="sourceFilePath">The path of the source mock file in case of offline test</param>
        /// <returns>A tuple containing the name and id of the created custom action</returns>
        internal static async Task <Tuple <string, Guid> > CreateTestUserCustomActionAsync(int contextId = default,
                                                                                           [System.Runtime.CompilerServices.CallerMemberName] string customActionName = null,
                                                                                           [System.Runtime.CompilerServices.CallerMemberName] string testName         = null,
                                                                                           string contextConfig     = null,
                                                                                           bool addToSiteCollection = false,
                                                                                           [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null)
        {
            contextConfig ??= TestCommon.TestSite;

            customActionName = TestCommon.GetPnPSdkTestAssetName(customActionName);

            using (var context = await TestCommon.Instance.GetContextAsync(contextConfig, contextId, testName, sourceFilePath))
            {
                var basePermissions = new BasePermissions();
                foreach (var permissionKind in CustomActionPermissions)
                {
                    basePermissions.Set(permissionKind);
                }
                var ucaOptions = new AddUserCustomActionOptions()
                {
                    Location = "ClientSideExtension.ApplicationCustomizer",
                    ClientSideComponentId         = new Guid(TestApplicationCustomizerClientSideComponentId),
                    ClientSideComponentProperties = $@"{{""message"":""Added from Test {testName}""}}",
                    Sequence         = 100,
                    Name             = customActionName,
                    Title            = customActionName,
                    RegistrationType = UserCustomActionRegistrationType.None,
                    Description      = customActionName,
                    Rights           = basePermissions
                };

                IUserCustomAction uca = addToSiteCollection
                    ? await context.Site.UserCustomActions.AddAsync(ucaOptions)
                    : await context.Web.UserCustomActions.AddAsync(ucaOptions);

                return(new Tuple <string, Guid>(uca.Name, uca.Id));
            }
        }
        public virtual void Provision()
        {
            if (RoleDefinitions != null)
            {
                var existingRoleDefinitions = new List <string>();
                foreach (var roleDef in _web.RoleDefinitions)
                {
                    existingRoleDefinitions.Add(roleDef.Name);
                }

                foreach (var key in RoleDefinitions.Keys)
                {
                    if (!existingRoleDefinitions.Contains(key))
                    {
                        OnNotify(ProvisioningNotificationLevels.Verbose, "Creating role definition " + key);
                        var creator = new RoleDefinitionCreationInformation
                        {
                            Name        = RoleDefinitions[key].Name,
                            Description = RoleDefinitions[key].Description
                        };
                        var perms = new BasePermissions();
                        foreach (var p in RoleDefinitions[key].BasePermissions)
                        {
                            perms.Set(p);
                        }

                        creator.BasePermissions = perms;
                        creator.Order           = RoleDefinitions[key].Order;
                        _web.RoleDefinitions.Add(creator);
                    }
                    else
                    {
                        OnNotify(ProvisioningNotificationLevels.Verbose, "Role definition " + key + " exists. Skipping");
                    }
                }
                _ctx.ExecuteQueryRetry();
            }
        }
示例#36
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);
        }
示例#37
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);
            }
        }
        public async Task AddWebUserCustomActionApplicationCustomizerAsyncTest()
        {
            //TestCommon.Instance.Mocking = false;
            using (var context = await TestCommon.Instance.GetContextAsync(TestCommon.TestSite))
            {
                var basePermissions = new BasePermissions();
                basePermissions.Set(PermissionKind.AddAndCustomizePages);
                IUserCustomAction newUserCustomAction = await context.Web.UserCustomActions.AddAsync(new AddUserCustomActionOptions()
                {
                    Location = "ClientSideExtension.ApplicationCustomizer",
                    ClientSideComponentId         = new Guid(TestAssets.TestApplicationCustomizerClientSideComponentId),
                    ClientSideComponentProperties = @"{""message"":""Added from AddWebUserCustomActionApplicationCustomizerAsyncTest""}",
                    Sequence         = 100,
                    Name             = "UCA_CustomHeader",
                    Title            = "Custom Header",
                    RegistrationType = UserCustomActionRegistrationType.None,
                    Description      = "TESTING",
                    Rights           = basePermissions
                });

                // Test the created object
                Assert.IsNotNull(newUserCustomAction);
                Assert.AreNotEqual(default, newUserCustomAction.Id);
示例#39
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);
        }
示例#40
0
        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);
            }
        }
示例#41
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();
        }
        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;
        }
示例#43
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;
        }
示例#45
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);
        }
示例#46
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;
        }                
示例#47
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;
        }
示例#48
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));
            }
        }
        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 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 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;
        }
示例#52
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();
        }