private void AddItemsFromDocLib(SPDocumentLibrary docLib) { if (Param.IncludeSubFolders) { AddItemsFromList(docLib.Items); } else { SPQuery q = new SPQuery(); q.Folder = docLib.RootFolder; AddItemsFromList(docLib.GetItems(q)); } }
protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, Microsoft.SharePoint.SPWorkItemCollection workItems, Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState) { // process the workItem using (var site = new SPSite(workItem.SiteId)) { using (var web = site.OpenWeb(workItem.WebId)) { //var logEntry = IronLogger.Entry.Base64Deserialize(workItem.TextPayload); if (true)//logEntry.Level <= WebLogLevel(web)) { SPDocumentLibrary logLib = null; try { logLib = (SPDocumentLibrary)web.GetList(web.ServerRelativeUrl + "/" + IronConstant.IronLogsListPath); } catch (Exception ex) { throw new SPException("Couldn't find IronLog document library", ex); throw ex; } if (logLib != null) { var logFileCandidates = logLib.GetItems(LogFileQuery(2)); if (logFileCandidates.Count > 0) { var logFile = logFileCandidates[0].File; AppendToFile(logFile, workItem.TextPayload); } else { var url = DateTime.Now.ToString("s").Replace(":", "_"); url = string.Format("{0}.log", url); logLib.RootFolder.Files.Add(url, GetBytes(workItem.TextPayload)); } } } // delete the workItem after we've processed it workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id); } } // returning true allows the timer job to process additional items in the queue // returning false will end this occurance of the timer job return(true); }
/// <summary> /// Adds the content of the list. /// </summary> /// <param name="library">The library.</param> /// <param name="filters">The filters.</param> /// <param name="sortField">The sort field.</param> /// <param name="content">The content within the list.</param> /// <param name="outlookRequest">if set to <c>true</c> [outlook request].</param> /// <param name="parentDocument">The parent document.</param> private void AddListContent(SPDocumentLibrary library, List <string> filters, string sortField, SPFolder content, bool outlookRequest, XmlDocument parentDocument) { XmlNode listContent = parentDocument.CreateElement("ListContent"); parentDocument.SelectSingleNode("/PageData").AppendChild(listContent); foreach (SPFolder folder in content.SubFolders) { listContent.AppendChild(CreateListItemEntry(parentDocument, folder.Name, folder.ParentWeb.Url + "/" + folder.Url, "folder", "", "", "", "folder.gif", "", "")); } SPQuery query = new SPQuery(); query.Query = Data.GetCamlNew(filters, sortField, true); query.Folder = content; SPListItemCollection col = library.GetItems(query); AddListItems(parentDocument, col, listContent, outlookRequest); }
public static void CopyFiles(SPDocumentLibrary sourceDocLib, SPDocumentLibrary targetDocLib, bool overwrite = false, bool includeHistory = false, string queryStr = "", string targetContentTypeName = "") { SPQuery query = new SPQuery { RowLimit = MaxRowLimit, Folder = sourceDocLib.RootFolder, Query = queryStr }; SPListItemCollectionPosition listItemCollectionPosition; do { SPListItemCollection items = sourceDocLib.GetItems(query.InScope(SPViewScope.FilesOnly)); listItemCollectionPosition = items.ListItemCollectionPosition; foreach (SPListItem item in items) { SPFile file = item.File; SPFolder targetFolder = targetDocLib.RootFolder; if (!file.Exists) { continue; } SPFile newFile = includeHistory ? CopyFileAndHistory(file, targetFolder, overwrite) : CopyFile(file, targetFolder, overwrite); SPListItem newItem = newFile.Item; newItem[SPBuiltInFieldId.ContentType] = string.IsNullOrEmpty(targetContentTypeName) ? item.ContentType.Name : targetContentTypeName; newItem[SPBuiltInFieldId.Created] = file.TimeCreated; //newItem[SPBuiltInFieldId.Modified] = file.TimeLastModified; newItem[SPBuiltInFieldId.Author] = newFile.Author; //newItem[SPBuiltInFieldId.Editor] = newFile.ModifiedBy; newFile.Item.SystemUpdate(false); } } while (listItemCollectionPosition != null); }
public void SyncReports(SPDocumentLibrary reportLibrary) { lock (_locks.GetOrAdd(siteCollectionId + "_ReportLibrary", s => new object())) { var errors = string.Empty; var spQuery = new SPQuery() { Query = "<Where><And><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq><Neq><FieldRef Name='Synchronized' /><Value Type='Boolean'>1</Value></Neq></And></Where>", ViewAttributes = "Scope=\"RecursiveAll\"" }; var items = reportLibrary.GetItems(spQuery).OfType <SPListItem>().OrderByDescending(x => new FileInfo(x.File.Name).Extension).ToList(); foreach (SPListItem item in items) { var reportItem = new ReportItem() { FileName = item.File.Name, LastModified = item.File.TimeLastModified, Folder = item.File.ParentFolder.Url, BinaryData = item.File.OpenBinary(), DatasourceCredentials = item.File.Name.ToLower().EndsWith(".rsds") ? CoreFunctions.Decrypt(Convert.ToString(item["Datasource Credentials"]), "FpUagQ2RG9") : null }; try { CreateFoldersIfNotExist(siteCollectionId.ToString(), reportItem.Folder); UploadReport(siteCollectionId.ToString(), reportItem); item["Synchronized"] = true; item["UpdatedBy"] = "RS"; item.SystemUpdate(); } catch (Exception exception) { errors += exception.ToString(); } } if (!string.IsNullOrEmpty(errors)) { throw new Exception(errors); } } }
private void lbWorkflows_SelectedIndexChanged(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; cmboExistingRulesets.Items.Clear(); pnlRuleSets.Enabled = false; if (WFDataCollection[lbWorkflows.SelectedIndex].AssemblyName == null) { WFDataCollection[lbWorkflows.SelectedIndex].AssemblyName = GetAssemblyName(WFDataCollection[lbWorkflows.SelectedIndex].ID.ToString()); } Assembly a = Assembly.Load(WFDataCollection[lbWorkflows.SelectedIndex].AssemblyName); foreach (Type type in a.GetTypes()) { if ((type.BaseType.Name.ToLower() == "sequentialworkflowactivity") || (type.BaseType.Name.ToLower() == "statemachineworkflowactivity")) { WFDataCollection[lbWorkflows.SelectedIndex].AssemblyType = type; break; } } SPSite site = new SPSite(sSiteURL); SPWeb web = site.OpenWeb(); SPDocumentLibrary dl = (SPDocumentLibrary)web.Lists["Rules"]; SPQuery qry = new SPQuery(); qry.Query = string.Format(@"<Where><Eq><FieldRef Name='WorkflowName' /><Value Type='Text'>{0}</Value></Eq></Where>", WFDataCollection[lbWorkflows.SelectedIndex].AssemblyType.Name); SPListItemCollection lic = dl.GetItems(qry); if (lic.Count > 0) { foreach (SPListItem li in lic) { cmboExistingRulesets.Items.Add(Path.GetFileNameWithoutExtension(li.File.Name)); } } cmboExistingRulesets.Items.Insert(0, "<New>"); cmboExistingRulesets.SelectedIndex = 0; pnlRuleSets.Enabled = true; Cursor.Current = Cursors.Default; }
/// <summary> /// Gets the item from the referenced library /// </summary> /// <param name="teamUrl"></param> /// <param name="listName"></param> /// <returns></returns> internal SPListItem GetTeamLibraryItem(string teamUrl, string libraryName, string camlQuery) { SPListItem spLibraryItem = null; SPDocumentLibrary library = this.GetTeamLibrary(teamUrl, libraryName); SPQuery query = new SPQuery(); query.Query = camlQuery; query.RowLimit = 1; SPListItemCollection items = library.GetItems(query); // only looking for a single item if (items != null) { spLibraryItem = items[0]; } else { throw new Exception(string.Format("No dpcument found. team:{0}; list:{1}; caml:{2}", teamUrl, libraryName, camlQuery)); } return(spLibraryItem); }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { ExternalPolicy parent = (ExternalPolicy)context.Instance; string sSourceSiteURL = parent.SourceSiteURL; string sDocLibName = parent.DocumentLibrary; if ( (sSourceSiteURL != null) && (sDocLibName != null) ) { frmEditor = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); ListBox lbRuleSets = new ListBox(); SPSite site = new SPSite(sSourceSiteURL); SPWeb web = site.OpenWeb(); SPDocumentLibrary dl = (SPDocumentLibrary)web.Lists[sDocLibName]; CompositeActivity workflow = Utility.GetRootWorkflow(parent.Parent); SPQuery qry = new SPQuery(); qry.Query = string.Format(@"<Where><Eq><FieldRef Name='WorkflowName' /><Value Type='Text'>{0}</Value></Eq></Where>", workflow.QualifiedName); SPListItemCollection lic = dl.GetItems(qry); if (lic.Count > 0) { foreach (SPListItem li in lic) { lbRuleSets.Items.Add(Path.GetFileNameWithoutExtension(li.File.Name)); } } lbRuleSets.SelectedValueChanged += new EventHandler(lbRuleSets_SelectedValueChanged); frmEditor.DropDownControl(lbRuleSets); return(lbRuleSets.SelectedItem); } else { MessageBox.Show(@"You must specify a Document Library first!"); return(null); } }
public SPLicense.LicenseFile.SPLicenseFile GetLicense(Type type, object instance, bool allowExceptions) { try { TestLicense test = new TestLicense(); SPLicenseFile license = test.Create(type, instance, allowExceptions); string key = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString(); SPAdministrationWebApplication centralWebApp = SPAdministrationWebApplication.Local; SPSite lowSite = centralWebApp.Sites[0]; SPUserToken oSysToken = GetSysToken(lowSite.ID); using (SPSite centralSite = new SPSite(lowSite.ID, oSysToken)) { centralSite.AllowUnsafeUpdates = true; using (SPWeb centralWeb = centralSite.OpenWeb()) { bool availableList = true; SPFile licenseFile = null; SPFolder licenseFolder = null; centralWeb.AllowUnsafeUpdates = true; try { SPList LicenseList = centralWeb.Lists["Hemrika License Files"]; SPDocumentLibrary LicenseLibrary = (SPDocumentLibrary)LicenseList; licenseFolder = centralWeb.Folders["Hemrika License Files"]; /* * if (!Farmbag.Contains("Hemrika_Encryption_Key")) * { * Farmbag["Hemrika_Encryption_Key"] = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString(); * } * * encrypt = Farmbag["Hemrika_Encryption_Key"]; */ SPQuery oQuery = new SPQuery(); oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">" + type.Assembly.FullName + "</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>"); SPListItemCollection colListItems = LicenseLibrary.GetItems(oQuery); foreach (SPListItem licenseItem in colListItems) { licenseFile = licenseItem.File; break; } } catch (Exception) { availableList = false; } MemoryStream lic = null; //= new MemoryStream(); XmlDocument xml = new XmlDocument(); if (licenseFile == null) { lic = new MemoryStream(); xml.LoadXml(license.ToXmlString()); SPLicenseFile.SaveFile(license, lic, false, String.Empty, false); if (availableList && licenseFolder != null) { licenseFile = licenseFolder.Files.Add(type.Assembly.FullName + ".lic", lic, true); licenseFile.Update(); licenseFile.Item.Update(); } } if (lic != null) { lic.Close(); //lic.Dispose(); } if (licenseFile != null) { //byte[] bytes = licenseFile.OpenBinary(); //lic = new MemoryStream(); //lic.Read(bytes, 0, bytes.Length); license = SPLicenseFile.LoadFile(licenseFile.OpenBinaryStream(), type, false, String.Empty);// true, key); } /* * if (lic != null) * { * lic.Close(); * //lic.Dispose(); * } */ centralWeb.AllowUnsafeUpdates = false; } centralSite.AllowUnsafeUpdates = false; } return(license); } catch (Exception ex) { throw new LicenseException(type, instance, ex.Message, ex); } }
public static XmlDocument QueryFormLibrary(string SiteURL, string FormLibraryTitle, string OptionalContentType, string OptionalCAMLFilter, string OptionalBooleanIncludeAttachments) { //declare variables string currentUser = ""; try { //open site context using (SPSite site = new SPSite(SiteURL)) { using (SPWeb web = site.OpenWeb()) { //initialize Stopwatch watch = new Stopwatch(); int countItem = 0; currentUser = web.CurrentUser.LoginName.ToString(); watch.Start(); //validate parameter - FormLibraryTitle if (String.IsNullOrEmpty(FormLibraryTitle)) { //missing Form Library name, try to find first one in current Web foreach (SPList l in web.GetListsOfType(SPBaseType.DocumentLibrary)) { if (l.BaseTemplate == SPListTemplateType.XMLForm) { FormLibraryTitle = l.Title; break; } } //unable to find one, return error if (String.IsNullOrEmpty(FormLibraryTitle)) { throw new System.NullReferenceException("Required parameter missing. No form library provided and none exists on this site."); } } //open Form Library SPDocumentLibrary list = (SPDocumentLibrary)web.Lists[FormLibraryTitle]; //CAML filter to reduce number of items SPListItemCollection items; if (!String.IsNullOrEmpty(OptionalCAMLFilter)) { SPQuery query = new SPQuery(list.DefaultView); query.Query = OptionalCAMLFilter; items = list.GetItems(query); } else { items = list.Items; } countItem = items.Count; //open XML documents with XSD schema string result = ""; int i = 0; foreach (SPListItem item in items) { if (item.File.Name.ToUpper().EndsWith(".XML")) { try { //read file as XML byte[] data = item.File.OpenBinary(); XmlDocument xml = new XmlDocument(); MemoryStream stream = new MemoryStream(); stream.Write(data, 0, data.Length); stream.Seek(0, SeekOrigin.Begin); XmlTextReader reader = new XmlTextReader(stream); xml.Load(reader); xml = RemoveXmlns(xml.OuterXml); //loop XML child nodes foreach (XmlNode n in xml.ChildNodes) { string outer = n.OuterXml.ToString(); if (!outer.StartsWith("<?")) { string append = String.Format("<{0}>{1}</{0}>", n.Name, n.InnerXml.Replace(" xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "")); result += append; break; } } } catch (Exception ex) { //unable to process file result += String.Format("<Exception><File>{0}</File><Message>{1}</Message><StackTrace>{2}</StackTrace></Exception>", item.File.Name, ex.Message, ex.StackTrace); } } //increment item counter i++; } //diagnostic watch.Stop(); string durationMS = watch.ElapsedMilliseconds.ToString(); //return merged output result = "<NewDataSet>" + result + String.Format("<Diagnostic><DurationMS>{0}</DurationMS><SPListItems>{1}</SPListItems></Diagnostic></NewDataSet>", durationMS, countItem); //ULS and EventLog InfoPathDBLog.writeLog(String.Format("Success\r\nDurationMS:{6}\r\nSPListItems:{5}\r\nSiteURL:{0}\r\nFormLibraryTitle:{1}\r\nOptionalContentType:{2}\r\nOptionalCAMLFilter:{3}\r\nOptionalBooleanIncludeAttachments:{4}", SPContext.Current.Web.Url, FormLibraryTitle, OptionalContentType, OptionalCAMLFilter, OptionalBooleanIncludeAttachments, countItem, durationMS)); //return XmlDocument doc = new XmlDocument(); doc.LoadXml(result); return(doc); } } } catch (System.Exception ex) { //error handling InfoPathDBLog.writeLog(ex); XmlDocument doc = new XmlDocument(); doc.InnerXml = String.Format("<ERROR><Type>{0}</Type><Message>{1}</Message><Source>{2}</Source><StackTrace>{3}</StackTrace><TargetSite>{4}</TargetSite><InnerException>{5}</InnerException><HelpLink>{6}</HelpLink><User>{7}</User></ERROR>", cleanXml(ex.GetType()), cleanXml(ex.Message), cleanXml(ex.Source), cleanXml(ex.StackTrace), cleanXml(ex.TargetSite), cleanXml(ex.InnerException), cleanXml(ex.HelpLink), cleanXml(currentUser)); return(doc); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { SPWeb web = SPContext.Current.Site.RootWeb; SPDocumentLibrary library = (SPDocumentLibrary)web.Lists.TryGetList(this.ListDataSource); if (library != null) { var query = new SPQuery() { Query = String.Format(@" <OrderBy> <FieldRef Name='Ordem' Ascending='True' /> </OrderBy> <Where> <And> <Leq> <FieldRef Name='DataInicio' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value> </Leq> <And> <Gt> <FieldRef Name='DataFim' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value> </Gt> <Eq> <FieldRef Name='_ModerationStatus' /> <Value Type='ModStat'>0</Value> </Eq> </And> </And> </Where>", SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)) }; SPListItemCollection items = library.GetItems(query); int num = 1; foreach (SPListItem item in items) { if (this.TVFlashHtml != null) { this.TVFlashHtml = this.TVFlashHtml + ", "; } var link = string.Format("{0}", Convert.ToString(item["Url"]).Replace("&", "{}")); this.TVFlashHtml += this.cliptemplate .Replace("{url}", web.Site.MakeFullUrl(item.Url)) .Replace("{text}", num++.ToString()) .Replace("{linkurl}", link) //.Replace("{destino}", (string)item["Destino"] ?? "") .Replace("{Posicao}", double.Parse((item["Posicao"] ?? "0").ToString()).ToString()) .Replace("{Duracao}", double.Parse((item["Duracao"] ?? "5").ToString()).ToString()); } } } }
private void PopulateListOfItems(SPDocumentLibrary lib, SPQuery query, ref List<Item> items) { SPListItemCollection listItems = lib.GetItems(query); PopulateListOfItems(listItems, ref items); }