public static List<string> ReadCSV() { try { LogInfoMessage("CSV loading..."); List<string> lstSiteURLs = new List<string>(); using (var reader = new StreamReader(ConfigurationManager.AppSettings.Get(Constants.CSV_FILE_PATH), Encoding.Default)) { int i = 0; while (!reader.EndOfStream) { var url = reader.ReadLine(); if (i > 0) { lstSiteURLs.Add(url); } i++; } } LogInfoMessage("CSV loaded successfully..."); return lstSiteURLs; } catch (Exception ex) { LogErrorMessage("Error occured in ReadCSV. Error details- " + ex.Message); return null; } } |
public static NetworkCredential GetCredentials() { try { return new NetworkCredential( ConfigurationManager.AppSettings.Get(Constants.ADMIN_USER_NAME), ConfigurationManager.AppSettings.Get(Constants.ADMIN_USER_PASS), ConfigurationManager.AppSettings.Get(Constants.DOMAIN) ); } catch (Exception ex) { LogErrorMessage("Error occured in GetCredentials. Error details- " + ex.Message); return null; } } |
public static void AddUserAsSiteAdmin(List<string> lstSites) { string logFilePath = ConfigurationManager.AppSettings.Get(Constants.FILE_PATH); IEnumerable<List> lstCollection = null; foreach (string siteURL in lstSites) { try { if (!string.IsNullOrWhiteSpace(siteURL)) { bool isSiteExists = Helper.IsSiteExist(siteURL, logFilePath); if (isSiteExists) { using (ClientContext clientContext = GetClientContext(GetSafeURL(siteURL))) { User spUser = null; spUser = clientContext.Web.EnsureUser("i:loinginfo "); spUser.IsSiteAdmin = true; spUser.Update(); clientContext.Load(spUser); clientContext.ExecuteQuery(); } } } } catch (Exception ex) { continue; } } } |
public static ClientContext GetClientContext(string siteURL) { try { var context = new ClientContext(GetSafeURL(siteURL)); context.ExecutingWebRequest += Ctx_ExecutingWebRequest; context.Credentials = GetCredentials(); context.RequestTimeout = -1; context.PendingRequest.RequestExecutor.RequestKeepAlive = true; context.PendingRequest.RequestExecutor.WebRequest.KeepAlive = false; context.PendingRequest.RequestExecutor.WebRequest.Timeout = -1; context.PendingRequest.RequestExecutor.WebRequest.ReadWriteTimeout = -1; return context; } catch (Exception ex) { LogErrorMessage("Error occured in GetClientContext. Error details- " + ex.Message); return null; } } private static void Ctx_ExecutingWebRequest(object sender, WebRequestEventArgs e) { if (e != null) { e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); } } |
public static bool IsSiteExist(string siteURL, string logFilePath) { bool isSiteExist = false; ClientContext context = GetClientContext(GetSafeURL(siteURL)); try { context.Credentials = GetCredentials(); Web oWebsite = context.Web; context.Load(oWebsite); context.ExecuteQuery(); if (oWebsite != null) { isSiteExist = true; } } catch (Exception ex) { isSiteExist = false; } finally { context.Dispose(); } return isSiteExist; } |
public static string GetSafeURL(string url) { if (url.Trim().EndsWith("/")) return url.TrimEnd('/'); else return url; } |
public static void ProgressReportLogging(string message, string filepath) { string strPath = filepath; if (!System.IO.File.Exists(strPath)) { System.IO.File.Create(strPath).Dispose(); } //using (StreamWriter sw = System.IO.File.AppendText(strPath)) //{ // sw.WriteLine(message); //} using (StreamWriter sw = new StreamWriter(strPath, true, Encoding.Default)) { sw.WriteLine(message); } } |
public static void AddChoiceItemList(List<string> lstSites) { IEnumerable<List> lstCollection = null; List list = null; foreach (string siteURL in lstSites) { try { if (!string.IsNullOrWhiteSpace(siteURL)) { bool isSiteExists = Helper.IsSiteExist(siteURL, LogFilePath); if (isSiteExists) { using (ClientContext clientContext = GetClientContext(GetSafeURL(siteURL))) { lstCollection = clientContext.LoadQuery(clientContext.Web.Lists.Where(l => l.Title == "Entity")); clientContext.ExecuteQuery(); list = lstCollection.First(); Field field1 = list.Fields.GetByInternalNameOrTitle("ColumnName"); FieldChoice fieldChoice1 = clientContext.CastTo<FieldChoice>(field1); clientContext.Load(fieldChoice1); clientContext.ExecuteQuery(); // Add the choice field values List<string> options = new List<string>(fieldChoice1.Choices); if (!options.Contains("Test1")) { options.Add(“Test1”); } fieldChoice1.Update(); clientContext.ExecuteQuery(); } } } } catch (Exception ex) { continue; } } } |
public static List<ListItem> GetAllListItemsThreshold(ClientContext ctx, List list) { List<ListItem> items = new List<ListItem>(); ListItemCollectionPosition coll = new ListItemCollectionPosition(); ListItemCollectionPosition position = null; int rowLimit = 4999; var camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View Scope='RecursiveAll'> <Query> <OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy> </Query> <ViewFields> <FieldRef Name='FileLeafRef'/><FieldRef Name='File_x0020_Size'/><FieldRef Name='FileLeafRef'/><FieldRef Name='File_x0020_Type' /><FieldRef Name='FileRef' /><FieldRef Name='Editor' /> </ViewFields> <RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>"; do { ListItemCollection listItems = null; camlQuery.ListItemCollectionPosition = position; listItems = list.GetItems(camlQuery); ctx.Load(listItems); ctx.ExecuteQuery(); position = listItems.ListItemCollectionPosition; items.AddRange(listItems.ToList()); } while (position != null); items = items.OrderBy(item => item.FieldValues["FileLeafRef"]).ToList(); return items; } |
public static void GetContentTypeListInfo(string List_NAME, string EntInflogFilePath, ClientContext clientContext, string contentTypeName) { bool isExists = false; IEnumerable<List> lstCollection = clientContext.LoadQuery(clientContext.Web.Lists.Where(l => l.Title == List_NAME)); clientContext.ExecuteQuery(); var count = lstCollection.Count(); if (count >= 1) { foreach (List ls in lstCollection) { clientContext.Load(ls.ContentTypes); clientContext.Load(ls.Fields); clientContext.ExecuteQuery(); var ctCOunt = ls.ContentTypes.Count; if (ctCOunt > 0) { isExists = false; foreach (ContentType ct in ls.ContentTypes) { if (ct.Name != "Folder") { clientContext.Load(ct.Fields); clientContext.ExecuteQuery(); StringBuilder fields = new StringBuilder(); StringBuilder internames = new StringBuilder(); isExists = true; foreach (Field fld in ct.Fields) { fields.Append(fld.Title + ";"); internames.Append(fld.InternalName + ";"); } } //do something } } else if (ctCOunt == 0) { //do something } } } else if (lstCollection == null || count == 0) { //do something } } |
public static void Get_Item_Level_Permissions_For_All_List_Items() { string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "ItemlevelPermission_" + string.Format("{0:yyyy-MM-dd_hh-mm-ss}", DateTime.Now) + ".csv"; string header = "SiteUrl,ListName,ListHasUniqueRoleAssignments,Status,Message,ItemID,ItemTitle,MemberLogin,Permission"; ProgressReportLogging(header, logFilePath); string sitrUrl = "site-url"; using (var ctx = GetClientContext(sitrUrl)) { ctx.Load(ctx.Web, a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName, roleAsg => roleAsg.Member.Title, roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.Description))); ctx.ExecuteQuery(); foreach (var roleAsg in ctx.Web.RoleAssignments) { List<string> roles = new List<string>(); foreach (var role in roleAsg.RoleDefinitionBindings) { roles.Add(role.Name); } Console.WriteLine("Permissions: " + string.Join("|", roles.ToArray())); Console.WriteLine("----------------"); string msg = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", sitrUrl, "", "", "Success", "web has unique permission", "", "", roleAsg.Member.Title, string.Join("|", roles.ToArray())); ProgressReportLogging(msg, logFilePath); } IEnumerable<List> lstCollection = ctx.LoadQuery(ctx.Web.Lists); ctx.ExecuteQuery(); foreach (List list in lstCollection) { if (!list.Hidden) { try { ctx.Load(list, l => l.HasUniqueRoleAssignments); var listItems = list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(listItems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments), permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName, roleAsg => roleAsg.Member.Title, roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name, roleDef => roleDef.Description)))); ctx.ExecuteQuery(); foreach (var item in listItems) { Console.WriteLine("List item: " + item["FileRef"].ToString()); if (item.HasUniqueRoleAssignments) { foreach (var roleAsg in item.RoleAssignments) { Console.WriteLine("User/Group: " + roleAsg.Member.LoginName); List<string> roles = new List<string>(); foreach (var role in roleAsg.RoleDefinitionBindings) { roles.Add(role.Name); } Console.WriteLine("Permissions: " + string.Join("|", roles.ToArray())); Console.WriteLine("----------------"); string msg = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", sitrUrl, list.Title, list.HasUniqueRoleAssignments, "Success", "Item has unique permission", item.Id, Convert.ToString(item["Title"]), roleAsg.Member.Title, string.Join("|", roles.ToArray())); ProgressReportLogging(msg, logFilePath); } } else { Console.WriteLine("No unique permission found"); string msg = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", sitrUrl, list.Title, list.HasUniqueRoleAssignments, "Success", "Item has NO unique permission", item.Id, Convert.ToString(item["Title"]), "N-A", "No unique permission found for the item"); ProgressReportLogging(msg, logFilePath); } } } catch (Exception ex) { string msg = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", sitrUrl, "N-A", "N-A", "Error: processing the list", ex.Message, "N-A", "N-A", "N-A", "N-A"); LogErrorMessage(msg + ex.Message); ProgressReportLogging(msg, logFilePath); continue; } } } } } |