Sunday, February 07, 2010

02/07: SP Site Management

 

Sample Code :

1. Create a site collection :

  • Object Model :
    • SPSite site = new SPSite(strServerPath);

      // Get the list of site collections for the web application
      SPSiteCollection siteCollection =  site.WebApplication.Sites;

      siteCollection.Add(….)

      // Release memory used by SPSite object
          site.Dispose();

  • Web Service:

2. Create a Site (Web) :

  • Object Model :
    • SPSite site = new SPSite(strSitePath);
    • SPWeb web = site.AllWebs.Add(…);
    • web.Dispose();
      site.Dispose();

  • Web Service:
    • http://admin site/_vti_bin/Sites.asmx(
    • To avoid any problems with user security, we’ll use the
      SPSecurity.RunWithElevatedPrivileges() method to ensure that the web service can
      add the requested web site. If you want to restrict who can call the web service, you
      can either add declarative security to the Web.config file of the service, or set Windows
      permissions on the folder containing the web service application.)

3.Adding and Modifying Properties of a Site

    SPSite site = new SPSite("http://localhost");

    SPWeb web = site.RootWeb;

    if (web.Properties.ContainsKey("mg_CustomerId"))

    web.AllowUnsafeUpdates = true;
        web.Properties["mg_CustomerId"] = …
        web.Properties["mg_BillCustomer"] = ….
        web.Properties.Update();

4. Add Web part

    • Object Model
      • //
      • Add an instance of a SharePoint "ContentEditorWebPart"

        // Create an empty content editor web part.
                  Microsoft.SharePoint.WebPartPages.ContentEditorWebPart cewp = new Microsoft.SharePoint.WebPartPages.ContentEditorWebPart();
                  // Create an xml element object and transfer the content into the web part.
                  XmlDocument xmlDoc = new XmlDocument();
                  System.Xml.XmlElement xmlElem = xmlDoc.CreateElement("xmlElem");
                  xmlElem.InnerText = strContent;
                  cewp.Content = xmlElem;
                  // Call generic method to add the web part
                  cewp =  (Microsoft.SharePoint.WebPartPages.ContentEditorWebPart) AddWebPart (
                      cewp, 
                      …)              

    • // add a web part
      • // Get handles to site, web and page to which web part will be added.
                   SPSite site = new SPSite(strSiteUrl);
                   SPWeb web = site.OpenWeb(strWebName);
                   // Enable update of page
                   web.AllowUnsafeUpdates = true;
                   SPLimitedWebPartManager webParts;
                   if ((strDocLibName != ""))
                   {
                       webParts = web.GetLimitedWebPartManager((strDocLibName + ("/" + strPage)), pScope);
                   }
                   else
                   {
                       webParts = web.GetLimitedWebPartManager(strPage, pScope);
                   }
                   // If web part page is in a document library, disable checkout requirement
                   // for duration of update
                   SPList list = null;
                   bool origForceCheckoutValue = false;
                   if ((strDocLibName != ""))
                   {
                       list = web.Lists[strDocLibName];
                       origForceCheckoutValue = list.ForceCheckout;
                       list.ForceCheckout = false;
                       list.Update();
                   }
                   // Add the web part
                   oWebPart.Title = strTitle;
                   webParts.AddWebPart(oWebPart, strZone, numOrder);
                   // Save changes back to the SharePoint database
                   webParts.SaveChanges(oWebPart);
                   web.Update();

 

5. Adding a Web Part by Using a .dwp or .webpart File

// Get handle to site and web to be edited
         SPSite site = new SPSite(strSiteUrl);
         SPWeb web = site.OpenWeb(strWebName);
         System.Web.UI.WebControls.WebParts.WebPart wp;

         // Step 1: Get handle to web part page to contain new web part
         SPLimitedWebPartManager webParts;
         if ((strDocLibName != ""))
         {
             webParts = web.GetLimitedWebPartManager(strDocLibName + "/" + strPage, pScope);
         }
         else
         {
             webParts = web.GetLimitedWebPartManager(strPage, pScope);
         }

         // Step 2: get handle to .DWP file and import definition
         XmlReader reader = XmlReader.Create(strDWPPath);
         string strErrMsg;
         wp = webParts.ImportWebPart(reader, out strErrMsg);

         // Step 3: allow web site to be edited
         web.AllowUnsafeUpdates = true;
         SPList list = null;
         bool origForceCheckoutValue = false;
         if (strDocLibName != "")
         {
             list = web.Lists[strDocLibName];
             origForceCheckoutValue = list.ForceCheckout;
             list.ForceCheckout = false;
             list.Update();
         }

         // Step 6: Add the web part
         webParts.AddWebPart(wp, strZone, 0);

         // Step 7: Save changes back to SharePoint database
         webParts.SaveChanges(wp);
         web.Update();

         // Step 8-9: If necessary, restore ForceCheckout setting
         if (strDocLibName != "")
         {
             list.ForceCheckout = origForceCheckoutValue;
             list.Update();
         }

 

  • Example of dwp file

<?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/WebPart/v2">
  <Title>This web part was added using it's .WEBPART file</Title>
  <FrameType>Default</FrameType>
  <Description>Use for formatted text, tables, and images.</Description>
  <IsIncluded>true</IsIncluded>
  <ZoneID>TopZone</ZoneID>
  <PartOrder>0</PartOrder>
  <FrameState>Normal</FrameState>
  <Height />
  <Width />
  <AllowRemove>true</AllowRemove>
  <AllowZoneChange>true</AllowZoneChange>
  <AllowMinimize>true</AllowMinimize>
  <AllowConnect>true</AllowConnect>
  <AllowEdit>true</AllowEdit>
  <AllowHide>true</AllowHide>
  <IsVisible>true</IsVisible>
  <DetailLink />
  <HelpLink />
  <HelpMode>Modeless</HelpMode>
  <Dir>Default</Dir>
  <PartImageSmall />
  <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
  <PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge>
  <IsIncludedFilter />
  <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
  <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
  <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor"><![CDATA[<FONT size=4>Now is the time for all <STRONG><FONT size=5>good </FONT></STRONG>SharePoint developers to learn new ways to programmatically add web parts to a page....</FONT>]]></Content>
  <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
</WebPart>

 

6. Calculating Storage for all Document Libraries in
a Site (usign xslt )

 

//Step 1: Open site collection and web site
      // for which we want to report on list storage
      SPSite site = new SPSite("http://localhost");
      SPWeb web = site.RootWeb;

      //Step 2: Get collection of all lists
      SPListCollection lists = web.Lists;

      //Step 3: iterate through all lists, finding
      // those which are document librarys
      DataTable dtListItems;
      foreach (SPList list in lists)
      {
          //Step 4: Is this a document library?
          if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
          {

              //Step 5: Get list of all documents in library
              dtListItems = list.Items.GetDataTable();

              //Step 6: is there at least one document in
              //  the library?
              if (dtListItems != null)
              {

                  //Step 7: Add heading
                  Label lbl = new Label();
                  lbl.Text = "<h1>" + list.Title + "</h1>";
                  this.Controls.Add(lbl);

                  //Step 8: Select just the desired columns
                  dtListItems = FormatTable(dtListItems);

                  //Step 9: Create XML representation of document list
                  StringBuilder sb = new StringBuilder();                   
                  System.IO.StringWriter sw = new System.IO.StringWriter(sb);
                  dtListItems.WriteXml(sw);

                  //Step 10: Format XML using XSLT
                  Xml xmlListItems = new Xml();
                  xmlListItems.DocumentContent = sb.ToString();
                  xmlListItems.TransformSource = "Recipes.xsl";
                  this.Controls.Add(xmlListItems);

web.dispose();

site.dispose();

  • xsl example
    • <?xml version="1.0" encoding="utf-8"?>
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:output method="html"/>

          <xsl:template match="/">
              <table>
                  <tr>
                      <td width="5%">
                          <strong>
                              <u>ID</u>
                          </strong>
                      </td>
                      <td width="45%">
                          <strong>
                              <u>File Name</u>
                          </strong>
                      </td>
                      <td align="right" width="10%">
                          <strong>
                              <u>Size</u>
                          </strong>
                      </td>
                      <td/>
                  </tr>
                  <xsl:for-each select="DocumentElement/ListItems">
                      <tr>
                          <td>
                              <xsl:value-of select="ID"/>
                          </td>
                          <td>
                              <xsl:value-of select="FileName"/>
                          </td>
                          <td align="right">
                              <xsl:value-of select="format-number(FileSize,' #,###')"/>
                          </td>
                          <td/>
                      </tr>
                  </xsl:for-each>
                  <tr>
                      <td/>
                      <td/>
                      <td align="right">---------------</td>
                      <td/>
                  </tr>
                  <tr>
                      <td/>
                      <td align="center">Total Bytes:</td>
                      <td align="right"><xsl:value-of select="format-number(sum(DocumentElement/ListItems/FileSize),'#,###')"/></td>
                      <td/>
                  </tr>
              </table>
          </xsl:template>
      </xsl:stylesheet><!-- Stylus Studio meta-information - (c) 2004-2006. Progress Software Corporation. All rights reserved.
      <metaInformation>
      <scenarios ><scenario default="yes" name="Scenario1" userelativepaths="yes" externalpreview="no" url="Recipes.xml" htmlbaseurl="" outputurl="" processortype="internal" useresolver="yes" profilemode="0" profiledepth="" profilelength="" urlprofilexml="" commandline="" additionalpath="" additionalclasspath="" postprocessortype="none" postprocesscommandline="" postprocessadditionalpath="" postprocessgeneratedext="" validateoutput="no" validator="internal" customvalidator=""/></scenarios><MapperMetaTag><MapperInfo srcSchemaPathIsRelative="yes" srcSchemaInterpretAsXML="no" destSchemaPath="" destSchemaRoot="" destSchemaPathIsRelative="yes" destSchemaInterpretAsXML="no"/><MapperBlockPosition></MapperBlockPosition><TemplateContext></TemplateContext><MapperFilter side="source"></MapperFilter></MapperMetaTag>
      </metaInformation>
      -->

         

7. Creating a Script to Back Up All Site Collections by
Using STSADM

' --------------------------------------------------------------
' Purpose:     Backup all SharePoint site collections on server
' By:        Mark Gerow
' Date:        1/3/08
' --------------------------------------------------------------
Option Explicit

' Set the path to the STSADM utility
Const STSADM_PATH =   _
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm"

' Set the path to where you want the backups made
Const BACKUP_PATH = "C:\SharePoint_Backups\"
' Define needed variables
Dim objFso, objFolder, objFiles, objFile, objShell
Dim objExec, strResult, objXml, objSc, objUrl
Dim strUrl, strFileName, strCmd

' Step 1: OPTIONAL: Delete any pre-existing backups
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(BACKUP_PATH)
Set objFiles = objFolder.Files
For Each objFile in objFiles
  objFile.Delete(True)
Next

' Step 2: Retrieve all site collections in XML format.
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec(STSADM_PATH & " -O ENUMSITES -URL http://localhost/")
strResult = objExec.StdOut.ReadAll

' Load XML in DOM document so it can be processed.
Set objXml = CreateObject("MSXML2.DOMDocument")
objXml.LoadXML(strResult)

' Step 3: Loop through each site collection and call stsadm.exe to make a backup.
For Each objSc in objXml.DocumentElement.ChildNodes
    strUrl = objSc.Attributes.GetNamedItem("Url").Text
    strFileName = BACKUP_PATH & _
        Replace(Replace(strUrl,"/","_"),":","") & ".bak"
    strCmd = STSADM_PATH & " -O BACKUP -URL """ & _
        strUrl + """ -FILENAME """ + strFileName + """"
    ' For testing, display pop-up for each collection backed up
    WScript.Echo "Backing up site collection " & _
        strUrl & " to file " & _
        strFileName & " using the following command " & _
        strCmd
    WScript.Echo
    objShell.Exec(strCmd)
    ' Optional, if there will be many site collections, may want
    ' to insert a delay to avoid overloading server memory
    GoSleep(3)

Next

' This function can be used to insert a delay in the processing
' to avoid overloading server memory if there are many
' site collections to be backed up.
Function GoSleep(seconds)
    Dim startTime, endTime, nowTime, dummy
     startTime = DateAdd("s",0,Now)
     endTime = DateAdd("s",seconds,Now)
     nowTime = DateAdd("s",0,Now)
     While endTime > nowTime
         ' Need some commands lin while loop to
         ' ensure it actually executes
         nowTime = DateAdd("s",0,Now)
         dummy = Time
     Wend    
End Function

0 Comments:

Post a Comment

<< Home