Beispiel #1
0
        public string getListFoldersInfo(string listName, string contextURL, string user, string password)
        {
            isConnected = setContext(contextURL, user, password);
            if (isConnected != true)
            {
                return("Could not establish connection");
            }

            List list = getListByName(listName);
            ListItemCollection items = getItemsByQuery(list, CamlQuery.CreateAllFoldersQuery().ViewXml);

            clientContext.Load(items);
            clientContext.ExecuteQuery();

            string itemInfo = "";

            foreach (ListItem i in items)
            {
                try
                {
                    itemInfo += i["Title"] + " : " + i.Id + "\n";
                }
                catch
                {
                    itemInfo += i["FileRef"] + " : " + i.Id + "\n";
                }
            }
            return(itemInfo);
        }
        public static bool FolderExists(Web web, string listTitle, string folderUrl)
        {
            var list    = web.Lists.GetByTitle(listTitle);
            var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());

            web.Context.Load(list.RootFolder);
            web.Context.Load(folders);
            web.Context.ExecuteQuery();
            var folderRelativeUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folderUrl);

            //Console.WriteLine(folderRelativeUrl);
            return(Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl));
        }
Beispiel #3
0
        protected override void ExecuteCmdlet()
        {
#if !SP2013
            DefaultRetrievalExpressions = new Expression <Func <Folder, object> >[] { f => f.ServerRelativeUrl, f => f.Name, f => f.TimeLastModified, f => f.ItemCount };
#else
            DefaultRetrievalExpressions = new Expression <Func <Folder, object> >[] { f => f.ServerRelativeUrl, f => f.Name, f => f.ItemCount };
#endif
            if (List != null)
            {
                // Gets the provided list
                var list = List.GetList(SelectedWeb);

                // Query for all folders in the list
                CamlQuery query = CamlQuery.CreateAllFoldersQuery();
                do
                {
                    // Execute the query. It will retrieve all properties of the folders. Refraining to using the RetrievalExpressions would cause a tremendous increased load on SharePoint as it would have to execute a query per list item which would be less efficient, especially on lists with many folders, than just getting all properties directly
                    ListItemCollection listItems = list.GetItems(query);
                    ClientContext.Load(listItems, item => item.Include(t => t.Folder), item => item.ListItemCollectionPosition);
                    ClientContext.ExecuteQueryRetry();

                    // Take all the folders from the resulting list items and put them in a list to return
                    var folders = new List <Folder>(listItems.Count);
                    foreach (ListItem listItem in listItems)
                    {
                        var folder = listItem.Folder;
                        folders.Add(folder);
                    }

                    WriteObject(folders, true);

                    query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                } while (query.ListItemCollectionPosition != null);
            }
            else
            {
                var webServerRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
                if (!Url.StartsWith(webServerRelativeUrl, StringComparison.OrdinalIgnoreCase))
                {
                    Url = UrlUtility.Combine(webServerRelativeUrl, Url);
                }
#if ONPREMISES
                var folder = SelectedWeb.GetFolderByServerRelativeUrl(Url);
#else
                var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(Url));
#endif
                folder.EnsureProperties(RetrievalExpressions);

                WriteObject(folder);
            }
        }
Beispiel #4
0
        /// <summary>
        /// To check if the folder is present in the list
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="folderPath">Folder path</param>
        /// <param name="documentLibraryName">Document library name</param>
        /// <returns>true or false</returns>
        public static bool CheckFolderPresent(ClientContext clientContext, string folderPath, string documentLibraryName)
        {
            bool folderFound = false;

            if (null != clientContext && !string.IsNullOrWhiteSpace(documentLibraryName) && !string.IsNullOrWhiteSpace(folderPath))
            {
                List list = clientContext.Web.Lists.GetByTitle(documentLibraryName);
                ListItemCollection folderList = list.GetItems(CamlQuery.CreateAllFoldersQuery());
                clientContext.Load(folderList, item => item.Include(items => items.Folder.Name, items => items.Folder.ServerRelativeUrl).Where(items => items.Folder.ServerRelativeUrl == folderPath));
                clientContext.ExecuteQuery();
                folderFound = 0 < folderList.Count;
            }
            return(folderFound);
        }
Beispiel #5
0
        //gavdcodeend 26

        //gavdcodebegin 27
        static void SpCsCsomReadAllFolders(ClientContext spCtx)
        {
            List myList = spCtx.Web.Lists.GetByTitle("TestList");
            ListItemCollection allItems = myList.GetItems(CamlQuery.CreateAllFoldersQuery());

            spCtx.Load(allItems, itms => itms.Include(itm => itm.Folder));

            spCtx.ExecuteQuery();

            List <Folder> allFolders = allItems.Select(itm => itm.Folder).ToList();

            foreach (Folder oneFolder in allFolders)
            {
                Console.WriteLine(oneFolder.Name + " - " + oneFolder.ServerRelativeUrl);
            }
        }
Beispiel #6
0
        public static bool FolderExists(string folderName)
        {
            ClientContext ctx = ConnectToSharePoint();

            List spList = ctx.Web.Lists.GetByTitle("Documents");

            ctx.Load(spList);
            ctx.ExecuteQuery();

            var folders = spList.GetItems(CamlQuery.CreateAllFoldersQuery());

            ctx.Load(spList.RootFolder);
            ctx.Load(folders);
            ctx.ExecuteQuery();
            var folderRelativeUrl = string.Format("/{0}/{1}", spList.RootFolder.ServerRelativeUrl, folderName);

            return(Enumerable.Any(folders, folderItem => (string)folderItem["FileRef"] == folderRelativeUrl));
        }
Beispiel #7
0
        //TODO: fix bug with nested folders
        public static async Task <bool> FolderExists(this List list, string folderUrl)
        {
            var folders = list.GetItems(CamlQuery.CreateAllFoldersQuery());

            list.Context.Load(list.RootFolder);
            list.Context.Load(folders);
            await list.Context.ExecuteQueryAsync();

            var folderRelativeUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folderUrl);

            folderRelativeUrl = folderRelativeUrl
                                .Replace(@"\", @"/")
                                .Replace(@"//", @"/");

            return(Enumerable.Any(
                       folders
                       , folderItem => (string)folderItem["FileRef"] == folderRelativeUrl
                       ));
        }
Beispiel #8
0
        /// <summary>
        /// get all libraries folders paths
        /// </summary>
        /// <param name="spLibrary">the guid of the SpLibrary</param>
        /// <param name="spWebSiteUrl">SharePoint webSite url</param>
        /// <returns></returns>
        public List <string> GetAllLibraryFolders(List spLibrary, string spWebSiteUrl)
        {
            var folderItems = spLibrary.GetItems(CamlQuery.CreateAllFoldersQuery());

            lock (locky)
            {
                try
                {
                    Context.Load(folderItems, f => f.Include(i => i.Folder));
                    Context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    TOOLS.LogErrorAndExitProgram($"Error while retriving All folders from library : {spLibrary.Id} \n {ex.Message}");
                }

                return(folderItems.Select(i => i.Folder.ServerRelativeUrl.Replace(spWebSiteUrl + "/", "")).ToList());
            }
        }
Beispiel #9
0
        public void SearchFolder(string siteUrl, string listName, string relativePath)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web  web  = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);

                string FolderFullPath = null;

                CamlQuery query = CamlQuery.CreateAllFoldersQuery();

                if (relativePath.Equals(string.Empty))
                {
                    FolderFullPath = "/lists/" + listName;
                }
                else
                {
                    FolderFullPath = "/lists/" + listName + "/" + relativePath;
                }
                if (!string.IsNullOrEmpty(FolderFullPath))
                {
                    query.FolderServerRelativeUrl = FolderFullPath;
                }
                IList <Folder> folderResult = new List <Folder>();

                var listItems = list.GetItems(query);

                clientContext.Load(list);
                clientContext.Load(listItems, litems => litems.Include(
                                       li => li["DisplayName"],
                                       li => li["Id"]
                                       ));

                clientContext.ExecuteQuery();

                foreach (var item in listItems)
                {
                    Console.WriteLine("{0}----------{1}", item.Id, item.DisplayName);
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Checks if the folder or the document library exists.
        /// </summary>
        /// <param name="folderPath">Relative path of folder</param>
        /// <param name="clientContext">Client context object for SharePoint</param>
        /// <param name="documentLibraryName">Name of the document library no which upload operation is being performed</param>
        /// <returns>Folder exists or not</returns>
        public static bool FolderExists(string folderPath, ClientContext clientContext, string documentLibraryName)
        {
            bool folderFound = false;

            try
            {
                if (!string.IsNullOrWhiteSpace(folderPath) && !string.IsNullOrWhiteSpace(documentLibraryName) && null != clientContext)
                {
                    string             folderName = folderPath.Substring(folderPath.LastIndexOf(ConstantStrings.ForwardSlash, StringComparison.OrdinalIgnoreCase) + 1);
                    List               docLibList = clientContext.Web.Lists.GetByTitle(documentLibraryName);
                    ListItemCollection folderList = docLibList.GetItems(CamlQuery.CreateAllFoldersQuery());
                    clientContext.Load(clientContext.Web, web => web.ServerRelativeUrl);
                    clientContext.Load(docLibList, list => list.Title);
                    clientContext.Load(folderList, item => item.Include(currentItem => currentItem.Folder.Name, currentItem => currentItem.Folder.ServerRelativeUrl).Where(currentItem => currentItem.Folder.ServerRelativeUrl == folderPath));
                    clientContext.ExecuteQuery();

                    if (null != docLibList)
                    {
                        string rootFolderURL = string.Concat(clientContext.Web.ServerRelativeUrl, ConstantStrings.ForwardSlash + folderName);
                        if (string.Equals(rootFolderURL, folderPath, StringComparison.OrdinalIgnoreCase))
                        {
                            //// Upload is performed on root folder
                            folderFound = null != docLibList && docLibList.Title.ToUpperInvariant().Equals(documentLibraryName.ToUpperInvariant());
                        }
                        else
                        {
                            //// Upload is performed on different folder other than root folder
                            folderFound = 0 < folderList.Count;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ConstantStrings.LogTableName);
            }
            return(folderFound);
        }
Beispiel #11
0
		static void Main(string[] args)
		{
			
			#region Site Details - Read the details from config file  
			string siteURL = ConfigurationManager.AppSettings["siteURL"];
			string ListName = ConfigurationManager.AppSettings["listName"];
			string userName = ConfigurationManager.AppSettings["userName"];
			string password = ConfigurationManager.AppSettings["password"];
			string sitrUrl = siteURL;
			#endregion
			
			SecureString securePassword = new SecureString();
			foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
			/// Add the Folder object to List collection 
			#region Folder
			using (var ctx = new ClientContext(sitrUrl))
			{
				List<permissionItem> lstPermissionItem = new List<permissionItem>();
				ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
				ctx.Load(ctx.Web, a => a.Lists);
				ctx.ExecuteQuery();

				List list = ctx.Web.Lists.GetByTitle(ListName);
				var Folderitems = list.GetItems(CamlQuery.CreateAllFoldersQuery());
				ctx.Load(Folderitems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.DisplayName),
					a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
					permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
					roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
					roleDef => roleDef.Description))));
				ctx.Load(Folderitems);
				ctx.ExecuteQuery();

				string sPermissionLevel = string.Empty;

				foreach (var item in Folderitems)
				{
					//Console.WriteLine("{0} folder permissions", item.DisplayName);
					//permissionItem oFolderPermissionItem = null;
					//if (item.HasUniqueRoleAssignments)
					//{
					foreach (var assignment in item.RoleAssignments)
					{
						var oFolderPermissionItem = new permissionItem();
						Console.WriteLine(assignment.Member.Title);
						oFolderPermissionItem.Title = item["FileRef"].ToString();
						oFolderPermissionItem.Type = "Folder";
						oFolderPermissionItem.UserGroup = assignment.Member.Title;
						List<string> roles = new List<string>();
						foreach (var role in assignment.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							switch (role.Name)
							{
								case "Full Control":
									oFolderPermissionItem.FullControl = assignment.Member.Title;
									break;
								case "Contribute":
									oFolderPermissionItem.Contribute = assignment.Member.Title;
									break;
								case "Read":
									oFolderPermissionItem.Read = assignment.Member.Title;
									break;
							}
							sPermissionLevel += role.Name + ",";
						}
						if (item.HasUniqueRoleAssignments)
						{
							oFolderPermissionItem.Inherited = "No";
						}
						else
						{
							oFolderPermissionItem.Inherited = "Yes";
						}
						oFolderPermissionItem.PermissionLevel = sPermissionLevel.TrimEnd(',');
						oFolderPermissionItem.PrincipalType = assignment.Member.PrincipalType.ToString();

						if (oFolderPermissionItem.FullControl == string.Empty && oFolderPermissionItem.Contribute == string.Empty && oFolderPermissionItem.Read == string.Empty)
						{
							
						}
						else
						{
							lstPermissionItem.Add(oFolderPermissionItem);
						}
						sPermissionLevel = string.Empty;
					}

				}
				#region Sample
				//ctx.Load(Folderitems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.DisplayName));
				//ctx.Load(Folderitems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments), a => a.di);
				//	ctx.Load(Folderitems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
				//permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
				//roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
				//roleDef => roleDef.Description))));

				//else
				/*{
					foreach (var assignment in item.RoleAssignments)
					{
						oFolderPermissionItem.Title = item.DisplayName;
						oFolderPermissionItem.Type = "Folder";
						oFolderPermissionItem.UserGroup = assignment.Member.Title;

						Console.WriteLine(assignment.Member.Title);
						List<string> roles = new List<string>();
						foreach (var role in assignment.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							sPermissionLevel += role.Description + ",";
						}
						oFolderPermissionItem.PermissionLevel = sPermissionLevel;
						{
							oFolderPermissionItem.Inherited = "No";
						}
						oFolderPermissionItem.PrincipalType = assignment.Member.PrincipalType.ToString();
						lstPermissionItem.Add(oFolderPermissionItem);
						sPermissionLevel = string.Empty;
					}
				}

				//lstPermissionItem.Add(oFolderPermissionItem);
			}
			*/
				#endregion

				/// <remarks>
				/// Add the item object to List collection 
				/// </remarks>
				#endregion
			#region File
				CamlQuery camlQuery = new CamlQuery();
				camlQuery.ViewXml =
					@"<View Scope='Recursive' />";

				var listItems = list.GetItems(camlQuery);
				//load all list items with default properties and HasUniqueRoleAssignments property
				ctx.Load(listItems, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.File.Name),
					a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
					permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
					roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
					roleDef => roleDef.Description))));
				ctx.ExecuteQuery();

				foreach (var item in listItems)
				{
					//Console.WriteLine("List item: " + item["FileRef"].ToString());
					//load permissions if item has unique permission
					foreach (var roleAsg in item.RoleAssignments)
					{
						var oItemPermissionItem = new permissionItem();
						Console.WriteLine(roleAsg.Member.Title);
						oItemPermissionItem.Title = item["FileRef"].ToString(); 
						oItemPermissionItem.Type = "File";
						oItemPermissionItem.UserGroup = roleAsg.Member.Title;

						Console.WriteLine("User/Group: " + roleAsg.Member.LoginName);
						List<string> roles = new List<string>();
						foreach (var role in roleAsg.RoleDefinitionBindings)
						{
							roles.Add(role.Description);
							switch (role.Name)
							{
								case "Full Control":
									oItemPermissionItem.FullControl = roleAsg.Member.Title;
									break;
								case "Contribute":
									oItemPermissionItem.Contribute = roleAsg.Member.Title;
									break;
								case "Read":
									oItemPermissionItem.Read = roleAsg.Member.Title;
									break;
							}
							sPermissionLevel += role.Name + ",";
						}
						if (item.HasUniqueRoleAssignments)
						{
							oItemPermissionItem.Inherited = "No";
						}
						else
						{
							oItemPermissionItem.Inherited = "Yes";
						}
						oItemPermissionItem.PermissionLevel = sPermissionLevel.TrimEnd(',');
						oItemPermissionItem.PrincipalType = roleAsg.Member.PrincipalType.ToString();
						if (oItemPermissionItem.FullControl == string.Empty && oItemPermissionItem.Contribute == string.Empty && oItemPermissionItem.Read == string.Empty)
						{

						}
						else
						{
							lstPermissionItem.Add(oItemPermissionItem);
						}
						sPermissionLevel = string.Empty;
					}
				}
				#endregion

			ExportToExcel(lstPermissionItem,ListName);
			Console.WriteLine("Report generated");
			Console.ReadLine();
			}
		} //Main  
Beispiel #12
0
        static void Main(string[] args)
        {
            string       webUrl   = "https://icpower.sharepoint.com/sites/Kallpa Generacion S.A_TI/"; //Console.ReadLine();
            string       userName = "******";                          // Console.ReadLine();
            SecureString password = new SecureString();

            foreach (char c in "SharePoint2017".ToCharArray())
            {
                password.AppendChar(c);
            }
            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new SharePointOnlineCredentials(userName, password);

                var list = context.Web.Lists.GetByTitle("ITDocs");
                // Create a query to get all items
                var camlQuery = CamlQuery.CreateAllFoldersQuery();
                var listItems = list.GetItems(camlQuery);
                context.Load(listItems, li => li.Include(i => i.HasUniqueRoleAssignments, i => i.DisplayName));
                context.ExecuteQuery();
                foreach (ListItem item in listItems)
                {
                    Console.WriteLine("{0} {1}", item.HasUniqueRoleAssignments, item.DisplayName);
                    if (item.HasUniqueRoleAssignments)
                    {
                        context.Load(item.RoleAssignments, ra => ra.Include(r => r.Member, r => r.RoleDefinitionBindings));
                        context.ExecuteQuery();
                        foreach (RoleAssignment role in item.RoleAssignments)
                        {
                            Console.WriteLine("  - {0} {1}", role.Member.PrincipalType, role.Member.LoginName);
                            foreach (RoleDefinition rd in role.RoleDefinitionBindings)
                            {
                                Console.WriteLine("    + {0}", rd.Name);
                            }
                            if (role.Member.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup)
                            {
                                Group group = context.Web.SiteGroups.GetById(role.Member.Id);
                                context.Load(group, gr => gr.Users);
                                context.ExecuteQuery();
                                foreach (User user in group.Users)
                                {
                                    Console.WriteLine("    :: {0}", user.LoginName);
                                }
                            }
                        }
                        Console.ReadLine();
                    }
                }
            }
            Console.WriteLine("shp");
            Console.ReadLine();

            string            strDirectory = @"D:\Israel Chemicals Ltd-6973382-ICP\TI - 00 Politicas y Procedimientos TI\01 Politicas y Procedimientos 2016";
            DirectorySecurity fSecurity    = System.IO.Directory.GetAccessControl(strDirectory);
            var perms = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            foreach (AccessRule rule in perms)
            {
                Console.WriteLine("{0} {1}", rule.IdentityReference, rule.AccessControlType);
            }
            AddFileSecurity(strDirectory, @"inkia\carlos.magan", FileSystemRights.ReadData, AccessControlType.Allow);
            fSecurity = System.IO.Directory.GetAccessControl(strDirectory);
            perms     = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
            Console.WriteLine("Nuevos permisos:");
            foreach (AccessRule rule in perms)
            {
                Console.WriteLine("{0} {1}", rule.IdentityReference, rule.AccessControlType);
            }
            Console.WriteLine("fin");
            Console.ReadLine();
        }
Beispiel #13
0
        //static void ResetToRead(ClientObject obj, string objType, ClientContext ctx)
        //{
        //    //Remove the existing permission..
        //    var objPrinciple;
        //    if(objType=="User"){
        //        objPrinciple = obj as User;
        //    }
        //    else if (objType == "Group")
        //    {
        //        objPrinciple = ctx.CastTo<Group>(obj);
        //    }
        //    RoleAssignment groupRoleAssiment = oWebsite.RoleAssignments.GetByPrincipal(group);
        //    groupRoleAssiment.RoleDefinitionBindings.RemoveAll();
        //    groupRoleAssiment.Update();
        //    try
        //    {
        //        ctx.Load(groupRoleAssiment);
        //        ctx.ExecuteQuery();
        //        LogSummery("Successfully removed the existing permission on group : " + group.Title);
        //    }
        //    catch (Exception ex) { LogSummery("Fail to remove the existing permission on group : " + group.Title + ". Baucase " + ex.Message.ToString()); }
        //    //Assign Read permission..
        //    RoleDefinition roleDefinition = ctx.Web.RoleDefinitions.GetByType(RoleType.Reader);
        //    RoleDefinitionBindingCollection roleDefinitionBindingColl = new RoleDefinitionBindingCollection(ctx);
        //    roleDefinitionBindingColl.Add(roleDefinition);
        //    RoleAssignment roleAssign = ctx.Web.RoleAssignments.Add(group, roleDefinitionBindingColl);

        //    try
        //    {
        //        ctx.ExecuteQuery();
        //        LogSummery("Successfully assigned Read permission on group : " + group.Title);
        //    }
        //    catch (Exception ex) { LogSummery("Fail to assign Read permission on group : " + group.Title + ". Baucause " + ex.Message.ToString()); }
        //}

        static void AssignFolderReadPermission(string oWebUrl)
        {
            LogSummery("=============Lib & Folder -- Start Working on unique Libraries & folders to make them read only.===============");
            ClientContext ctxFolder = new ClientContext(oWebUrl);
            Web           oWebsite  = ctxFolder.Web;

            ctxFolder.Load(oWebsite,
                           website => website.Webs,
                           website => website.Title,
                           website => website.Url
                           );
            ctxFolder.ExecuteQuery();
            LogSummery("Library -- Getting document libraries for web " + oWebsite.Url);
            //var Libraries = ctxFolder.LoadQuery(ctxFolder.Web.Lists.Where(l => l.BaseTemplate == 101).Include(l => l.HasUniqueRoleAssignments, l => l.Title, l => l.RoleAssignments));
            var Libraries = ctxFolder.LoadQuery(ctxFolder.Web.Lists.Include(l => l.HasUniqueRoleAssignments, l => l.Title, l => l.RoleAssignments));

            ctxFolder.ExecuteQuery();
            LogSummery("Library -- Checking all libraries for unique folders under ther web " + oWebsite.Url);
            foreach (List _oDoc in Libraries)
            {
                LogSummery("Library -- Checking for library " + _oDoc.Title + " if it has unique permission then setting read only.");
                ctxFolder.Load(_oDoc, o => o.RootFolder.ServerRelativeUrl);
                ctxFolder.ExecuteQuery();
                //Console.WriteLine("VipinTest" + _oDoc.RootFolder.ServerRelativeUrl);
                #region Unique Folder to read only.
                if (_oDoc.HasUniqueRoleAssignments)
                {
                    LogSummery("Library -- Found folder " + _oDoc.Title + " as unique library. Now setting it to read only.");
                    // RoleAssignmentCollection roleDocAssignments = _oDoc.RoleAssignments;

                    var roleDocAssignments = ctxFolder.LoadQuery(_oDoc.RoleAssignments.Include(l => l.Member.Title, l => l.Member.LoginName, l => l.Member.Id, l => l.PrincipalId, l => l.Member.PrincipalType, l => l.RoleDefinitionBindings.Include(d => d.Name)));
                    ctxFolder.ExecuteQuery();
                    foreach (var assignemtn in roleDocAssignments)
                    {
                        //Console.WriteLine(assignemtn.Member.Title);
                        //Console.WriteLine(assignemtn.Member.LoginName);
                        LogSummery("Library -- Working on group : " + assignemtn.Member.Title + " has permission: " + (assignemtn.RoleDefinitionBindings[0].Name));
                        if (assignemtn.Member.PrincipalType.ToString() == "SharePointGroup")
                        {
                            daTable.Rows.Add(oWebsite.Title, oWebUrl, assignemtn.Member.Title, _oDoc.RootFolder.ServerRelativeUrl, assignemtn.RoleDefinitionBindings[0].Name);
                        }
                        else if (assignemtn.Member.PrincipalType.ToString() == "User")
                        {
                            User user          = null;
                            var  userLoginName = assignemtn.Member.LoginName.Split('|')[1];
                            if (userLoginName != "hcltech\\devadmin")
                            {
                                user = ctxFolder.Web.EnsureUser(userLoginName);
                                ctxFolder.Load(user);
                                ctxFolder.ExecuteQuery();
                            }

                            LogSummery("Site Group -- Working on User : "******" has permission:" + (assignemtn.RoleDefinitionBindings[0].Name));

                            daTable.Rows.Add(oWebsite.Title, oWebUrl, userLoginName = (userLoginName == "hcltech\\devadmin") ? userLoginName : userLoginName + "(" + user.Email + ")", _oDoc.RootFolder.ServerRelativeUrl, assignemtn.RoleDefinitionBindings[0].Name);
                        }
                        RoleAssignment groupRoleAssiment = _oDoc.RoleAssignments.GetByPrincipal(assignemtn.Member);
                        //groupRoleAssiment.RoleDefinitionBindings.RemoveAll();
                        //groupRoleAssiment.Update();
                        try
                        {
                            ctxFolder.Load(groupRoleAssiment);
                            ctxFolder.ExecuteQuery();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                            LogSummery("Library -- Fail in removing existing role assignment on library " + _oDoc.Title + " because : " + ex.Message.ToString());
                        }
                        // Assign Read permission..
                        //RoleDefinition userRoleDefinition = ctxFolder.Web.RoleDefinitions.GetByType(RoleType.Reader);
                        //RoleDefinitionBindingCollection userRoleDefinitionBindingColl = new RoleDefinitionBindingCollection(ctxFolder);
                        //userRoleDefinitionBindingColl.Add(userRoleDefinition);
                        //RoleAssignment userRoleAssign = _oDoc.RoleAssignments.Add(assignemtn.Member, userRoleDefinitionBindingColl);

                        try
                        {
                            ctxFolder.ExecuteQuery();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                            LogSummery("Library -- Fail in setting library to read-only because : " + ex.Message.ToString() + "Error on line number 268.");
                        }
                    }
                }
                #endregion
                ctxFolder.Load(_oDoc, l => l.BaseType);
                try
                {
                    ctxFolder.ExecuteQuery();
                }
                catch (Exception ex) { }
                if (_oDoc.BaseType == BaseType.DocumentLibrary)
                {
                    LogSummery("Folders -- Getting all folders for library " + _oDoc.Title);
                    var folders = _oDoc.GetItems(CamlQuery.CreateAllFoldersQuery());
                    //var folders = _oDoc.GetItems(_query);
                    ctxFolder.Load(folders, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member, ra => ra.Member.LoginName, ra => ra.Member.PrincipalType), i => i.DisplayName, i => i.Folder));
                    try
                    {
                        ctxFolder.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                        LogSummery("Folders -- Fail to load folder " + _oDoc.Title + " baucause " + ex.Message);
                    }
                    LogSummery("Folders -- Checking all folders of library " + _oDoc.Title + "for unique permission to male them read only");
                    LogSummery("Folders -- Found total folders " + folders.Count + " to work.");
                    foreach (var _oFolder in folders)
                    {
                        try
                        {
                            ctxFolder.Load(_oFolder, f => f.HasUniqueRoleAssignments, f => f["FileDirRef"]);
                            try
                            {
                                ctxFolder.ExecuteQuery();
                            }
                            catch (Exception ex) { }
                            if (_oFolder.HasUniqueRoleAssignments)
                            {
                                Console.WriteLine((string)_oFolder["FileDirRef"]);
                                var parentFolder = _oFolder.ParentList.ParentWeb.GetFolderByServerRelativeUrl((string)_oFolder["FileDirRef"]);
                                _oFolder.Context.Load(parentFolder);
                                _oFolder.Context.ExecuteQuery();
                                Console.WriteLine(parentFolder.ServerRelativeUrl);
                                LogSummery("Folders -- Folder: " + _oFolder.DisplayName + " found unique permission. Working on to make it read only.");

                                //Console.WriteLine(_oFolder.DisplayName);

                                var roleAssignments = ctxFolder.LoadQuery(_oFolder.RoleAssignments.Include(i => i.Member.Id, i => i.Member.LoginName, i => i.Member.PrincipalType, i => i.Member.Title, i => i.RoleDefinitionBindings.Include(s => s.Name)));
                                ctxFolder.ExecuteQuery();
                                foreach (var assignemtn in roleAssignments.ToList())
                                {
                                    try
                                    {
                                        //daTable.Rows.Add(oWebsite.Title, oWebsite.Url, sGroupName, 78, 59, 72, 95, 83, 77);
                                        LogSummery("Folders -- Working on group : " + assignemtn.Member.Title + " has permission: " + (assignemtn.RoleDefinitionBindings[0].Name));
                                        if (assignemtn.Member.PrincipalType.ToString() == "SharePointGroup")
                                        {
                                            daTable.Rows.Add(oWebsite.Title, oWebUrl, assignemtn.Member.Title, parentFolder.ServerRelativeUrl + "/" + _oFolder.DisplayName, assignemtn.RoleDefinitionBindings[0].Name);
                                        }
                                        else if (assignemtn.Member.PrincipalType.ToString() == "User")
                                        {
                                            User user          = null;
                                            var  userLoginName = assignemtn.Member.LoginName.Split('|')[1];
                                            if (userLoginName != "hcltech\\devadmin")
                                            {
                                                user = ctxFolder.Web.EnsureUser(userLoginName);
                                                ctxFolder.Load(user);
                                                ctxFolder.ExecuteQuery();
                                            }

                                            LogSummery("Site Group -- Working on User : "******" has permission:" + (assignemtn.RoleDefinitionBindings[0].Name));

                                            daTable.Rows.Add(oWebsite.Title, oWebUrl, userLoginName = (userLoginName == "hcltech\\devadmin") ? userLoginName : userLoginName + "(" + user.Email + ")", parentFolder.ServerRelativeUrl + "/" + _oFolder.DisplayName, assignemtn.RoleDefinitionBindings[0].Name);
                                        }
                                        //Console.WriteLine(assignemtn.Member.Title);
                                        //Console.WriteLine(assignemtn.Member.LoginName);
                                        RoleAssignment groupRoleAssiment = _oFolder.RoleAssignments.GetByPrincipal(assignemtn.Member);
                                        //groupRoleAssiment.RoleDefinitionBindings.RemoveAll();
                                        // groupRoleAssiment.Update();
                                        ctxFolder.Load(groupRoleAssiment);
                                        ctxFolder.ExecuteQuery();
                                        // Assign Read permission..
                                        // RoleDefinition userRoleDefinition = ctxFolder.Web.RoleDefinitions.GetByType(RoleType.Reader);
                                        //RoleDefinitionBindingCollection userRoleDefinitionBindingColl = new RoleDefinitionBindingCollection(ctxFolder);
                                        //userRoleDefinitionBindingColl.Add(userRoleDefinition);
                                        //RoleAssignment userRoleAssign = _oFolder.RoleAssignments.Add(assignemtn.Member, userRoleDefinitionBindingColl);
                                        //ctxFolder.ExecuteQuery();
                                        LogSummery("Folders -- Folder read enabled operation successfull for fodler " + _oFolder.DisplayName);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                            LogSummery("Folders -- Fail in role assignment because : " + ex.Message.ToString() + " for folder " + _oFolder.DisplayName);
                        }
                    }
                }
                else
                {
                    LogSummery("Folders -- Getting all folders for List " + _oDoc.Title);
                    var folders = _oDoc.GetItems(CamlQuery.CreateAllFoldersQuery());
                    //var folders = _oDoc.GetItems(_query);
                    ctxFolder.Load(folders, icol => icol.Include(i => i.RoleAssignments.Include(ra => ra.Member), i => i.DisplayName, i => i.Folder));
                    try
                    {
                        ctxFolder.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        LogSummery("Folders -- Fail to load folder " + _oDoc.Title + " baucause " + ex.Message);
                    }
                    LogSummery("Folders -- Checking all folders of list " + _oDoc.Title + "for unique permission to make them read only");
                    LogSummery("Folders -- Found total folders " + folders.Count + " to work.");
                    foreach (var _oFolder in folders)
                    {
                        try
                        {
                            ctxFolder.Load(_oFolder, f => f.HasUniqueRoleAssignments, f => f["FileDirRef"]);
                            try
                            {
                                ctxFolder.ExecuteQuery();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                            }
                            if (_oFolder.HasUniqueRoleAssignments)
                            {
                                Console.WriteLine((string)_oFolder["FileDirRef"]);
                                var parentFolder = _oFolder.ParentList.ParentWeb.GetFolderByServerRelativeUrl((string)_oFolder["FileDirRef"]);
                                _oFolder.Context.Load(parentFolder);
                                _oFolder.Context.ExecuteQuery();
                                Console.WriteLine(parentFolder.ServerRelativeUrl);
                                LogSummery("Folders -- Folder: " + _oFolder.DisplayName + " found unique permission. Working on to make it read only.");

                                //Console.WriteLine(_oFolder.DisplayName);

                                var roleAssignments = ctxFolder.LoadQuery(_oFolder.RoleAssignments.Include(i => i.Member.Id, i => i.Member.LoginName, i => i.Member.PrincipalType, i => i.Member.Title, i => i.RoleDefinitionBindings.Include(s => s.Name)));
                                ctxFolder.ExecuteQuery();
                                foreach (var assignemtn in roleAssignments.ToList())
                                {
                                    try
                                    {
                                        //daTable.Rows.Add(oWebsite.Title, oWebsite.Url, sGroupName, 78, 59, 72, 95, 83, 77);
                                        LogSummery("Folders -- Working on group : " + assignemtn.Member.Title + " has permission: " + (assignemtn.RoleDefinitionBindings[0].Name));

                                        if (assignemtn.Member.PrincipalType.ToString() == "SharePointGroup")
                                        {
                                            daTable.Rows.Add(oWebsite.Title, oWebUrl, assignemtn.Member.Title, parentFolder.ServerRelativeUrl + "/" + _oFolder.DisplayName, assignemtn.RoleDefinitionBindings[0].Name);
                                        }
                                        else if (assignemtn.Member.PrincipalType.ToString() == "User")
                                        {
                                            User user          = null;
                                            var  userLoginName = assignemtn.Member.LoginName.Split('|')[1];
                                            if (userLoginName != "hcltech\\devadmin")
                                            {
                                                user = ctxFolder.Web.EnsureUser(userLoginName);
                                                ctxFolder.Load(user);
                                                ctxFolder.ExecuteQuery();
                                            }

                                            LogSummery("Site Group -- Working on User : "******" has permission:" + (assignemtn.RoleDefinitionBindings[0].Name));

                                            daTable.Rows.Add(oWebsite.Title, oWebUrl, userLoginName = (userLoginName == "hcltech\\devadmin") ? userLoginName : userLoginName + "(" + user.Email + ")", parentFolder.ServerRelativeUrl + "/" + _oFolder.DisplayName, assignemtn.RoleDefinitionBindings[0].Name);
                                        }
                                        //Console.WriteLine(assignemtn.Member.Title);
                                        //Console.WriteLine(assignemtn.Member.LoginName);
                                        RoleAssignment groupRoleAssiment = _oFolder.RoleAssignments.GetByPrincipal(assignemtn.Member);
                                        //groupRoleAssiment.RoleDefinitionBindings.RemoveAll();
                                        // groupRoleAssiment.Update();
                                        ctxFolder.Load(groupRoleAssiment);
                                        ctxFolder.ExecuteQuery();
                                        // Assign Read permission..
                                        // RoleDefinition userRoleDefinition = ctxFolder.Web.RoleDefinitions.GetByType(RoleType.Reader);
                                        //RoleDefinitionBindingCollection userRoleDefinitionBindingColl = new RoleDefinitionBindingCollection(ctxFolder);
                                        //userRoleDefinitionBindingColl.Add(userRoleDefinition);
                                        //RoleAssignment userRoleAssign = _oFolder.RoleAssignments.Add(assignemtn.Member, userRoleDefinitionBindingColl);
                                        //ctxFolder.ExecuteQuery();
                                        LogSummery("Folders -- Folder read enabled operation successfull for fodler " + _oFolder.DisplayName);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error Found in " + ex.StackTrace + "and the error is" + ex.Message.ToString());
                            LogSummery("Folders -- Fail in role assignment because : " + ex.Message.ToString() + " for folder " + _oFolder.DisplayName);
                        }
                    }
                }
            }
            LogSummery("=============Lib & Folder -- Completed Working on unique Libraries & folders to make them read only.===============");
        }