private void DeleteChildrenItems(SPItemEventProperties properties) { SPList parentList = properties.List; ICollection <ListRelation> childrenLists = GetChildrenLists(parentList).ToList(); int parentItemId = properties.ListItemId; foreach (var childList in childrenLists) { string fieldName = childList.LookupFieldName; var query = new SPQuery() { Query = string.Format("<Where><Eq><FieldRef Name='{0}' LookupId='TRUE' /><Value Type='Lookup'>{1}</Value></Eq></Where>", fieldName, parentItemId) }; childList.ChildListUrl = childList.ChildListUrl.FirstOrDefault() == '/' ? childList.ChildListUrl : "/" + childList.ChildListUrl; SPList spList = properties.Web.GetList(childList.ChildListUrl); SPListItemCollection childrenListItems = spList.GetItems(query); var childrenItems = childrenListItems.Cast <SPListItem>().ToList(); for (int i = 0; i < childrenItems.Count(); i++) { childrenItems[i].Delete(); } } }
internal static List <ListItem> GetAvailableValues(FilteredLookupField f, HttpContext ctx) { List <ListItem> _v = null; SPListItemCollection items = null; Guid fId = new Guid(f.LookupField); SPSite s = SPControl.GetContextSite(ctx); SPWeb lookupWeb = s.OpenWeb(f.LookupWebId); SPList lookupList = lookupWeb.Lists[new Guid(f.LookupList)]; try { if (f.QueryFilter != null) { items = lookupList.GetItems(f.QueryFilter); } } catch { } if (items == null) { items = lookupList.Items; } if ((items != null && items.Count > 0)) { _v = items .Cast <SPListItem>() .Where(e => e[fId] != null) .Select(e => new ListItem(( e.Fields[fId].GetFieldValueAsText(e[fId])), e.ID.ToString())) .ToList <ListItem>(); } return(_v); }
/// <summary> /// Gets an item by its Id /// </summary> /// <param name="id">Id of the item to return</param> /// <returns>Returns the original SPListItem object found</returns> public SPListItem GetSPListItem(int id) { Logger.Logger.Debug("SharePointRepository.GetSPListItem", "ID = {0}", id); SPListItem result = Call(() => { using (_context.Web) { var list = _context.Web.Lists.TryGetList(Title); if (list == null) { throw new Exception($"The list \"{Title}\" not found"); } SPQuery query = new SPQuery { Query = $"<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{id}</Value></Eq></Where>" }; SPListItemCollection items = list.GetItems(query); return(items.Cast <SPListItem>().SingleOrDefault()); } }); return(result); }
private List <NewsNumberInCategoryDTO> GetCategoriesWithNewsNumberOrderedByDesc() { CategoriesRepository categoriesRepo = new CategoriesRepository(web); SPListItemCollection categories = categoriesRepo.GetCategoriesList(); SPListItemCollection allNews = web.Lists["News"].Items; List <NewsNumberInCategoryDTO> categoriesWithNewsNumber = new List <NewsNumberInCategoryDTO>(); foreach (SPListItem category in categories) { int newsNumberInCurrentCategory = allNews.Cast <SPListItem>() .Where(n => categories.Cast <SPListItem>() .Any(c => n["Category"].ToString() .Contains(category.Title))).Count(); categoriesWithNewsNumber.Add(new NewsNumberInCategoryDTO() { CategoryName = category.Title, NumberOfNews = newsNumberInCurrentCategory }); newsNumberInCurrentCategory++; } return(categoriesWithNewsNumber.OrderByDescending(c => c.NumberOfNews).ToList()); }
private IList <string> GetLookupChoices(SPField spField) { var list = new List <string>(); var spFieldLookup = (SPFieldLookup)spField; string lookupField = spFieldLookup.LookupField; using (var spSite = new SPSite(spFieldLookup.ParentList.ParentWeb.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb(spFieldLookup.LookupWebId)) { SPList spList = spWeb.Lists[new Guid(spFieldLookup.LookupList)]; SPListItemCollection spListItemCollection = spList.GetItems(new[] { lookupField }); foreach (string value in spListItemCollection.Cast <SPListItem>() .Select(li => li.ID + "|" + li[lookupField]) .Where(value => !list.Contains(value))) { list.Add(value); } } } return(list); }
protected void btnViewAvailability_Click(object sender, EventArgs e) { SPLimitedWebPartManager webPartManager = null; try { SPList list = null; SPView view = null; // get WebPartManager to identify current List/View SPWeb web = SPContext.Current.Web; webPartManager = SPContext.Current.File.GetLimitedWebPartManager(PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts) { XsltListViewWebPart xlvwp = wp as XsltListViewWebPart; if (xlvwp != null) { list = web.Lists[xlvwp.ListId]; view = xlvwp.View; break; } } // get list data by Filters FieldFilterOperatorsLayer fol = new FieldFilterOperatorsLayer(this.FilterConditions); CamlFiltersLayer fl = new CamlFiltersLayer(list, this.FilterQuery, fol); string myQuery = fl.GetQueryByFilters(); SPListItemCollection navigator = list.GetItems(new SPQuery() { Query = myQuery, ViewFields = "<FieldRef Name=\"ID\" />", RowLimit = view.RowLimit }); // get filter IDs string filteredIDs = string.Empty; if (navigator != null && navigator.Count > 0) { filteredIDs = String.Join(",", navigator.Cast <SPListItem>().Select(x => x.ID.ToString()).ToArray()); } string redigUrl = string.Format("{0}/{1}?FilteredIDs={2}&OrigSchiftId={3}{4}{5}", web.ServerRelativeUrl.TrimEnd('/'), this.RedirectUrl.TrimStart('/'), filteredIDs, this.Page.Request.QueryString["SchiftId"], string.IsNullOrEmpty(this.CalendarPeriod) ? "" : string.Format("&CalendarPeriod={0}", this.CalendarPeriod), FormatedCalendarDate); SPUtility.Redirect(redigUrl, SPRedirectFlags.Default, this.Context); } catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; } finally { if (webPartManager != null) { webPartManager.Web.Dispose(); } } }
/// <summary> /// Returns first item that matched CAML query filtering. /// </summary> /// <param name="list"></param> /// <param name="caml"></param> /// <returns></returns> public static SPListItem GetItemByQuery(this SPList list, string caml) { SPQuery query = new SPQuery(); query.ViewAttributes = "Scope=\"Recursive\""; query.Query = caml; query.RowLimit = 1; SPListItemCollection items = list.GetItems(query); return(items.Cast <SPListItem>().FirstOrDefault()); }
private ICollection <TEntity> PopulateItems(SPListItemCollection items) { ICollection <TEntity> entities = new Collection <TEntity>(); if (items.Count > 0) { foreach (var listItem in items.Cast <SPListItem>().ToList()) { var entity = (TEntity)Activator.CreateInstance(typeof(TEntity)); SetProperties(entity, listItem); entities.Add(entity); } } return(entities); }
public static SPListItem GetEmailTemplate(string url, SPWeb web, string templateName) { SPList list = GetListFromURL(url, web); SPQuery query = new SPQuery(); System.Text.StringBuilder strQuery = new System.Text.StringBuilder(); strQuery.Append(" <Where>"); strQuery.Append(" <Eq>"); strQuery.Append(" <FieldRef Name='Title' />"); strQuery.AppendFormat(" <Value Type='Text'>{0}</Value>", templateName); strQuery.Append(" </Eq>"); strQuery.Append(" </Where>"); query.Query = strQuery.ToString(); SPListItemCollection items = list.GetItems(query); return(items.Cast <SPListItem>().FirstOrDefault()); }
/// <summary> /// Gets an item by its Id /// </summary> /// <param name="id">Id of the item to return</param> /// <returns>Returns a domain object representing the SPListItem found</returns> public TEntity GetById(int id) { // log execution Logger.Logger.Debug("SharePointRepository.GetById", "ID = {0}", id); TEntity result = Call(() => { using (_context.Web) { // find target list var list = _context.Web.Lists.TryGetList(Title); if (list == null) { throw new Exception($"The list \"{Title}\" not found"); } SPQuery query = new SPQuery { Query = $"<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{id}</Value></Eq></Where>" }; SPListItemCollection items = list.GetItems(query); if (items.Count == 0) { return(null); } else { var entity = (TEntity)Activator.CreateInstance(typeof(TEntity)); var listItem = items.Cast <SPListItem>().Single(); SetProperties(entity, listItem); return(entity); } } }); return(result); }
private void GetItemIndex(string ListName) { if (ItemID != 0) { string myurl = Request.Url.AbsoluteUri; int id = myurl.IndexOf("?ID="); id = id + 4; myurl = myurl.Substring(0, id); id = myurl.IndexOf("Lists"); string siteUrl = myurl.Substring(0, id - 1); //string ItemId = ItemID.ToString(); try { SPSecurity.RunWithElevatedPrivileges(delegate() //模拟管理员权限执行,让匿名用户也可以查看此Web部件 { using (SPSite mySite = new SPSite(siteUrl)) { using (SPWeb myWeb = mySite.OpenWeb()) { SPList mylist = myWeb.Lists.TryGetList(ListName); if (mylist != null) { SPQuery qry = new SPQuery(); qry.Query = @"<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>"; SPListItemCollection myItems = mylist.GetItems(qry); //获取sharepoint列表集合 //SPListItem oListItem = mylist.Items.GetItemById(ItemID); List <SPListItem> listItems = myItems.Cast <SPListItem>().ToList(); //将SharePoint列表数据集合转化为普通列表集合 SPListItem myItem = listItems.FirstOrDefault(p => p.ID == ItemID); //查询指定ID的列表项 int index = listItems.IndexOf(myItem); //获取指定列表项的索引 int rCount = mylist.ItemCount; //获取列表的计数 if (rCount >= 2) //多余两条显示导航 { if (index == 0) { //itemindex = myItems[rCount - 1]["ID"].ToString() + ";" + myItems[rCount - 1]["Title"].ToString() + ";" + myItems[i+1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString(); itemNav.InnerHtml = "<div id='container'><div id='left'> 当前已是第一条 </div><div id='content'> 共计 <b>" + rCount + "</b> 条 </div><div id='right'> 下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'> <b>" + myItems[index + 1]["Title"].ToString() + "</b> </a></div></div>"; } else if (index == rCount - 1) { //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i - 1]["Title"].ToString() + ";" + myItems[0]["ID"].ToString() + ";" + myItems[0]["Title"].ToString(); itemNav.InnerHtml = "<div id='container'><div id='left'>上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'> <b>" + myItems[index - 1]["Title"].ToString() + "</b> </a></div><div id='content'> 共计 <b>" + rCount + "</b> 条 </div><div id='right'> 当前已是最后一条 </div></div>"; } else { //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i-1]["Title"].ToString()+";"+ myItems[i + 1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString(); itemNav.InnerHtml = "<div id='container'><div id='left'>上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'><b>" + " " + myItems[index - 1]["Title"].ToString() + "</b> </a></div><div id='content'> 当前第 <b>" + (index + 1).ToString() + "</b> 条,共计 <b>" + rCount + "</b> 条 </div><div id='right'> 下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'> <b>" + myItems[index + 1]["Title"].ToString() + "</b> </a></div></div>"; } } else { itemNav.Visible = false; } } } } }); } catch (System.Exception ex) { itemNav.InnerHtml = ex.ToString(); } } }
internal static IEnumerable <T> ToEntities <T>(SPListItemCollection items) { return(items.Cast <SPListItem>().Select(i => ToEntity <T>(i))); }
internal static IEnumerable <T> ToEntities <T>(SPListItemCollection items) where T : Item { return(items.Cast <SPListItem>().Select(ToEntity <T>)); }
private void GetItemNav(string lstName) { if (ItemID == 0) { itemNav.InnerHtml = "无法获取当前项目数据"; } else { try { SPSecurity.RunWithElevatedPrivileges(delegate() //模拟管理员权限执行,让匿名用户也可以查看此Web部件 { string siteUrl = SPContext.Current.Site.Url; using (SPSite mySite = new SPSite(siteUrl)) { using (SPWeb myWeb = SPContext.Current.Web) { SPList mylist = myWeb.Lists.TryGetList(lstName); if (mylist != null) { string queryStr = ""; SPListItem currentItem = mylist.GetItemById(ItemID); if (currentItem != null) { string flag = "0"; if (currentItem["Flag"] != null) { flag = currentItem["Flag"].ToString();; } string isOnly = webpartObj.OnlyAudit;//是否只显示待审记录 string showYear = webpartObj.ByYear; if (string.IsNullOrEmpty(showYear)) { showYear = DateTime.Now.Year.ToString(); } if (isOnly == "是") //只显示未审 { if (flag != "1") //当前未审 { queryStr += "<Where><And><Eq><FieldRef Name='Year'/><Value Type='Text'>" + showYear + "</Value></Eq><Eq><FieldRef Name='Flag'/><Value Type='Number'>0</Value></Eq></And></Where>"; } else//当前已审,不参与导航 { itemNav.Visible = false; return; } } else { queryStr += "<Where><Eq><FieldRef Name='Year'/><Value Type='Text'>" + showYear + "</Value></Eq></Where>"; } string myurl = mylist.DefaultDisplayFormUrl + "?ID="; SPQuery qry = new SPQuery(); SPFieldCollection fields = mylist.Fields; queryStr += GenQuery(fields); if (queryStr == null) { itemNav.InnerHtml = "设置项中的某个字段名设置错误"; } else { qry.Query = queryStr; SPListItemCollection myItems = mylist.GetItems(qry);//获取sharepoint列表集合 if (myItems.Count > 0) { List <SPListItem> listItems = myItems.Cast <SPListItem>().ToList(); //将SharePoint列表数据集合转化为普通列表集合 SPListItem myItem = listItems.FirstOrDefault(p => p.ID == ItemID); //查询指定ID的列表项 int index = listItems.IndexOf(myItem); //获取指定列表项的索引 int rCount = myItems.Count; //获取列表的计数 if (rCount >= 2) //多余两条显示导航 { if (index == 0) { //itemindex = myItems[rCount - 1]["ID"].ToString() + ";" + myItems[rCount - 1]["Title"].ToString() + ";" + myItems[i+1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString(); itemNav.InnerHtml = "<ul><li>当前已是第一条</li><li> 共计 <b>" + rCount + "</b> 条</li><li>▽下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'>" + GetSubString(myItems[index + 1]["Title"].ToString(), 50) + "</a></li></ul>"; } else if (index == rCount - 1) { //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i - 1]["Title"].ToString() + ";" + myItems[0]["ID"].ToString() + ";" + myItems[0]["Title"].ToString(); itemNav.InnerHtml = "<ul><li>△上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'>" + GetSubString(myItems[index - 1]["Title"].ToString(), 50) + "</a></li><li> 共计 <b>" + rCount + "</b> 条</li><li>当前已是最后一条</li></ul>"; } else { //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i-1]["Title"].ToString()+";"+ myItems[i + 1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString(); itemNav.InnerHtml = "<ul><li>△上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'>" + GetSubString(myItems[index - 1]["Title"].ToString(), 50) + "</a></li><li> 当前第 <b>" + (index + 1).ToString() + "</b> 条,共计 <b>" + rCount + "</b> 条</li><li>▽下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'>" + GetSubString(myItems[index + 1]["Title"].ToString(), 50) + "</a></li></ul>"; } } else { itemNav.Visible = false;//不够两条,无须导航 } } else { itemNav.Visible = false;//没有数据 } } } } else { itemNav.Visible = false;//列表不存在 } } } }); } catch (System.Exception ex) { itemNav.InnerHtml = ex.ToString(); } } }
public override bool Perform() { try { SPSecurity.RunWithElevatedPrivileges(() => { using (var spSite = new SPSite(Web.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb(Web.ID)) { if (!spWeb.IsRootWeb) { LogMessage(spWeb.Title + " is not a root web.", MessageKind.SKIPPED, 2); return; } LogMessage("Downloading new " + SETTINGS_LIST + " list", 2); var catalog = (SPDocumentLibrary)Web.Site.GetCatalog(SPListTemplateType.ListTemplateCatalog); const string TEMPLATE_NAME = SETTINGS_LIST + " [5.5]"; using (var webClient = new WebClient()) { byte[] bytes = webClient.DownloadData(_storeUrl + "/Upgrade/" + SETTINGS_LIST.ToLower() + ".stp"); SPFile file = catalog.RootFolder.Files.Add(SETTINGS_LIST.Replace(" ", "_") + "_55.stp", bytes, true); SPListItem li = file.GetListItem(); li["Title"] = TEMPLATE_NAME; li.SystemUpdate(); } SPList list = Web.Lists.TryGetList(SETTINGS_LIST); if (list != null) { LogMessage("Deleting old " + SETTINGS_LIST + " list", 2); if (!list.AllowDeletion) { list.AllowDeletion = true; list.Update(); } list.Delete(); LogMessage(null, MessageKind.SUCCESS, 4); } LogMessage("Creating the " + SETTINGS_LIST + " list", 2); SPListTemplateCollection listTemplates = spSite.GetCustomListTemplates(spWeb); SPListTemplate template = listTemplates[TEMPLATE_NAME]; spWeb.Lists.Add(SETTINGS_LIST, string.Empty, template); SPList spList = spWeb.Lists[SETTINGS_LIST]; spList.Title = SETTINGS_LIST; spList.Hidden = true; spList.AllowDeletion = false; spList.Update(); LogMessage(null, MessageKind.SUCCESS, 4); SPList appList = spWeb.Lists["Installed Applications"]; SPListItemCollection apps = appList.Items; var tsAppExists = apps.Cast <SPListItem>().Any(app => app.Title.Equals("Timesheets")); if (tsAppExists) { return; } LogMessage("The Timesheets app is not installed", 2); LogMessage("Removing the Timesheets link from the navigation", 3); SPList settingsList = spWeb.Lists[SETTINGS_LIST]; SPListItem tsItem = settingsList.GetItemById(90); tsItem.Delete(); settingsList.Update(); LogMessage(null, MessageKind.SUCCESS, 4); } } }); } catch (Exception e) { LogMessage(e.Message, MessageKind.FAILURE, 2); } finally { try { CacheStore.Current.RemoveSafely(Web.Url, new CacheStoreCategory(Web).Navigation); } catch { } } return(true); }