private static void Copy_Attachement(SPListItem newItem, SPFile file) { int bufferSize = 20480; byte[] byteBuffer = new byte[bufferSize]; byteBuffer = file.OpenBinary(); newItem.Attachments.Add(file.Name, byteBuffer); }
public FileNode(SPFile file, bool showVersions) { this.Tag = file; this.ShowVersions = showVersions; int index = Program.Window.Explorer.AddImage(this.ImageUrl()); this.ImageIndex = index; this.SelectedImageIndex = index; this.Setup(); this.Nodes.Add(new ExplorerNodeBase("Dummy")); try { if (file.Item != null) { this.SPParent = file.Item.ParentList; } } catch { // Do nothing // sometimes the file.Item throws an exception } }
protected void AddFileItem() { SPContentTypeId listItemContentTypeId = new SPContentTypeId(_ContentTypeId); _FieldValues.Add("ContentType", _SPWeb.ContentTypes[listItemContentTypeId].Name); _File= _List.RootFolder.Files.Add(_FileName, _FileData, _FieldValues, _Overwrite); _ListItem = _File.Item; }
internal SPGENRepositoryDataItemFile(SPFile file, SPGENEntityFileOperationArguments fileOperationParams) { this.FileName = file.Name; if (fileOperationParams.FileMappingMode == SPGENEntityFileMappingMode.MapFileNameAndContentAsStreamLazy) { this.FileStreamFunc = new Func<Stream>(() => { if (_isInternalCall && !_skipInternalCallCheck) return null; return file.OpenBinaryStream(fileOperationParams.OpenFileOptions); }); } else if (fileOperationParams.FileMappingMode == SPGENEntityFileMappingMode.MapFileNameAndContentAsByteArrayLazy || fileOperationParams.FileMappingMode == SPGENEntityFileMappingMode.MapFileNameAndContentAsByteArray) { this.FileByteArrayFunc = new Func<byte[]>(() => { if (_isInternalCall && !_skipInternalCallCheck) return null; return file.OpenBinary(fileOperationParams.OpenFileOptions); }); } else { throw new NotSupportedException(); } }
/// <summary> /// Adds new web parts to the default home page. /// </summary> /// private void AddWebParts(SPWeb CurrentWeb) { try { /* Retrieve an instance of the default.aspx as a SPFile object. */ this._homePage = CurrentWeb.GetFile("default.aspx"); /* Retrieve an instance of the SPLimitedWebPartManager object. */ SPLimitedWebPartManager wpm = this._homePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); /* Create an instance ofthe AsyncWebPart1 object. */ this._asyncWP = new AsyncWP1(); this._asyncWPExists = false; /* Loop through the web part manager to see if the web part exists. */ foreach (WebPart webPart in wpm.WebParts) { if (webPart.GetType().FullName == this._asyncWP.GetType().FullName) { _asyncWPExists = true; break; } } /* Add the web part to the page if not found on the page. */ if (this._asyncWPExists == false) { this._asyncWP.Title = "Asynchronous Web Part Example (SPDudes)"; this._asyncWP.ToolTip = "Asynchronous Web Part Example (SPDudes)"; wpm.AddWebPart(this._asyncWP, "left", 0); } } catch (Exception ex) { throw; } }
private void CheckinFile(SPFile file) { if (file.CheckOutType != SPFile.SPCheckOutType.None) { file.CheckIn("Checked in via feature activation.", SPCheckinType.MajorCheckIn); //styleFile.Approve("Approved via feature activation."); } }
private static void AddFile(ZipFileBuilder builder, SPFile file, string folder) { using (Stream fileStream = file.OpenBinaryStream()) { builder.Add(folder + "\\" + file.Name, fileStream); fileStream.Close(); } }
public FileContentParser(SPFile file) { this.mainFile = file; this.parentFolder = file.ParentFolder; this.mainContent = GetContent(mainFile); IncludedFiles = FileInclusionParser.GetIncludedFiles(mainContent); }
public FileVersionCollectionNode(SPFile file) { this.Tag = file.Versions; this.SPParent = file; this.Setup(); this.Nodes.Add(new ExplorerNodeBase("Dummy")); }
private string GetContent(SPFile file) { string content = Encoding.UTF8.GetString(RemoveBOM(file.OpenBinary())); if (file.Name.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase)) content = new CssRelativePathResolver(file.ServerRelativeUrl, content).Resolve(); return content; }
public EntityLockInfo(SPFile file) { if (file == null) throw new ArgumentNullException("file"); LockType = file.LockType; LockId = file.LockId; LockExpires = file.LockExpires; LockedByUser = file.LockedByUser; LockedDate = file.LockedDate; }
public void AddListToPage(SPFile homePage, SPList list) { XsltListViewWebPart wp = new XsltListViewWebPart(); wp.ListName = list.ID.ToString("B").ToUpper(); ModifyViewClass viewOperations = new ModifyViewClass(); SPView defaultView = viewOperations.GetDefaultView(list); SPView copiedView = viewOperations.CopyView(defaultView, list); viewOperations.SetToolbarType(copiedView, "Standard"); wp.ViewGuid = defaultView.ID.ToString("B").ToUpper(); wp.Title = list.Title; InsertWebPartIntoWikiPage(homePage, wp, "{{1}}"); }
public static bool Add_FileFromURL(SPWeb web, int zadanieId, SPFile file) { bool result = false; string srcUrl = file.ServerRelativeUrl; SPList list = web.Lists.TryGetList(targetList); SPListItem item = list.GetItemById(zadanieId); if (item != null) { try { srcUrl = web.Url + "/" + file.Url; SPFile attachmentFile = web.GetFile(srcUrl); //item.Attachments.Add(attachmentFile.Name, attachmentFile.OpenBinaryStream(); //FileStream fs = new FileStream(srcUrl, FileMode.Open, FileAccess.Read); Stream fs = attachmentFile.OpenBinaryStream(); // Create a byte array of file stream length byte[] buffer = new byte[fs.Length]; //Read block of bytes from stream into the byte array fs.Read(buffer, 0, System.Convert.ToInt32(fs.Length)); //Close the File Stream fs.Close(); item.Attachments.AddNow(attachmentFile.Name, buffer); //aktualizuj informacje o załączonej fakturze item["colBR_FakturaZalaczona"] = true; item.SystemUpdate(); } catch (Exception) { //zabezpieczenie przed zdublowaniem plików } } return result; }
public void ClearWikiPage(SPFile wikiFile, SPWeb web) { wikiFile.RequireNotNull("wikiFile"); web.RequireNotNull("web"); ChangeWikiContent(wikiFile, string.Empty); using (SPLimitedWebPartManager limitedWebPartManager = wikiFile.GetLimitedWebPartManager(PersonalizationScope.Shared)) { List<Microsoft.SharePoint.WebPartPages.WebPart> webParts = new List<Microsoft.SharePoint.WebPartPages.WebPart>( from Microsoft.SharePoint.WebPartPages.WebPart w in limitedWebPartManager.WebParts select w); webParts.ForEach(w => limitedWebPartManager.DeleteWebPart(w)); } web.Update(); }
private void GetRequestedPage() { try { string RequestedURL = HttpContext.Current.Request.Url.ToString; //Do only when the requested page is aspx. if (System.IO.Path.GetExtension(RequestedURL).ToLower() == ".aspx") { using (SPSite Site = new SPSite(RequestedURL)) { using (SPWeb objWeb = Site.OpenWeb()) { SPFile RequestedPage = objWeb.GetFile(RequestedURL); if (RequestedPage != null && RequestedPage.Exists && (RequestedPage.MajorVersion == 0)) { HttpContext.Current.Response.Redirect("/_layouts/Pages/custom404page.aspx"); } } } } } catch (Exception ex) { throw; } }
/// <summary> /// Adds new web parts to the default home page. /// </summary> /// private void AddWebParts(SPWeb CurrentWeb) { try { /* Retrieve an instance of the default.aspx as a SPFile object. */ this._homePage = CurrentWeb.GetFile("default.aspx"); /* Retrieve an instance of the SPLimitedWebPartManager object. */ SPLimitedWebPartManager wpm = this._homePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); /* Create an instance ofthe AsyncWebPart1 object. */ SPDudesAsyncWP.SPDudesAsyncWP _asyncWP = new SPDudesAsyncWP.SPDudesAsyncWP(); _asyncWP.Title = "Asynchronous Web Part Example (SPDudes)"; _asyncWP.ToolTip = "Asynchronous Web Part Example (SPDudes)"; wpm.AddWebPart(_asyncWP, "left", 0); } catch (Exception ex) { throw; } }
private void AddFile(string filename, string remotefile) { using (WebClient webClient = new WebClient()) { ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; webClient.Headers.Add(FBAHeader, FBAValue); webClient.Credentials = CoreFunctions.GetStoreCreds(); byte[] fileBytes = null; fileBytes = webClient.DownloadData(storeurl + "/43Upgrade/" + remotefile); SPFile f = SPWeb.RootFolder.Files.Add(filename, fileBytes, true); } }
private file AddFile(SPFile spFile, SPRoleAssignmentCollection roleAssignments) { file file = new file(); file.fileName = spFile.Name; file.serverRelativeUrl = spFile.ServerRelativeUrl; foreach (SPRoleAssignment roleAssignment in roleAssignments) { SPPrincipal principal = roleAssignment.Member; string principalLogin = (principal is SPUser) ? principal.ParentWeb.AllUsers.GetByID(principal.ID).LoginName : principal.ID.ToString(); bool isGroup = !(principal is SPUser); file.AddPrincipal(principalLogin, principal.Name, isGroup, roleAssignment.RoleDefinitionBindings); } return(file); }
public static void WriteXmlFile <type>(SPFile docFile, type content, string stylesheetName) { XmlSerializer _srlzr = new XmlSerializer(typeof(type)); XmlWriterSettings _setting = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\r\n" }; using (Stream _docStrm = new MemoryStream(30000)) { using (XmlWriter _file = XmlWriter.Create(_docStrm, _setting)) { _file.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" " + String.Format("href=\"{0}.xslt\"", stylesheetName)); _srlzr.Serialize(_file, content); } docFile.SaveBinary(_docStrm); } docFile.Update(); }
/// <summary> /// Provisions the welcome page. /// </summary> /// <param name="contentType">The content type.</param> /// <returns>The welcome page.</returns> private SPFile ProvisionWelcomePage(SPContentType contentType) { // Guard if (contentType == null) { throw new ArgumentNullException("contentType"); } SPFile file = this.GetWelcomePage(contentType); if (file != null) { return(file); } byte[] buffer = File.ReadAllBytes(SPUtility.GetVersionedGenericSetupPath(@"Template\Features\DocumentSet\docsethomepage.aspx", 0)); SPFolder resourceFolder = contentType.ResourceFolder; return(resourceFolder.Files.Add(this.DocumentSetWelcomePage, buffer, true)); }
public void AppendToFile(SPFile file, string message) { using (var stream = file.OpenBinaryStream()) { using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); if (!content.EndsWith(Environment.NewLine)) { content += Environment.NewLine; } var writeStream = new MemoryStream(); using (var writer = new StreamWriter(writeStream, Encoding.UTF8)) { writer.Write(content); writer.WriteLine(message); } file.SaveBinary(writeStream.ToArray()); } } }
private static bool SaveFile(ISharePointCommandContext context, FileNodeInfo fileNodeInfo) { bool result = false; try { SPFile f = context.Web.GetFile(fileNodeInfo.ServerRelativeUrl); f.SaveBinary(Encoding.UTF8.GetBytes(fileNodeInfo.Contents)); result = true; } catch (Exception ex) { context.Logger.WriteLine(String.Format(Resources.FileSharePointCommands_SaveException, fileNodeInfo.ServerRelativeUrl, ex.Message, Environment.NewLine, ex.StackTrace), LogCategory.Error); } return(result); }
private static bool CheckInFile(ISharePointCommandContext context, FileNodeInfo fileNodeInfo) { bool result = false; try { SPFile f = context.Web.GetFile(fileNodeInfo.ServerRelativeUrl); f.CheckIn(String.Empty); result = true; } catch (Exception ex) { context.Logger.WriteLine(String.Format(Resources.FileSharePointCommands_CheckInException, fileNodeInfo.ServerRelativeUrl, ex.Message, Environment.NewLine, ex.StackTrace), LogCategory.Error); } return(result); }
/// <summary> /// Reflection crawl process of webpart properties and xml files /// </summary> /// <param name="folder"></param> protected void Crawl(SPFolder folder) { SPFile MyFile = null; if (folder != null) { foreach (SPFile CurrentFile in folder.Files) { MyFile = CurrentFile; try { string FileExtension = Path.GetExtension(CurrentFile.Url); if (CurrentFile.InDocumentLibrary && CurrentFile.Item != null && m_Parameters.IncludeXmlFilesLibraries && XmlFileLibraryInFilteredList(CurrentFile.Item.ParentList as SPDocumentLibrary) && XmlFileLibraryInFilteredList(CurrentFile)) { ReadXmlFile(CurrentFile); continue; } else if (FileExtension.ToLower() == ".aspx" && m_Parameters.IncludeWebParts) { CrawlWebPartPage(CurrentFile); } } catch (Exception ex) { OnError(ex, "ERROR: Cannot process file " + MyFile.Name); } } foreach (SPFolder SubFolder in folder.SubFolders) { Crawl(SubFolder); } } }
/// <summary> /// An item is being deleted. /// </summary> public override void ItemDeleting(SPItemEventProperties properties) { base.ItemDeleting(properties); if (properties.ListItem.Name.Contains(".pdf")) { using (SPSite site = new SPSite(properties.WebUrl)) { using (SPWeb web = site.OpenWeb()) { SPListItem _currentItem = web.Lists[properties.ListId].GetItemById(properties.ListItemId); string orderId = _currentItem[clmOrderNumber].ToString(); //Wenn der Auftrag ausgecheckt ist, soll das Auschecken verworfen werden SPFile _currentFile = _currentItem.File; if (_currentFile.CheckOutType != SPFile.SPCheckOutType.None) { undoCheckOut(properties); } //Aufragsformular löschen deleteFile(libNameOrderForm, orderId + fileExtensionOrderForm, web); //Begründung löschen deleteFile(libNameReason, orderId + fileExtensionReason, web); //Temp-Ordner löschen SPQuery query = new SPQuery(); query.Query = "<Where><And><BeginsWith><FieldRef Name='ContentTypeId'/><Value Type='ContentTypeId'>0x0120</Value></BeginsWith><Eq>><FieldRef Name='Title'/><Value Type='Text'>" + orderId + "</Value></Eq></And></Where>"; query.ViewAttributes = "Scope='RecursiveAll'"; SPList list = web.Lists[libNameTemp]; SPListItemCollection items = list.GetItems(query); foreach (SPListItem i in items) { i.Folder.Recycle(); } } } } }
/// <summary> /// główna procedura dystrybucji wiadomości /// </summary> public static bool SendMailWithAttachment(SPListItem item, MailMessage message) { bool result = false; try { SmtpClient client = new SmtpClient(); client.Host = item.Web.Site.WebApplication.OutboundMailServiceInstance.Server.Address; //ustaw adres nadawcy na sztywno string emailDefaultSender = BLL.admSetup.GetValue(item.Web, "EMAIL_DEFAULT_SENDER"); string emailNazwaFirmy = BLL.admSetup.GetValue(item.Web, "EMAIL_NAZWA_FIRMY"); message.From = new MailAddress(emailDefaultSender, emailNazwaFirmy); //ustaw adres zwrotny na sztywno string emailBiura = BLL.admSetup.GetValue(item.Web, "EMAIL_BIURA"); message.ReplyTo = new MailAddress(emailBiura, emailNazwaFirmy); for (int attachmentIndex = 0; attachmentIndex < item.Attachments.Count; attachmentIndex++) { string url = item.Attachments.UrlPrefix + item.Attachments[attachmentIndex]; SPFile file = item.ParentList.ParentWeb.GetFile(url); message.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name)); } //client.Send(message); BLL.Tools.DoWithRetry(() => client.Send(message)); result = true; } catch (Exception ex) { var r = ElasticEmail.EmailGenerator.ReportError(ex, item.ParentList.ParentWeb.Url); return(false); } return(result); }
private static void PublishAssetInternal(string assetUrl, SPListItem sourceItem) { if (!CommonHelper.IsNullOrWhiteSpace(assetUrl)) { object fileSystemObj; try { int pathEndPos = assetUrl.IndexOfAny(new[] { '?', '#' }); if (pathEndPos >= 0) { assetUrl = assetUrl.Substring(0, pathEndPos); } fileSystemObj = sourceItem.Web.Site.GetFileOrFolder(assetUrl); } catch { return; } try { if (fileSystemObj is SPFolder) { SPFolder folder = (SPFolder)fileSystemObj; if (folder.ParentListId != Guid.Empty) { folder.EnsureApproved(); } } else if (fileSystemObj is SPFile) { SPFile file = (SPFile)fileSystemObj; if (file.ParentFolder.ParentListId != Guid.Empty) { if (file.Item != null && file.Item.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Document) && !file.Item.ContentTypeId.IsChildOf(ContentTypeId.MasterPage.Parent) && !file.Item.ContentTypeId.IsChildOf(ContentTypeId.Page.Parent)) { file.EnsurePublished(String.Concat("Publish linked asset from ", SPUrlUtility.CombineUrl(sourceItem.Web.ServerRelativeUrl, sourceItem.Url))); } } } } catch (Exception ex) { throw new Exception(String.Concat("Cannot approve or publish content at ", assetUrl), ex); } } }
private void CreateBinCard(object sender, EventArgs e) { try { using (Entities _entities = new Entities(workflowProperties.WebUrl)) { CustomsWarehouse _cw = Element.GetAtIndex <CustomsWarehouse>(_entities.CustomsWarehouse, workflowProperties.ItemId); BinCardContentType _newBinCard = Factory.CreateContent(_cw); if (_cw.CWL_CW2BinCardTitle == null) { string _documentName = Settings.BinCardDocumentName(_entities, workflowProperties.ItemId); SPFile _newFile = File.CreateXmlFile <BinCardContentType>(workflowProperties.Web, _newBinCard, _documentName, BinCardLib.LibraryName, BinCardContentType.StylesheetNmane); BinCardLib _BinCardLibRntry = Element.GetAtIndex <BinCardLib>(_entities.BinCardLibrary, _newFile.Item.ID); _BinCardLibRntry.Archival = false; _cw.CWL_CW2BinCardTitle = _BinCardLibRntry; _entities.SubmitChanges(); } else { int _binCardId = _cw.CWL_CW2BinCardTitle.Id.Value; SPDocumentLibrary _lib = (SPDocumentLibrary)workflowProperties.Web.Lists[BinCardLib.LibraryName]; SPFile _file = _lib.GetItemByIdSelectedFields(_binCardId).File; File.WriteXmlFile <BinCardContentType>(_file, _newBinCard, BinCardContentType.StylesheetNmane); } } logToHistoryListActivity_HistoryOutcome = "Success"; logToHistoryListActivity_HistoryDescription = "Document created successfully"; } catch (CAS.SharePoint.ApplicationError _ap) { logToHistoryListActivity_HistoryOutcome = "ApplicationError"; logToHistoryListActivity_HistoryDescription = _ap.Message; } catch (Exception _ex) { logToHistoryListActivity_HistoryOutcome = "Exeption"; logToHistoryListActivity_HistoryDescription = _ex.Message; } }
public void RaiseCallbackEvent(string eventArgument) { try { string[] eventArg = eventArgument.Split(new string[1] { "#;" }, StringSplitOptions.RemoveEmptyEntries); List <WebPartGalleryItem> webparts = Sources.Where(n => n.Id == eventArg[0]).Select(n => n).ToList(); SPListItem item = SPContext.Current.ListItem; SPFile currentFile = item.File; if (item != null && item != null) { if (currentFile != null && currentFile.Exists) { if (currentFile.CheckOutType == SPFile.SPCheckOutType.None && currentFile.RequiresCheckout) { currentFile.CheckOut(); } } } if (webparts.Count > 0) { foreach (WebPartGalleryItem galleryItem in webparts) { WebPartZoneBase zone = WebPartManager.Zones[eventArg[1]]; //base.waitScreenText = string.Format("Adding {0} in {1} zone.", item.Title, zone.DisplayTitle); galleryItem.Source.AddItemToPage(zone, 0, galleryItem, galleryItem.Id); } //SPContext.Current.ListItem.Update(); } } catch (Exception ex) { result = ex; } }
private SPFile GetFinishedFile(SPWeb web, string JobId) { SPFile res = null; SPList list = GetOASList(web); SPListItemCollection listItems = list.Items; int itemCount = listItems.Count; for (int k = 0; k < itemCount; k++) { SPListItem item = listItems[k]; if (JobId == item["JobId"].ToString()) { string fileid = item["FileId"].ToString(); SPFolder lib = GetOASLibrary(web); res = lib.Files[fileid]; break; } } return(res); }
/// <summary> /// Copies the metadata. /// </summary> /// <param name="srcFile">The SRC file.</param> /// <param name="newFile">The new file.</param> /// <param name="update">if set to <c>true</c> [update].</param> private void CopyMetadata(SPFile srcFile, SPFile newFile, bool update) { foreach (SPField srcField in srcFile.Item.Fields) { try { string internalName = srcField.InternalName; SPField destField = newFile.Item.Fields.GetField(internalName); if (destField != null && !srcField.Hidden && !srcField.ReadOnlyField && srcField.CanBeDeleted) { newFile.Item[destField.Id] = srcFile.Item[srcField.Id]; Debug.WriteLine(string.Format("{0}[{1}]", srcField.InternalName, srcFile.Item[destField.Id])); Debug.WriteLine(string.Format("{0}[{1}]", destField.InternalName, newFile.Item[destField.Id])); } } catch (Exception ex) { Debug.WriteLine("*CopyMetadata"); Debug.WriteLine(ex); } } if (update) { try { newFile.Item.Update(); newFile.Update(); } catch (Exception ex) { Debug.WriteLine("*CopyMetadata2"); Debug.WriteLine(ex); } } }
internal SPUserSolution DeploySolution(FileInfo _featuteFile) { try { if (SiteCollection == null) { throw new ApplicationException(Resources.SiteCollectionNotExist); } SPDocumentLibrary solutionGallery = (SPDocumentLibrary)SiteCollection.GetCatalog(SPListTemplateType.SolutionCatalog); SPFile file = solutionGallery.RootFolder.Files.Add(_featuteFile.Name, _featuteFile.OpenRead(), true); return(SiteCollection.Solutions.Add(file.Item.ID)); } catch (Exception ex) { string _msg = String.Format( Resources.DeploySolutionFailed, SiteCollection != null ? SiteCollection.Url : Resources.NullReference, _featuteFile.Name, ex.Message); throw new ApplicationException(_msg); } }
protected void setUpList(int baseId) { string siteUrl = SPContext.Current.Web.Url; SPSite oSiteCollection = SPContext.Current.Site; oList = SPContext.Current.Web.Lists["Alerts Noticeboard"]; SPWeb web = SPContext.Current.Web; web.AllowUnsafeUpdates = true; string pageUrl = "SitePages/managealerts.aspx"; SPFile page = web.GetFile(pageUrl); SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared); Guid storageKey = Guid.NewGuid(); string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_')); SPLimitedWebPartCollection WebParts = wpmgr.WebParts; XsltListViewWebPart xwp = new XsltListViewWebPart(); //SPViewCollection viewsCol = oList.Views; xwp.ID = wpId; xwp.ListName = oList.ID.ToString("B").ToUpper(); wpmgr.AddWebPart(xwp, "WebPartZone1", 0); if (WebParts.Count > 1) { wpmgr.DeleteWebPart(xwp); } }
protected override void ValidateHtmlPage(SPFile file, string pageUrl, string pageContent, DefinitionBase definitionBase) { var definition = definitionBase as XsltListViewWebPartGridModePresenceDefinition; var assert = ServiceFactory.AssertService .NewAssert(definition, file) // dont' need to check that, not the pupose of the test //.ShouldBeEqual(m => m.PageFileName, o => o.GetName()) .ShouldNotBeNull(file); //if (definition.WebPartDefinitions.Any()) //{ assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.WebPartDefinitions); var isValid = true; IndentableTrace.WithScope(trace => { trace.WriteLine(string.Format("Checking InitGridFromView presence:[{0}]", pageUrl)); isValid = pageContent.Contains("InitGridFromView"); }); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, //Dst = dstProp, IsValid = isValid }); }); //} //else //{ // assert.SkipProperty(m => m.WebPartDefinitions, "WebPartDefinitions.Count = 0. Skipping"); //} }
private void GetImageFile() { if (ImageFile == null) { SPContext currentContext = SPContext.Current; if (currentContext != null) { SPSite currentSite = currentContext.Site; using (SPWeb fileWeb = currentSite.OpenWeb(Source, false)) { string fullUrl = currentSite.MakeFullUrl(Source); ImageFile = fileWeb.GetFile(fullUrl); } } if (ImageFile != null || !ImageFile.Exists) { throw new FileNotFoundException(FileNotFoundErrorMessage, Source); } } }
private void PopulateSelectedDocs() { string[] items; if (!Request.QueryString.AllKeys.Contains(SusDeb.DOI.Common.Utilities.eCaseConstants.QueryStringKeys.BATCH_COPY_MANY_ITEMS_QUERYSTRING_KEY)) { items = Request.QueryString["items"].ToString().Split('|'); } else { items = Session[SusDeb.DOI.Common.Utilities.eCaseConstants.SessionKeys.BATCH_COPY_ITEMS_SESSION_KEY_NAME].ToString().Split('|'); } for (int i = 0; i < items.Length; i++) { var url = items[i].ToString(); if (!string.IsNullOrEmpty(url)) { using (SPSite site = new SPSite(url)) { using (SPWeb web = site.OpenWeb()) { SPFile file = web.GetFile(url); if (file != null) { TreeNode tn = new TreeNode(); tn.ShowCheckBox = true; tn.SelectAction = TreeNodeSelectAction.None; tn.Checked = true; tn.Text = file.Name; tn.Value = web.Url + "/" + file.Url; tn.ImageUrl = web.Url + "/_layouts/images/" + file.IconUrl; treeViewSelectedDocs.Nodes.Add(tn); tn = null; } } } } } }
/// <summary> /// Provisions the document set. /// </summary> /// <param name="contentType">Type of the content.</param> private void ProvisionDocumentSet(SPContentType contentType) { ProvisionEventHandler(contentType); SPFile file = this.ProvisionWelcomePage(contentType); using (SPLimitedWebPartManager manager = GetWelcomePageWebPartmanager(file)) { if (this.EnsureWebParts) { if (manager.WebParts != null) { List <WebPart> webParts = new List <WebPart>(manager.WebParts.Cast <WebPart>()); foreach (WebPart webPart in webParts) { manager.DeleteWebPart(webPart); } } } this.ProvisionWebParts(manager); } }
public static XmlDocument GetConfigFile(SPList list, string filename) { try { SPFile file = list.ParentWeb.GetFile(SPUtility.GetFullUrl(list.ParentWeb.Site, list.RootFolder.ServerRelativeUrl.TrimEnd('/') + "/" + filename)); if (file.Exists) { XmlDocument doc = new XmlDocument(); doc.Load(file.OpenBinaryStream()); return(doc); } else { return(null); } } catch (Exception exp) { } return(null); }
private void btn_Import_Click(object sender, EventArgs e) { using (SPSite site = new SPSite(siteUrl)) { using (SPWeb web = site.OpenWeb(webUrl)) { SPFile thePage = web.GetFile(pageUrl); SPLimitedWebPartManager theWebPartManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); string[] webParts = Directory.GetFiles(tb_ImportPath.Text); XmlReader xReader = null; System.Web.UI.WebControls.WebParts.WebPart wp = null; for (int i = 0; i < webParts.Length; i++) { string customError = string.Empty; xReader = new XmlTextReader(webParts[i]); wp = theWebPartManager.ImportWebPart(xReader, out customError); theWebPartManager.AddWebPart(wp, "Rich Content", 1); tb_Message.Text += wp.Title + "Import Success..."; } } } }
protected override void ValidateHtmlPage(SPFile file, string pageUrl, string pageContent, DefinitionBase definitionBase) { var definition = definitionBase as XsltListViewWebPartGridModePresenceDefinition; var assert = ServiceFactory.AssertService .NewAssert(definition, file) // dont' need to check that, not the pupose of the test //.ShouldBeEqual(m => m.PageFileName, o => o.GetName()) .ShouldNotBeNull(file); //if (definition.WebPartDefinitions.Any()) //{ assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.WebPartDefinitions); var isValid = true; TraceUtils.WithScope(trace => { trace.WriteLine(string.Format("Checking InitGridFromView presence:[{0}]", pageUrl)); isValid = pageContent.Contains("InitGridFromView"); }); return new PropertyValidationResult { Tag = p.Tag, Src = srcProp, //Dst = dstProp, IsValid = isValid }; }); //} //else //{ // assert.SkipProperty(m => m.WebPartDefinitions, "WebPartDefinitions.Count = 0. Skipping"); //} }
/// <summary>Returns all files for an assignment grouped by learner.</summary> /// <param name="assignmentKey">The key of the assignment.</param> public Dictionary <string, List <SPFile> > AllFiles(long assignmentKey) { string queryXml = @"<Where> <And> <Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq> <Eq><FieldRef Name='{2}'/><Value Type='Boolean'>1</Value></Eq> </And> </Where>"; queryXml = string.Format(CultureInfo.InvariantCulture, queryXml, ColumnAssignmentId, assignmentKey, ColumnIsLatest); SPQuery query = new SPQuery(); query.ViewAttributes = "Scope=\"Recursive\""; query.Query = queryXml; SPListItemCollection items = DropBoxList.GetItems(query); SPFieldUser learnerField = (SPFieldUser)DropBoxList.Fields[ColumnLearner]; Dictionary <string, List <SPFile> > files = new Dictionary <string, List <SPFile> >(); foreach (SPListItem item in items) { SPFile file = item.File; SPFieldUserValue learnerValue = (SPFieldUserValue)learnerField.GetFieldValue(item[ColumnLearner].ToString()); SPUser learner = learnerValue.User; List <SPFile> learnerFiles; string learnerAccount = learner.LoginName.Replace("\\", "-"); if (files.TryGetValue(learnerAccount, out learnerFiles) == false) { learnerFiles = new List <SPFile>(); files.Add(learnerAccount, learnerFiles); } learnerFiles.Add(item.File); } return(files); }
public override bool Perform() { storeurl = CoreFunctions.getFarmSetting("workenginestore"); SPFile file = SPWeb.GetFile("Resources.aspx"); if (!file.Exists) { try { AddFile("Resources.aspx", "Resources.txt"); LogMessage("Add Resources.aspx"); } catch (Exception ex) { LogMessage("", "Add Resources.aspx: " + ex.Message, 3); } } return(true); }
public static SPFile CreateXmlFile <type>(SPWeb site, type content, string fileName, string listName, string stylesheetName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException("fileName"); } if (string.IsNullOrEmpty(listName)) { throw new ArgumentNullException("listName"); } if (string.IsNullOrEmpty(stylesheetName)) { throw new ArgumentNullException("stylesheetName"); } if (site == null) { throw new ArgumentNullException("site"); } if (content == null) { throw new ArgumentNullException("content"); } SPDocumentLibrary _lib = (SPDocumentLibrary)site.Lists[listName]; SPFile _newFile = default(SPFile); XmlWriterSettings _setting = new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\r\n" }; using (MemoryStream _docStream = new MemoryStream()) { XmlFile.WriteXmlFile <type>(content, _docStream, stylesheetName); _newFile = _lib.RootFolder.Files.Add(fileName + ".xml", _docStream, true); } _newFile.DocumentLibrary.Update(); return(_newFile); }
//Methode: Decodieren der Anlagen und Speichern in Bibliothek "Temp" im entsprechenden Unterordner public void UploadAttachments(XPathNodeIterator anlagen, string xanhang, XmlNamespaceManager nsmgr, string DocID, SPFolder tempfolder, string tempuploadurl, SPWeb web) { Helper helper = new Helper(); //"Moven" durch jede Zeiler der wiederholten Tabelle der Anlagen mit MoveNext while (anlagen.MoveNext()) { //Verwenden von "try" und "catch", da der Code im "try"-Block fehlschlägt und das ganze Programm abbricht, wenn KEINE Anlagen vorhanden sind. Durch try - und catch wird nicht abgebrochen. try { //Dekodieren des Anlagenfelds. Durch anlagen.current.selectsinglenode wird nicht die ganze Zeile, sondern nur das Feld in der Zeile zum Dekodieren ausgewählt. //Das ist wichtig, da noch das Boolean-Feld zur Weitergabe in jeder Zeile enthalten ist und das Dekodieren mit diesem Feld nicht möglich ist. InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(anlagen.Current.SelectSingleNode(xanhang, nsmgr).Value); string fileNamewithoutextension = Path.GetFileNameWithoutExtension(decoder.Filename); SPFile attachmentuploadfile = tempfolder.Files.Add(tempuploadurl + decoder.Filename, decoder.DecodedAttachment, true); SPListItem attachmentitem = attachmentuploadfile.Item; //Updaten des Elements damit Änderungen übernommen werden. SystemUpdate() ist eine "silent"-Änderung (dh. Änderungsdatum und Editor werden nicht erfasst). Wenn nur "Update()" verwendet wird, werden diese erfasst. attachmentitem.SystemUpdate(); } catch { } } }
private void MoveAndSetCustomerWizardFile(SPWeb web) { try { web.AllowUnsafeUpdates = true; SPFile file = web.GetFile("Style Library/Module/CustomForms/CustomerWizard.aspx"); if (file == null) //moved already { return; } file.MoveTo("/Lists/" + CustomerList + "/CustomerWizard.aspx", true); file.Update(); SPList list = web.Lists[CustomerList]; list.NavigateForFormsPages = true; SPContentType ct = list.ContentTypes["ListFieldsContentType"]; ct.NewFormUrl = "/Lists/" + CustomerList + "/CustomerWizard.aspx"; ct.DisplayFormUrl = "/Lists/" + CustomerList + "/CustomerWizard.aspx"; ct.EditFormUrl = "/Lists/" + CustomerList + "/CustomerWizard.aspx"; ct.Update(); list.Update(); } catch (Exception ex) { Logging.WriteToLog(SPContext.Current, ex.Message); } finally { web.AllowUnsafeUpdates = false; } }
private void Initialization(SPWeb web) { object cachedValue = System.Web.HttpContext.Current.Cache["FilterConditionsKey"]; if (cachedValue == null) { SPLimitedWebPartManager webPartManager = null; try { //string wpPageUrl = "workerfilterpageurl"; //web.Properties[Constants.BAG_KEY_FILTER_PAGE_URL]; SPFile page = web.GetFile(System.Web.HttpContext.Current.Request.UrlReferrer.AbsolutePath); webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts) { AvailabilityButtonWebPart abwp = wp as AvailabilityButtonWebPart; if (abwp != null) { this.operatorsAsString = abwp.FilterConditions; break; } } } catch { } finally { if (webPartManager != null) { webPartManager.Web.Dispose(); } } } else { // get Value from ASP.NET Cache this.operatorsAsString = cachedValue.ToString(); } }
void AddAltChunk(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename) { string altChunkId = "AltChunkId" + id; id++; byte[] byteArray = filename.OpenBinary(); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (MemoryStream mem = new MemoryStream()) { mem.Write(byteArray, 0, (int)byteArray.Length); mem.Seek(0, SeekOrigin.Begin); chunk.FeedData(mem); } Word.AltChunk altChunk = new Word.AltChunk(); altChunk.Id = altChunkId; // Replace content control with altChunk information. OpenXmlElement parent = sdt.Parent; parent.InsertAfter(altChunk, sdt); sdt.Remove(); }
public static DataTable ParseExcel(SPFile file, string positionKeyValue, string primaryKeyValue, string colsKeyValue, string sheetName) { //Using workbookPath this way will allow //you to call the workbook remotely. string targetWorkbookPath = SPContext.Current.Site.Url + file.ServerRelativeUrl; ES.ExcelService es = new ES.ExcelService(); es.Credentials = System.Net.CredentialCache.DefaultCredentials; ES.Status[] outStatus; string sessionId = es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus); string[] pos = positionKeyValue.Split(','); ES.RangeCoordinates rangeCoordinates = GetRangeCoordinates(es, sessionId, pos, primaryKeyValue, sheetName, outStatus); //string positionKeyValue = ConfigurationManager.AppSettings[positionKey]; object[] excelObjctData = es.GetRange(sessionId, sheetName, rangeCoordinates, false, out outStatus); DataTable excelDataTable = ConvertToDataTable(excelObjctData, primaryKeyValue, colsKeyValue); //Close workbook. This also closes session. es.CloseWorkbook(sessionId); return excelDataTable; }
private void LogProperties(SPFile file) { Logger.LogMethod(); try { foreach (SPField field in file.Item.Fields) { Logger.Log.Debug(file.Name + "->" + field.Title + " == " + file.Item[field.InternalName]); } } catch (Exception ex) { Logger.LogException("Exception thrown parsing fields", ex); } }
public static void CheckOutFile(SPFile homePageFile) { try { if (homePageFile.CheckOutStatus == SPFile.SPCheckOutStatus.None) homePageFile.CheckOut(); } catch (Exception ee) { EssnLog.logInfo("Error on CheckOutFile in FeatureActivated."); EssnLog.logExc(ee); } }
public static void CheckInAndPublishFile(SPFile homePageFile, string message) { try { homePageFile.CheckIn(message); } catch (Exception ee) { EssnLog.logInfo("Error on homePageFile.CheckIn in CheckInAndPublishFile in FeatureActivated."); EssnLog.logExc(ee); } try { homePageFile.Publish(message); } catch (Exception ee) { EssnLog.logInfo("Error on homePageFile.Publish in CheckInAndPublishFile in FeatureActivated."); EssnLog.logExc(ee); } }
public void ChangeWikiContent(SPFile wikiFile, string content) { wikiFile.RequireNotNull("wikiFile"); wikiFile.Item["WikiField"] = content; wikiFile.Item.Update(); }
private SPListItem CopyFile(SPFile sourceFile, SPFolder destFolder, SPContentType destContentType) { string filename = BuildDestinationFilename(sourceFile.Name, destFolder); byte[] content = sourceFile.OpenBinary(); Hashtable fileProperties = new Hashtable(); fileProperties["ContentType"] = destContentType.Name; SPFile destFile = destFolder.Files.Add(destFolder.ServerRelativeUrl + "/" + filename, content, fileProperties, true); return destFile.Item; }
/// <summary> /// Gets the welcome page web part manager. /// </summary> /// <param name="file">The file to return a <see cref="Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager"/> instance for.</param> /// <returns>The web part manager of the welcome page.</returns> protected static SPLimitedWebPartManager GetWelcomePageWebPartmanager(SPFile file) { // Guard if (file == null) { throw new ArgumentNullException("file"); } return file.Web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared); }
private void SetProperties(SPFile file, Field[] fields) { if ((fields == null) || (fields.Length == 0)) { return; } SPListItem item = file.Item; foreach (Field field in fields) { item[field.Name] = field.Value; } item.Update(); }
private void AddProperties(SPFile file, Field[] fields) { if (fields == null) return; SPListItem item = file.Item; foreach (Field field in fields) { try { if (item.Properties.ContainsKey(field.Name) || IsBuiltInProperty(field.Name)) { item[field.Name] = field.Value; } else { item.Properties.Add(field.Name, field.Value); } } catch (Exception ex) { Logger.LogException("Error adding property (" + field.Name + ") ", ex); } } item.Update(); }
private Hashtable GetProperties(SPFile file) { Hashtable fields = new Hashtable(); foreach (SPField field in file.Item.Fields) { fields.Add(field.InternalName, file.Item[field.InternalName]); } return fields; }
private bool CheckForceCheckOut(SPFile file) { bool bForceCheckOut = false; if( file.InDocumentLibrary ) { SPList spList = file.Item.ParentList; if( spList != null ) { bForceCheckOut = spList.ForceCheckout; } } return bForceCheckOut; }
public SPLimitedWebPartCollectionNode(SPFile file) { this.File = file; }