/// <summary> /// Backups and exports lists /// </summary> /// <param name="clientContextWeb">client context url</param> /// <param name="backupListTarget">list that is exported and deleted</param> /// <param name="backupListSource">list that needs to be backedup</param> /// <param name="pipelineBackupDocLib">doc library for backup of excel file</param> public BackupHelper(string clientContextWeb, string backupListTarget, string backupListSource, string pipelineBackupDocLib) { try { using (var clientContext = new ClientContext(clientContextWeb)) { try { Web web = clientContext.Web; List oldList = web.Lists.GetByTitle(backupListTarget); List newList = web.Lists.GetByTitle(backupListSource); // This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" // so that it grabs all list items, regardless of the folder they are in. CamlQuery query = CamlQuery.CreateAllItemsQuery(2000); CamlQuery newquery = CamlQuery.CreateAllItemsQuery(2000); ListItemCollection oldItems = oldList.GetItems(query); ListItemCollection newItems = newList.GetItems(newquery); int counter = 0; var listFields = newList.Fields; clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName, field => field.ReadOnlyField)); clientContext.Load(oldItems); clientContext.Load(newItems); clientContext.ExecuteQuery(); // Retrieve all items in the ListItemCollection from List.GetItems(Query). DataTable dt = new DataTable("ExportData"); foreach (Field f in listFields) { //Console.WriteLine("Checking Field: {0}", f.Title); try { // if (Array.IndexOf(stringArray, f.Title) >= 0) // { if (Array.IndexOf(badTitleArray, f.InternalName) < 0 && !f.ReadOnlyField) { //Console.WriteLine("Adding Field: {0}", f.Title); dt.Columns.Add(f.Title); } } catch (Exception ex) { log.Error("error creating table", ex); } } foreach (ListItem item in oldItems) { DataRow dr = dt.NewRow(); foreach (Field f in listFields) { if (Array.IndexOf(badTitleArray, f.InternalName) < 0 && !f.ReadOnlyField) { try { dr[f.Title] = item[f.InternalName]; } catch (Exception ex) { log.Debug("found a problem with field"); Console.WriteLine("Error with: {0} \n", f.InternalName.ToString()); Console.WriteLine("Error message {0}", ex.Message); } } } dt.Rows.Add(dr); // WORKING DELETE OBJECTS oldItems.GetById(item.Id).DeleteObject(); if (counter > 50) { try { clientContext.ExecuteQuery(); counter = 0; } catch (Exception ex) { log.Error("caught and exception in delete object", ex); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("We had an issue:{0}", ex.ToString())); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Connectivity was lost please try again"); throw ex; } } else { counter++; } } //finish up the final documents counter = 0; try { clientContext.ExecuteQuery(); } catch (Exception ex) { log.Error("caught and exception while cleaning up objects", ex); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("We had an issue:{0}", ex.ToString())); Console.WriteLine("Connectivity was lost please try again"); throw ex; } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Items are all deleted we are about to save our file"); // save excel file XLWorkbook wb = new XLWorkbook(); wb.Worksheets.Add(dt, "WorksheetName"); string timestamp = DateTime.Now.ToString("yyyyMMddhhmm"); string fileName = "backup" + timestamp + ".xlsx"; wb.SaveAs(fileName); using (var fs = new FileStream(fileName, FileMode.Open)) { var fi = new FileInfo(fileName); var list = clientContext.Web.Lists.GetByTitle(pipelineBackupDocLib); clientContext.Load(list.RootFolder); clientContext.ExecuteQuery(); var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name); Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("The file was successfully saved and we are about to copy lists"); foreach (ListItem item in newItems) { var itemCreateInfo = new ListItemCreationInformation(); var newListItem = oldList.AddItem(itemCreateInfo); StringBuilder sbLog = new StringBuilder(); foreach (Field f in listFields) { // if (Array.IndexOf(stringArray, f.Title) >= 0) // { if (Array.IndexOf(badTitleArray, f.InternalName) < 0 && !f.ReadOnlyField) { if (f.InternalName.ToLower() == "title") { sbLog.Append(string.Format("Field Name:{0}", f.InternalName)); } newListItem[f.InternalName] = item[f.InternalName]; } //} } newListItem.Update(); if (counter > 50) { try { clientContext.ExecuteQuery(); } catch (Exception ex) { log.Error("caught an update exception", ex); log.Debug(string.Format("ERROR: {0} with update.", newListItem["HPOppID"].ToString())); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("We had an issue:{0}", ex.ToString())); Console.WriteLine("Connectivity was lost please try again"); // throw ex; } } else { counter++; //log.Debug(string.Format("added item:{0}", sbLog.ToString())); } } //finish up the final documents counter = 0; try { clientContext.ExecuteQuery(); } catch (Exception ex) { log.Error("caught and exception", ex); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("We had an issue:{0}", ex.ToString())); Console.WriteLine("Connectivity was lost please try again"); log.Error(string.Format("Connectivity was lost. Please try again:{0}", ex.ToString())); // throw ex; } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("We had an issue Please record, exit and try again:{0}", ex.ToString())); log.Error(string.Format("We had an issue Please record, exit and try again:{0}", ex.ToString())); //Console.ReadLine(); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Client context was lost: Pleasse record and press enter"); log.Error("Client context was lost", ex); //Console.ReadLine(); } log.Debug("------------------------------------------------------------"); log.Debug("Backup Completed."); log.Debug("------------------------------------------------------------"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Successfully completed Backup."); Console.ForegroundColor = ConsoleColor.White; //Console.ReadLine(); }
public List <Template> GetAvailableTemplates() { List <Template> _templates = new List <Template>(); UsingContext(ctx => { var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(LISTTITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", LISTTITLE, _web.Url); Log.Fatal("SPSiteTemplateManager.GetAvailableTemplates", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(LISTTITLE); var _listItemCollection = _list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(_listItemCollection, eachItem => eachItem.Include( item => item, item => item[TemplateFields.TTILE_NAME], item => item[TemplateFields.DESCRIPTION_NAME], item => item[TemplateFields.TEMPLATEIMAGE_NAME], item => item[TemplateFields.HOSTPATH_NAME], item => item[TemplateFields.TENANTURL_NAME], item => item[TemplateFields.ONPREM_NAME], item => item[TemplateFields.TEMPLATE_NAME], item => item[TemplateFields.STORAGEMAX_NAME], item => item[TemplateFields.STORAGEWARN_NAME], item => item[TemplateFields.USERCODEMAX_NAME], item => item[TemplateFields.USERCODEWARN_NAME], item => item[TemplateFields.PROVISIONINGTEMPLATE_NAME], item => item[TemplateFields.ENABLED_NAME], item => item[TemplateFields.ROOTWEBONLY_NAME], item => item[TemplateFields.SUBWEBONLY_NAME] )); ctx.ExecuteQuery(); foreach (var item in _listItemCollection) { _templates.Add(new Template() { Title = item.BaseGet(TemplateFields.TTILE_NAME), Description = item.BaseGet(TemplateFields.DESCRIPTION_NAME), Enabled = item.BaseGet <bool>(TemplateFields.ENABLED_NAME), ProvisioningTemplate = item.BaseGet(TemplateFields.PROVISIONINGTEMPLATE_NAME), // ManagedPath = item.BaseGet(TemplateFields.MANAGEDPATH_NAME), ImageUrl = item.BaseGet <FieldUrlValue>(TemplateFields.TEMPLATEIMAGE_NAME).Url, TenantAdminUrl = item.BaseGet <FieldUrlValue>(TemplateFields.TENANTURL_NAME).Url, HostPath = item.BaseGet <FieldUrlValue>(TemplateFields.HOSTPATH_NAME).Url, RootWebOnly = item.BaseGet <bool>(TemplateFields.ROOTWEBONLY_NAME), SubWebOnly = item.BaseGet <bool>(TemplateFields.SUBWEBONLY_NAME), StorageMaximumLevel = item.BaseGetInt(TemplateFields.STORAGEMAX_NAME), StorageWarningLevel = item.BaseGetInt(TemplateFields.STORAGEWARN_NAME), UserCodeMaximumLevel = item.BaseGetInt(TemplateFields.USERCODEMAX_NAME), UserCodeWarningLevel = item.BaseGetInt(TemplateFields.USERCODEWARN_NAME), SharePointOnPremises = item.BaseGet <bool>(TemplateFields.ONPREM_NAME), RootTemplate = item.BaseGet(TemplateFields.TEMPLATE_NAME) }); } }); return(_templates.Where(t => t.Enabled).ToList()); }
protected override void ExecuteCmdlet() { var list = List.GetList(SelectedWeb); if (list == null) { throw new PSArgumentException($"No list found with id, title or url '{List}'", "List"); } if (HasId()) { var listItem = list.GetItemById(Id); if (Fields != null) { foreach (var field in Fields) { ClientContext.Load(listItem, l => l[field]); } } else { ClientContext.Load(listItem); } ClientContext.ExecuteQueryRetry(); WriteObject(listItem); } else if (HasUniqueId()) { CamlQuery query = new CamlQuery(); var viewFieldsStringBuilder = new StringBuilder(); if (HasFields()) { viewFieldsStringBuilder.Append("<ViewFields>"); foreach (var field in Fields) { viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field); } viewFieldsStringBuilder.Append("</ViewFields>"); } query.ViewXml = $"<View><Query><Where><Eq><FieldRef Name='GUID'/><Value Type='Guid'>{UniqueId.Id}</Value></Eq></Where></Query>{viewFieldsStringBuilder}</View>"; var listItem = list.GetItems(query); ClientContext.Load(listItem); ClientContext.ExecuteQueryRetry(); WriteObject(listItem); } else { CamlQuery query = HasCamlQuery() ? new CamlQuery { ViewXml = Query } : CamlQuery.CreateAllItemsQuery(); query.FolderServerRelativeUrl = FolderServerRelativeUrl; if (Fields != null) { var queryElement = XElement.Parse(query.ViewXml); var viewFields = queryElement.Descendants("ViewFields").FirstOrDefault(); if (viewFields != null) { viewFields.RemoveAll(); } else { viewFields = new XElement("ViewFields"); queryElement.Add(viewFields); } foreach (var field in Fields) { XElement viewField = new XElement("FieldRef"); viewField.SetAttributeValue("Name", field); viewFields.Add(viewField); } query.ViewXml = queryElement.ToString(); } if (HasPageSize()) { var queryElement = XElement.Parse(query.ViewXml); var rowLimit = queryElement.Descendants("RowLimit").FirstOrDefault(); if (rowLimit != null) { rowLimit.RemoveAll(); } else { rowLimit = new XElement("RowLimit"); queryElement.Add(rowLimit); } rowLimit.SetAttributeValue("Paged", "TRUE"); rowLimit.SetValue(PageSize); query.ViewXml = queryElement.ToString(); } do { var listItems = list.GetItems(query); ClientContext.Load(listItems); ClientContext.ExecuteQueryRetry(); WriteObject(listItems, true); if (ScriptBlock != null) { ScriptBlock.Invoke(listItems); } query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; } while (query.ListItemCollectionPosition != null); } }
private CamlQuery GetQuery(QueryType type) { CamlQuery query = new CamlQuery(); if (type == QueryType.IN_PROGRESS) { query.ViewXml = "<View><Query>" + "<Where>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.IN_PROGRESS + "</Value>" + "</Eq>" + "</Where>" + "</Query></View>"; } else if (type == QueryType.FUTURE) { query.ViewXml = "<View><Query>" + "<Where>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.FUTURE_PIPELINE + "</Value>" + "</Eq>" + "</Where>" + "</Query></View>"; } else if (type == QueryType.APPROVED) { query.ViewXml = "<View><Query>" + "<Where>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.APPROVED + "</Value>" + "</Eq>" + "</Where>" + "</Query></View>"; } else if (type == QueryType.UNDER_REVIEW) { query.ViewXml = "<View><Query>" + "<Where>" + "<Or>" + "<Or>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.SUBMIT_APPROVAL + "</Value>" + "</Eq>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.FINANCE_REVIEW + "</Value>" + "</Eq>" + "</Or>" + "<Or>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.READY_FINANCE_REVIEW + "</Value>" + "</Eq>" + "<Eq>" + "<FieldRef Name='Idea_x0020_Status' /><Value Type='Choice'>" + Status.PENDING_ACTUALS + "</Value>" + "</Eq>" + "</Or>" + "</Or>" + "</Where>" + "</Query></View>"; } else if (type == QueryType.ALL) { query = CamlQuery.CreateAllItemsQuery(); } else { query = CamlQuery.CreateAllItemsQuery(); } return(query); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { var lists = web.Lists; web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url, w => w.Id); web.Context.Load(lists, lc => lc.IncludeWithDefaultProperties( l => l.RootFolder.ServerRelativeUrl, l => l.EnableAttachments, l => l.ContentTypes, l => l.Fields.IncludeWithDefaultProperties( f => f.Id, f => f.Title, f => f.TypeAsString, f => f.ReadOnlyField, f => f.Hidden, f => f.InternalName, f => f.DefaultValue, f => f.Required)) ); web.Context.ExecuteQueryRetry(); var allLists = new List <List>(); var listsToProcess = lists.AsEnumerable().Where(l => l.Hidden == false || l.Hidden == creationInfo.IncludeHiddenLists).ToArray(); foreach (var siteList in listsToProcess) { if (ShouldNotExtractList(creationInfo, siteList)) { continue; } var extractionConfig = creationInfo.ExtractConfiguration.Lists.Lists.FirstOrDefault(e => e.Title.Equals(siteList.Title) || siteList.RootFolder.ServerRelativeUrl.EndsWith(e.Title, StringComparison.InvariantCultureIgnoreCase)); CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(); Model.Configuration.Lists.Lists.ExtractListsQueryConfiguration queryConfig = null; if (extractionConfig.Query != null) { queryConfig = extractionConfig.Query; camlQuery = new CamlQuery(); if (string.IsNullOrEmpty(queryConfig.CamlQuery)) { queryConfig.CamlQuery = "<Order><FieldRef Name='ID' /></Order>"; } string viewXml = $"<View Scope=\"RecursiveAll\"><Query>{queryConfig.CamlQuery}</Query>"; if (queryConfig.IncludeAttachments && siteList.EnableAttachments) { if (queryConfig.ViewFields == null) { queryConfig.ViewFields = new List <string>(); } else if (!queryConfig.ViewFields.Contains("Attachments")) { queryConfig.ViewFields.Add("Attachments"); } } if (queryConfig.ViewFields != null && queryConfig.ViewFields.Count > 0) { viewXml += "<ViewFields>"; foreach (var viewField in queryConfig.ViewFields) { viewXml += $"<FieldRef Name='{viewField}' />"; } viewXml += "</ViewFields>"; } if (queryConfig.RowLimit > 0 || queryConfig.PageSize > 0) { viewXml += $"<RowLimit{(queryConfig.PageSize > 0 ? " Paged=\"TRUE\"" : "")}>{(queryConfig.PageSize > 0 ? queryConfig.PageSize : queryConfig.RowLimit)}</RowLimit>"; } viewXml += "</View>"; camlQuery.ViewXml = viewXml; } var listInstance = template.Lists.FirstOrDefault(l => siteList.RootFolder.ServerRelativeUrl.Equals(UrlUtility.Combine(web.ServerRelativeUrl, l.Url))); if (listInstance != null) { do { camlQuery.ListItemCollectionPosition = RetrieveItems(web, template, creationInfo, scope, siteList, extractionConfig, camlQuery, queryConfig, listInstance, siteList.ContentTypes[0].Id.StringValue); } while (camlQuery.ListItemCollectionPosition != null); } } } return(template); }
public ApiList <SPListItem> List(SPList list, [Documentation(Name = "ViewFields", Type = typeof(List <string>)), Documentation(Name = "ViewQuery", Type = typeof(string))] IDictionary options) { if (list == null) { return(new ApiList <SPListItem>()); } var cacheId = string.Concat(SharePointListItemCacheId, string.Format("{0}_{1}", list.SPWebUrl, list.Id)); var cacheList = (ApiList <SPListItem>)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process); if (cacheList == null) { using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl))) { var sharepointList = clientContext.ToList(list.Id); ListItemCollection listItemCollection; if (options != null && options["ViewQuery"] != null) { var camlQuery = new CamlQuery { ViewXml = String.Format("<View><Query>{0}</Query></View>", options["ViewQuery"]) }; listItemCollection = sharepointList.GetItems(camlQuery); } else { listItemCollection = sharepointList.GetItems(CamlQuery.CreateAllItemsQuery()); } IEnumerable <ListItem> items; if (options != null && options["ViewFields"] != null) { var viewFields = (List <string>)options["ViewFields"]; items = clientContext.LoadQuery(listItemCollection.Include(CreateListItemLoadExpressions(viewFields))); } else { items = clientContext.LoadQuery(listItemCollection.Include(SPItemService.InstanceQuery)); } var userItemCollection = clientContext.Web.SiteUserInfoList.GetItems(CamlQuery.CreateAllItemsQuery()); IEnumerable <SP.ListItem> userItems = clientContext.LoadQuery( userItemCollection.Include(new Expression <Func <ListItem, object> >[] { item => item.Id, item => item["Picture"] })); var fieldsQuery = clientContext.LoadQuery(sharepointList.Fields.Where(field => !field.Hidden && field.Group != "_Hidden")); clientContext.ExecuteQuery(); var apiList = new ApiList <SPListItem>(); var fields = fieldsQuery.ToList(); foreach (var item in items) { apiList.Add(new SPListItem(item, fields)); } cacheService.Put(cacheId, apiList, CacheScope.Context | CacheScope.Process, new[] { GetTag(list.Id) }, CacheTimeOut); return(apiList); } } return(cacheList); }
protected override void ExecuteCmdlet() { var list = List.GetList(SelectedWeb); if (Id != -1) { var listItem = list.GetItemById(Id); if (Fields != null) { foreach (var field in Fields) { ClientContext.Load(listItem, l => l[field]); } } else { ClientContext.Load(listItem); } ClientContext.ExecuteQueryRetry(); WriteObject(listItem); } else if (UniqueId != null && UniqueId.Id != Guid.Empty) { CamlQuery query = new CamlQuery(); var viewFieldsStringBuilder = new StringBuilder(); if (Fields != null) { viewFieldsStringBuilder.Append("<ViewFields>"); foreach (var field in Fields) { viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field); } viewFieldsStringBuilder.Append("</ViewFields>"); } query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='GUID'/><Value Type='Guid'>{0}</Value></Eq></Where></Query>{1}</View>", UniqueId.Id, viewFieldsStringBuilder); var listItem = list.GetItems(query); ClientContext.Load(listItem); ClientContext.ExecuteQueryRetry(); WriteObject(listItem); } else if (Query != null) { CamlQuery query = new CamlQuery { ViewXml = Query }; var listItems = list.GetItems(query); ClientContext.Load(listItems); ClientContext.ExecuteQueryRetry(); WriteObject(listItems, true); } else { var query = CamlQuery.CreateAllItemsQuery(); if (Fields != null) { var queryElement = XElement.Parse(query.ViewXml); var viewFields = queryElement.Descendants("ViewFields").FirstOrDefault(); if (viewFields != null) { viewFields.RemoveAll(); } else { viewFields = new XElement("ViewFields"); queryElement.Add(viewFields); } foreach (var field in Fields) { XElement viewField = new XElement("FieldRef"); viewField.SetAttributeValue("Name", field); viewFields.Add(viewField); } query.ViewXml = queryElement.ToString(); } var listItems = list.GetItems(query); ClientContext.Load(listItems); ClientContext.ExecuteQueryRetry(); WriteObject(listItems, true); } }
public IEnumerable <CalendarItem> GetCalendarItems(string siteUrl, string listName) { List <CalendarItem> calItems = new List <CalendarItem>(); string realm = ConfigurationManager.AppSettings["ida:Audience"]; string appId = ConfigurationManager.AppSettings["ida:ClientId"]; string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret)) { try { List oList = context.Web.Lists.GetByTitle(listName); CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100); ListItemCollection listItems = oList.GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); foreach (ListItem oListItem in listItems) { var fields = oListItem.FieldValues; var calItem = new CalendarItem(); foreach (var field in fields) { switch (field.Key) { case "ID": calItem.ID = Convert.ToInt32(field.Value); break; case "Title": calItem.Title = field.Value.ToString(); break; case "Description": calItem.Description = WebUtility.HtmlDecode(field.Value.ToString()); break; case "FileDirRef": calItem.FileDirRef = field.Value.ToString(); break; case "FileRef": calItem.FileRef = field.Value.ToString(); break; case "Location": calItem.Location = field.Value.ToString(); break; case "Created": calItem.Created = DateTime.Parse(field.Value.ToString()); break; case "Modified": calItem.Modified = DateTime.Parse(field.Value.ToString()); break; case "EndDate": calItem.EndDate = DateTime.Parse(field.Value.ToString()); break; case "EventDate": calItem.EventDate = DateTime.Parse(field.Value.ToString()); break; case "Author": FieldUserValue itemAuthor = field.Value as FieldUserValue; var author = new Models.UserModel(); author.Email = itemAuthor.Email; author.LookupId = itemAuthor.LookupId; author.LookupValue = itemAuthor.LookupValue; calItem.Author = author; break; case "Editor": FieldUserValue itemEditor = field.Value as FieldUserValue; var editor = new Models.UserModel(); editor.Email = itemEditor.Email; editor.LookupId = itemEditor.LookupId; editor.LookupValue = itemEditor.LookupValue; calItem.Editor = editor; break; } } calItem.ListName = listName; calItem.SiteUrl = siteUrl; calItems.Add(calItem); } return(calItems); } catch (Exception ex) { return(null); } } }
protected void btnScenario1_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); string ContosoWebPageCTId = "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4002CA362904d604607B0F1E39BE59D76E0"; using (var clientContext = spContext.CreateUserClientContextForSPHost()) { // Create content type for the page layouts if (!clientContext.Web.ContentTypeExistsByName("ContosoWebPage")) { // Let's create a content type which is inherited from oob welcome page clientContext.Web.CreateContentType("ContosoWebPage", ContosoWebPageCTId, "Contoso Web Content Types"); } // Upload page layouts to the master page gallery clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksBelow.aspx")), "Contoso Links Below", "Contoso Links Below", ContosoWebPageCTId); clientContext.Web.DeployPageLayout(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/ContosoLinksRight.aspx")), "Contoso Links Right", "Contoso Links Right", ContosoWebPageCTId); // Add content type to Pages library clientContext.Web.AddContentTypeToListById("Pages", ContosoWebPageCTId); // Deploy addditional JS to site DeployJStoContosoFoldersInStyleLibrary(clientContext); // Create a new page based on the page layout List pages = clientContext.Web.Lists.GetByTitle("Pages"); Microsoft.SharePoint.Client.ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(pages); clientContext.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "demo")); clientContext.ExecuteQuery(); // Check if page already exists and delete old version if existed if (existingPages != null && existingPages.Count > 0) { existingPages[0].DeleteObject(); clientContext.ExecuteQuery(); } // Solve layout and create new page Microsoft.SharePoint.Client.ListItem pageLayout = clientContext.Web.GetPageLayoutListItemByName("ContosoLinksRight.aspx"); PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(clientContext, clientContext.Web); PublishingPageInformation publishingPageInfo = new PublishingPageInformation(); publishingPageInfo.Name = "demo.aspx"; publishingPageInfo.PageLayoutListItem = pageLayout; PublishingPage publishingPage = pWeb.AddPublishingPage(publishingPageInfo); if (pages.ForceCheckout || pages.EnableVersioning) { publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); publishingPage.ListItem.File.Publish(string.Empty); if (pages.EnableModeration) { publishingPage.ListItem.File.Approve(string.Empty); } } clientContext.ExecuteQuery(); lblStatus1.Text = string.Format("New content type created, page layouts uploaded and new page created to the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString() + "/pages/demo.aspx"); } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // Extract the Home Page web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url); var homepageUrl = web.RootFolder.WelcomePage; if (string.IsNullOrEmpty(homepageUrl)) { homepageUrl = "Default.aspx"; } var welcomePageUrl = UrlUtility.Combine(web.ServerRelativeUrl, homepageUrl); List pagesLibrary = web.GetPagesLibrary(); var items = pagesLibrary.GetItems(CamlQuery.CreateAllItemsQuery()); web.Context.Load(items, i => i.Include(it => it.DisplayName, it => it.File)); web.Context.ExecuteQuery(); foreach (ListItem listItem in items) { try { //var listItem = file.EnsureProperty(f => f.ListItemAllFields); if (listItem != null) { File file = listItem.File; if (listItem.FieldValues.ContainsKey("WikiField") && listItem.FieldValues["WikiField"] != null) { // Wiki page var fullUri = new Uri(UrlUtility.Combine(new Uri(web.Url).GetLeftPart(UriPartial.Authority), file.ServerRelativeUrl)); var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'); LimitedWebPartManager limitedWPManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); web.Context.Load(limitedWPManager); var webParts = web.GetWebParts(file.ServerRelativeUrl); var page = new Page() { Layout = WikiPageLayout.Custom, Overwrite = true, Url = Tokenize(fullUri.PathAndQuery, web.Url), }; var pageContents = listItem.FieldValues["WikiField"].ToString(); Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)"); if (regexClientIds.IsMatch(pageContents)) { foreach (Match webPartMatch in regexClientIds.Matches(pageContents)) { String serverSideControlId = webPartMatch.Groups["ControlId"].Value; try { String serverSideControlIdToSearchFor = String.Format("g_{0}", serverSideControlId.Replace("-", "_")); WebPartDefinition webPart = limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor); web.Context.Load(webPart, wp => wp.Id, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex ); web.Context.ExecuteQueryRetry(); var webPartxml = TokenizeWebPartXml(web, web.GetWebPartXml(webPart.Id, file.ServerRelativeUrl)); page.WebParts.Add(new Model.WebPart() { Title = webPart.WebPart.Title, Contents = webPartxml, Order = (uint)webPart.WebPart.ZoneIndex, Row = 1, // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly. Column = 1 // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly. }); pageContents = Regex.Replace(pageContents, serverSideControlId, string.Format("{{webpartid:{0}}}", webPart.WebPart.Title), RegexOptions.IgnoreCase); } catch (ServerException) { scope.LogWarning("Found a WebPart ID which is not available on the server-side. ID: {0}", serverSideControlId); } } } page.Fields.Add("WikiField", pageContents); template.Pages.Add(page); // Set the homepage if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION)) { // Not a wikipage template = GetFileContents(web, template, file.ServerRelativeUrl, creationInfo, scope); if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { WriteMessage(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning); scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION); } } } } catch (ServerException ex) { if (ex.ServerErrorCode != -2146232832) { throw; } else { if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION)) { // Page does not belong to a list, extract the file as is template = GetFileContents(web, template, welcomePageUrl, creationInfo, scope); if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { WriteMessage(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning); scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION); } } } } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
private void ProcessAction(List <Web> webs) { bool processAction; int webCount = webs.Count; for (int webIndex = 0; webIndex < webCount; webIndex++) { Web currentWeb = webs[webIndex]; //Update current connection context to the web that is beeing process //So commands like Get-PnPList returns the correct list for the current web beeing proccess SPOnlineConnection.CurrentConnection.Context = (ClientContext)currentWeb.Context; currentWeb.LoadProperties(_webActions.Properties); UpdateWebProgressBar(webs, webIndex, webCount, 0, _totalExecutionTimeStopWatch); if (!_webActions.ShouldProcessAnyAction(currentWeb)) { continue; } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessAction, _webActions.Action, ref _currentWebsProcessed, ref _averageWebTime, ref _averageShouldProcessWebTime); if (!processAction) { continue; } if (_listActions.HasAnyAction || _listItemActions.HasAnyAction) { ListCollection lists = currentWeb.Lists; int listCount = lists.Count; for (int listIndex = 0; listIndex < listCount; listIndex++) { List currentList = lists[listIndex]; currentList.LoadProperties(_listActions.Properties); if (_isListNameSpecified && !currentList.Title.Equals(_listName, StringComparison.CurrentCultureIgnoreCase)) { continue; } UpdateWebProgressBar(webs, webIndex, webCount, listIndex, _totalExecutionTimeStopWatch); UpdateListProgressBar(lists, listIndex, listCount); processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessAction, _listActions.Action, ref _currentListsProcessed, ref _averageListTime, ref _averageShouldProcessListTime); if (!processAction) { continue; } if (_listItemActions.HasAnyAction) { ListItemCollection listItems = currentList.GetItems(CamlQuery.CreateAllItemsQuery()); currentList.Context.Load(listItems); currentList.Context.ExecuteQueryRetry(); int listItemCount = listItems.Count; for (int listItemIndex = 0; listItemIndex < listItemCount; listItemIndex++) { ListItem currentListItem = listItems[listItemIndex]; currentListItem.LoadProperties(_listItemActions.Properties); WriteIterationProgress(ListItemProgressBarId, ListProgressBarId, "Iterating list items", GetTitle(currentListItem), listItemIndex, listItemCount, CalculateRemainingTimeForListItems(listItemCount, listItemIndex)); ProcessAction(currentListItem, GetTitle, _listItemActions.Properties, _listItemActions.ShouldProcessAction, _listItemActions.Action, ref _currentListItemsProcessed, ref _averageListItemTime, ref _averageShouldProcessListItemTime); } CompleteProgressBar(ListItemProgressBarId); } processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessPostAction, _listActions.PostAction, ref _currentPostListsProcessed, ref _averagePostListTime, ref _averageShouldProcessPostListTime); } CompleteProgressBar(ListProgressBarId); } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessPost, _webActions.PostAction, ref _currentPostWebsProcessed, ref _averagePostWebTime, ref _averageShouldProcessPostWebTime); } CompleteProgressBar(WebProgressBarId); }
/// <summary> /// Process the request /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); siteColumns = new List <SPFieldDefinitionModel>(); try { //Load list var siteUrl = this.ClientContext.Url; var listInSite = this.ClientContext.Web.Lists.GetByTitle(ListTitle); this.ClientContext.Load(listInSite); this.ClientContext.ExecuteQuery(); //#TODO: Provision datamigrated column for holder var camlWhereClause = CAML.Neq(CAML.FieldValue("DataMigrated", "Integer", "1")); // get ezforms site and query the list for approved requests ListItemCollectionPosition ListItemCollectionPosition = null; var camlQuery = CamlQuery.CreateAllItemsQuery(); camlQuery.ViewXml = string.Format("<View Scope='RecursiveAll'><Query><Where>{0}</Where>", camlWhereClause); camlQuery.ViewXml += "<RowLimit>50</RowLimit>"; camlQuery.ViewXml += "</Query></View>"; camlQuery.ListItemCollectionPosition = ListItemCollectionPosition; var output = new List <object>(); while (true) { camlQuery.ListItemCollectionPosition = ListItemCollectionPosition; var spListItems = listInSite.GetItems(camlQuery); this.ClientContext.Load(spListItems, lti => lti.ListItemCollectionPosition, lti => lti.IncludeWithDefaultProperties(lnc => lnc.Id, lnc => lnc.ContentType)); this.ClientContext.ExecuteQuery(); ListItemCollectionPosition = spListItems.ListItemCollectionPosition; foreach (var requestItem in spListItems) { var requestId = requestItem.Id; ListItem _item = listInSite.GetItemById(requestId); //#TODO: add list item column includes for specific columns of operation ClientContext.Load(_item); ClientContext.ExecuteQuery(); try { output.Add(ProcessListItem(_item)); } catch (Exception e) { LogError(e, "Failed to update list item {0}", e.Message); } } if (ListItemCollectionPosition == null) { break; } } LogVerbose("Writing objects to memory stream."); output.ForEach(s => WriteObject(s)); } catch (Exception ex) { LogError(ex, "Migrate failed for list items MSG:{0}", ex.Message); } }
/// <summary> /// Execute the command and query the app catalog scanning for App permissions /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var models = new List <SPAppManifestModel>(); try { // Set connection to app catalog var appCatalogListName = "App Requests"; var appCatalogSiteContext = this.ClientContext.Clone(AppCatalogUrl); var appCatalogWeb = appCatalogSiteContext.Web; var appCatalogList = appCatalogWeb.Lists.GetByTitle(appCatalogListName); appCatalogSiteContext.Load(appCatalogWeb); appCatalogSiteContext.Load(appCatalogList); appCatalogSiteContext.ExecuteQueryRetry(); LogVerbose("App Catalog list: {0}", appCatalogList.Title); ListItemCollectionPosition itemPosition = null; var tmpFalg = true; var viewFields = new string[] { "Title", "AppPublisher", "AppRequester", "AppRequestJustification", "AppRequestIsSiteLicense", "AppRequestPermissionXML", "AppRequestStatus", "AssetID" }; var camlQuery = CamlQuery.CreateAllItemsQuery(50, viewFields); while (tmpFalg) { camlQuery.ListItemCollectionPosition = itemPosition; ListItemCollection spListItems = appCatalogList.GetItems(camlQuery); appCatalogSiteContext.Load(spListItems); appCatalogSiteContext.ExecuteQueryRetry(); itemPosition = spListItems.ListItemCollectionPosition; var tmpTitle = string.Empty; foreach (var item in spListItems) { var itemTitle = item.RetrieveListItemValue("Title"); if (!itemTitle.Equals(tmpTitle, StringComparison.CurrentCultureIgnoreCase)) { var model = new SPAppManifestModel() { Title = itemTitle, AssetId = item.RetrieveListItemValue("AssetID"), AppRequestStatus = item.RetrieveListItemValue("AppRequestStatus"), AppRequestIsSiteLicense = item.RetrieveListItemValue("AppRequestIsSiteLicense") }; LogVerbose("Scanning {0}", itemTitle); var xmlFromField = item.RetrieveListItemValue("AppRequestPermissionXML"); if (!string.IsNullOrEmpty(xmlFromField)) { var appXml = XDocument.Parse(string.Format("<appxml xmlns=\"{1}\">{0}</appxml>", xmlFromField, "http://schemas.microsoft.com/sharepoint/2012/app/manifest"), LoadOptions.None); var appType = appXml.Root.GetType(); var appRequestsName = XName.Get("AppPermissionRequests", "http://schemas.microsoft.com/sharepoint/2012/app/manifest"); var appRequests = appXml.Root.Element(appRequestsName); if (appRequests != null) { var appRequestName = XName.Get("AppPermissionRequest", "http://schemas.microsoft.com/sharepoint/2012/app/manifest"); var appRequestItems = appRequests.Elements(appRequestName); foreach (var appItem in appRequestItems) { var appRight = appItem.Attribute("Right").Value; var appScope = appItem.Attribute("Scope").Value; model.AppPermissions.Add(new SPAppScopePermissionModel() { AppRights = appRight, AppScope = appScope }); } } } models.Add(model); } } if (itemPosition == null) { break; } } // Write the app information to the console models.ForEach(app => WriteObject(app)); } catch (Exception ex) { LogError(ex, "Failed in QueryAppMonitor for {0}", this.AppCatalogUrl); } }
static void Main(string[] args) { // Office 365 Multi-tenant sample ClientContext cc = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com/sites/130020", "*****@*****.**", GetPassWord()); //if (!cc.Site.IsInPlaceRecordsManagementActive()) //{ // cc.Site.EnableSiteForInPlaceRecordsManagement(); //} FileStream ostrm; StreamWriter writer = null; TextWriter oldOut = Console.Out; string fileName = @"c:\temp\recordsmanagement.txt"; //Redirect console to file if needed if (!toConsole) { try { if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } ostrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter(ostrm); } catch (Exception e) { Console.WriteLine("Cannot open recordsmanagement.txt for writing"); Console.WriteLine(e.Message); return; } Console.SetOut(writer); } List ecm = cc.Web.GetListByTitle("Documents"); //List ecm = cc.Web.GetListByTitle("ECMTest"); cc.Load(ecm.RootFolder, p => p.Properties); cc.Load(ecm.EventReceivers); cc.Load(cc.Web, t => t.AllProperties); cc.ExecuteQuery(); Console.WriteLine("Web properties:"); foreach (var prop in cc.Web.AllProperties.FieldValues) { Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : "")); } Console.WriteLine("======================================================="); Console.WriteLine("Rootfolder props = list props:"); foreach (var prop in ecm.RootFolder.Properties.FieldValues) { Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : "")); } Console.WriteLine("======================================================="); Console.WriteLine("List event receivers:"); foreach (var eventReceiver in ecm.EventReceivers) { Console.WriteLine(String.Format("Name: {0}", eventReceiver.ReceiverName)); Console.WriteLine(String.Format("Type: {0}", eventReceiver.EventType)); Console.WriteLine(String.Format("Assembly: {0}", eventReceiver.ReceiverAssembly)); Console.WriteLine(String.Format("Class: {0}", eventReceiver.ReceiverClass)); Console.WriteLine(String.Format("Url: {0}", eventReceiver.ReceiverUrl)); Console.WriteLine(String.Format("Sequence: {0}", eventReceiver.SequenceNumber)); Console.WriteLine(String.Format("Synchronisation: {0}", eventReceiver.Synchronization)); } Console.WriteLine("======================================================="); Console.WriteLine("List items:"); CamlQuery query = CamlQuery.CreateAllItemsQuery(100); ListItemCollection items = ecm.GetItems(query); cc.Load(items); cc.ExecuteQuery(); foreach (ListItem listItem in items) { foreach (var field in listItem.FieldValues) { Console.WriteLine("{0} : {1}", field.Key, field.Value); } Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++"); } if (!toConsole) { writer.Flush(); Console.Out.Close(); Console.SetOut(oldOut); } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
static void Main(string[] args) { #region Site Details - Read the details from app.config string URL = ConfigurationManager.AppSettings["URL"]; string username = ConfigurationManager.AppSettings["username"]; string password = ConfigurationManager.AppSettings["password"]; string listName = ConfigurationManager.AppSettings["listName"]; string viewName = ConfigurationManager.AppSettings["viewName"]; string path = ConfigurationManager.AppSettings["path"]; #endregion using (ClientContext context = new ClientContext(URL)) { SecureString securePassword = GetSecureString(password); context.Credentials = new SharePointOnlineCredentials(username, securePassword); List list = context.Web.Lists.GetByTitle(listName); context.Load(list); context.ExecuteQuery(); View view = list.Views.GetByTitle(viewName); context.Load(view); context.ExecuteQuery(); CamlQuery query = CamlQuery.CreateAllItemsQuery(); query.ViewXml = "<View><Query>" + view.ViewQuery + "</Query></View>"; ListItemCollection items = list.GetItems(query); context.Load(items); context.ExecuteQuery(); //Console.WriteLine("Total Count: " + items.Count); /* foreach (ListItem item in items) * { * Console.WriteLine("Title " + item["Title"]); * } * */ #region -- Datatable //new datatable DataTable data = new DataTable(); //add column names - (Column headers as needed in csv file) data.Columns.Add("Title", typeof(string)); data.Columns.Add("Actual_Units_Scanned", typeof(Int32)); data.Columns.Add("Attainment", typeof(double)); data.Columns.Add("Created_By", typeof(string)); //add each row to datarow - (internal name of column from URL) foreach (ListItem item in items) { data.Rows.Add(item["LineLead"], item["Actual_x0020_Units_x0020_Scanned"], item["Attainment"], item["Created"]); } //Just to display the data table foreach (DataRow row in data.Rows) { Console.WriteLine(); for (int x = 0; x < data.Columns.Count; x++) { Console.Write(row[x].ToString() + " "); } } #endregion #region --generate csv PutDataTableToCsv(path, data, true); #endregion Console.ReadKey(); } }
/// <summary> /// Gets the list items of specified list based on CAML query. /// </summary> /// <param name="clientContext">Client context</param> /// <param name="listName">Name of the list</param> /// <param name="camlQuery">CAML Query that need to be executed on list</param> /// <returns>Collection of list items</returns> public static ListItemCollection GetData(ClientContext clientContext, string listName, string camlQuery = null) { ListItemCollection listItemCollection = null; if (null != clientContext && !string.IsNullOrWhiteSpace(listName)) { try { CamlQuery query = new CamlQuery(); if (!string.IsNullOrWhiteSpace(camlQuery)) { query.ViewXml = camlQuery; listItemCollection = clientContext.Web.Lists.GetByTitle(listName).GetItems(query); } else { listItemCollection = clientContext.Web.Lists.GetByTitle(listName).GetItems(CamlQuery.CreateAllItemsQuery()); } clientContext.Load(listItemCollection); clientContext.ExecuteQuery(); } catch (Exception) { listItemCollection = null; throw; } } return(listItemCollection); }
public async Task StartAsync(IDialogContext context) { //context.Wait(MessageReceivedAsync); //return Task.CompletedTask; ClientContext ctx = new ClientContext("https://wbsharepoint.sharepoint.com/sites/POCs/"); Web web = ctx.Web; string pwd = ConfigurationManager.AppSettings["SPPassword"].ToString(); string userName = ConfigurationManager.AppSettings["SPUserName"].ToString(); SecureString passWord = new SecureString(); foreach (char c in pwd.ToCharArray()) { passWord.AppendChar(c); } ctx.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord); List quizList = ctx.Web.Lists.GetByTitle("SPQuiz"); CamlQuery query = CamlQuery.CreateAllItemsQuery(100); query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Category'/>" + "<Value Type='Text'>SharePoint</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>"; ListItemCollection items = quizList.GetItems(query); ctx.Load(items); ctx.ExecuteQuery(); foreach (ListItem listItem in items) { // We have all the list item data. For example, Title. quiz.Add(new QuizEntity { Question = listItem["Title"].ToString(), Option1 = listItem["Option1"].ToString(), Option2 = listItem["Option2"].ToString(), Option3 = listItem["Option3"]?.ToString(), Option4 = listItem["Option4"]?.ToString(), Answer = listItem["Answer"].ToString() }); } var heroCard = new ThumbnailCard { Title = "SharePoint", Subtitle = "Welcome to SharePoint Quiz", Text = "Total number of questions are " + quiz.Count + ". Type go to start the Quiz.", Images = new List <CardImage> { new CardImage("https://techquizbot.azurewebsites.net/images/SPIcon.png") }, Buttons = new List <CardAction> { new CardAction(ActionTypes.ImBack, "Take Quiz", value: "Take Quiz") } }; var message = context.MakeMessage(); message.Attachments.Add(heroCard.ToAttachment()); await context.PostAsync(message); context.Wait(MessageReceivedStartQuestions); }
/// <summary> /// Analyses a web for it's blog page usage /// </summary> /// <param name="cc">ClientContext instance used to retrieve blog data</param> /// <returns>Duration of the blog analysis</returns> public override TimeSpan Analyze(ClientContext cc) { try { // Is this a blog site if (cc.Web.WebTemplate.Equals("BLOG", StringComparison.InvariantCultureIgnoreCase)) { var web = cc.Web; base.Analyze(cc); BlogWebScanResult blogWebScanResult = new BlogWebScanResult() { SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, WebRelativeUrl = this.SiteUrl.Replace(this.SiteCollectionUrl, ""), }; // Log used web template if (web.WebTemplate != null) { blogWebScanResult.WebTemplate = $"{web.WebTemplate}#{web.Configuration}"; } // Load additional web properties web.EnsureProperty(p => p.Language); blogWebScanResult.Language = web.Language; // Get the blog page list List blogList = null; var lists = web.GetListsToScan(); if (lists != null) { blogList = lists.Where(p => p.BaseTemplate == (int)ListTemplateType.Posts).FirstOrDefault(); } // Query the blog posts if (blogList != null) { CamlQuery query = CamlQuery.CreateAllItemsQuery(10000, new string[] { "Title", "Body", "NumComments", "PostCategory", "PublishedDate", "Modified", "Created", "Editor", "Author" }); var pages = blogList.GetItems(query); cc.Load(pages); cc.ExecuteQueryRetry(); if (pages != null) { blogWebScanResult.BlogPageCount = pages.Count; blogWebScanResult.LastRecentBlogPageChange = blogList.LastItemUserModifiedDate; blogWebScanResult.LastRecentBlogPagePublish = blogList.LastItemUserModifiedDate; foreach (var page in pages) { string pageUrl = null; try { if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString())) { pageUrl = page[FileRefField].ToString().ToLower(); } else { //skip page continue; } BlogPageScanResult blogPageScanResult = new BlogPageScanResult() { SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, WebRelativeUrl = blogWebScanResult.WebRelativeUrl, PageRelativeUrl = pageUrl, }; if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString())) { blogPageScanResult.PageTitle = page["Title"].ToString(); } // Add modified information blogPageScanResult.ModifiedBy = page.LastModifiedBy(); blogPageScanResult.ModifiedAt = page.LastModifiedDateTime(); blogPageScanResult.PublishedDate = page.LastPublishedDateTime(); if (blogPageScanResult.ModifiedAt > blogWebScanResult.LastRecentBlogPageChange) { blogWebScanResult.LastRecentBlogPageChange = blogPageScanResult.ModifiedAt; } if (blogPageScanResult.PublishedDate > blogWebScanResult.LastRecentBlogPagePublish) { blogWebScanResult.LastRecentBlogPagePublish = blogPageScanResult.PublishedDate; } if (!this.ScanJob.BlogPageScanResults.TryAdd($"blogScanResult.PageURL.{Guid.NewGuid()}", blogPageScanResult)) { ScanError error = new ScanError() { Error = $"Could not add blog page scan result for {blogPageScanResult.SiteColUrl}", SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, Field1 = "BlogPageAnalyzer", }; this.ScanJob.ScanErrors.Push(error); } } catch (Exception ex) { ScanError error = new ScanError() { Error = ex.Message, SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, Field1 = "BlogPageAnalyzer", Field2 = ex.StackTrace, Field3 = pageUrl }; this.ScanJob.ScanErrors.Push(error); } } } } if (!this.ScanJob.BlogWebScanResults.TryAdd($"blogScanResult.WebURL.{Guid.NewGuid()}", blogWebScanResult)) { ScanError error = new ScanError() { Error = $"Could not add blog web scan result for {blogWebScanResult.SiteColUrl}", SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, Field1 = "BlogWebAnalyzer", }; this.ScanJob.ScanErrors.Push(error); } } } catch (Exception ex) { ScanError error = new ScanError() { Error = ex.Message, SiteColUrl = this.SiteCollectionUrl, SiteURL = this.SiteUrl, Field1 = "BlogPageAnalyzerMainLoop", Field2 = ex.StackTrace }; this.ScanJob.ScanErrors.Push(error); } finally { this.StopTime = DateTime.Now; } // return the duration of this scan return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks))); }
public void GetWebCreatorBuilder(SiteDefinition siteDefinition, WebCreator webDefinition, WebCreatorBuilderOptions options, ClientContext sourceContext, ClientContext baseContext) { _baseContext = baseContext; _sourceContext = sourceContext; var js = new JavaScriptSerializer(); var tempManifestFromBase = new AppManifestBase(); if (webDefinition == null) { throw new ArgumentException("WebDefinition is required!"); } if (options != null) { _options = options; } else { _options = new WebCreatorBuilderOptions(); } var web = _sourceContext.Web; _sourceContext.Site.EnsureProperties(p => p.RootWeb); var isRootWeb = web.Url == _sourceContext.Site.RootWeb.Url; if (isRootWeb) { webDefinition.Url = "/"; } //If this isn't the root and there isn't a value already, //set it to the site collection relative url by striping the rootweb url. else if (string.IsNullOrEmpty(webDefinition.Url)) { webDefinition.Url = web.ServerRelativeUrl.Substring(_sourceContext.Site.RootWeb.ServerRelativeUrl.Length); } //Ensure that the Url is valid per the structure of the site definition if (!ValidateUrl(siteDefinition, webDefinition)) { throw new InvalidOperationException( "Web definition is invalid because the url either doesn't match the collection key or because it doesn't respect the hierarchy!"); } if (siteDefinition.StorageType == StorageTypes.AzureStorage) { var storageInfo = siteDefinition.GetAzureStorageInfo(); webDefinition.AppManifest.SetAzureStorageInfo(storageInfo.Account, storageInfo.AccountKey, storageInfo.Container); } webDefinition.AppManifest.BaseFilePath = Path.GetFullPath(siteDefinition.BaseFilePath + (webDefinition.Url != "/" ? webDefinition.Url : string.Empty)); GetBaseWebDefinition(webDefinition, isRootWeb); var creatorBuilder = new CreatorBuilder(); creatorBuilder.VerboseNotify += (sender, args) => OnVerboseNotify(args.Message); if (_options.IncludeNavigation) { OnVerboseNotify("Getting top navigation"); creatorBuilder.GetCreator(_sourceContext, web, "Top", webDefinition.AppManifest, CreatorTypes.Navigation); creatorBuilder.GetCreator(_baseContext, _baseContext.Web, "Top", tempManifestFromBase, CreatorTypes.Navigation); if (js.Serialize(webDefinition.AppManifest.Navigation.TopNavigationNodes) == js.Serialize(tempManifestFromBase.Navigation.TopNavigationNodes)) { OnVerboseNotify("No differences in top nav found."); webDefinition.AppManifest.Navigation.TopNavigationNodes = null; } else { OnVerboseNotify("Differences in top nav found."); } OnVerboseNotify("Getting left navigation"); creatorBuilder.GetCreator(_sourceContext, web, "Left", webDefinition.AppManifest, CreatorTypes.Navigation); creatorBuilder.GetCreator(_baseContext, _baseContext.Web, "Left", tempManifestFromBase, CreatorTypes.Navigation); if (js.Serialize(webDefinition.AppManifest.Navigation.LeftNavigationNodes) == js.Serialize(tempManifestFromBase.Navigation.LeftNavigationNodes)) { OnVerboseNotify("No differences in left nav found."); webDefinition.AppManifest.Navigation.LeftNavigationNodes = null; } else { OnVerboseNotify("Differences in left nav found."); } } if (_options.IncludeRemoteEventReceivers) { OnVerboseNotify("Getting remote event receivers"); creatorBuilder.GetCreator(_sourceContext, web, string.Empty, webDefinition.AppManifest, CreatorTypes.RemoteEvents); if (webDefinition.AppManifest.RemoteEventRegistrationCreators == null || webDefinition.AppManifest.RemoteEventRegistrationCreators.Count == 0) { OnVerboseNotify("No remote event receivers found"); } else { creatorBuilder.GetCreator(_baseContext, _baseContext.Web, string.Empty, tempManifestFromBase, CreatorTypes.RemoteEvents); var matchingReceivers = webDefinition.AppManifest.RemoteEventRegistrationCreators.Where( s => tempManifestFromBase.RemoteEventRegistrationCreators.FirstOrDefault( b => b.ListTitle == s.ListTitle && b.EndpointUrl == s.EndpointUrl && b.EventReceiverType == s.EventReceiverType && b.Eventname == s.Eventname) != null).ToList(); if (matchingReceivers.Count != 0) { for (int c = matchingReceivers.Count; c >= 0; c--) { webDefinition.AppManifest.RemoteEventRegistrationCreators.Remove(matchingReceivers[c]); } } if (webDefinition.AppManifest.RemoteEventRegistrationCreators.Count == 0) { OnVerboseNotify("No remote event receivers found"); } else { OnVerboseNotify("Found remote event receivers"); } } } if (_options.IncludeLookAndFeel) { OnVerboseNotify("Getting look and feel"); creatorBuilder.GetCreator(_sourceContext, web, string.Empty, webDefinition.AppManifest, CreatorTypes.LookAndFeel); creatorBuilder.GetCreator(_baseContext, _baseContext.Web, string.Empty, tempManifestFromBase, CreatorTypes.LookAndFeel); if (webDefinition.AppManifest.LookAndFeel.SiteLogoUrl == tempManifestFromBase.LookAndFeel.SiteLogoUrl) { webDefinition.AppManifest.LookAndFeel.SiteLogoUrl = string.Empty; } else { OnVerboseNotify($"Setting SiteLogoUrl to {webDefinition.AppManifest.LookAndFeel.SiteLogoUrl}"); } if (webDefinition.AppManifest.LookAndFeel.AlternateCssUrl == tempManifestFromBase.LookAndFeel.AlternateCssUrl) { webDefinition.AppManifest.LookAndFeel.AlternateCssUrl = string.Empty; } else { OnVerboseNotify($"Setting AlternateCssUrl to {webDefinition.AppManifest.LookAndFeel.AlternateCssUrl}"); } if (webDefinition.AppManifest.LookAndFeel.CustomMasterPageUrl == tempManifestFromBase.LookAndFeel.CustomMasterPageUrl) { webDefinition.AppManifest.LookAndFeel.CustomMasterPageUrl = string.Empty; } else { OnVerboseNotify($"Setting CustomMasterPageUrl to {webDefinition.AppManifest.LookAndFeel.CustomMasterPageUrl}"); } if (webDefinition.AppManifest.LookAndFeel.DefaultMasterPageUrl == tempManifestFromBase.LookAndFeel.DefaultMasterPageUrl) { webDefinition.AppManifest.LookAndFeel.DefaultMasterPageUrl = string.Empty; } else { OnVerboseNotify($"Setting DefaultMasterPageUrl to {webDefinition.AppManifest.LookAndFeel.DefaultMasterPageUrl}"); } if (js.Serialize(webDefinition.AppManifest.LookAndFeel.CurrentComposedLook) == js.Serialize(tempManifestFromBase.LookAndFeel.CurrentComposedLook)) { webDefinition.AppManifest.LookAndFeel.CurrentComposedLook = null; } else { OnVerboseNotify("Found differences in current composed looks."); } } var customActionCreatorBuilder = new CustomActionCreatorBuilder(); customActionCreatorBuilder.VerboseNotify += (sender, args) => OnVerboseNotify(args.Message); if (_options.IncludeSiteCustomActions || _options.IncludeWebCustomActions) { if (_options.IncludeSiteCustomActions) { OnVerboseNotify("Getting site custom actions"); customActionCreatorBuilder.GetCustomActionCreators(_sourceContext, web, webDefinition.AppManifest, true); customActionCreatorBuilder.GetCustomActionCreators(_baseContext, _baseContext.Web, tempManifestFromBase, true); } if (_options.IncludeWebCustomActions) { OnVerboseNotify("Getting web custom actions"); customActionCreatorBuilder.GetCustomActionCreators(_sourceContext, web, webDefinition.AppManifest, false); customActionCreatorBuilder.GetCustomActionCreators(_baseContext, _baseContext.Web, tempManifestFromBase, false); } var matchingCustomActions = webDefinition.AppManifest.CustomActionCreators.Values.Where( sca => tempManifestFromBase.CustomActionCreators.Values.FirstOrDefault( bca => bca.SiteScope == sca.SiteScope && bca.Url == sca.Url && bca.CommandUIExtension == sca.CommandUIExtension && bca.Description == sca.Description && bca.Group == sca.Group && bca.ImageUrl == sca.ImageUrl && bca.Location == sca.Location && bca.RegistrationId == sca.RegistrationId && bca.ScriptBlock == sca.ScriptBlock && bca.ScriptSrc == sca.ScriptSrc && bca.Title == sca.Title) != null); foreach (var matchingCustomAction in matchingCustomActions) { webDefinition.AppManifest.CustomActionCreators.Remove(matchingCustomAction.Title); } if (webDefinition.AppManifest.CustomActionCreators.Count > 0) { OnVerboseNotify("Found custom actions."); } } if (_options.IncludeFilesFromTheseLibraries.Count > 0) { var fileCreatorBuilder = new FileCreatorBuilder(); fileCreatorBuilder.VerboseNotify += (sender, args) => OnVerboseNotify(args.Message); foreach (var libraryTitle in _options.IncludeFilesFromTheseLibraries) { var library = web.Lists.GetByTitle(libraryTitle); CamlQuery query = CamlQuery.CreateAllItemsQuery(2000); var fileItems = library.GetItems(query); _sourceContext.Load(fileItems, fi => fi.Include(f => f.FieldValuesAsText, f => f.File)); _sourceContext.ExecuteQuery(); foreach (var fileItem in fileItems) { //Folders items don't have an associated file if (fileItem.File.ServerObjectIsNull != null && fileItem.File.ServerObjectIsNull == false) { fileCreatorBuilder.GetFileCreator(_sourceContext, web, fileItem.File.ServerRelativeUrl.Replace(web.ServerRelativeUrl, ""), webDefinition.AppManifest.BaseFilePath, webDefinition.AppManifest, false); } } } } if (_options.IncludeFilesFromTheseFolders.Count > 0) { var baseUrl = web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl; var fileCreatorBuilder = new FileCreatorBuilder(); fileCreatorBuilder.VerboseNotify += (sender, args) => OnVerboseNotify(args.Message); foreach (var folder in _options.IncludeFilesFromTheseFolders) { var searchFolder = folder; if (!searchFolder.StartsWith("/")) { searchFolder = "/" + folder; } var containerFolderUrl = baseUrl + searchFolder; var spFolder = web.GetFolderByServerRelativeUrl(containerFolderUrl); _sourceContext.Load(spFolder, f => f.Files.Include(file => file.Name, file => file.ServerRelativeUrl)); _sourceContext.ExecuteQueryRetry(); foreach (var file in spFolder.Files) { fileCreatorBuilder.GetFileCreator(_sourceContext, web, file.ServerRelativeUrl.Replace(web.ServerRelativeUrl, ""), webDefinition.AppManifest.BaseFilePath, webDefinition.AppManifest, false); } } } }
private UserFromSharePoint GetUserById(ClientContext clientContext, int mentorId) { var users = new List <UserFromSharePoint>(); var splist = clientContext.Web.Lists.GetByTitle("yMentors"); clientContext.Load(splist, l => l.Title, l => l.RootFolder); clientContext.ExecuteQuery(); ListItemCollectionPosition ListItemCollectionPosition = null; var camlQuery = CamlQuery.CreateAllItemsQuery(); camlQuery.ViewXml = "<View><Query>"; camlQuery.ViewXml += string.Format("<Where><Eq><FieldRef Name='MentorName' LookupId='TRUE' /><Value Type='User'>{0}</Value></Eq></Where>", mentorId); camlQuery.ViewXml += @"<ViewFields> <FieldRef Name='MentorName'/> <FieldRef Name='MentorBio'/> <FieldRef Name='MentorCareer'/> <FieldRef Name='MentorTechnical'/> <FieldRef Name='MentorPresentation'/> <FieldRef Name='MentorSkillsTechnical'/> <FieldRef Name='MentorSkillsProfessional'/> <FieldRef Name='MentorComments'/> <FieldRef Name='MentorLkupCareer'/> <FieldRef Name='MentorLkupCommunity'/> <FieldRef Name='MentorLkupCountry'/> </ViewFields>"; camlQuery.ViewXml += "<RowLimit>1</RowLimit>"; camlQuery.ViewXml += "</Query></View>"; camlQuery.ListItemCollectionPosition = ListItemCollectionPosition; var splistitems = splist.GetItems(camlQuery); clientContext.Load(splistitems); clientContext.ExecuteQuery(); foreach (var requestItem in splistitems) { var displayName = RetrieveListItemUserValue(requestItem, "MentorName"); var bio = RetrieveListItemValue(requestItem, "MentorBio"); var career = RetrieveListItemLookupValue(requestItem, "MentorLkupCareer"); var country = RetrieveListItemLookupValue(requestItem, "MentorLkupCountry"); var community = RetrieveListMultiLookupValue(requestItem, "MentorLkupCommunity"); var boolTechnical = RetrieveListItemAsBoolValue(requestItem, "MentorTechnical"); var boolPresentation = RetrieveListItemAsBoolValue(requestItem, "MentorPresentation"); var boolCareer = RetrieveListItemAsBoolValue(requestItem, "MentorCareer"); var comments = RetrieveListItemValue(requestItem, "MentorComments"); var skillsTechnical = RetrieveListItemValue(requestItem, "MentorSkillsTechnical"); var skillsProfessional = RetrieveListItemValue(requestItem, "MentorSkillsProfessional"); users.Add(new UserFromSharePoint() { UserId = requestItem.Id, DisplayName = displayName.LookupValue, IdentityLoginId = displayName.LookupId, IdentityLogin = displayName.LookupId.ToString(), UserBio = bio, CareerOptions = boolCareer, TechnicalOptions = boolTechnical, PresentationOptions = boolPresentation, SkillsProfessional = skillsProfessional, SkillTechnical = skillsTechnical, Comments = comments, LkupCareerValue = career.LookupValue, LkupCountryValue = country.LookupValue, LkupCommunityValue = community.Select(s => s.LookupValue).ToList(), Email = displayName.Email }); } return(users.FirstOrDefault()); }
internal EntityList(DataContext dataContext, EntityListItemsCollection <TEntity> itemsCollection) { this.Query = CamlQuery.CreateAllItemsQuery(); this.m_AllItemsCollection = itemsCollection; this.m_DataContext = dataContext; }
async public Task <IHttpActionResult> SearchMentors([FromUri] SPHostedParameters parameters, string searchName) { var users = new List <UserWithSkillsModel>(); var userId = 0; try { var spContext = SharePointApiControllerAcsContextProvider.Current.GetSharePointContext(ControllerContext); //var searchName = parameters.searchName; using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { var spuser = clientContext.Web.CurrentUser; clientContext.Load(spuser, l => l.Title, l => l.Id); clientContext.ExecuteQuery(); userId = spuser.Id; var splist = clientContext.Web.Lists.GetByTitle("yMentors"); clientContext.Load(splist, l => l.Title, l => l.RootFolder); clientContext.ExecuteQuery(); var xmlQuery = @" <Where> <And> <Neq><FieldRef Name='MentorName' LookupId='TRUE' /><Value Type='User'>{1}</Value></Neq> <Or> <Or> <Contains><FieldRef Name='MentorName' /><Value Type='User'>{0}</Value></Contains> <Contains><FieldRef Name='MentorLkupCareer' /><Value Type='Lookup'>{0}</Value></Contains> </Or> <Contains><FieldRef Name='MentorSkillsTechnical' /><Value Type='Text'>{0}</Value></Contains> </Or> </And> </Where>"; ListItemCollectionPosition ListItemCollectionPosition = null; var camlQuery = CamlQuery.CreateAllItemsQuery(); camlQuery.ViewXml = "<View><Query>"; camlQuery.ViewXml += string.Format(xmlQuery, searchName, userId); camlQuery.ViewXml += "<ViewFields><FieldRef Name='MentorName'/><FieldRef Name='MentorBio'/><FieldRef Name='MentorLkupCareer'/></ViewFields>"; camlQuery.ViewXml += "<RowLimit>50</RowLimit>"; camlQuery.ViewXml += "</Query></View>"; camlQuery.ListItemCollectionPosition = ListItemCollectionPosition; var splistitems = splist.GetItems(camlQuery); clientContext.Load(splistitems); clientContext.ExecuteQuery(); foreach (var requestItem in splistitems) { var displayName = RetrieveListItemUserValue(requestItem, "MentorName"); var bio = RetrieveListItemValue(requestItem, "MentorBio"); var career = RetrieveListItemLookupValue(requestItem, "MentorLkupCareer"); users.Add(new UserWithSkillsModel() { UserId = requestItem.Id, IdentityObjectId = displayName.LookupId, DisplayName = displayName.LookupValue, UserBio = bio, CareerOptions = career.LookupValue }); } } } using (var pfeContext = new PfeContext()) { var profiles = await pfeContext.UserEntities.Where(w => w.DisplayName.Contains(searchName)).ToListAsync(); var relationships = await pfeContext.RelationshipEntities.Where(w => w.MentorLookup.DisplayName.Contains(searchName)).ToListAsync(); LogProvider.LogInformation("User found {0}", profiles.Count()); LogProvider.LogInformation("User has {0} relaitonships", relationships.Count()); } } catch (Exception ex) { LogProvider.LogError(ex, "failed to query mentor list for {0}", searchName); return(BadRequest(ex.Message)); } return(Ok(users)); }
public void CanProvisionObjects() { if (TestCommon.AppOnlyTesting()) { Assert.Inconclusive("Taxonomy tests are not supported when testing using app-only"); } var template = new ProvisioningTemplate(); var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; listInstance.FieldRefs.Add(new FieldRef() { Id = new Guid("23f27201-bee3-471e-b2e7-b64fd8b7ca38") }); using (var ctx = TestCommon.CreateClientContext()) { //Create term var taxSession = TaxonomySession.GetTaxonomySession(ctx); var termStore = taxSession.GetDefaultSiteCollectionTermStore(); // Termgroup termGroupId = Guid.NewGuid(); var termGroup = termStore.CreateGroup("Test_Group_" + DateTime.Now.ToFileTime(), termGroupId); ctx.Load(termGroup); var termSet = termGroup.CreateTermSet("Test_Termset_" + DateTime.Now.ToFileTime(), Guid.NewGuid(), 1033); ctx.Load(termSet); Guid termId = Guid.NewGuid(); string termName = "Test_Term_" + DateTime.Now.ToFileTime(); termSet.CreateTerm(termName, 1033, termId); Dictionary <string, string> dataValues = new Dictionary <string, string>(); dataValues.Add("Title", "Test"); dataValues.Add("TaxKeyword", $"{termName}|{termId.ToString()}"); DataRow dataRow = new DataRow(dataValues); listInstance.DataRows.Add(dataRow); template.Lists.Add(listInstance); var parser = new TokenParser(ctx.Web, template); // Create the List parser = new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); // Load DataRows new ObjectListInstanceDataRows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var items = list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(items, itms => itms.Include(item => item["Title"], i => i["TaxKeyword"])); ctx.ExecuteQueryRetry(); Assert.IsTrue(items.Count == 1); Assert.IsTrue(items[0]["Title"].ToString() == "Test"); //Validate taxonomy field data var value = items[0]["TaxKeyword"] as TaxonomyFieldValueCollection; Assert.IsNotNull(value); Assert.IsTrue(value[0].WssId > 0, "Term WSS ID not set correctly"); Assert.AreEqual(termName, value[0].Label, "Term label not set correctly"); Assert.AreEqual(termId.ToString(), value[0].TermGuid, "Term GUID not set correctly"); } }
public ActionResult ConnectToIssue(string issueTitle, string issueDescription, string assignTo, string documentName, string documentUrl, string status, string priority, string SPHostUrl) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var ctx = spContext.CreateUserClientContextForSPHost()) { User spUser = null; List list = ctx.Web.Lists.GetByTitle("MVCDemo Issue"); List Doclist = ctx.Web.Lists.GetByTitle("MVCDemo"); ctx.Load(list); ctx.Load(Doclist); ctx.ExecuteQuery(); UserCollection users = ctx.Web.SiteUsers; ctx.Load(users); ctx.ExecuteQuery(); //var test = list.GetItemById(3); //ctx.Load(test, include => include.File, include => include["DocumentIssue"], include => include["Status"], include => include["Priority"]); //ctx.ExecuteQuery(); //var s = test["Status"]; //var s2 = test["Priority"]; FieldUrlValue newUrl = new FieldUrlValue(); newUrl.Description = documentName; newUrl.Url = documentUrl; foreach (User user in users) { ctx.Load(user, include => include.Email); ctx.ExecuteQuery(); if (user.Email.ToLower() == assignTo.ToLower()) { spUser = user; } } ListItemCollection AllItems = Doclist.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(AllItems); ctx.ExecuteQuery(); ListItem itemToUse; foreach (ListItem singleItem in AllItems) { ctx.Load(singleItem, include => include.File.Name); ctx.ExecuteQuery(); if (singleItem.File.Name == documentName) { itemToUse = singleItem; } } // Attachment at = new Attachment(ctx, ); ListItem item = list.AddItem(new ListItemCreationInformation()); item["Title"] = issueTitle; item["Comment"] = issueDescription; item["AssignedTo"] = spUser; item["DocumentIssue"] = newUrl; item["Status"] = status; item["Priority"] = priority; item.Update(); ctx.ExecuteQuery(); var testing = list.GetItemById(1); ctx.Load(testing, include => include["AssignedTo"]); ctx.ExecuteQuery(); Console.WriteLine(testing); var usersss = testing["AssignedTo"]; return(View()); } }
/// <summary> /// Configures the variation settings /// 1. Go to "Site Actions" -> "Site settings" /// 2. Under "Site collection administration", click "Variation Settings". /// This method is for the page above to change or update the "Variation Settings" /// </summary> /// <param name="context">Context for SharePoint objects and operations</param> /// <param name="variationSettings">Variation settings</param> public static void ConfigureVariationsSettings(this ClientContext context, VariationInformation variationSettings) { if (variationSettings == null) { throw new ArgumentException("variationSettings"); } // Get current web Web web = context.Web; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); // Try to get _VarRelationshipsListId property from web property bag string variationListId = web.GetPropertyBagValueString(VARIATIONRELATIONSHIPSLISTID, string.Empty); if (!string.IsNullOrEmpty(variationListId)) { // Load the lists var lists = web.Lists; context.Load(lists); context.ExecuteQueryRetry(); // Get the "Variation RelationShips" List by id Guid varRelationshipsListId = new Guid(variationListId); var variationRelationshipList = lists.GetById(varRelationshipsListId); if (variationRelationshipList != null) { // Get the root folder Folder rootFolder = variationRelationshipList.RootFolder; context.Load(rootFolder); context.Load(variationRelationshipList); context.ExecuteQueryRetry(); // Automatic creation rootFolder.Properties["EnableAutoSpawnPropertyName"] = variationSettings.AutomaticCreation.ToString(); // Recreate Deleted Target Page; set to false to enable recreation rootFolder.Properties["AutoSpawnStopAfterDeletePropertyName"] = variationSettings.RecreateDeletedTargetPage.ToString(); // Update Target Page Web Parts rootFolder.Properties["UpdateWebPartsPropertyName"] = variationSettings.UpdateTargetPageWebParts.ToString(); // Resources rootFolder.Properties["CopyResourcesPropertyName"] = variationSettings.CopyResources.ToString(); // Notification rootFolder.Properties["SendNotificationEmailPropertyName"] = variationSettings.SendNotificationEmail.ToString(); // Configuration setting site template to be used for the top sites of each label rootFolder.Properties["SourceVarRootWebTemplatePropertyName"] = variationSettings.RootWebTemplate; rootFolder.Update(); context.ExecuteQueryRetry(); // Get the variationRelationshipList list items ListItemCollection collListItems = variationRelationshipList.GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(collListItems); context.ExecuteQueryRetry(); if (collListItems.Count > 0) { // Update the first item ListItem item = collListItems[0]; item["Deleted"] = false; item["ObjectID"] = web.ServerRelativeUrl; item["ParentAreaID"] = string.Empty; item.Update(); context.ExecuteQueryRetry(); } else { // Create the new item ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem olistItem = variationRelationshipList.AddItem(itemCreateInfo); // Root web relationship which should always have this guid olistItem["GroupGuid"] = new Guid("F68A02C8-2DCC-4894-B67D-BBAED5A066F9"); olistItem["Deleted"] = false; olistItem["ObjectID"] = web.ServerRelativeUrl; olistItem["ParentAreaID"] = string.Empty; olistItem.Update(); context.ExecuteQueryRetry(); } } } }
/// <summary> /// Update Pipeline list /// </summary> /// <param name="clientContextWeb">client context url</param> /// <param name="backupListTarget">list that is exported and deleted</param> /// <param name="excelIndexTarget">list that needs to be backedup</param> /// <param name=sharepointIndexTarget">doc library for backup of excel file</param> public UpdatePipelineList(string clientContextWeb, string backupListTarget, string excelIndexTarget, string sharepointIndexTarget) { System.IO.Directory.CreateDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\"); string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\"; string filter = "*.xlsx"; string[] files = Directory.GetFiles(folder, filter); string pipelinefile = "Pipeline.xlsx"; string dhcfile = "DHCUpdate.xlsx"; Regex regexPipeline = FindFilesPatternToRegex.Convert("*pipeline*.xlsx"); Regex regexDHC = FindFilesPatternToRegex.Convert("*dhc*.xlsx"); foreach (string file in files) { //Console.WriteLine("Inside File check: {0}", file); if (regexPipeline.IsMatch(file.ToLower())) { pipelinefile = file; } else if (regexDHC.IsMatch(file.ToLower())) { dhcfile = file; } } Console.WriteLine("------Update Pipeline ----------------"); //Console.WriteLine("Folder : {0}", folder); Console.WriteLine("Pipelinefile: {0}", pipelinefile); Console.WriteLine("DHCfile : {0}", dhcfile); Console.WriteLine("--------------------------------------"); log.Debug(string.Format("------ Update Pipeline Files ------")); log.Debug(string.Format("Pipelinefile: {0}", pipelinefile)); log.Debug(string.Format("DHCfile : {0}", dhcfile)); log.Debug(string.Format("---------------------------------------")); FileStream stream, streamDHC; try { //update for reading files stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read); //update for reading files streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read); } catch (Exception ex) { Console.WriteLine("Please close the excel file and press enter"); Console.ReadLine(); //update for reading files stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read); //update for reading files streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read); } IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(stream); reader.IsFirstRowAsColumnNames = true; DataSet ds = reader.AsDataSet(); IExcelDataReader readerDHC = ExcelReaderFactory.CreateOpenXmlReader(streamDHC); readerDHC.IsFirstRowAsColumnNames = true; DataSet dsDHC = readerDHC.AsDataSet(); DataRowSharepointMappingCollection mapping = MyRetriever.GetTheCollection(); DataRowSharepointMappingCollection mappingDHC = MyRetriever.GetTheCollection("DataRowDHCMappingsSection"); DataTable dt = ds.Tables[0]; DataColumn dcParent = dt.Columns["Opportunity Name"]; //using (var clientContext = new ClientContext(clientContextWeb)) using (ClientContext clientContext = ClaimClientContext.GetAuthenticatedContext(clientContextWeb)) { Web web = clientContext.Web; //------------------------------------ // GetItems for PipeLine list //------------------------------------ // DEV NOTES: // Aug. 4, 2017 - Removed 2000 limitation from CamlQueries (MAT) // List oldList = web.Lists.GetByTitle(backupListTarget); CamlQuery query = CamlQuery.CreateAllItemsQuery(); ListItemCollection oldItems = oldList.GetItems(query); clientContext.Load(oldItems); var listFields = oldList.Fields; clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName, field => field.ReadOnlyField, field => field.StaticName)); clientContext.ExecuteQuery(); //-------------------------------------------------- // GetItems from LOB (LineOfBusiness list here..... //-------------------------------------------------- // DEV NOTES: // Aug. 4, 2017 - Removed 1000 limitation from CamlQueries (MAT) // List LOBList = web.Lists.GetByTitle("LOB-MPP-Map"); CamlQuery LOBquery = CamlQuery.CreateAllItemsQuery(); ListItemCollection LOBitems = LOBList.GetItems(LOBquery); clientContext.Load(LOBitems); var LOBFields = LOBList.Fields; clientContext.Load(LOBFields, fields => fields.Include(field => field.Title, field => field.InternalName)); clientContext.ExecuteQuery(); //UpdateLOBFields( clientContext, oldList, oldItems, LOBitems); // Console.WriteLine("Finished return from LOB update"); //oldList.Update(); //Console.WriteLine("Finished return from oldList update"); //clientContext.ExecuteQuery(); //------------------------- //Stop here for now. //------------------------- // Console.ReadLine(); // System.Environment.Exit(0); //log.Debug(string.Format("Opening List: {0}", backupListTarget)); //log.Debug("Internal fields"); //log.Debug("-------------------------"); //foreach (Field f in listFields) //{ // log.Debug(string.Format("Title: {0}, Internal Name: {1}", f.Title, f.InternalName)); // log.Debug(string.Format("Static Name: {0}", f.StaticName)); // log.Debug("-----------------"); // //log.Debug(f.InternalName); //} foreach (DataRow dr in ds.Tables[0].Rows) { //log.Debug("------- Inside For -----------------"); //log.Debug(dr[excelIndexTarget].ToString()); var my_itemlist = oldItems.ToList(); // ---------------BEGIN MY COMMENT SECTION -------------------------- //Console.WriteLine("Sales Opportunity Id: {0}", dr["Sales Opportunity Id"].ToString()); //Console.WriteLine(" My_itemlist count: {0}", my_itemlist.Count); ////---------MAT ----DEBUG TEST-------------------- ////-- List out item list for verification --- //// --------------------------------------------- //if (my_itemlist.Count() == 0) //{ // Console.WriteLine("My List count in 0"); //} //else //{ // log.Debug("-- Item List ------"); // foreach (ListItem targetListItem in my_itemlist) // { // log.Debug(string.Format("Title: {0}, HPOppID: {1}", targetListItem["Title"], targetListItem["HPOppID"].ToString())); // Console.WriteLine(targetListItem["Title"]); // } //} //log.Debug(string.Format(".....MAT - Listing COMPLETED HERE")); //Console.WriteLine(" -------- MAT list completed here ---------------"); // ---------------END MY COMMENT SECTION -------------------------- var page = from ListItem itemlist in oldItems.ToList() // var page = from ListItem itemlist in my_itemlist //where itemlist["HPOppID"].ToString() == dr["Sales Opportunity Id"].ToString() where itemlist["HPOppID"].ToString() == dr[excelIndexTarget.ToString()].ToString() select itemlist; //Console.WriteLine("Page Count is: {0}", page.Count()); //this is an update if (page.Count() == 1) { Console.ForegroundColor = ConsoleColor.Blue; //Console.WriteLine(string.Format("UPDATE RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); //log.Debug(string.Format("UPDATE: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); Console.WriteLine(string.Format("UPDATE RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); log.Debug(string.Format("UPDATE: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); ListItem item = page.FirstOrDefault(); //iterate the mapping between sharepoint list items and excel spreadsheet items foreach (DataRowSharepointMapping map in mapping) { UpdateField(item, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget); } CompareSalesStage(item, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget); //Console.WriteLine("- Before Item update."); // just update the item item.Update(); //Console.WriteLine("- Before List update."); //update the list oldList.Update(); countupdate++; } // This is a new record //else if (page.Count() == 0 && !string.IsNullOrEmpty(dr["Sales Opportunity Id"].ToString())) ----MAT else if (page.Count() == 0 && !string.IsNullOrEmpty(dr[excelIndexTarget.ToString()].ToString())) { Console.ForegroundColor = ConsoleColor.Yellow; //Console.WriteLine(string.Format("------- Inside ELSE NEW RECORD-----------------")); //Console.WriteLine(string.Format("NEW RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); Console.WriteLine(string.Format("NEW RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); //log.Debug("------- Inside ELSE NEW RECORD-----------------"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = oldList.AddItem(itemCreateInfo); // -- iterate the mapping between sharepoint list items and excel spreadsheet items foreach (DataRowSharepointMapping map in mapping) { UpdateField(oListItem, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget); } CompareSalesStage(oListItem, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget); // -- just update the item //Console.WriteLine("- Before Item update."); oListItem.Update(); // -- update the list //Console.WriteLine("- Before List update."); oldList.Update(); countnew++; } else { //----------------------------------------------------- // DUPLICATE RECORDS CHECK (MAT) - 8/31/17 //----------------------------------------------------- //log.Debug(string.Format("DUPLICATE RECORD TEST inside PAGE: {0}", page.ToList().Count())); if (page.ToList().Count() > 1) { Console.ForegroundColor = ConsoleColor.DarkGray; log.Debug(string.Format("DUPLICATE RECORD (NO ACTION TAKEN): Name:{0} ID:{1} --- ", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); Console.WriteLine(string.Format("DUPLICATE RECORD (NO ACTION TAKEN): Name:{0} ID:{1} -- ", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); dupcount++; } //------------------------------------------------------- //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine("ERROR"); } // Not sure about this one. (MAT) clientContext.ExecuteQuery(); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(string.Format("We updated: {0} records and added {1} records", countupdate.ToString(), countnew.ToString())); Console.WriteLine(string.Format("Duplicates found: {0} records", dupcount.ToString())); log.Debug(string.Format("------------------------------------------------------------")); log.Debug(string.Format("We updated: {0} records and added {1} records", countupdate.ToString(), countnew.ToString())); log.Debug(string.Format("Duplicates found: {0} records", dupcount.ToString())); Console.WriteLine("Completed first set of updates. \n"); Console.WriteLine("Starting LOB checks........ \n"); log.Debug(string.Format("------------------------------------------------------------")); log.Debug(string.Format("Starting LOB Checks........")); UpdateLOBFields(clientContext, oldList, oldItems, LOBitems, sharepointIndexTarget); //Console.WriteLine("Finished return from LOB update..."); //oldList.Update(); clientContext.ExecuteQuery(); Console.WriteLine("Finished Line Of Business updates... \n"); } }
protected void BackupButton_Click(object sender, EventArgs e) { DestSiteName = SiteNameTextBox.Text; ClientContext SourceCC = new ClientContext("https://acuvatehyd.sharepoint.com/teams/FirstSite"); ClientContext DestinationCC = new ClientContext("https://acuvatehyd.sharepoint.com/teams/" + DestSiteName); string UserName = "******"; string Password = "******"; SecureString securepwd = new SecureString(); foreach (char c in Password) { securepwd.AppendChar(c); } SourceCC.Credentials = new SharePointOnlineCredentials(UserName, securepwd); DestinationCC.Credentials = new SharePointOnlineCredentials(UserName, securepwd); ListCollection listcollection = SourceCC.Web.Lists; //getting list colectiom SourceCC.Load(listcollection); List SourceList = listcollection.GetByTitle("newlistforbackup"); SourceCC.Load(SourceList); SourceCC.ExecuteQuery(); //------creating list in dest ListCreationInformation NewList = new ListCreationInformation(); NewList.Title = SourceList.Title + "asdfghjkxvzsdf"; NewList.TemplateType = SourceList.BaseTemplate; NewList.Description = SourceList.Description; List Destlist = DestinationCC.Web.Lists.Add(NewList); DestinationCC.Load(Destlist.Fields); DestinationCC.ExecuteQuery(); //-----------adding list item ListItemCollection listitemcollection = SourceList.GetItems(CamlQuery.CreateAllItemsQuery()); SourceCC.Load(listitemcollection); SourceCC.ExecuteQuery(); foreach (ListItem li in listitemcollection) { ListItemCreationInformation NewListItem = new ListItemCreationInformation(); List destlistitem = Destlist.ParentWeb.Lists.GetByTitle(NewList.Title); ListItem listItem = Destlist.AddItem(NewListItem); listItem["Title"] = li["Title"]; listItem.Update(); DestinationCC.ExecuteQuery(); } }
public GradesViewModel GetMyLogin(GradesViewModel vm) { //TokenModel result = new TokenModel(); try { ProjectTokenHelper.CheckValidAccessToken(vm.spHostURL, vm.accessToken); using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(vm.spHostURL, vm.accessToken)) { User spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); clientContext.ExecuteQuery(); //result.Name = spUser.Title; // The SharePoint web site contains a list called "Student Gradebook" - grab and store it in a List variable. // Linking to the list, like finding a table in a database List studentGradebook = clientContext.Web.Lists.GetByTitle("Student Gradebook"); // CAML = Collaborative Application Markup Language // Query allows you to query for specific items from a list, using the ViewXml property. // Using CamlQuery.CreateAllItemsQuery() creates a query that retrieves all list items. CamlQuery query = CamlQuery.CreateAllItemsQuery(); // This line grabs items from the studentGradebook List object based on the specified query, and // stores them all in a ListItemCollection object. ListItemCollection studentGradebookCollection = studentGradebook.GetItems(query); // This line ties the ListItemCollection to the ClientContext object, providing a line of communication // between the program and the SharePoint server. Without this line, the items queried for will // not be retrieved from SharePoint. clientContext.Load(studentGradebookCollection); // Call ExecuteQuery() to perform the query, loading the specified items from SharePoint. clientContext.ExecuteQuery(); //GradesViewModel gradesViewModel = new GradesViewModel(); foreach (ListItem grade in studentGradebookCollection) { string courseTitle = (string)grade["Title"]; string passed = (string)grade["Result"]; vm.GradeBook.Add(new Grade(courseTitle, passed)); } // Call ExecuteQuery to commit changes made to the list. clientContext.ExecuteQuery(); // Changing display ResultColour of Grade Passed string // This is done in the controller because it has direct access to the GradeBook List of Grade objects. foreach (Grade grade in vm.GradeBook) { grade.ResultColor = grade.Passed.ToLower() == "pass" ? "color:Green" : "color:Red"; } } } catch (Exception) { } return(vm); }
public ActionResult Index() { User spUser = null; var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); Web myWeb = clientContext.Web; clientContext.Load(myWeb); List myList = myWeb.Lists.GetByTitle("Uppgift2Lista"); clientContext.Load(myList); var webListsTitles = myWeb.Lists; clientContext.Load(webListsTitles); CamlQuery query = CamlQuery.CreateAllItemsQuery(100); ListItemCollection items = myList.GetItems(query); clientContext.Load(items); int counter = 0; int counter2 = 0; int counter3 = 0; List <string> Titles = new List <string>(); List <string> WebTitles = new List <string>(); clientContext.ExecuteQuery(); foreach (var lists in webListsTitles) { WebTitles.Add(lists.Title); } foreach (var item in items) { if (item["Status"].ToString() == "Started" && item["Priority"].ToString() == "Hög") { Titles.Add(item["Title"].ToString()); } if (item["Priority"].ToString() == "Hög" && item["Status"].ToString() == "Created") { counter++; } if (item["Priority"].ToString() == "Medel" || item["Priority"].ToString() == "Låg" && (item["Status"].ToString() == "Created" || item["Status"].ToString() == "Started")) { counter2++; } if (item["Priority"].ToString() != "Hög" && item["Status"].ToString() != "Finished") { counter3++; } } ViewBag.UserName = spUser.Title; ViewBag.WebTitle = myWeb.Title; ViewBag.MyList = myList.Title; ViewBag.ItemTitle = Titles; ViewBag.ListTitles = WebTitles; ViewBag.Counter = counter; ViewBag.Counter2 = counter2; ViewBag.Counter3 = counter3; } } return(View()); }
private static List <SharepointCalendarEvent> ParseSharepointList(ClientContext sharepointContext, List sharepointList) { List <SharepointCalendarEvent> returnMe = new List <SharepointCalendarEvent>(); List <SharepointCalendarEvent> deletedRecurringEvents = new List <SharepointCalendarEvent>(); List <SharepointCalendarEvent> recurringEvents_Unexpanded = new List <SharepointCalendarEvent>(); CamlQuery query = CamlQuery.CreateAllItemsQuery(); Microsoft.SharePoint.Client.ListItemCollection sharepointListItems = sharepointList.GetItems(query); sharepointContext.Load(sharepointListItems); sharepointContext.ExecuteQuery(); foreach (ListItem item in sharepointListItems) { try { // We need to deal with "Deleted" events // These are events that cancel out existing events, if the events are recurring // Deal with recurring events, somehow string title = string.Empty; if (item.FieldValues.ContainsKey("Title")) { if (!string.IsNullOrEmpty((string)item["Title"])) { title = item["Title"].ToString(); } } ; string location = string.Empty; string description = string.Empty; if (item.FieldValues.ContainsKey("Description")) { if (!string.IsNullOrEmpty((string)item["Description"])) { // The description will almost always contain HTML, which we can't include in the JSON file or it won't validate // For now, we dont need the description // In the future perhaps we can strip out the HTML tags somehow description = Helpers.SanitizeForJSON(item["Description"].ToString()); } } string author = string.Empty; // Haven't figured out how to get this yet DateTime eventStarts = DateTime.MinValue; if (item.FieldValues.ContainsKey("EventDate")) { eventStarts = Parsers.ParseDate(item["EventDate"].ToString()); } DateTime eventEnds = DateTime.MinValue; if (item.FieldValues.ContainsKey("EndDate")) { eventEnds = Parsers.ParseDate(item["EndDate"].ToString()); } ; bool isTimeGMT = true; // Previously we would have had to check the times to see if they are sane, but I think when loading data this way, all times are UTC instead // Events that are "all day" events don't need to be adjusted because they are just 0:00 to 23:59. Adjusting them will set them into the previous day and mess things up. // Determine if this is an "all day" event. bool allDay = false; if (item.FieldValues.ContainsKey("fAllDayEvent")) { allDay = Parsers.ParseBool(item["fAllDayEvent"].ToString()); } // Times returned are all in UTC - adjust to local time if (isTimeGMT) { if (!allDay) { eventStarts = eventStarts + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); eventEnds = eventEnds + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); } } bool recurring = false; if (item.FieldValues.ContainsKey("fRecurrence")) { recurring = Parsers.ParseBool(item["fRecurrence"].ToString()); } string recurrenceData = string.Empty; if (item.FieldValues.ContainsKey("RecurrenceData")) { if (!string.IsNullOrEmpty((string)item["RecurrenceData"])) { recurrenceData = item["RecurrenceData"].ToString(); } } ; SharepointCalendarEvent newCalendarEvent = new SharepointCalendarEvent() { Title = title, Location = location, Description = description, Author = author, AllDay = allDay, Recurring = recurring, EventStart = eventStarts, EventEnd = eventEnds, RecurrenceInfo = recurrenceData }; // Correct start and end dates if the event is recurring if (recurring) { // Deal with recurring events differently - Their dates will be screwed up, so use the data from them to create "phantom" events that line up with the dates required // Events that start with "Deleted" cancel out recurring events if (item["Title"].ToString().StartsWith("Deleted:")) { newCalendarEvent.Title = newCalendarEvent.Title.Remove(0, 8).Trim(); deletedRecurringEvents.Add(newCalendarEvent); } else { recurringEvents_Unexpanded.Add(newCalendarEvent); } } else { returnMe.Add(newCalendarEvent); } } catch { } } // Deal with recurring events #region Deal with recurring events foreach (SharepointCalendarEvent ev in recurringEvents_Unexpanded) { // Figure out when this even reocurrs // the field "RecurrenceData" can have data in two different formats - either a string that looks like this: // Every 1 month(s) on the fourth Wednesday // Every 1 week(s) on: Wednesday // Every 1 month(s) on the fourth Wednesday // or XML data that looks like this: // <recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><weekly we="TRUE" weekFrequency="1" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence> // This apparently means every wednesday, every week // <recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><monthlyByDay we="TRUE" weekdayOfMonth="first" monthFrequency="1" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence> // This apparently means every first wednesday of every month // <recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><monthlyByDay we="TRUE" weekdayOfMonth="second" monthFrequency="1" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence> // This apparently means every second wednesday of every month // The "<firstDayOfWeek>su</firstDayOfWeek>" means that Sunday is considered the first day of the week // Time range for phantom events // Daily events: 2 weeks back, 6 weeks ahead // Weekly events: 4 weeks back, 8 weeks ahead // Monthly events: 2 months back, 12 months ahead // Yearly events: 1 year back, 5 years ahead // Repeating: // Could be: // <repeatInstances>10</repeatInstances> // <repeatForever>FALSE</repeatForever> // <windowEnd>2007-05-31T22:00:00Z</windowEnd> // parse XML recurrence data if (ev.RecurrenceInfo.StartsWith("<recurrence")) { // Extract the <repeat> section(s), because we don't really care about the rest // Regex: <repeat>(.+?)<\/repeat> Regex regex = new Regex(@"<repeat>(.+?)<\/repeat>"); MatchCollection matches = regex.Matches(ev.RecurrenceInfo); foreach (Match match in matches) { if (match.Success) { // Strip the <repeat> and </repeat> from the start and end of the segment string segment = match.Value.Substring(8, match.Value.Length - (8 + 9)); // Daily if (segment.StartsWith("<daily")) { // parse the "dayFrequency", then just multiply int dayFrequency = 1; Regex dayFrequencyRegex = new Regex(@"dayFrequency=\""(\d+)\"""); Match dayFrequencyMatch = dayFrequencyRegex.Match(segment); if (dayFrequencyMatch.Success) { dayFrequency = Parsers.ParseInt(dayFrequencyMatch.Value.Substring(14, dayFrequencyMatch.Value.Length - (14 + 1))); if (dayFrequency < 1) { dayFrequency = 1; } } // Get the original start date, and accellerate it to a date closer to now DateTime startDate = ev.EventStart; if (startDate <= DateTime.Now) { while (startDate <= DateTime.Now.AddDays(-7)) { startDate = startDate.AddDays(dayFrequency); } } // Get the current week (Sunday), then subtract 1 week //DateTime startOfWeek = DateTime.Today.AddDays(-1 * (int)(DateTime.Today.DayOfWeek)).AddDays(-7); for (int dayCounter = 0; dayCounter <= 30; dayCounter += dayFrequency) { DateTime newEventStartDate = startDate.AddDays(dayCounter); //DateTime newEventEndDate = newEventStartDate.Add(ev.Duration); returnMe.Add(ev.CloneWithNewDates(newEventStartDate, newEventStartDate)); } } // Weekly if (segment.StartsWith("<weekly")) { // For weekly events we want to create phantom events 4 weeks back, and 8 weeks ahead (12 weeks total) // We need to factor in the weekFrequency="1", to handle events that might be every second week or something int weekFrequency = 1; Regex weekFrequencyRegex = new Regex(@"weekFrequency=\""(\d+)\"""); Match weeklyFrequencyMatch = weekFrequencyRegex.Match(segment); if (weeklyFrequencyMatch.Success) { weekFrequency = Parsers.ParseInt(weeklyFrequencyMatch.Value.Substring(15, weeklyFrequencyMatch.Value.Length - (15 + 1))); if (weekFrequency < 1) { weekFrequency = 1; } } // Get the original start date, and accellerate it to a date closer to now DateTime startDate = ev.EventStart; if (startDate <= DateTime.Now) { while (startDate <= DateTime.Now.AddDays(-28)) { startDate = startDate.AddDays(weekFrequency * 7); } } // Get the current week (Sunday), then subtract 4 weeks from it for a start date //DateTime startOfWeek = DateTime.Today.AddDays(-1 * (int)(DateTime.Today.DayOfWeek)).AddDays(-28); // Translate detected days into day numbers (Sunday = 0) List <int> eventDayNumbers = new List <int>(); if (segment.Contains("su=\"TRUE\"")) { eventDayNumbers.Add(0); } if (segment.Contains("mo=\"TRUE\"")) { eventDayNumbers.Add(1); } if (segment.Contains("tu=\"TRUE\"")) { eventDayNumbers.Add(2); } if (segment.Contains("we=\"TRUE\"")) { eventDayNumbers.Add(3); } if (segment.Contains("th=\"TRUE\"")) { eventDayNumbers.Add(4); } if (segment.Contains("fr=\"TRUE\"")) { eventDayNumbers.Add(5); } if (segment.Contains("sa=\"TRUE\"")) { eventDayNumbers.Add(6); } // Get the sunday of the week of the start date of the event DateTime startingWeekSunday = startDate.AddDays(-1 * (int)startDate.DayOfWeek); for (int weekCounter = 0; weekCounter < 12; weekCounter += weekFrequency) { foreach (int dayNum in eventDayNumbers) { DateTime newEventStartDate = startingWeekSunday.AddDays(dayNum).AddDays(7 * weekCounter); returnMe.Add(ev.CloneWithNewDates(newEventStartDate, newEventStartDate)); } } } // Monthly, given day numbers (Every 2nd of the month, for example) if (segment.StartsWith("<monthly ")) { // If the user sets it to every ___ day of every __ month, it looks like this: // <monthly monthFrequency="2" day="6" /> int monthFrequency = 1; Regex monthFrequencyRegex = new Regex(@"monthFrequency=\""(\d+)\"""); Match monthFrequencyMatch = monthFrequencyRegex.Match(segment); if (monthFrequencyMatch.Success) { monthFrequency = Parsers.ParseInt(monthFrequencyMatch.Value.Substring(16, monthFrequencyMatch.Value.Length - 17)); if (monthFrequency < 1) { monthFrequency = 1; } } // We ignore the actual day of the start date, in favor of this value (this is what Sharepoint does anyway) int dayNumber = 0; Regex dayNumberRegex = new Regex(@"day=\""(\d+)\"""); Match dayNumberMatch = dayNumberRegex.Match(segment); if (dayNumberMatch.Success) { dayNumber = Parsers.ParseInt(dayNumberMatch.Value.Substring(5, dayNumberMatch.Value.Length - (5 + 1))); if (dayNumber < 1) { dayNumber = 1; } } // Rebuild the event start date based on the recurrence information ev.EventStart = new DateTime(ev.EventStart.Year, ev.EventStart.Month, dayNumber, ev.EventStart.Hour, ev.EventStart.Minute, ev.EventStart.Second); // Find the original month and acellerate to a time closer to now, so we don't incorrectly assume that this month includes the event (if the month frequency causes it to skip the current month) DateTime startDate = ev.EventStart; if (startDate <= DateTime.Now) { while (startDate <= DateTime.Now.AddDays(-1 * (31 * (monthFrequency + 1)))) { startDate = startDate.AddMonths(monthFrequency); } } for (int monthCounter = 0; monthCounter < 12; monthCounter += monthFrequency) { DateTime newEventStartDate = startDate.AddMonths(monthFrequency * monthCounter); returnMe.Add(ev.CloneWithNewDates(newEventStartDate, newEventStartDate)); } } // Monthly by Day (Every third wednesday, for example) if (segment.StartsWith("<monthlyByDay ")) { // weekdayOfMonth="first" // First|Second|Third|Fourth|Last // Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|Weekday|Weekend Day, etc // Sharepoint only lets monthly events happen on a single day per event so we dont need to deal with multiple days int monthFrequency = 1; Regex monthFrequencyRegex = new Regex(@"monthFrequency=\""(\d+)\"""); Match monthFrequencyMatch = monthFrequencyRegex.Match(segment); if (monthFrequencyMatch.Success) { monthFrequency = Parsers.ParseInt(monthFrequencyMatch.Value.Substring(16, monthFrequencyMatch.Value.Length - 17)); if (monthFrequency < 1) { monthFrequency = 1; } } // Get the weekday of month string string weekdayOfMonthString = string.Empty; Regex weekdayOfMonthRegex = new Regex(@"weekdayOfMonth=\""(.+?)\"""); Match weekdayOfMonthMatch = weekdayOfMonthRegex.Match(segment); if (weekdayOfMonthMatch.Success) { weekdayOfMonthString = weekdayOfMonthMatch.Value.Substring(16, weekdayOfMonthMatch.Value.Length - 17); } // Make a list of years and months that we care about, because the contextual days will differ year to year // If we're missing the weekday of the month string, we can't continue if (!string.IsNullOrEmpty(weekdayOfMonthString)) { int goalIteration = 0; switch (weekdayOfMonthString.ToLower()) { case "first": goalIteration = 1; break; case "second": goalIteration = 2; break; case "third": goalIteration = 3; break; case "fourth": goalIteration = 4; break; case "last": goalIteration = 999; break; } DayOfWeek goalDayOfWeek = DayOfWeek.Saturday; if (segment.Contains("su=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Sunday; } if (segment.Contains("mo=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Monday; } if (segment.Contains("tu=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Tuesday; } if (segment.Contains("we=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Wednesday; } if (segment.Contains("th=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Thursday; } if (segment.Contains("fr=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Friday; } if (segment.Contains("sa=\"TRUE\"")) { goalDayOfWeek = DayOfWeek.Saturday; } // Get the original start date, and accellerate it to a date closer to now DateTime startDate = ev.EventStart; if (startDate <= DateTime.Now) { while (startDate <= DateTime.Now.AddDays(-1 * monthFrequency * 31)) { startDate = startDate.AddMonths(monthFrequency); } } // Make a list of months, in the form of datetimes of the first of those months, for each phantom event we want to create // We'll need to go through all the below BS for eachof them seperately, because they will differ year to year List <DateTime> phantomEventMonths = new List <DateTime>(); for (int monthCount = 0; monthCount <= 12; monthCount += monthFrequency) { phantomEventMonths.Add(new DateTime(startDate.Year, startDate.Month, 1).AddMonths(monthCount)); } foreach (DateTime phantomEventMonth in phantomEventMonths) { DateTime newEventStartDate = phantomEventMonth; if (goalIteration == 999) { // We're finding the last day of the month instead of the first day if (segment.ToLower().Contains("weekend_day=\"true\"")) { newEventStartDate = Helpers.GetDayOfMonth_Backwards(phantomEventMonth.Year, phantomEventMonth.Month, 1, Helpers.GetWeekendDays()); } else if (segment.ToLower().Contains("weekday=\"true\"")) { newEventStartDate = Helpers.GetDayOfMonth_Backwards(phantomEventMonth.Year, phantomEventMonth.Month, 1, Helpers.GetWeekdays()); } else if (segment.ToLower().Contains("day=\"true\"")) { // Just the last day of the month newEventStartDate = new DateTime(phantomEventMonth.Year, phantomEventMonth.Month, DateTime.DaysInMonth(phantomEventMonth.Year, phantomEventMonth.Month)); } else { // Find the day specifically newEventStartDate = Helpers.GetDayOfMonth_Backwards(phantomEventMonth.Year, phantomEventMonth.Month, 1, goalDayOfWeek); } } else { if (segment.ToLower().Contains("weekend_day=\"true\"")) { newEventStartDate = Helpers.GetDayOfMonth(phantomEventMonth.Year, phantomEventMonth.Month, goalIteration, Helpers.GetWeekendDays()); } else if (segment.ToLower().Contains("weekday=\"true\"")) { newEventStartDate = Helpers.GetDayOfMonth(phantomEventMonth.Year, phantomEventMonth.Month, goalIteration, Helpers.GetWeekdays()); } else if (segment.ToLower().Contains("day=\"true\"")) { newEventStartDate = new DateTime(phantomEventMonth.Year, phantomEventMonth.Month, goalIteration); } else { // Find the day specifically newEventStartDate = Helpers.GetDayOfMonth(phantomEventMonth.Year, phantomEventMonth.Month, goalIteration, goalDayOfWeek); } } returnMe.Add(ev.CloneWithNewDates(newEventStartDate, newEventStartDate)); } } } // Yearly if (segment.StartsWith("<yearly")) { // Don't support yearly events at the moment - I don't have the patience to deal with this right now, and theres little chance a yearly event will be in our calendars } } } } } #endregion // Deal with deleted events List <SharepointCalendarEvent> finalReturnedEventsList = new List <SharepointCalendarEvent>(); foreach (SharepointCalendarEvent ev in returnMe) { bool foundDeletedEvent = false; foreach (SharepointCalendarEvent deletedEvent in deletedRecurringEvents) { if (( (ev.Title == deletedEvent.Title) && (ev.EventStart.Year == deletedEvent.EventStart.Year) && (ev.EventStart.Month == deletedEvent.EventStart.Month) && (ev.EventStart.Day == deletedEvent.EventStart.Day) )) { foundDeletedEvent = true; } } if (!foundDeletedEvent) { finalReturnedEventsList.Add(ev); } } return(finalReturnedEventsList.OrderBy(e => e.EventStart).ThenBy(e => e.EventEnd).ToList()); }