in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

Sharepoint Space

It is all about Sharepoint
  • export Keywords/Best Bet for Sharepoint 2007

    Sharepoint 2007 save Keywords and Best Bet to the SSP_DB database rather than the content database. If you use stsadm -o backup/restore to perform backup/restore, you will quickly find it does not work for Keywords and Best Bet. My solution to address this issue is to export/import those settings by extending stsadm command. Here is the article of how to extend stsadm from MSDN. http://msdn.microsoft.com/en-us/library/bb417382.aspx

    Here is my keywords/best bet xml format:
    <?xml version="1.0" encoding="UTF-8"?>
    <Keywords>
     <Keyword>
      <Term>Test</Term>
      <Synonyms DefaultSeperator=";">
       <Synonym>test<Synonm>
       <Synonym>TEST<Synonm>
      </Synonyms>
      <Definition></Definition>
      <Contact></Contact>
      <StartDate></StartDate>
      <EndDate></EndDate>
      <ReviewDate></ReviewDate>
      <BestBets>
       <BestBet>
        <Title></Title>
        <Url></Url>
        <Description></Description>
       </BestBet>
       <BestBet>
        <Title></Title>
        <Url></Url>
        <Description></Description>
       </BestBet>
      <BestBets>
     </Keyword>
    </Keywords>

    Here is the code to export

            private int ExportKeywords(StringDictionary keyValues, out string output)
            {
                if (!keyValues.ContainsKey("url"))
                {
                    throw new InvalidOperationException("The url parameter was not specified.");
                }
                if (!keyValues.ContainsKey("filename"))
                {
                    throw new InvalidOperationException("The filename parameter was not specified.");
                }

                String url = keyValues["url"];
                string filename = keyValues["filename"];

                try
                {
                    using (SPSite site = new SPSite(url))
                    {
                        //get keyword
                        SearchContext searchContext = SearchContext.GetContext(site);
                        Keywords keywords = new Keywords(searchContext, new Uri(url));
                        //write to xml
                        XmlDocument xmlDoc = new XmlDocument();
                        XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                        xmlWriter.Formatting = Formatting.Indented;
                        xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                        xmlWriter.WriteStartElement("Keywords");
                        xmlWriter.Close();
                        xmlDoc.Load(filename);
                        foreach (Keyword thisKeyword in keywords.AllKeywords)
                        {
                            XmlNode root = xmlDoc.DocumentElement;
                            XmlElement node_keyword = xmlDoc.CreateElement("Keyword");
                            root.AppendChild(node_keyword);

                            CreateElement("Term", thisKeyword.Term, node_keyword, xmlDoc);

                            XmlElement node_Synonyms = xmlDoc.CreateElement("Synonyms");
                            node_keyword.AppendChild(node_Synonyms);
                            foreach (Synonym syn in thisKeyword.Synonyms)
                                CreateElement("Synonym", syn.Term, node_Synonyms, xmlDoc);
                           
                            CreateElement("Definition", thisKeyword.Definition, node_keyword, xmlDoc);
                           
                            CreateElement("Contact", thisKeyword.Contact, node_keyword, xmlDoc);
                           
                            if (thisKeyword.StartDate.Date !=DateTime.MaxValue.Date)
                                CreateElement("StartDate", thisKeyword.StartDate.ToShortDateString(), node_keyword, xmlDoc);
                            else
                                CreateElement("StartDate", "", node_keyword, xmlDoc);
                           
                            if (thisKeyword.EndDate.Date != DateTime.MaxValue.Date)
                                CreateElement("EndDate", thisKeyword.EndDate.ToShortDateString(), node_keyword, xmlDoc);
                            else
                                CreateElement("EndDate", "", node_keyword, xmlDoc);
                           
                            if (thisKeyword.ReviewDate.Date != DateTime.MaxValue.Date)
                                CreateElement("ReviewDate", thisKeyword.ReviewDate.ToShortDateString(), node_keyword, xmlDoc);
                            else
                                CreateElement("ReviewDate", "", node_keyword, xmlDoc);
                           
                            XmlElement node_BestBets = xmlDoc.CreateElement("BestBets");
                            node_keyword.AppendChild(node_BestBets);
                            foreach (BestBet bestBet in thisKeyword.BestBets)
                            {
                                XmlElement node_BestBet = xmlDoc.CreateElement("BestBet");
                                node_BestBets.AppendChild(node_BestBet);
                                CreateElement("Title", bestBet.Title, node_BestBet, xmlDoc);
                                CreateElement("Url", bestBet.Url.ToString(), node_BestBet, xmlDoc);
                                CreateElement("Description", bestBet.Description, node_BestBet, xmlDoc);
                            }
                        }
                        xmlDoc.Save(filename);
                    }
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Error retrieving url '" + url + "'.  Please check the format of your url, and ensure that the site exists.  Details: " + e.Message);
                }

                StringBuilder sb = new StringBuilder();

                output = "";
                return 0;
            }

            private void CreateElement(string elementName, string elementValue, XmlElement parentElement, XmlDocument xmlDoc)
            {
                XmlElement newElement = xmlDoc.CreateElement(elementName);
                XmlText newElementText = xmlDoc.CreateTextNode("");
                newElementText.Value = elementValue;
                parentElement.AppendChild(newElement);
                newElement.AppendChild(newElementText);
            }

    After deploy the dll and config the xml, you could export Keyword/bestbet using following command

    stsadm -o exportkeywords -url http://yoursite -filename c:\test.xml

    This method can also used to export/import search scope, site settings etc.

  • create folder, subfolder in Sharepoint programically

    //Create folder: 
    SPDocumentLibrary docLib = GetYourDocumentLibrary("YourSiteName","Pages");
    SPListItem newFolder = docLib.Items.Add("",SPFileSystemObjectType.Folder,"first folder")
    newFolder.Update();
    //Create subfolder: 
    SPDocumentLibrary docLib = GetYourDocumentLibrary("YourSiteName","Pages");
    SPListItem newFolder = docLib.Items.Add("http://yoursharepointsite/yoursite/pages/first folder",SPFileSystemObjectType.Folder,"first folder")
    newFolder.Update();

    Only thing needs to mention is Items.Add() function. First parameter is url, when create folder at the root, use "", when create subfolder, you have to provide the full URL including site collection, site, document library name and parent folder name. It took me 1 hour to figure out, hope this post will save your time.

  • export/import site structure using XML

    The following class can import/export entire sharepoint site structure, page library folder, content types to XML. Format like

     <?xml version="1.0" encoding="UTF-8"?>
    <Root>
      <Web>
        <SiteUrl>en-ca/PPM</SiteUrl>
        <SiteTitle>PPM</SiteTitle>
        <SiteDescription>
        </SiteDescription>
     <Pages>
      <Folders>
       <Folder>Folder1</Folder>
       <Folder>Folder2</Folder>
      </Folders>
        </Pages>
      </Web>
      <Web>
        <SiteUrl>en-ca/tetsdasdfs</SiteUrl>
        <SiteTitle>ddd</SiteTitle>
        <SiteDescription>
        </SiteDescription>
     <Pages>
          <ContentTypes>
            <ContentType>Page</ContentType>
            <ContentType>Article Page</ContentType>
            <ContentType>Welcome Page</ContentType>
          </ContentTypes>
      <Folders>
       <Folder>Folder1</Folder>
       <Folder>Folder2</Folder>
      </Folders>
        </Pages>
      </Web>
    </Root>

     When import, it will create each web and create folder to the page library, also, it will try match the content type and assign it to the page library. Class also has a delegate to indicate the progress if necessary.
    If you having hundreds of site to create, this might be a good approach. Hope help.

     

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using Microsoft.SharePoint;
    using System.Xml;
    using System.IO;
    using System.Windows;
    using System.Threading;

    namespace Sharepoint.SetupWizard
    {
        public delegate void DelegateHandle(object sender, CustomeEvetnArgs e);

        public class CustomeEvetnArgs : EventArgs
        {
            string name = "";
            public CustomeEvetnArgs()
            { }
            public string SiteName
            {
                get { return this.name; }
                set { this.name = value; }
            }
        }

        class SiteStructure
        {
            private string _SourceUrl;
            private string _ExportPath;
            private string _DestinationUrl;
            private bool _doSiteStructure;
            private bool _doPpmFolder;
            private bool _doPageLibraryContentType;
            private Hashtable _SitesTable = new Hashtable();

            public string SourceUrl
            {
                get { return _SourceUrl; }
                set { _SourceUrl = value; }
            }
            public string ExportPath
            {
                get { return _ExportPath; }
                set { _ExportPath = value; }
            }
            public string DestinationUrl
            {
                get { return _DestinationUrl; }
                set { _DestinationUrl = value; }
            }
            public bool DoSiteStructure
            {
                get { return _doSiteStructure; }
                set { _doSiteStructure = value; }
            }
            public bool DoPpmFolder
            {
                get { return _doPpmFolder; }
                set { _doPpmFolder = value; }
            }
            public bool DoPageLibraryContentType
            {
                get { return _doPageLibraryContentType; }
                set { _doPageLibraryContentType = value; }
            }
            public Hashtable SitesTable
            {
                get { return _SitesTable; }
                set { _SitesTable = value; }
            }

            public struct SiteInfo
            {
                internal string _SiteUrl;
                internal string _SiteTitle;
                internal string _SiteDescription;
                internal string[] _PpmFolder;
                internal string[] _ContentTypeNames;
                internal SPContentTypeCollection _ContentTypes;
            }

            public SiteInfo[] PpmSiteInfoCollection;

            public event DelegateHandle CreateSite;

            public PpmSiteStructure(string PpmSourceSitesUrl,string ExportPath)
            {
                _SourceUrl = PpmSourceSitesUrl;
                _ExportPath = ExportPath;
                _doSiteStructure = true;
                _doPpmFolder = true;
                _doPageLibraryContentType = true;
            }

            public void export()
            {
                if (_SourceUrl != null)
                {
                    try
                    {
                        SPSite PpmSites = new SPSite(this._SourceUrl);
                        if (PpmSites != null)
                        {
                            PpmSiteInfoCollection = new SiteInfo[PpmSites.AllWebs.Count - 1];
                            for (int i = 0; i < PpmSites.AllWebs.Count - 2; i++)
                            {
                                PpmSiteInfoCollectionIdea._SiteUrl = PpmSites.AllWebs[i + 1].Url.Replace(this._SourceUrl + "/", "");
                                PpmSiteInfoCollectionIdea._SiteTitle = PpmSites.AllWebs[i + 1].Title;
                                PpmSiteInfoCollectionIdea._SiteDescription = PpmSites.AllWebs[i + 1].Description;
                                PpmSiteInfoCollectionIdea._PpmFolder = GetPpmFolder(PpmSites.AllWebs[i + 1]);
                                PpmSiteInfoCollectionIdea._ContentTypes = GetPagesLibraryContentTypes(PpmSites.AllWebs[i + 1]);
                                SitesTable.Add(i, PpmSiteInfoCollectionIdea);
                            }
                        }
                        WriteXML();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                }
            }

            private string[] GetPpmFolder(SPWeb web)
            {
                SPDocumentLibrary docLibrary = GetLibraryByName(web.Url.Replace(this._SourceUrl + "/", ""),"Pages");
                if (docLibrary != null)
                {
                    int approvedFolderCount = 0;
                    for (int i = 0; i < docLibrary.Folders.Count; i++)
                    {
                        if (docLibrary.FoldersIdea["Approval Status"].ToString() == "0")
                        {
                            approvedFolderCount++;
                        }
                    }

                    string[] ppmFolderlists = new string[approvedFolderCount];

                    for (int i = 0; i < docLibrary.Folders.Count ; i++)
                    {
                        if (docLibrary.FoldersIdea["Approval Status"].ToString() == "0")//only export approved folder
                        {
                            ppmFolderlistsIdea = docLibrary.FoldersIdea.Name;
                        }
                    }
                    return ppmFolderlists;
                }
                else
                    return null;
            }

            private SPContentTypeCollection GetPagesLibraryContentTypes(SPWeb web)
            {
                SPDocumentLibrary docLibrary = GetLibraryByName(web.Url.Replace(this._SourceUrl + "/", ""), "Pages");
                return docLibrary.ContentTypes;       
            }

            private SPDocumentLibrary GetLibraryByName(string siteStr, string libraryName)
            {
                SPSite ppmSite = new SPSite(this.SourceUrl);
                foreach (SPList list in ppmSite.OpenWeb(siteStr).Lists)
                {
                    if (list.BaseType == SPBaseType.DocumentLibrary && list.Title == libraryName)
                        return (SPDocumentLibrary)list;
                }
                return null;
            }

            private void WriteXML()
            {
                string filename = "PPMSiteStructure" + DateTime.Now.Date.Year.ToString()
                    + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Day.ToString() + ".xml";
                XmlDocument xmlDoc = new XmlDocument();
                XmlTextWriter xmlWriter = new XmlTextWriter(this.ExportPath + "\\" + filename, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteStartElement("Root");
                xmlWriter.Close();
                xmlDoc.Load(this.ExportPath+"\\"+filename);
                for (int i = 0; i < this.SitesTable.Count - 1; i++)
                {
                    XmlNode root = xmlDoc.DocumentElement;
                    XmlElement webNode = xmlDoc.CreateElement("Web");
                    XmlElement urlNode = xmlDoc.CreateElement("SiteUrl");
                    XmlElement titleNode = xmlDoc.CreateElement("SiteTitle");
                    XmlElement descriptionNode = xmlDoc.CreateElement("SiteDescription");
                    XmlText textNodeUrl = xmlDoc.CreateTextNode("");
                    XmlText textNodeTitle = xmlDoc.CreateTextNode("");
                    XmlText textNodeDescription = xmlDoc.CreateTextNode("");

                    root.AppendChild(webNode);

                    webNode.AppendChild(urlNode);
                    textNodeUrl.Value = ((SiteInfo)SitesTableIdea)._SiteUrl;
                    urlNode.AppendChild(textNodeUrl);

                    webNode.AppendChild(titleNode);
                    textNodeTitle.Value = ((SiteInfo)SitesTableIdea)._SiteTitle;
                    titleNode.AppendChild(textNodeTitle);

                    webNode.AppendChild(descriptionNode);
                    textNodeDescription.Value = ((SiteInfo)SitesTableIdea)._SiteDescription;
                    descriptionNode.AppendChild(textNodeDescription);

                    if (DoPpmFolder || DoPageLibraryContentType)
                    {
                        XmlElement pagesNode = xmlDoc.CreateElement("Pages");
                        webNode.AppendChild(pagesNode);
                        if (DoPpmFolder)
                        {
                            if (((SiteInfo)SitesTableIdea)._PpmFolder.Length > 0)
                            {
                                XmlElement ppmFolderNode = xmlDoc.CreateElement("Folders");
                                pagesNode.AppendChild(ppmFolderNode);
                                for (int j = 0; j < ((SiteInfo)SitesTableIdea)._PpmFolder.Length; j++)
                                {
                                    XmlElement folderNode = xmlDoc.CreateElement("Folder");
                                    XmlText textNodeFolder = xmlDoc.CreateTextNode("");
                                    textNodeFolder.Value = ((SiteInfo)SitesTableIdea)._PpmFolder[j];
                                    ppmFolderNode.AppendChild(folderNode);
                                    folderNode.AppendChild(textNodeFolder);
                                }
                            }
                        }
                        if (DoPageLibraryContentType)
                        {
                            if (((SiteInfo)SitesTableIdea)._ContentTypes.Count > 0)
                            {
                                XmlElement pagesContentTypeNode = xmlDoc.CreateElement("ContentTypes");
                                pagesNode.AppendChild(pagesContentTypeNode);
                                for (int j = 0; j < ((SiteInfo)SitesTableIdea)._ContentTypes.Count; j++)
                                {
                                    XmlElement contentTypeNode = xmlDoc.CreateElement("ContentType");
                                    XmlText textNodeContentType = xmlDoc.CreateTextNode("");
                                    textNodeContentType.Value = ((SiteInfo)SitesTableIdea)._ContentTypes[j].Name;
                                    pagesContentTypeNode.AppendChild(contentTypeNode);
                                    contentTypeNode.AppendChild(textNodeContentType);
                                }
                            }
                        }
                    }
                }
                xmlDoc.Save(this.ExportPath + "\\" + filename);
            }

            private void WriteNode(XmlTextWriter xmlWriter)
            {
                for (int i = 0; i < this.SitesTable.Count - 1; i++)
                {
                    xmlWriter.WriteStartElement("Web");
                    xmlWriter.WriteElementString("SiteUrl", ((SiteInfo)SitesTableIdea)._SiteUrl);
                    xmlWriter.WriteElementString("SiteTitle", ((SiteInfo)SitesTableIdea)._SiteTitle);
                    xmlWriter.WriteElementString("SiteDescription", ((SiteInfo)SitesTableIdea)._SiteDescription);
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteEndDocument();
            }

            private void ReadXML(string fileName)
            {
                this.SitesTable.Clear();
                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.Load(fileName);
                }
                catch (FileNotFoundException ex)
                {
                    throw (ex);
                }
                XmlNodeList webList = doc.GetElementsByTagName("Web");

                foreach (XmlNode node in webList)
                {
                    XmlElement webElement = (XmlElement)node;
                    SiteInfo xmlSiteInfo = new SiteInfo();
                    xmlSiteInfo._SiteUrl = webElement.GetElementsByTagName("SiteUrl")[0].InnerText;
                    xmlSiteInfo._SiteTitle = webElement.GetElementsByTagName("SiteTitle")[0].InnerText;
                    xmlSiteInfo._SiteDescription = webElement.GetElementsByTagName("SiteDescription")[0].InnerText;

                    XmlNodeList pagesList = webElement.GetElementsByTagName("Pages");
                    foreach (XmlNode pagesNode in pagesList)
                    {
                        //reading Folders
                        XmlElement foldersElement = (XmlElement)pagesNode;
                        XmlNodeList foldersList = foldersElement.GetElementsByTagName("Folders");
                        foreach (XmlNode folder in foldersList)
                        {
                            XmlElement folderElement = (XmlElement)folder;
                            XmlNodeList folderList = folderElement.GetElementsByTagName("Folder");
                            xmlSiteInfo._PpmFolder = new string[folderList.Count];
                            for (int i = 0; i < folderList.Count; i++)
                                xmlSiteInfo._PpmFolderIdea = folderElement.GetElementsByTagName("Folder")Idea.InnerText;
                        }
                        //reading ContentTypes
                        XmlElement contentTypesElement = (XmlElement)pagesNode;
                        XmlNodeList contentTypesList = foldersElement.GetElementsByTagName("ContentTypes");
                        foreach (XmlNode contentType in contentTypesList)
                        {
                            XmlElement contentTypeElement = (XmlElement)contentType;
                            XmlNodeList contentTypeList = contentTypeElement.GetElementsByTagName("ContentType");
                            xmlSiteInfo._ContentTypeNames = new string[contentTypeList.Count];
                            for (int i = 0; i < contentTypeList.Count; i++)
                            {
                                xmlSiteInfo._ContentTypeNamesIdea = contentTypeElement.GetElementsByTagName("ContentType")Idea.InnerText;
                            }
                        }

                    }

                    this.SitesTable.Add(this.SitesTable.Count, xmlSiteInfo);
                }
            }

            private SPContentType GetContentTypeByName(SPWeb web,string contentTypeName)
            {
                foreach (SPContentType contentType in web.ContentTypes)
                {
                    if (contentType.Name == contentTypeName)
                        return contentType;
                }
                return null;
            }

            public void import(string fileName)
            {
                if (CreateSite != null)
                {
                    try
                    {
                        ReadXML(fileName);
                        SPSite Sites = new SPSite(this._SourceUrl);
                        for (int i = 0; i < this.SitesTable.Count; i++)
                        {
                            Thread.Sleep(10);

                            CustomeEvetnArgs e = new CustomeEvetnArgs();
                            e.SiteName = _SourceUrl+"/"+((SiteInfo)SitesTableIdea)._SiteUrl;
                            CreateSite(this, e);

                            if (DoSiteStructure)
                            {
                                if (!Sites.OpenWeb(((SiteInfo)SitesTableIdea)._SiteUrl).Exists)
                                {
                                    Sites.AllWebs.Add(((SiteInfo)SitesTableIdea)._SiteUrl);
                                    SPWeb newWeb = Sites.OpenWeb(((SiteInfo)SitesTableIdea)._SiteUrl);
                                    newWeb.Title = ((SiteInfo)SitesTableIdea)._SiteTitle;
                                    newWeb.Description = ((SiteInfo)SitesTableIdea)._SiteDescription;
                                    newWeb.Update();
                                }
                            }
                            if (DoPpmFolder)
                            {
                                if (Sites.OpenWeb(((SiteInfo)SitesTableIdea)._SiteUrl).Exists)
                                {
                                    SPDocumentLibrary docLibrary = GetLibraryByName(((SiteInfo)SitesTableIdea)._SiteUrl, "Pages");
                                    if (((SiteInfo)SitesTableIdea)._PpmFolder != null)
                                    {
                                        for (int j = 0; j < ((SiteInfo)SitesTableIdea)._PpmFolder.Length; j++)
                                        {
                                            if (!GetPageLibraryFolderByName(docLibrary, "/" + ((SiteInfo)SitesTableIdea)._SiteUrl + "/Pages/" + ((SiteInfo)SitesTableIdea)._PpmFolder[j]))
                                            {
                                                SPListItem newFolder = docLibrary.Items.Add("", SPFileSystemObjectType.Folder, ((SiteInfo)SitesTableIdea)._PpmFolder[j]);
                                                newFolder.Update();

                                                SPFolder thisFolder = getFolderByName(Sites.OpenWeb(((SiteInfo)SitesTableIdea)._SiteUrl), "/" + ((SiteInfo)SitesTableIdea)._SiteUrl + "/Pages/" + ((SiteInfo)SitesTableIdea)._PpmFolder[j], "Pages");
                                                thisFolder.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
                                                thisFolder.Item.Update();
                                            }
                                        }
                                    }
                                }
                            }
                            if (DoPageLibraryContentType)
                            {
                                if (Sites.OpenWeb(((SiteInfo)SitesTableIdea)._SiteUrl).Exists)
                                {
                                    if (((SiteInfo)SitesTableIdea)._ContentTypeNames != null)
                                    {
                                        SPDocumentLibrary docLibrary = GetLibraryByName(((SiteInfo)SitesTableIdea)._SiteUrl, "Pages");

                                        foreach (string xmlContentTypeName in ((SiteInfo)SitesTableIdea)._ContentTypeNames)
                                            if (!IsContentTypeExists(docLibrary, xmlContentTypeName))
                                            {
                                                SPContentType newType = GetContentTypeByName(Sites.OpenWeb(), xmlContentTypeName);
                                                if (newType != null)
                                                {
                                                    docLibrary.ContentTypes.Add(newType);
                                                    docLibrary.Update();
                                                }
                                            }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                }
            }

            private bool IsContentTypeExists(SPDocumentLibrary docLib, string contentTypeName)
            {
                foreach (SPContentType contentType in docLib.ContentTypes)
                    if (contentType.Name == contentTypeName)
                        return true;
                return false;
            }

            private bool GetPageLibraryContentType(SPDocumentLibrary pageLibrary, SPContentTypeCollection contentTypes)
            {
                foreach (SPContentType contentType in pageLibrary.ContentTypes)
                {
                    foreach (SPContentType xmlContentType in contentTypes)
                        if (xmlContentType == contentType)
                            return true;
                }
                return false;
            }

            private bool GetPageLibraryFolderByName(SPDocumentLibrary docLib, string folderName)
            {
                foreach (SPListItem item in docLib.Folders)
                    if (item.Folder.ServerRelativeUrl == folderName)
                        return true;
                return false;
            }

            private SPFolder getFolderByName(SPWeb web, string folderServerRelativeUrl, string libName)
            {
                SPListCollection lists = web.Lists;
                foreach (SPList list in lists)
                {
                    if (list.BaseType == SPBaseType.DocumentLibrary)
                    {
                        SPDocumentLibrary docLibrary = (SPDocumentLibrary)list;
                        if (!docLibrary.IsCatalog &&
                            list.BaseTemplate != SPListTemplateType.XMLForm &&
                            docLibrary.Title == libName)
                        {
                            SPListItemCollection docLibFolders = docLibrary.Folders;
                            foreach (SPListItem docLibItem in docLibFolders)
                            {
                                if (docLibItem.Folder.ServerRelativeUrl == folderServerRelativeUrl)
                                    return docLibItem.Folder;
                            }
                        }
                    }
                }
                return null;
            }


        }
    }

  • how to publish the entire document library

    Sharepoint does not provide "Publish All" feature. If you select Site Action -> Manage Content and Structure you will soon find this page is kind of buggy. You could select multiple files to publish all but it is page based, which means it only publish the files you selected in the current page not the entire document library. Also, if the work flow is enabled for this document library, "Publish All" item will greyed out.

    so....write you own code to do this.

            protected bool PublishPpmContent(SPWeb web)
            {
                try
                {
                    SPDocumentLibrary docLibrary = GetLibraryByName("myDocLibName");
                    //publish files
                    SPListItemCollection docLibItems = docLibrary.Items;
                    foreach (SPListItem docLibItem in docLibItems)
                    {
                        if (docLibItem["Approval Status"].ToString() != GlobalConst.Approved && docLibItem["Approval Status"].ToString() != GlobalConst.Rejected)//not approved, not rejected
                        {
                            SPFile thisFile = getFileByName(web, docLibItem.Url);
                            if (thisFile != null && thisFile.CheckedOutBy == null)
                            {
                                thisFile.Publish(string.Format("Published by {0} at {1}", web.CurrentUser.Name, DateTime.Now.ToLongDateString()));
                                thisFile.Approve(string.Format("Approved by {0} at {1}", web.CurrentUser.Name, DateTime.Now.ToLongDateString()));
                            }
                        }
                    }
                    //approve all folders
                    SPListItemCollection docFolderCollection = docLibrary.Folders;
                    foreach (SPListItem docFolder in docFolderCollection)
                    {
                        if (docFolder["Approval Status"].ToString() != GlobalConst.Approved &&
                            docFolder["Approval Status"].ToString() != GlobalConst.Rejected)
                        {
                            SPFolder thisFolder = getFolderByName(web, docFolder.Url);
                            if (thisFolder.Exists)
                            {
                                thisFolder.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
                                thisFolder.Item.Update();
                            }
                        }
                    }
                    return true;
                }
                catch
                {
                    return false;
                }

            }

            private SPDocumentLibrary GetLibraryByName(string libraryName)
            {
                SPSite mySite = new SPSite("Your site url");
                foreach (SPList list in mySite.OpenWeb().Lists)
                {
                    if (list.BaseType == SPBaseType.DocumentLibrary && list.Title == libraryName)
                        return (SPDocumentLibrary)list;
                }
                return null;
            }
             public SPFolder getFolderByName(SPWeb web, string folderName)
            {
                SPListCollection lists = web.Lists;
                foreach (SPList list in lists)
                {
                    if (list.BaseType == SPBaseType.DocumentLibrary)
                    {
                        SPDocumentLibrary docLibrary = (SPDocumentLibrary)list;
                        if (!docLibrary.IsCatalog &&
                            list.BaseTemplate != SPListTemplateType.XMLForm &&
                            docLibrary.Title == GlobalConst.PpmSourceFileLibraryName)
                        {
                            SPListItemCollection docLibFolders = docLibrary.Folders;
                            foreach (SPListItem docLibItem in docLibFolders)
                            {
                                if (docLibItem.Folder.ServerRelativeUrl == "/" + folderName)
                                    return docLibItem.Folder;
                            }
                        }
                    }
                }
                return null;
            }

     

    Note: 

    1. Document library may contains folder, you need approve files and folders when do the entire publish. 
    2. GlobalConst has a property Approved = "0", Rejected = "1", Pending = "2", Draft = "3"
    3. Only work with VSS 3.0 not for Sharepoint 2003.

     

  • Lesson learned when create list instance in Sharepoint solution

    It took me plenty of time to figure out how to create a sharepoint list/document library instance and delpoy to the Sharepoint in a solution. I experienced some weird error message and it is really frustrating untill everything works at the last!

    1. Project structure and features
    Make sure completely understand how feature and solution works in Sharepoint. Understand how to create feature head file and feature detail file. Not necessary to memorize all the element but you must know where and how to find it at msdn. It is also very important to build your file structure properly first, otherwise it will easy comfuse youself later when the project grows. A good practice is create a Sharepoint list using VseWSS and study the structure. Key files to study are: Manifest.xml, setup.bat, feature.xml, instance.xml. You need also has the knowledge to create ddf file for your own projects. You could also implement MSBuild for your project in the future...

    2. Make sure follow the rules
    Exception from HRESULT: 0x81070201
    I got this error message once and really took me long time to fix the problem. Finally, I found the folder name has to be exactly the same you defined in your element.xml. Sounds weird? Ask MS but to make it work, you have to rename the folder name and your ddf file as well.

    3. Only Content controls are allowed directly in a content page that contains Content controls.
    This error message is also misleading. If you got this message, simply remove the commented line in the AllItems.aspx and the rest .aspx pages. (Who says the commented line does not impact your project??? )

    4. Two features for 1 list
    When create list or document library, Sharepoint actually wants you to create 2 features for it.
    First one is just instance of the list or document library. You might need:
    feature.xml and instance.xml
    the second actually is the schema and default aspx pages.
    For list, this feature by default should contain: AllItems.aspx, DispForm.aspx, EditForm.aspx, NewForm.asxp, schema.xml, elementManifest.xml
    For docLib, this feature by default should contains: AllItems.aspx, combine.aspx, dispform.aspx, editdlg.htm, editform.aspx, filedlg.htm, repair.aspx, schema.xml, upload.aspx, webfldr.aspx
    The second feature acutally defines the default behavior of the list or docLib.

    5. Event receiver
    Event receiver defines the event and action during or after certain activity. For example, after the feature activated or after the item added. It is quite useful when you build your installation package and control your list/docLib. This can be defined in your feature.xml. For example:
     <Feature
    Title
    ="XXXYYYZZZ"
    Id="282A5A9B-465F-4b4d-BB79-B5F6DD2B5A40"
    Description
    ="Your description"
    Version
    ="1.0.0.0"
    Scope
    ="Web"
    Hidden="FALSE"
    DefaultResourceFile
    ="core"
    ReceiverAssembly
    ="MyTest.Sharepoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f1cf6b1266b9b906" ReceiverClass="MyTest.Sharepoint.MyTestFeatureEventReceiver"
    xmlns
    ="http://schemas.microsoft.com/sharepoint/">

    -   <ElementManifests>
           <ElementManifest Location="instance.xml" />
     </ElementManifests>
    </Feature>
     
  • SPSite, SPWeb and SPWebCollection

    Sharepoint come with many class. Some class name is confusing.

    SPSite:
    Represents a collection of sites on a virtual server, including a top-level site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections on the virtual server.
    Note: SPSite is NOT a Collection, in another words, you can not use foreach to loop SPSite. To do this, you have to use SPWebCollection.

    SPWebCollection:
    Represents a collection of SPWeb objects.

    SPWeb:
    Represents a SharePoint Web site.

    SPFolder:
    Represents a folder on a SharePoint Web site. 

    The following snipet is copy from a class:

            #region properties
            /// <summary>
            /// site collection url address
            /// </summary>
            public string _RootSiteUrl
            {
                get { return RootSiteUrl; }
                set { RootSiteUrl = value; }
            }
            /// <summary>
            /// Site collection, get SPSite object repsent a "collection"
            /// </summary>
            public SPSite _Sites
            {
                get { return new SPSite(this._RootSiteUrl); }
                set { Sites = value; }
            }
            /// <summary>
            /// Web collection, SPWebCollection, this is the real Collection
            /// </summary>
            public SPWebCollection _Webs
            {
                get { return this._Sites.AllWebs; }
            }

            public string _PPMAspxPageSiteUrl
            {
                get { return this.PPMTargetSiteUrl; }
                set { PPMTargetSiteUrl = value; }
            }

            public SPWeb this[string SiteName] // indexer, represent a SPWeb
            {
                get
                {
                    int i = 0;
                    foreach (SPWeb web in this._Webs)
                    {
                        if (web.Url == SiteName)
                            return this._Webs[ i ];
                        i++;
                    }
                    return null;
                }
            }

            #endregion

    The indexer is quite useful, to get a SPWeb object, simply use mySharePointClass["your site or subsite url"] to access!

  • Convert html to Sharepoint aspx page

    In my previous post http://www.sharepointblogs.com/mingssn/archive/2007/10/06/word-documents-to-sharepoint.aspx explained the idea of edit Sharepoint aspx content directly instead of using the out of box converter. This is the complete class to import word html into Sharepoint. Somehow, SPWeb, SPSite, SPWebcollection, SPSiteCollection is kind of confusing. Make sure read document from MSDN

    Also, this class removed the <style>  section from the html file...

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Publishing;

    namespace PPM
    {
        class PPMWeb
        {
            private string RootSiteUrl;
            private string PPMTargetSiteUrl;
            private SPSite Sites;

            #region properties
            public string _RootSiteUrl
            {
                get { return RootSiteUrl; }
                set { RootSiteUrl = value; }
            }
            public SPSite _Sites
            {
                get { return new SPSite(this._RootSiteUrl); }
                set { Sites = value; }
            }
            public SPWebCollection _Webs
            {
                get { return this._Sites.AllWebs; }
            }

            public string _PPMAspxPageSiteUrl
            {
                get { return this.PPMTargetSiteUrl; }
                set { PPMTargetSiteUrl = value; }
            }

            public SPWeb this[string SiteName]
            {
                get
                {
                    int i = 0;
                    foreach (SPWeb web in this._Webs)
                    {
                        if (web.Url == SiteName)
                            return this._Webs[ i ] ;
                        i++;
                    }
                    return null;
                }
            }

            #endregion

            public PPMWeb(string RootSiteUrl, string PPMAspxSiteUrl)
            {
                this._RootSiteUrl = RootSiteUrl;
                this._PPMAspxPageSiteUrl = PPMAspxSiteUrl;
            }

            public void ConvertHtmlToAspx(string HtmlFileFolder, string HtmlFileName, string TargetWeb, PageLayout PPMPageLayout, string PPMContentField)
            {
                foreach (SPWeb web in this._Webs)
                {
                    if (web.Url == TargetWeb )
                    {
                        PublishingPage AspxPage = GetPublishingPagebyName(HtmlFileName.Replace(".htm", ".aspx"), web);
                        if (AspxPage != null) //if page exists, update content field
                        {
                            UpdateAspxPageContent(web, HtmlFileFolder, HtmlFileName, PPMCon