private void SetPermissions(Talent talent, ListItem newItem, ClientContext ctx, RoleDefinition editPermissionLevel)
        {
            newItem.BreakRoleInheritance(false, true);
            RoleDefinitionBindingCollection collRoleDefinitionBinding =
                new RoleDefinitionBindingCollection(ctx);

            collRoleDefinitionBinding.Add(editPermissionLevel);


            //Add access to Talent Admins and Division group
            newItem.RoleAssignments.Add(this._talentAdmins, collRoleDefinitionBinding);
            newItem.RoleAssignments.Add(this._divisionAllRecordsSecurityGroup, collRoleDefinitionBinding);
            newItem.RoleAssignments.Add(this._streamAllRecordsSecurityGroup, collRoleDefinitionBinding);

            if (talent.IsL2Employee())
            {
                newItem.RoleAssignments.Add(this._upToL2SecurityGroup, collRoleDefinitionBinding);
            }

            if (talent.IsL1Employee())
            {
                newItem.RoleAssignments.Add(this._upToL2SecurityGroup, collRoleDefinitionBinding);
                newItem.RoleAssignments.Add(this._upToL1SecurityGroup, collRoleDefinitionBinding);
            }

            if (talent.IsCorMEmployee())
            {
                newItem.RoleAssignments.Add(this._upToL2SecurityGroup, collRoleDefinitionBinding);
                newItem.RoleAssignments.Add(this._upToL1SecurityGroup, collRoleDefinitionBinding);
                newItem.RoleAssignments.Add(this._upToM3SecurityGroup, collRoleDefinitionBinding);
            }
        }
Ejemplo n.º 2
0
        private void ApplyItemLevelPermissions(ListItem item, ListItemPermission lip, bool alwaysBreakItemLevelPermissions = false)
        {
            if (lip == null || item == null)
            {
                return;
            }

            //item.EnsureProperties(p => p.RoleAssignments, p => p.HasUniqueRoleAssignments);

            // Break permission inheritance on the item if not done yet
            if (alwaysBreakItemLevelPermissions || !item.HasUniqueRoleAssignments)
            {
                item.BreakRoleInheritance(false, false);
                this.clientContext.ExecuteQueryRetry();
            }

            // Assign item level permissions
            foreach (var roleAssignment in lip.RoleAssignments)
            {
                if (lip.Principals.TryGetValue(roleAssignment.Member.LoginName, out Principal principal))
                {
                    var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(this.clientContext);
                    foreach (var roleDef in roleAssignment.RoleDefinitionBindings)
                    {
                        roleDefinitionBindingCollection.Add(roleDef);
                    }

                    item.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                }
            }

            this.clientContext.ExecuteQueryRetry();
        }
        /// <summary>
        /// Breaks item level permission.
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="listName">Site pages library</param>
        /// <param name="copyPermissionsFromParent">Copy parent permissions</param>
        /// <param name="listItemId">List item Id to break permission</param>
        /// <returns></returns>
        internal static bool BreakItemPermission(ClientContext clientContext, string listName, bool copyPermissionsFromParent, int listItemId)
        {
            bool flag = false;

            try
            {
                Web      web      = clientContext.Web;
                ListItem listItem = web.Lists.GetByTitle(listName).GetItemById(listItemId);
                clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
                clientContext.ExecuteQuery();
                if (!listItem.HasUniqueRoleAssignments)
                {
                    listItem.BreakRoleInheritance(copyPermissionsFromParent, true);
                    listItem.Update();
                    clientContext.ExecuteQuery();
                    flag = true;
                }
            }
            catch (Exception exception)
            {
                MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                throw;
            }
            return(flag);
        }
Ejemplo n.º 4
0
 public static void ResetBreakRoleInheritance(ClientContext ctx, ListItem item)
 {
     item.ResetRoleInheritance();
     item.BreakRoleInheritance(false, true);
     item.SystemUpdate();
     ctx.ExecuteQuery();
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Manages the permissions.
        /// </summary>
        /// <param name="sourceContext">The source context.</param>
        /// <param name="targetContext">The target context.</param>
        /// <param name="sourceItem">The source item.</param>
        /// <param name="targetItem">The target item.</param>
        protected void ManagePermissions(ClientContext sourceContext, ClientContext targetContext, ListItem sourceItem, ListItem targetItem)
        {
            if (targetContext != null && sourceItem != null && targetItem != null)
            {
                Logger.Log("Into ManagePermissions for " + sourceItem.DisplayName);

                try
                {
                    var targetWeb = targetContext.Web;
                    var sourceItemRoleAssignmentCollection = sourceItem.RoleAssignments;

                    targetContext.Load(targetItem, ti => ti.RoleAssignments);
                    targetContext.ExecuteQueryWithIncrementalRetry(RetryCount, Delay);

                    //var sourceRoleDefinitionCollection = sourceContext.Web.RoleDefinitions;
                    targetItem.BreakRoleInheritance(false, true);

                    foreach (var sourceItemRoleAssignment in sourceItemRoleAssignmentCollection)
                    {
                        ManageSecurityPrincipal(targetContext, targetItem, targetWeb, sourceItemRoleAssignment);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError("Error in Manage Permissions for " + sourceItem.DisplayName + Environment.NewLine + ex.Message);
                    //throw ex;
                }
            }
        }
Ejemplo n.º 6
0
        //gavdcodeend 16

        //gavdcodebegin 17
        static void SpCsCsomBreakSecurityInheritanceListItem(ClientContext spCtx)
        {
            List     myList     = spCtx.Web.Lists.GetByTitle("TestList");
            ListItem myListItem = myList.GetItemById(1);

            spCtx.Load(myListItem, hura => hura.HasUniqueRoleAssignments);
            spCtx.ExecuteQuery();

            if (myListItem.HasUniqueRoleAssignments == false)
            {
                myListItem.BreakRoleInheritance(false, true);
            }
            myListItem.Update();
            spCtx.ExecuteQuery();
        }
Ejemplo n.º 7
0
        public void AsignarPermisos(Web web, ListItem item, Principal grupo, RoleType roleType)
        {
            ClientContext clientContext = this.context;

            clientContext.Load(item, it => it.HasUniqueRoleAssignments);
            clientContext.ExecuteQuery();

            if (!item.HasUniqueRoleAssignments)
            {
                item.BreakRoleInheritance(false, false);
            }

            clientContext.Load(web);
            clientContext.ExecuteQuery();

            UserCollection users = web.SiteUsers;
            RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(web.Context);
            RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(roleType);

            collRoleDefinitionBinding.Add(roleDefinition);

            item.RoleAssignments.Add(grupo, collRoleDefinitionBinding);


            clientContext.Load(item, it => it.RoleAssignments);
            clientContext.Load(users);
            clientContext.ExecuteQuery();

            bool existsysuser = false;

            foreach (RoleAssignment itemfe in item.RoleAssignments)
            {
                clientContext.Load(itemfe, it => it.Member);
                clientContext.Load(itemfe.Member, itm => itm.LoginName);
                clientContext.ExecuteQuery();
                if (itemfe.Member.LoginName.Equals("SHAREPOINT\\system"))
                {
                    existsysuser = true;
                }
            }

            if (existsysuser)
            {
                Principal      sysuser = users.GetByLoginName("SHAREPOINT\\system");
                RoleAssignment ra      = item.RoleAssignments.GetByPrincipal(sysuser);
                ra.DeleteObject();
            }
        }
Ejemplo n.º 8
0
        public void DCMSetRoleAssignments(int storageObjID, BaseCollection <DCTRoleAssignment> roleAssignments)
        {
            (storageObjID > 0).FalseThrow <ArgumentException>("ID值{0}无效,请传入大于0的值.", storageObjID);

            using (DocLibContext context = new DocLibContext(ServiceHelper.GetDocumentLibraryName()))
            {
                ListItem listItem = GetListItemById(storageObjID, context);
                if (null == listItem)
                {
                    return;
                }
                context.Load(listItem);

                listItem.BreakRoleInheritance(true, true);

                context.Load(listItem.RoleAssignments);
                context.ExecuteQuery();

                foreach (RoleAssignment roleAssignment in listItem.RoleAssignments)
                {
                    roleAssignment.RoleDefinitionBindings.RemoveAll();
                    roleAssignment.Update();
                }

                context.ExecuteQuery();

                foreach (DCTRoleAssignment dctRoleAssignment in roleAssignments)
                {
                    bool ignore = false;
                    RoleDefinitionBindingCollection binding = BuildRoleDefninitionBinding(context, dctRoleAssignment, out ignore);

                    Principal principal = BuildSharepointPrincipal(context, dctRoleAssignment);

                    if (ignore)
                    {
                        continue;
                    }

                    listItem.RoleAssignments.Add(principal, binding);
                    listItem.Update();
                }

                context.ExecuteQuery();
            }
        }
Ejemplo n.º 9
0
        public void MigrarDatos(List <Persona> ListPersona, HttpContextBase HttpContext)
        {
            LimpiarTabla(HttpContext);
            foreach (Persona persona in ListPersona)
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    //var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

                    //ClientContext clientContext = new ClientContext(siteUrl);
                    SP.List oList = clientContext.Web.Lists.GetByTitle("Persona");

                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    oListItem["Title"]           = persona.Id;
                    oListItem["Nombre"]          = persona.Nombre;
                    oListItem["Comuna"]          = persona.Comuna;
                    oListItem["Direccion"]       = persona.Direccion;
                    oListItem["FechaNacimiento"] = persona.FechaNacimiento;
                    oListItem["EsHumano"]        = persona.EsHumano;

                    oListItem.Update();

                    clientContext.ExecuteQuery();

                    if (persona.Id % 2 == 0)
                    {
                        oListItem.BreakRoleInheritance(false, false);

                        User spUser = clientContext.Web.CurrentUser;
                        clientContext.Load(spUser, user => user.LoginName);
                        clientContext.ExecuteQuery();

                        //spUser.LoginName
                        User oUser = clientContext.Web.SiteUsers.GetByLoginName("i:0#.f|membership|[email protected]");
                        RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);
                        collRoleDefinitionBinding.Add(clientContext.Web.RoleDefinitions.GetByType(RoleType.Reader));
                        oListItem.RoleAssignments.Add(oUser, collRoleDefinitionBinding);
                        clientContext.ExecuteQuery();
                    }
                }
            }
        }
Ejemplo n.º 10
0
 private void Clear(ClientContext clientContext, ListItem listItem, List <string> accountList)
 {
     if (listItem.HasUniqueRoleAssignments)
     {
         for (var index = listItem.RoleAssignments.Count - 1; index >= 0; index--)
         {
             clientContext.Load(listItem.RoleAssignments[index].Member);
             clientContext.ExecuteQuery();
             if (listItem.RoleAssignments[index].Member.LoginName.Equals(accountList[0]))
             {
                 listItem.RoleAssignments[index].DeleteObject();
             }
         }
     }
     else
     {
         listItem.BreakRoleInheritance(false, true);
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Validates and breaks the item level permission for the specified list item under the list/library.
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="listName">List name</param>
        /// <param name="listItemId">Unique list item id to break item level permission</param>
        /// <param name="isCopyRoleAssignment">Flag to copy permission from parent</param>
        /// <returns>String stating success flag</returns>
        public static bool BreakItemPermission(ClientContext clientContext, string listName, int listItemId, bool isCopyRoleAssignment)
        {
            bool result = false;

            if (null != clientContext && !string.IsNullOrWhiteSpace(listName))
            {
                ListItem listItem = clientContext.Web.Lists.GetByTitle(listName).GetItemById(listItemId);
                clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
                clientContext.ExecuteQuery();

                if (!listItem.HasUniqueRoleAssignments)
                {
                    listItem.BreakRoleInheritance(isCopyRoleAssignment, true);
                    listItem.Update();
                    clientContext.ExecuteQuery();
                    result = true;
                }
            }
            return(result);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Used to break item level permissions
 /// </summary>
 /// <param name="clientContext">Client context object</param>
 /// <param name="listName">List name</param>
 /// <param name="listItemId">List item id</param>
 internal static void BreakItemPermission(ClientContext clientContext, string listName, int listItemId)
 {
     try
     {
         ListItem listItem = clientContext.Web.Lists.GetByTitle(listName).GetItemById(listItemId);
         clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
         clientContext.ExecuteQuery();
         // Check if item has unique permissions
         if (!listItem.HasUniqueRoleAssignments)
         {
             listItem.BreakRoleInheritance(false, true);
             listItem.Update();
             clientContext.ExecuteQuery();
         }
     }
     catch (Exception exception)
     {
         ErrorLogger.DisplayErrorMessage(string.Format(CultureInfo.InvariantCulture, Constants.BreakingPermissionExceptionMessage, Constants.SettingsPage, exception.Message));
     }
 }
        private void ExecuteBreakItemInheritanceById()
        {
            ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0];

            string listTitle = serviceObject.GetListTitle();
            string siteURL   = GetSiteURL();
            int    id        = base.GetIntProperty(Constants.SOProperties.ID, true);

            using (ClientContext context = InitializeContext(siteURL))
            {
                Web spWeb = context.Web;

                List     list     = spWeb.Lists.GetByTitle(listTitle);
                ListItem listItem = list.GetItemById(id);
                context.Load(listItem);
                context.ExecuteQuery();

                listItem.BreakRoleInheritance(false, true);
                context.ExecuteQuery();
            }
        }
Ejemplo n.º 14
0
        public static void SyncList(this List srcList, ClientContext ctxTarget, string cListName, string cSyncFields, DateTime dtLastRun)
        {
            try
            {
                List tgtList = ctxTarget.Web.Lists.GetByTitle(cListName);
                ctxTarget.Load(tgtList, l => l.ItemCount);
                ctxTarget.ExecuteQuery();
                srcList.Context.Load(srcList, s => s.ItemCount, s => s.HasUniqueRoleAssignments);
                srcList.Context.ExecuteQuery();

                ListItemCollection workItems = null;

                if (srcList.ItemCount != tgtList.ItemCount)
                {
                    workItems = srcList.GetAllItems();
                }
                else
                {
                    workItems = srcList.GetModifiedItems(dtLastRun);
                }
                foreach (ListItem item in workItems)
                {
                    try
                    {
                        srcList.Context.Load(item);
                        srcList.Context.ExecuteQueryRetry();

                        ListItem tgtItem = tgtList.GetListItemByTitle(item["Title"].ToString());
                        if (tgtItem == null)
                        {
                            ListItemCreationInformation lici = new ListItemCreationInformation();
                            tgtItem          = tgtList.AddItem(lici);
                            tgtItem["Title"] = item["Title"];
                            tgtItem.Update();
                        }

                        string[] aFields = cSyncFields.Split(';');
                        foreach (string cField in aFields)
                        {
                            try
                            {
                                if (cField.Contains("`"))
                                {
                                    string[] cFieldInfo = cField.Split('`');


                                    if (item[cFieldInfo[1]] != null)
                                    {
                                        string cText = item[cFieldInfo[1]].ToString();
                                        if (cText.Contains("/Departments/Marketing/MarketingStore"))
                                        {
                                            if (cFieldInfo[0].ToLower().Contains("image"))
                                            {
                                                cText = cText.Replace("/Departments/Marketing/MarketingStore", "");
                                                string cUrl = cText.Substring(cText.IndexOf("<img"));
                                                cUrl = cUrl.Substring(cUrl.IndexOf("src") + 5);
                                                Int32 iEnd = cUrl.IndexOf("\"");
                                                cUrl = cUrl.Substring(0, iEnd);
                                                cUrl = cUrl.Replace("/Catalog%20Images/", "https://sandbox.rammware.net/sites/Sebia/BrochureImages/");
                                                tgtItem[cFieldInfo[0]] = cUrl;
                                            }
                                            else
                                            {
                                                cText = cText.Replace("/Departments/Marketing/MarketingStore", "");
                                                string cUrl = cText.Substring(cText.IndexOf("href") + 6);
                                                Int32  iEnd = cUrl.IndexOf("\"");
                                                cUrl = cUrl.Substring(0, iEnd);
                                                tgtItem[cFieldInfo[0]] = cUrl;
                                            }
                                        }
                                        else
                                        {
                                            tgtItem[cFieldInfo[0]] = item[cFieldInfo[1]];
                                        }
                                    }
                                }
                                else
                                {
                                    tgtItem[cField.Trim()] = item[cField.Trim()];
                                }
                            } catch (Exception ex)
                            {
                                System.Diagnostics.Trace.WriteLine(ex.Message);
                            }
                            tgtItem.Update();
                            ctxTarget.ExecuteQuery();
                        }
                        tgtItem.Update();
                        srcList.Context.Load(item, i => i.HasUniqueRoleAssignments, i => i.RoleAssignments);
                        srcList.Context.ExecuteQuery();
                        if (item.HasUniqueRoleAssignments)
                        {
                            tgtItem.BreakRoleInheritance(false, true);
                            tgtItem.Update();
                            ctxTarget.ExecuteQuery();
                            SyncPemrissions(ctxTarget, tgtItem, item);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("An error occured in SyncList for (Inside): " + srcList.Title + " " + ex.Message);
                    }
                }
            } catch (Exception ex)
            {
                throw new Exception("An error occured in SyncList for: " + srcList.Title + " " + ex.Message);
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            StreamReader sr  = new StreamReader(@"C:\Dev\talent-portal-refresh\Kier_Talent_DB\Provisioning\Test_Dummy_Data_2706.csv");
            var          csv = new CsvReader(sr);

            csv.Read(); //Skip Header
            Console.WriteLine(DateTime.Now.ToLongTimeString());
            while (csv.Read())
            {
                var employeeId      = csv.GetField <string>(0);
                var firstName       = csv.GetField <string>(2);
                var lastName        = csv.GetField <string>(1);
                var fullName        = string.Concat(lastName + ", " + firstName);
                var employeeEmail   = csv.GetField <string>(3);
                var gender          = csv.GetField <string>(4);
                var divison         = csv.GetField <string>(5);
                var stream          = csv.GetField <string>(6);
                var unit            = csv.GetField <string>(7);
                var reportingUnit   = csv.GetField <string>(8);
                var position        = csv.GetField <string>(9);
                var grade           = csv.GetField <string>(10);
                var managerNametext = csv.GetField <string>(11);
                var location        = csv.GetField <string>(13);
                var performance     = csv.GetField <string>(14);
                var potential       = csv.GetField <string>(15);
                var flightRisk      = csv.GetField <string>(16);
                var businessRisk    = csv.GetField <string>(17);
                var movement        = csv.GetField <string>(18);
                var function        = csv.GetField <string>(19);
                var managerEmail    = csv.GetField <string>(20);



                try
                {
                    using (var ctx = SharePointOnlineHelper.GetElevatedContext())
                    {
                        var talent = new Talent()
                        {
                            EmployeeId = employeeId,
                            Name       = new SharedKernal.Models.User()
                            {
                                value = employeeEmail, text = fullName
                            },
                            Manager = new SharedKernal.Models.User()
                            {
                                value = managerEmail, text = managerNametext
                            },
                            Division      = divison,
                            Stream        = stream,
                            Unit          = unit,
                            ReportingUnit = reportingUnit,
                            ManagerName   = managerNametext,

                            Function = function,
                            Grade    = grade,
                            Location = location,

                            Performance  = performance,
                            Potential    = potential,
                            BusinessRisk = businessRisk,
                            FlightRisk   = flightRisk,
                            Movement     = movement,

                            SubmissionYear      = 2017,
                            IsCurrentSubmission = false,
                            Position            = position,
                            Gender   = gender,
                            IsLeaver = false
                        };

                        var _roleDefinition = ctx.Web.RoleDefinitions.GetByType(RoleType.Reader);
                        var _divisionAllRecordsSecurityGroup = ctx.Web.SiteGroups.GetByName(talent.GetAllDivisionRecordsGroupName());
                        var _streamAllRecordsSecurityGroup   = ctx.Web.SiteGroups.GetByName(talent.GetAllStreamRecordsGroupName());
                        var _upToL1SecurityGroup             = ctx.Web.SiteGroups.GetByName(talent.GetUptoL1GroupName());
                        var _upToL2SecurityGroup             = ctx.Web.SiteGroups.GetByName(talent.GetUptoL2GroupName());
                        var _upToM3SecurityGroup             = ctx.Web.SiteGroups.GetByName(talent.GetUpToM3GroupName());
                        var _talentAdmins = ctx.Web.SiteGroups.GetByName(talent.GetTalentAdminsGroupName());

                        ctx.Load(_divisionAllRecordsSecurityGroup);
                        ctx.Load(_upToL1SecurityGroup);
                        ctx.Load(_upToL2SecurityGroup);
                        ctx.Load(_upToM3SecurityGroup);
                        ctx.Load(_talentAdmins);

                        ctx.ExecuteQuery();

                        var list = ctx.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["listName"]);
                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem newItem = list.AddItem(itemCreateInfo);
                        newItem = Talent.ToSPListItem(talent, newItem);
                        newItem.Update();


                        newItem.BreakRoleInheritance(false, true);
                        RoleDefinitionBindingCollection collRoleDefinitionBinding =
                            new RoleDefinitionBindingCollection(ctx);
                        collRoleDefinitionBinding.Add(_roleDefinition);


                        //Add access to Talent Admins and Division group
                        newItem.RoleAssignments.Add(_talentAdmins, collRoleDefinitionBinding);
                        newItem.RoleAssignments.Add(_divisionAllRecordsSecurityGroup, collRoleDefinitionBinding);
                        newItem.RoleAssignments.Add(_streamAllRecordsSecurityGroup, collRoleDefinitionBinding);

                        if (talent.IsL2Employee())
                        {
                            newItem.RoleAssignments.Add(_upToL2SecurityGroup, collRoleDefinitionBinding);
                        }

                        if (talent.IsL1Employee())
                        {
                            newItem.RoleAssignments.Add(_upToL2SecurityGroup, collRoleDefinitionBinding);
                            newItem.RoleAssignments.Add(_upToL1SecurityGroup, collRoleDefinitionBinding);
                        }

                        if (talent.IsCorMEmployee())
                        {
                            newItem.RoleAssignments.Add(_upToL2SecurityGroup, collRoleDefinitionBinding);
                            newItem.RoleAssignments.Add(_upToL1SecurityGroup, collRoleDefinitionBinding);
                            newItem.RoleAssignments.Add(_upToM3SecurityGroup, collRoleDefinitionBinding);
                        }


                        ctx.ExecuteQuery();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }


            //csv.Configuration.HeaderValidated = null;
            //csv.Configuration.MissingFieldFound = null;
            //var records = csv.GetRecords<Talent>().ToList();
            Console.WriteLine(DateTime.Now.ToLongTimeString());
            Console.Read();
        }
Ejemplo n.º 16
0
        internal void ApplyItemLevelPermissions(bool hasTargetContext, ListItem item, ListItemPermission lip, bool alwaysBreakItemLevelPermissions = false)
        {
            if (lip == null || item == null)
            {
                return;
            }

            // Break permission inheritance on the item if not done yet
            if (alwaysBreakItemLevelPermissions || !item.HasUniqueRoleAssignments)
            {
                item.BreakRoleInheritance(false, false);
                item.Context.ExecuteQueryRetry();
            }

            if (hasTargetContext)
            {
                // Ensure principals are available in the target site
                Dictionary <string, Principal> targetPrincipals = new Dictionary <string, Principal>(lip.Principals.Count);

                foreach (var principal in lip.Principals)
                {
                    var targetPrincipal = GetPrincipal(this.targetClientContext.Web, principal.Key, hasTargetContext);
                    if (targetPrincipal != null)
                    {
                        if (!targetPrincipals.ContainsKey(principal.Key))
                        {
                            targetPrincipals.Add(principal.Key, targetPrincipal);
                        }
                    }
                }

                // Assign item level permissions
                foreach (var roleAssignment in lip.RoleAssignments)
                {
                    if (targetPrincipals.TryGetValue(roleAssignment.Member.LoginName, out Principal principal))
                    {
                        var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(this.targetClientContext);
                        foreach (var roleDef in roleAssignment.RoleDefinitionBindings)
                        {
                            var targetRoleDef = this.targetClientContext.Web.RoleDefinitions.GetByName(roleDef.Name);
                            if (targetRoleDef != null)
                            {
                                roleDefinitionBindingCollection.Add(targetRoleDef);
                            }
                        }
                        item.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                    }
                }

                this.targetClientContext.ExecuteQueryRetry();
            }
            else
            {
                // Assign item level permissions
                foreach (var roleAssignment in lip.RoleAssignments)
                {
                    if (lip.Principals.TryGetValue(roleAssignment.Member.LoginName, out Principal principal))
                    {
                        var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(this.sourceClientContext);
                        foreach (var roleDef in roleAssignment.RoleDefinitionBindings)
                        {
                            roleDefinitionBindingCollection.Add(roleDef);
                        }

                        item.RoleAssignments.Add(principal, roleDefinitionBindingCollection);
                    }
                }

                this.sourceClientContext.ExecuteQueryRetry();
            }

            LogInfo(LogStrings.TransformCopiedItemPermissions, LogStrings.Heading_ApplyItemLevelPermissions);
        }
Ejemplo n.º 17
0
        private void SyncPemrissions(ClientContext ctxTarget, ListItem tgtItem, ListItem item)
        {
            try
            {
                ctxTarget.Load(tgtItem, a => a.HasUniqueRoleAssignments);
                ctxTarget.ExecuteQuery();
                if (!tgtItem.HasUniqueRoleAssignments)
                {
                    tgtItem.BreakRoleInheritance(false, true);
                }
                item.Context.Load(item, i => i.RoleAssignments);
                item.Context.ExecuteQuery();
                foreach (RoleAssignment ra in item.RoleAssignments)
                {
                    try
                    {
                        item.Context.Load(ra.Member);
                        item.Context.ExecuteQuery();
                        if (!HasRole(ctxTarget, tgtItem, ra.Member))
                        {
                            var roleDefBindCol = new RoleDefinitionBindingCollection(ctxTarget);
                            roleDefBindCol.Add(tgtItem.ParentList.ParentWeb.RoleDefinitions.GetByType(RoleType.Reader));
                            if (ra.Member.PrincipalType.ToString() != "SharePointGroup")
                            {
                                var user_group = tgtItem.ParentList.ParentWeb.EnsureUser(ra.Member.LoginName);
                                tgtItem.RoleAssignments.Add(user_group, roleDefBindCol);
                            }
                            else
                            {
                                tgtItem.ParentList.ParentWeb.EnsureGroup(ra.Member.LoginName);

                                var newgroup = tgtItem.ParentList.ParentWeb.SiteGroups.GetByName(ra.Member.LoginName);
                                var srcgroup = item.ParentList.ParentWeb.SiteGroups.GetByName(ra.Member.LoginName);
                                item.Context.Load(srcgroup, sg => sg.Users);
                                item.Context.ExecuteQuery();
                                foreach (User usr in srcgroup.Users)
                                {
                                    try
                                    {
                                        newgroup.EnsureUser(tgtItem.ParentList.ParentWeb, usr.LoginName);
                                    } catch (Exception ex)
                                    {
                                        System.Diagnostics.Trace.WriteLine(ex.Message);
                                    }
                                }

                                var roleDefBindCol2 = new RoleDefinitionBindingCollection(ctxTarget);
                                roleDefBindCol2.Add(tgtItem.ParentList.ParentWeb.RoleDefinitions.GetByType(RoleType.Reader));

                                tgtItem.RoleAssignments.Add(newgroup, roleDefBindCol2);
                            }

                            tgtItem.Update();
                            ctxTarget.ExecuteQuery();
                        }
                    }
                    catch (Exception ex)
                    {
                        string cMessage = "Unable to Add User: "******" - " + ex.Message;
                        listBox1.Items.Add(cMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                string cMessage = "An error occured in SyncPemrissions for: " + item.Id + " " + ex.Message;
                listBox1.Items.Add(cMessage);
            }
        }
Ejemplo n.º 18
0
 public override void BreakRoleInheritance(bool copyRoleDefinitions)
 {
     _item.BreakRoleInheritance(copyRoleDefinitions, false);
 }
Ejemplo n.º 19
0
 public override void BreakRoleInheritance(bool copyRoleDefinitions)
 {
     _item.BreakRoleInheritance(copyRoleDefinitions, false);
     _context.ExecuteQuery();
 }