Question : Best way to access Sharepoint programatically

Hi,

I have to write a tool to make Sharepoint contents available offline. it needs also to be able to add new contents programatically.

I know that there are some products on the market, but I need to write it by myself.

What is the best access method to achieve this? I plan to write a webservice and the clients should communicate with this webservice. Every access to the SharePoint server is done by this WebService. The question is, should I access Sharepoint via the object model? Or would it be better to use WebDAV?

Is one of the two access methods limited in the functionalities? How about the performance?

Every information is very welcome.

Thanks in Advance

Answer : Best way to access Sharepoint programatically

This is an early version of a web service I used to connect to sharepoint:


Service.asmx.cs


using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using WorkflowGen.My.Data;
using Microsoft.SharePoint;

namespace doc2sps
{
      #region XML comments
      ///
      /// DOC2SPS Web Service
      ///

      #endregion
      public class Service : System.Web.Services.WebService
      {
            /*
             * Members variables
             */
      
            #region private members
            private string previousFilesCleanup = ConfigurationSettings.AppSettings.Get("PreviousFilesCleanup");
            private Context contextWorkflowGen = null;
            private SPList wssList = null;
            #endregion

            public Service()
            {
                  //CODEGEN: This call is required by the ASP.NET Web Services Designer
                  InitializeComponent();
            }

            #region XML comments
            ///
            /// This will create the file error.log with the infos of an exception
            ///

            /// Exception>
            #endregion
            private void CreateLog(Exception ex)
            {
                  // We put all in a try/catch because as this is called in a catch, we don't want this to
                  // generate an error to allow the catch to be completed.
                  try
                  {
                        string fileName = Server.MapPath("error.log");
                        StreamWriter streamWriterLog = new System.IO.StreamWriter(fileName,false);
                        streamWriterLog.WriteLine("Error log created on: " + DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentCulture));

                        streamWriterLog.WriteLine("CurrentUser: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                        streamWriterLog.WriteLine("Exception Type: " + ex.GetType().ToString());
                        streamWriterLog.WriteLine("Message: " + ex.Message);
                        streamWriterLog.WriteLine("HelpLink: " + ex.HelpLink);
                        streamWriterLog.WriteLine("Source: " + ex.Source);
                        streamWriterLog.WriteLine("TargetSite: " + ex.TargetSite.ToString());
                        streamWriterLog.WriteLine("StackTrace: " + ex.StackTrace);

                        streamWriterLog.Flush();
                        streamWriterLog.Close();
                        streamWriterLog = null;
                  }
                  catch {};
            }
            
            #region Component Designer generated code
            
            //Required by the Web Services Designer
            private IContainer components = null;
                        
            ///
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            ///

            private void InitializeComponent()
            {
            }

            ///
            /// Clean up any resources being used.
            ///

            protected override void Dispose( bool disposing )
            {
                  if(disposing && components != null)
                  {
                        components.Dispose();
                  }
                  base.Dispose(disposing);            
            }
            
            #endregion

            #region XML comments
            ///      Initialize the class properties
            ///      
            ///            Define the Context WorkflowGen
            ///            Open the connection to SharePoint Document Library
            ///      

            ///      WorkflowGen XML Recodset Context
            ///      Thrown when SPS_URL or SPS_LIBRARY parameter is missing
            #endregion
            private void InitializeProperties(string wfgXmlContext)
            {
                  /* Define WFG Context
                   */
                  this.contextWorkflowGen = new Context(wfgXmlContext);

                  /* Connect to Share Point Library
                   */
                  // Get SPS URL
                  string wssUrl = contextWorkflowGen.GetParameter("SPS_URL").ToString();
                  if (wssUrl == null || wssUrl.Length == 0)
                        throw new SoapException("DOC2SPS Error: SPS_URL parameter is required", SoapException.ServerFaultCode);

                  // Get SPS Library name
                  string wssListTitle = contextWorkflowGen.GetParameter("SPS_LIBRARY").ToString();
                  if (wssUrl == null || wssUrl.Length == 0)
                        throw new SoapException("DOC2SPS Error: SPS_LIBRARY parameter is required", SoapException.ServerFaultCode);

                  // Connect to SPS
                  int returnID = ConnectToDocumentLibrary(wssUrl, wssListTitle);
                  if (returnID <= 0)
                        ThrowContextualError(returnID);
            }

            #region XML comments
            /// Method called by WorkflowGen
            ///      
            ///      

            /// WorkflowGen XML Recodset Context
            ///
            ///      Thrown when SPS_FILE parameter is missing
            #endregion
            [WebMethod]
            public string DOC2SPS(string WFGEN_CONTEXT)
            {
                  // Retrieve the WFG CONTEXT data and load it into a recordset
                  InitializeProperties(WFGEN_CONTEXT);
                  // Retrieve required parameters
                  FileInfo fileInfoDataSet = contextWorkflowGen.GetParameter("SPS_FILE") as FileInfo;
                  if (fileInfoDataSet == null)
                        throw new SoapException("DOC2SPS Error: SPS_FILE parameter is required", SoapException.ServerFaultCode);
                  string filePath = fileInfoDataSet.FullName;
                  string fileName = contextWorkflowGen.GetFileNameParameter("SPS_FILE");

                  //* Delete old files in archive folder
                  if (previousFilesCleanup == "Y")
                        ArchiveHelper.DeleteOldFiles(DateTime.Now,Server);

                  // Create temporary folder
                  string strFolderPathRel = ArchiveHelper.CreateEformPath(Server);

                  // Absolute Path
                  string strFolderPath;
                  if (strFolderPathRel.StartsWith("/"))
                        strFolderPath = Server.MapPath(strFolderPathRel);
                  else
                        strFolderPath = strFolderPathRel;
            
                  // Dulicate file to approve
                  if (filePath.StartsWith("/"))
                        File.Copy(Server.MapPath(filePath),strFolderPath + "\\" + Path.GetFileName(filePath),true);
                  else
                        File.Copy(filePath,strFolderPath + "\\" + Path.GetFileName(filePath),true);
                  filePath = strFolderPath + "\\" + Path.GetFileName(filePath);

                  // Other parameters to fieldList
                  Hashtable fieldList = contextWorkflowGen.GetParameters("PARAM<>'SPS_LIBRARY' and PARAM<>'SPS_URL' and DATATYPE <> 'FILE'");

                  /* Send to SPS
                   */
                  int itemID = ToWSS_DocumentLibrary(fieldList,filePath,fileName);

                  /* On error, throw contextual error message
                   */
                  if (itemID <= 0)
                        ThrowContextualError(itemID);

                  /* Return the Xml content of the recordset
                   */
                  return WFGEN_CONTEXT;
            }

            #region XML comments
            ///
            /// Export to a Sharepoint DocumentLibrary
            ///

            ///
            ///            Hashtable(fieldName,fieldValue)
            ///
            /// File Path
            /// File Name into SPP
            ///
            ///            Success : SPListItem.ID
            ///            Error      :
            ///                   0      :      File not exist
            ///                  -4      :      Can't create SPFile
            ///                  -5      :      Can't retrieve SPListItem
            ///

            #endregion
            private int ToWSS_DocumentLibrary(Hashtable fieldList, string filePath, string fileName)
            {
                  try
                  {
                        //Check if currentFilePath validity
                        if (File.Exists(filePath))
                        {
                              //Add the file to SPList
                              FileInfo fi = new FileInfo(filePath);
                              FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                              BinaryReader br = new BinaryReader(fs);
                              Byte[] fb = new Byte[fi.Length];
                              br.Read(fb,0,fb.Length);
                              int fcpt = 0;
                              SPFile wssFile = null;
                              //Modified: filePath to FileName to not use the WFG temp filename in SPP
                              //Added: Replace if exists and CheckIn
                              try
                              {
                                    if (wssList.RootFolder.Files[fileName].Exists)
                                    {
                                          wssFile = wssList.RootFolder.Files.Add(Path.GetFileName(fileName),fb,true);
                                          if (wssFile.CheckOutStatus != 0)
                                                wssFile.CheckIn("");
                                    }
                              }
                              catch{;}
                              try
                              {
                                    if (wssFile==null)
                                          wssFile = wssList.RootFolder.Files.Add(Path.GetFileName(fileName),fb,true);
                              }
                              catch{;}
                              while(wssFile==null)
                              {
                                    try
                                    {
                                          fcpt++;
                                          //Modified: Specify IFormatProvider
                                          wssFile = wssList.RootFolder.Files.Add(Path.GetFileNameWithoutExtension(fileName) + " (" + fcpt.ToString(CultureInfo.CurrentCulture) + ")"+Path.GetExtension(fileName),fb);
                                    }
                                    catch
                                    {
                                          if (fcpt == int.MaxValue)
                                                throw;
                                    }
                              }

                              try
                              {
                                    //Retrieve the SPListItem
                                    SPListItem wssListItem = wssFile.Item;
                                    if(fieldList!=null)
                                    {
                                          //Initialise the SPListItem with fieldList
                                          IDictionaryEnumerator currentField = fieldList.GetEnumerator();
                                          while (currentField.MoveNext())
                                          {
                                                try
                                                {
                                                      //Copy field value in SPListItem
                                                      wssListItem[currentField.Key.ToString()]=currentField.Value;
                                                }
                                                catch{;}
                                          }
                                    }
                                    //Update SPListItem
                                    wssListItem.Update();
                                    //Return SPListItem.ID
                                    return wssListItem.ID;
                              }
                              catch (Exception ex)
                              {
                                    CreateLog(ex);
                                    return -5;
                              }
                        }
                        else
                        {
                              return 0;
                        }
                  }
                  catch (Exception ex)
                  {
                        CreateLog(ex);
                        return -4;
                  }
            }
            
            #region XML comments
            ///
            /// Connect to a Sharepoint DocumentLibrary
            ///

            /// SPWeb.Urlaram>
            /// SPList.Title>
            ///
            ///            Success : 1
            ///            Error      :
            ///                  -1      :      SPList.BaseType != SPBaseType.DocumentLibrary
            ///                  -2      :      SPWeb  not found
            ///                  -3      :      SPList not found
            ///                  -31      :      SPList not found / Access Denied
            ///

            #endregion
            private int ConnectToDocumentLibrary(string wssUrl, string listTitle)
            {
                  SPList wssList;

                  try
                  {
                        //Retrieve the SPWeb
                        SPWeb wssWeb = new SPSite(wssUrl).OpenWeb();
                        wssWeb.Lists.IncludeRootFolder = true;

                        // IMPORTANT: to make the function working via a web script
                        wssWeb.AllowUnsafeUpdates=true;
                        try
                        {
                              //Retrieve the SPList
                              wssList = wssWeb.Lists[listTitle];
                              if(wssList.BaseType!=SPBaseType.DocumentLibrary)
                              {
                                    return -1;
                              }
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                              CreateLog(ex);
                              return -31;
                        }
                        catch (Exception ex)
                        {
                              CreateLog(ex);
                              return -3;
                        }
                  }
                  catch (SecurityException ex)
                  {
                        CreateLog(ex);
                        return -21;
                  }
                  catch (Exception ex)
                  {
                        CreateLog(ex);
                        return -2;
                  }
                  
                  this.wssList = wssList;
                  return 1;
            }

            #region XML comments
            ///
            /// Throw a contextual text error depending on the number returned by funtions that use SPS
            ///

            /// Error Number
            #endregion
            private void ThrowContextualError(int errorID)
            {
                  string error;
                  switch(errorID)      
                  {        
                        case 0:  
                              error = "0 : File not exist";
                              break;                  
                        case -1:            
                              error = "-1 : SharePoint Library is not a DocumentLibrary";
                              break;                  
                        case -2:            
                              error = "-2 : SharePoint Website not found";
                              break;                  
                        case -21:            
                              error = "-2.1 : SharePoint Website not found, Security Error with user " + System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                              break;                  
                        case -3:            
                              error = "-3 : SharePoint Library not found";
                              break;                  
                        case -31:            
                              error = "-3.1 : SharePoint Library not found, Access Denied to user " + System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                              break;                  
                        case -4:            
                              error = "-4 : Cannot create SharePoint File";
                              break;                  
                        case -5:            
                              error = "-5 : Cannot retreive or update SharePoint Item List, probably a field value was invalid";
                              break;                  
                        default:            
                              error = "Unknown error";            
                              break;
                  }
                  throw new SoapException("DOC2SPS Error "+error, SoapException.ServerFaultCode);
            }
      }
}
Random Solutions  
 
programming4us programming4us