private static void RemoveOldFiles(SPWeb web) { SPList list = GetOASList(web); DateTime limit_date = DateTime.Now.Subtract(new TimeSpan(TIME_LIMIT, 0, 0)); web.AllowUnsafeUpdates = true; bool removed = false; do { removed = false; SPListItemCollection listItems = list.Items; int itemCount = listItems.Count; for (int k = 0; k < itemCount; k++) { SPListItem item = listItems[k]; if ((DateTime)item["Started"] < limit_date) { //source file string fileid = item["FileId"].ToString(); //conveted file string source = Path.GetFileNameWithoutExtension(fileid); SPFolder lib = GetOASLibrary(web); //delete result file SPFile res = GetFile(lib, fileid); if (res != null) { res.Delete(); lib.Update(); } //delete source file res = GetFile(lib, source); if (res != null) { res.Delete(); lib.Update(); } listItems.Delete(k); removed = true; break; } } }while (removed); web.AllowUnsafeUpdates = false; }
public static void WriteLogFile(SPWeb web, string message) { string sLibrary = "Έγγραφα"; string sFilename = "log.txt"; web.AllowUnsafeUpdates = true; SPDocumentLibrary documentLibrary = (SPDocumentLibrary)web.Lists[sLibrary]; string log = documentLibrary.RootFolder.Url + @"/" + sFilename; SPFile spf = web.GetFile(log); ASCIIEncoding enc = new ASCIIEncoding(); string dt = DateTime.Now.ToString("yyyy-MM-dd hh:mm"); message = dt + " " + message; if (!spf.Exists) { SPFolder myLibrary = web.Folders["Shared Documents"]; Boolean replaceExistingFiles = true; String fileName = System.IO.Path.GetFileName("log.txt"); byte[] buffer = enc.GetBytes(message); SPFile spfile = myLibrary.Files.Add(fileName, buffer, replaceExistingFiles); myLibrary.Update(); } else { byte[] contents = spf.OpenBinary(); string newContents = enc.GetString(contents) + Environment.NewLine + message; spf.SaveBinary(enc.GetBytes(newContents)); } }
private void DeployWelcomePage(object modelHost, DefinitionBase model, SPFolder folder, WelcomePageDefinition welcomePgaeModel) { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = welcomePgaeModel, ModelHost = modelHost }); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Changing welcome page to: [{0}]", welcomePgaeModel.Url); // https://github.com/SubPointSolutions/spmeta2/issues/431 folder.WelcomePage = UrlUtility.RemoveStartingSlash(welcomePgaeModel.Url); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = welcomePgaeModel, ModelHost = modelHost }); folder.Update(); }
private static void EnsureUniqueContentTypeOrder(SPFolder folder, FolderInfo folderInfo) { if (folderInfo.UniqueContentTypeOrder != null && folderInfo.UniqueContentTypeOrder.Count > 0) { SPContentTypeCollection listContentTypes = folder.ParentWeb.Lists[folder.ParentListId].ContentTypes; IList <SPContentType> uniqueOrder = new List <SPContentType>(); foreach (ContentTypeInfo needToEnsureThisCTInfo in folderInfo.UniqueContentTypeOrder) { var foundRealCT = listContentTypes[needToEnsureThisCTInfo.ContentTypeId]; if (foundRealCT == null) { // Failed to find CT with direct ID lookup: now let's assume that we were given site collection CT IDs as // input and that we need to inspect the list CTs' parents to find a match. foreach (var listCT in listContentTypes.Cast <SPContentType>()) { if (listCT.Id.Parent == needToEnsureThisCTInfo.ContentTypeId) { foundRealCT = listCT; break; } } } uniqueOrder.Add(foundRealCT); } folder.UniqueContentTypeOrder = uniqueOrder; folder.Update(); } }
public static void PushFile() { String fileToUpload = @"C:\YourFile.txt"; String sharePointSite = "http://yoursite.com/sites/Research/"; String documentLibraryName = "Shared Documents"; using (SPSite oSite = new SPSite(sharePointSite)) { using (SPWeb oWeb = oSite.OpenWeb()) { if (!System.IO.File.Exists(fileToUpload)) { throw new FileNotFoundException("File not found.", fileToUpload); } SPFolder myLibrary = oWeb.Folders[documentLibraryName]; // Prepare to upload Boolean replaceExistingFiles = true; String fileName = System.IO.Path.GetFileName(fileToUpload); FileStream fileStream = System.IO.File.OpenRead(fileToUpload); // Upload document SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles); // Commit myLibrary.Update(); } } }
protected static async Task copyTemplatesAsync(Guid siteId, Guid webId, Guid listId, int itemId, SPUserToken userToken, bool addTemplates, bool isProtected) { await Task.Run(() => { using (SPSite qSite = new SPSite(siteId, userToken)) using (SPWeb qWeb = qSite.OpenWeb(webId)) { SPList qList = qWeb.Lists[listId]; SPListItem qBriefingItem = qList.GetItemById(itemId); string folderUrl = Config.System.RootWebBriefingTemplatesFolder; if (addTemplates && folderUrl != null) { SPFolder bfTemplateFolder = qWeb.ParentWeb.GetFolder(SPUrlUtility.CombineUrl(qWeb.ParentWeb.Url, folderUrl)); copyTemplates(bfTemplateFolder, qBriefingItem.Folder, isProtected); } string libraryUrl = Config.System.CurrentWebBriefingTemplatesLibrary; if (libraryUrl != null) { SPFolder briefingFolder = qBriefingItem.Folder; if (addTemplates) { SPList bfTemplateLibrary = qWeb.GetList(SPUrlUtility.CombineUrl(qWeb.Url, libraryUrl)); copyTemplates(bfTemplateLibrary.RootFolder, briefingFolder, isProtected); } List <SPContentType> contenttypes = new List <SPContentType>(); contenttypes.Add(qBriefingItem.ParentList.ContentTypes["Document"]); briefingFolder.UniqueContentTypeOrder = contenttypes; briefingFolder.Update(); } } }); }
/// <summary> /// Error message: /// An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll /// Additional information: Could not load file or assembly 'Microsoft.SharePoint.Library, /// Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' /// or one of its dependencies.The system cannot find the file specified. /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine(12345); String fileToUpload = @"D:\test.txt"; String sharePointSite = "http://yoursite.com/sites/Research/"; sharePointSite = @"https://microsoft.sharepoint.com/teams/Office365CoreSharedDataEngineeringManagers/"; String documentLibraryName = @"Data Build\StreamAvailabilityCheck\test.txt"; using (SPSite oSite = new SPSite(sharePointSite)) { using (SPWeb oWeb = oSite.OpenWeb()) { if (!File.Exists(fileToUpload)) { throw new FileNotFoundException("File not found.", fileToUpload); } SPFolder myLibrary = oWeb.Folders[documentLibraryName]; // Prepare to upload Boolean replaceExistingFiles = true; String fileName = System.IO.Path.GetFileName(fileToUpload); FileStream fileStream = File.OpenRead(fileToUpload); // Upload document SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles); // Commit myLibrary.Update(); } } }
private void DeployWelcomePage(object modelHost, DefinitionBase model, SPFolder folder, WelcomePageDefinition welcomePgaeModel) { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = welcomePgaeModel, ModelHost = modelHost }); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Changing welcome page to: [{0}]", welcomePgaeModel.Url); folder.WelcomePage = welcomePgaeModel.Url; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = welcomePgaeModel, ModelHost = modelHost }); folder.Update(); }
protected void update_folder_time(SPFolder current_folder) { if (current_folder == null || !current_folder.Url.Contains("/")) return; current_folder.SetProperty("Name", current_folder.Name); current_folder.Update(); update_folder_time(current_folder.ParentFolder); }
private static void DeleteSubFoldersAndFiles(SPFolder spFolder) { for (var i = spFolder.SubFolders.Count - 1; i >= 0; i--) { //delete the subfolder first DeleteSubFoldersAndFiles(spFolder.SubFolders[i]); } //now delete all of these files for (var i = spFolder.Files.Count - 1; i >= 0; i--) { try { spFolder.Files[i].Delete(); } catch (Exception se) { /*Error("Deactivate: Unable to delete: " + subsubFolder.Name + " - " + i.ToString() + " " + ex.Message);*/ } } //then delete the sub directory try { spFolder.Update(); spFolder.Delete(); } catch (Exception se) { /*Error("Deactivate: Unable to delete folder: " + subFolder.Folder.Name + " - " + j.ToString() + " " + ex.Message);*/ } }
public Guid AddFile(string Site, string List, string Filename, string Extension, byte[] Content) { try { using (SPSite spsite = new SPSite(Site)) { using (SPWeb spweb = spsite.OpenWeb()) { spweb.AllowUnsafeUpdates = true; SPFolder spfolder = spweb.Folders[Site + "/" + List]; string nombreArchivo = Filename + Extension; int contador = 0; while (spfolder.Files[nombreArchivo].Exists) { contador++; nombreArchivo = Filename + "_" + contador.ToString() + Extension; } SPFile spfile = spfolder.Files.Add(nombreArchivo, Content, true); spfolder.Update(); spweb.Update(); return(spfile.UniqueId); } } } catch (Exception ex) { ISException.RegisterExcepcion(ex); throw ex; } }
public static void RemoveWelcomePage(SPSite site) { if (site != null) { SPFolder folder = site.RootWeb.RootFolder; folder.WelcomePage = site.RootWeb.Properties[KeyCustomWelcomePage]; folder.Update(); } }
public static void RemoveCustomSettings <T>(this SPList list, AIAPortalFeatures featureName) { string strKey = Utility.BuildKey <T>(featureName); SPFolder rootFolder = list.RootFolder; rootFolder.Properties.Remove(strKey); rootFolder.Update(); }
public ArtDevFeature SetHomePage(string url) { SPWeb web = this.Web(); SPFolder rootFolder = web.RootFolder; rootFolder.WelcomePage = url; rootFolder.Update(); return(this); }
public string UploadFileToDocLib(string OutputFolder, string SelectedfilePath, string DocLib) { try { string url = ""; SPSite Site = new SPSite(ConfigurationManager.AppSettings["SharePointOnPremURL"].ToString()); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = Site.OpenWeb()) { web.AllowUnsafeUpdates = true; if (!System.IO.File.Exists(SelectedfilePath)) { throw new FileNotFoundException("File not found.", SelectedfilePath); } SPFolder libFolder = web.Folders[DocLib]; // Prepare to upload string fileName = System.IO.Path.GetFileName(SelectedfilePath); FileStream fileStream = System.IO.File.OpenRead(SelectedfilePath); //Check the existing File out if the Library Requires CheckOut if (libFolder.RequiresCheckout) { try { SPFile fileOld = libFolder.Files[fileName]; url = fileOld.Url; fileOld.CheckOut(); } catch { } } // Upload document SPFile spfile = libFolder.Files.Add(fileName, fileStream, true); libFolder.Update(); url = spfile.Url; try { fileStream.Close(); } catch (Exception) { } web.AllowUnsafeUpdates = false; } }); return(url); } catch (Exception ex) { new GenerateTxt().GenerateTxtLogError(OutputFolder, ex.Message, "UploadFileToDocLib - " + DocLib); return(""); } }
public static void SetCustomProperty(this SPList list, string key, string value) { list.ParentWeb.AllowUnsafeUpdates = true; SPFolder rootFolder = list.RootFolder; rootFolder.Properties[key] = value; rootFolder.Update(); list.ParentWeb.AllowUnsafeUpdates = false; }
/// <summary> /// Copy a file /// </summary> /// <param name="file">Source file</param> /// <param name="destinationFolder">Destination folder</param> /// <returns></returns> private void CopyFile(SPFile file, SPFolder destinationFolder) { Debug.WriteLine("* CopyFile"); SPFile newFile; string fileName = GetNewFileName(file.Name, destinationFolder, 0); Debug.WriteLine("* CopyFile " + fileName); try { if (file.Versions != null && file.Versions.Count > 0) { SPSecurity.RunWithElevatedPrivileges(() => CopyVersions(file, destinationFolder, fileName)); Debug.WriteLine("* VCopyFile " + file.Name + " " + file.MajorVersion + "." + file.MinorVersion); newFile = CopyFileEnsureCheckIn(destinationFolder, file, fileName); } else { Debug.WriteLine("* CopyFile " + file.Name); newFile = destinationFolder.Files.Add(fileName, file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan), true, file.CheckInComment, false); EnsureCheckIn(newFile, file.CheckInComment); CopyMetadata(file, newFile, false); newFile.Item["Created"] = file.TimeCreated; newFile.Item["Modified"] = file.TimeLastModified; newFile.Item["Author"] = file.Author; newFile.Item.UpdateOverwriteVersion(); } if (file.Level.ToString() == "Published" && destinationFolder.Item != null && destinationFolder.Item.ParentList.EnableMinorVersions && newFile != null) { newFile.Publish(file.CheckInComment); } } catch (Exception ex) { Debug.WriteLine("CF"); Debug.WriteLine(ex); } destinationFolder.Update(); }
public static void CopyAllItemsToList(this SPList source, SPList destinationList) { //using (SPWeb web = SPContext.Current.Web) SPWeb web = SPContext.Current.Web; { web.AllowUnsafeUpdates = true; foreach (SPListItem item in source.Items) { //SPListItem SourceItem = CurrentList.GetItemById(int.Parse(Request.QueryString["ID"])); SPListItem newDestItem; if (item.File == null) { newDestItem = destinationList.Items.Add(); foreach (string fileName in item.Attachments) { SPFile file = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + fileName); byte[] imageData = file.OpenBinary(); newDestItem.Attachments.Add(fileName, imageData); } try { foreach (SPField field in item.Fields) { if ((!field.ReadOnlyField) && (field.InternalName != "Attachments")) { newDestItem[field.InternalName] = item[field.InternalName]; } } } catch { } //newDestItem["Title"] = ""; } else { SPFolder currentFolder = item.Folder == null ? source.RootFolder : item.Folder; SPFile newFile = currentFolder.Files.Add(item.File.Name, item.File.OpenBinary()); currentFolder.Update(); newDestItem = newFile.Item; foreach (SPField field in item.Fields) { if ((!field.ReadOnlyField) && (field.InternalName != "Attachments") && (field.InternalName != "FileLeafRef")) { newDestItem[field.InternalName] = item[field.InternalName]; } } } newDestItem.Update(); } web.AllowUnsafeUpdates = false; } }
protected void update_folder_time(SPFolder current_folder) { if (current_folder == null || !current_folder.Url.Contains("/")) { return; } current_folder.SetProperty("Name", current_folder.Name); current_folder.Update(); update_folder_time(current_folder.ParentFolder); }
void SaveFile(SPFolder folder, string fileName, ZipEntry entry) { using (MemoryStream stream = new MemoryStream()) { entry.Extract(stream); stream.Flush(); SPFile file = folder.Files.Add(fileName, stream, true); folder.Update(); } }
private static void RemoveConversionFiles(SPWeb web, string JobId) { SPList list = GetOASList(web); SPListItemCollection listItems = list.Items; int itemCount = listItems.Count; web.AllowUnsafeUpdates = true; for (int k = 0; k < itemCount; k++) { SPListItem item = listItems[k]; if (JobId == item["JobId"].ToString()) { //source file string fileid = item["FileId"].ToString(); //conveted file string source = Path.GetFileNameWithoutExtension(fileid); SPFolder lib = GetOASLibrary(web); //delete result file SPFile res = GetFile(lib, fileid); if (res != null) { res.Delete(); lib.Update(); } //delete source file res = GetFile(lib, source); if (res != null) { res.Delete(); lib.Update(); } listItems.Delete(k); break; } } web.AllowUnsafeUpdates = false; }
/// <summary> /// Creates sub folder under a specific assignment folder, it is being named after the specified learner's name. /// </summary> SPListItem CreateSubFolder(string newFolderName) { SPFolder folder = assignmentFolder.Folder; using (new AllowUnsafeUpdates(web)) { SPFolder learnerSubFolder = folder.SubFolders.Add(newFolderName); learnerSubFolder.Update(); DropBoxCreator.ClearPermissions(learnerSubFolder.Item); return(learnerSubFolder.Item); } }
// Uncomment the method below to handle the event raised before a feature is deactivated. public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { SPWeb curWeb = (SPWeb)properties.Feature.Parent; //Create full Home page URL if (curWeb != null) { SPFolder rootFolder = curWeb.RootFolder; rootFolder.WelcomePage = "SitePages/Home.aspx"; rootFolder.Update(); } }
/// <summary> /// Saves the provided byte[] as a file to the specified document library /// </summary> /// <param name="teamUrl">Url to target team site</param> /// <param name="fileName">Name of the file to save</param> /// <param name="fileStream">file contents in bytes</param> /// <param name="replaceExistingFile">flag to overwrite file</param> internal void SaveFileToLibrary(string teamUrl, string fileName, byte[] fileStream, bool replaceExistingFile) { string libraryName = "KPDocuments"; SPWeb spWeb = GetTeamWeb(teamUrl); SPFolder library = spWeb.Folders[libraryName]; // Upload document SPFile spfile = library.Files.Add(fileName, fileStream, replaceExistingFile); // Commit library.Update(); }
public SPFileInstance AddFile(object file, [DefaultParameterValue(true)] bool overwrite) { SPFile result; if (file is Base64EncodedByteArrayInstance) { var byteArray = file as Base64EncodedByteArrayInstance; if (String.IsNullOrEmpty(byteArray.FileName)) { throw new JavaScriptException(Engine, "Error", "The specified Base64EncodedByteArray did not specify a filename."); } m_folder.ParentWeb.AllowUnsafeUpdates = true; result = m_folder.Files.Add(m_folder.ServerRelativeUrl + "/" + byteArray.FileName, byteArray.Data, overwrite); m_folder.Update(); m_folder.ParentWeb.AllowUnsafeUpdates = false; } else { throw new JavaScriptException(Engine, "Error", "Unsupported type when adding a file: " + file.GetType()); } return(new SPFileInstance(Engine.Object.InstancePrototype, result)); }
public override void WebProvisioned(SPWebEventProperties properties) { try { if (properties.Web.WebTemplate.ToLower() == "websiteabout") { properties.Web.AllowUnsafeUpdates = true; SPFolder rootFolder = properties.Web.RootFolder; //SPFile file = properties.Web.GetFile("Pages/Default.aspx"); rootFolder.WelcomePage = "Pages/default.aspx"; rootFolder.Update(); properties.Web.Update(); properties.Web.AllowUnsafeUpdates = false; } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } SPUtility.ValidateFormDigest(); try { SPList page = properties.Web.Lists["Pages"]; //page.DraftVersionVisibility = DraftVisibilityType.Author | DraftVisibilityType.Approver; page.EnableVersioning = true; page.EnableMinorVersions = true; page.EnableThrottling = true; page.Update(); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data); //ex.ToString(); } if (properties.Web.WebTemplate.ToLower() == "websiteabout") { CreateWorkItem(properties, "/Pages/default.aspx", ""); CreateWorkItem(properties, "/Pages/People.aspx", "/People"); CreateWorkItem(properties, "/Pages/About.aspx", "/About"); CreateWorkItem(properties, "/Pages/Legal.aspx", "/Legal"); CreateWorkItem(properties, "/Pages/History.aspx", "/History"); } }
/// <summary> /// Copy a folder inside other folder /// </summary> /// <param name="folder">Source folder</param> /// <param name="destinationFolder">Destination folder</param> /// <returns></returns> /// TODO: Comprobar si una carpeta se copia sobre si misma. private void CopyFolder(SPFolder folder, SPFolder destinationFolder) { //if (!destinationFolder.Url.Contains(folder.Url)) try { SPList list = destinationFolder.ParentWeb.Lists[destinationFolder.ParentListId]; string newFolderUrl = destinationFolder.Url + "/" + folder.Name; Debug.WriteLine("Destination Folder Name:" + destinationFolder.Name); Debug.WriteLine("Destination Folder Url :" + destinationFolder.Url); Debug.WriteLine(" New Folder Url :" + newFolderUrl); // Make the new folder SPFolder newFolder = destinationFolder.SubFolders.Add(folder.Name); destinationFolder.Update(); SPUser user = SPContext.Current.Web.CurrentUser; Debug.WriteLine("USER & PERMISSIONS: " + user.Name); Debug.WriteLine(list.ParentWeb.EffectiveBasePermissions.ToString()); // list.Update(); BUG !! list.ParentWeb.AllowUnsafeUpdates = true; list.ParentWeb.Update(); list.ParentWeb.AllowUnsafeUpdates = false; Debug.WriteLine("Folder:" + folder.Name + " Dest:" + destinationFolder.Name); // Copy Folders recursive foreach (SPFolder subFolder in folder.SubFolders) { CopyFolder(subFolder, newFolder); } // Recursive file and folder copies foreach (SPFile file in folder.Files) { CopyFile(file, newFolder); } } catch (Exception ex) { Debug.WriteLine("*CopyFolder"); Debug.WriteLine(ex); } return; }
public void SaveToListProperty(SPList list) { SPFolder folder = list.RootFolder; IEnumerable <FieldInfo> fields = GetCfgFields(); foreach (FieldInfo field in fields) { folder.SetProperty(PropertyKeyPrefix + field.Name, Convert.ToString(field.GetValue(this))); } bool allowUnsafeUpdates = list.ParentWeb.AllowUnsafeUpdates; list.ParentWeb.AllowUnsafeUpdates = true; folder.Update(); list.ParentWeb.AllowUnsafeUpdates = allowUnsafeUpdates; }
public static void SetWelcomePage(SPSite site, string pageUrl) { if (site != null) { SPFolder folder = site.RootWeb.RootFolder; var properties = site.RootWeb.Properties; if (properties.ContainsKey(KeyCustomWelcomePage)) { properties[KeyCustomWelcomePage] = folder.WelcomePage; properties.Update(); } folder.WelcomePage = pageUrl; folder.Update(); } }
/// <summary>Creates the assignment folder.</summary> /// <param name="properties">The assignment properties.</param> /// <returns>The assignment folder.</returns> public AssignmentFolder CreateAssignmentFolder(AssignmentProperties properties) { string url = DropBoxList.RootFolder.ServerRelativeUrl; SPFolder noPermissionsFolder = GetNoPermissionsFolder().Folder; using (new AllowUnsafeUpdates(web)) { string name = GenerateFolderName(properties); SPFolder folder = noPermissionsFolder.SubFolders.Add(name); folder.MoveTo(url + "\\" + name); folder.Update(); SPListItem assignmentFolder = folder.Item; DropBoxCreator.ClearPermissions(assignmentFolder); DropBoxList.Update(); CreateAssignmentView(properties); return(new AssignmentFolder(assignmentFolder, false, properties)); } }
private void SaveToSharePoint(string data, string DestinationFile) { byte[] bytes = Encoding.ASCII.GetBytes(data); //Upload file to SharePoint document linrary //Read create stream using (MemoryStream stream = new MemoryStream(bytes)) { //Get handle of library SPFolder spLibrary = CurrentWeb.Folders[DestinationLibName]; //Replace existing file var replaceExistingFile = true; //Upload document to library SPFile spfile = spLibrary.Files.Add(DestinationFile, stream, replaceExistingFile); spLibrary.Update(); } }
private void AddFolderPages(SPList library, SPFolder folder, IFolderInfo folderInfo) { if (folderInfo.Pages != null) { var publishingSite = new PublishingSite(library.ParentWeb.Site); var publishingWeb = PublishingWeb.GetPublishingWeb(library.ParentWeb); var publishingPages = publishingWeb.GetPublishingPages(); foreach (var page in folderInfo.Pages) { PageLayout pageLayout; // If a page layout was specified and its from the correct web. if (page.PageLayout != null && page.PageLayout.ListItem.ParentList.ParentWeb.ID == publishingSite.RootWeb.ID) { // Associate the page layout specified in the page. pageLayout = page.PageLayout; } else { // Get the first page layout with the specified content type id. var pageContentType = publishingSite.ContentTypes[page.ContentTypeId]; var pageLayouts = publishingSite.GetPageLayouts(pageContentType, true); pageLayout = pageLayouts[0]; // default to first associated page layout } var pageServerRelativeUrl = folder.ServerRelativeUrl + "/" + page.Name + ".aspx"; var existingPage = publishingWeb.GetPublishingPage(pageServerRelativeUrl); if (existingPage == null) { // Only create the page if it doesn't exist yet var publishingPage = publishingPages.Add(pageServerRelativeUrl, pageLayout); this.EnsurePageCheckOut(publishingPage); var item = publishingPage.ListItem; ApplyPageValues(item, page); publishingPage.Update(); // Add webparts to the page this.EnsureWebpartsOnPage(publishingPage); if (page.IsWelcomePage) { folder.WelcomePage = item.Name; folder.Update(); EnsureFolderPublish(folder); if (folder.UniqueId == library.RootFolder.UniqueId) { // We are setting the Pages library's root folder's welcome page, so let's assume this means we also need to set it as the website's welcome page as well var webRootFolder = library.ParentWeb.RootFolder; webRootFolder.WelcomePage = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", publishingPages.PubWeb.PagesListName, publishingPage.Name); webRootFolder.Update(); EnsureFolderPublish(folder); } } EnsurePageCheckInAndPublish(publishingPage); } else { this.logger.Info("Folder maker is skipping the creation of page '{0}' because it already exists.", existingPage.Url); if (this.defaultPageWebPartIndex.GetDefaultWebPartsForPageUrl(existingPage.Url) != null) { // If there are some registered on the index, add the // webparts to the page (make sure to checkout/checkin). this.logger.Info("Ensuring the existance of the webparts on page '{0}'.", existingPage.Url); this.EnsurePageCheckOut(existingPage); this.EnsureWebpartsOnPage(existingPage); EnsurePageCheckInAndPublish(existingPage); } } } } }
private void DeployContentTypeOrder(object modelHost, SPList list, SPFolder folder, UniqueContentTypeOrderDefinition contentTypeOrderDefinition) { var oldContentTypeOrder = folder.ContentTypeOrder; var newContentTypeOrder = new List<SPContentType>(); var listContentTypes = list.ContentTypes.OfType<SPContentType>().ToList(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); // re-order foreach (var srcContentTypeDef in contentTypeOrderDefinition.ContentTypes) { SPContentType listContentType = null; if (!string.IsNullOrEmpty(srcContentTypeDef.ContentTypeName)) { listContentType = listContentTypes.FirstOrDefault(c => c.Name.ToUpper() == srcContentTypeDef.ContentTypeName.ToUpper()); if (listContentType != null) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, string.Format("Found content type by name:[{0}]", srcContentTypeDef.ContentTypeName)); } } if (listContentType == null && !string.IsNullOrEmpty(srcContentTypeDef.ContentTypeId)) { listContentType = listContentTypes.FirstOrDefault(c => c.Id.ToString().ToUpper().StartsWith(srcContentTypeDef.ContentTypeId.ToUpper())); if (listContentType != null) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, string.Format("Found content type by matching ID start:[{0}]", srcContentTypeDef.ContentTypeId)); } } if (listContentType != null && !newContentTypeOrder.Contains(listContentType)) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, string.Format("Adding content type to new ordering")); newContentTypeOrder.Add(listContentType); } } // filling up gapes foreach (var oldCt in oldContentTypeOrder) { if (newContentTypeOrder.Count(c => c.Name == oldCt.Name || c.Id.ToString().ToUpper().StartsWith(oldCt.Id.ToString().ToUpper())) == 0) newContentTypeOrder.Add(oldCt); } if (newContentTypeOrder.Count() > 0) folder.UniqueContentTypeOrder = newContentTypeOrder; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); folder.Update(); }
private void DeployContentTypeOrder(object modelHost, SPList list, SPFolder folder, UniqueContentTypeOrderDefinition contentTypeOrderDefinition) { var oldContentTypeOrder = folder.ContentTypeOrder; var newContentTypeOrder = new List<SPContentType>(); var listContentTypes = list.ContentTypes.OfType<SPContentType>().ToList(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); // re-order foreach (var srcContentTypeDef in contentTypeOrderDefinition.ContentTypes) { SPContentType listContentType = null; if (!string.IsNullOrEmpty(srcContentTypeDef.ContentTypeName)) listContentType = listContentTypes.FirstOrDefault(c => c.Name == srcContentTypeDef.ContentTypeName); if (listContentType == null && !string.IsNullOrEmpty(srcContentTypeDef.ContentTypeId)) listContentType = listContentTypes.FirstOrDefault(c => c.Id.ToString().ToUpper().StartsWith(srcContentTypeDef.ContentTypeId.ToUpper())); if (listContentType != null && !newContentTypeOrder.Contains(listContentType)) newContentTypeOrder.Add(listContentType); } // filling up gapes foreach (var oldCt in oldContentTypeOrder) { if (newContentTypeOrder.Count(c => c.Name == oldCt.Name || c.Id.ToString().ToUpper().StartsWith(oldCt.Id.ToString().ToUpper())) == 0) newContentTypeOrder.Add(oldCt); } if (newContentTypeOrder.Count() > 0) folder.UniqueContentTypeOrder = newContentTypeOrder; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); folder.Update(); }
private static void EnsureUniqueContentTypeOrder(SPFolder folder, FolderInfo folderInfo) { if (folderInfo.UniqueContentTypeOrder != null && folderInfo.UniqueContentTypeOrder.Count > 0) { SPContentTypeCollection listContentTypes = folder.ParentWeb.Lists[folder.ParentListId].ContentTypes; IList<SPContentType> uniqueOrder = new List<SPContentType>(); foreach (ContentTypeInfo needToEnsureThisCTInfo in folderInfo.UniqueContentTypeOrder) { var foundRealCT = listContentTypes[needToEnsureThisCTInfo.ContentTypeId]; if (foundRealCT == null) { // Failed to find CT with direct ID lookup: now let's assume that we were given site collection CT IDs as // input and that we need to inspect the list CTs' parents to find a match. foreach (var listCT in listContentTypes.Cast<SPContentType>()) { if (listCT.Id.Parent == needToEnsureThisCTInfo.ContentTypeId) { foundRealCT = listCT; break; } } } uniqueOrder.Add(foundRealCT); } folder.UniqueContentTypeOrder = uniqueOrder; folder.Update(); } }
private void DeployHideContentTypeLinks(object modelHost, SPList list, SPFolder folder, HideContentTypeLinksDefinition contentTypeOrderDefinition) { var oldContentTypeOrder = folder.ContentTypeOrder; var newContentTypeOrder = oldContentTypeOrder; var listContentTypes = list.ContentTypes.OfType<SPContentType>().ToList(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); // re-order foreach (var srcContentTypeDef in contentTypeOrderDefinition.ContentTypes) { SPContentType listContentType = null; if (!string.IsNullOrEmpty(srcContentTypeDef.ContentTypeName)) listContentType = listContentTypes.FirstOrDefault(c => c.Name == srcContentTypeDef.ContentTypeName); if (listContentType == null && !string.IsNullOrEmpty(srcContentTypeDef.ContentTypeId)) listContentType = listContentTypes.FirstOrDefault(c => c.Id.ToString().ToUpper().StartsWith(srcContentTypeDef.ContentTypeId.ToUpper())); if (listContentType != null) { var existingCt = newContentTypeOrder.FirstOrDefault(ct => ct.Name == listContentType.Name || ct.Id == listContentType.Id); if (existingCt != null && newContentTypeOrder.Contains(existingCt)) newContentTypeOrder.Remove(existingCt); } } if (newContentTypeOrder.Count() > 0) folder.UniqueContentTypeOrder = newContentTypeOrder; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = folder, ObjectType = typeof(SPFolder), ObjectDefinition = contentTypeOrderDefinition, ModelHost = modelHost }); folder.Update(); }