Library tutorials & articles

SharePoint, Document Library and SQL Server

Code Discussion

Now, let’s spend a few minutes to see the application code:

The following files have been taken from the “Event Handler Toolkit”:

  • BaseEventSink.cs
  • LoggerEventSink.cs
  • SPListEventArgs.cs
  • LibraryEventSink.cs

We will not discuss these files. If you want more information about how to use the “Event Handler Toolkit”, read following detailed article on Microsoft’s site: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/spptsdk/html/tsptDocLibEvents_SV01034973.asp

We added our code in “LibraryEventSink” class. Let’s take a look!

private void OnInsert()
{
    try
    {

        spFile = EventWeb.GetFile(EventFileUrl);
        if (spFile.Exists)
        {
            spListItem = spFile.Item;

            //Retrieve Database string from config file
            string strDB;
            StreamReader sr = new StreamReader(@"C:\db.config");
            strDB = sr.ReadLine();
            sr.Close();

We write our code in “OnInsert()” because we want to capture the document information  at the time when it gets added to the library. If we wanted to capture the document when someone updated it, we would write our code in “OnUpdate()”. First of all, we get the URL of the file just added to the library.

spFile = EventWeb.GetFile( EventFileUrl ); 

spFile is an instance of class SPFile that represents a file in a SharePoint web site that is an item in a document library. Next, we open the “db.config” file that contains the connection string to the SQL Server. We read the connection string into the “strDB” variable.

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(strDB);
SqlCommand myCommand = new SqlCommand("sp_AddDocInfo", myConnection);

// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure; 

Instances of Connection and Command objects are created. Stored procedure expects parameters that will contain the values to be added in the database. In the following piece of code, we define the parameters and assign values to them. We capture following document details:

  1. Document Name
  2. Date of Modification
  3. Approval Status
  4. Approver Comments
  5. Modified By
 // Add Parameters to SPROC
SqlParameter pName= new SqlParameter("@Name", SqlDbType.VarChar , 50);
pName.Value = spListItem["Name"];
myCommand.Parameters.Add(pName);

SqlParameter pModified= new SqlParameter("@Modified", SqlDbType.DateTime, 8);
pModified.Value = spListItem["Modified"];
myCommand.Parameters.Add(pModified);

SqlParameter pApprovalStatus= new SqlParameter("@ApprovalStatus", SqlDbType.Int , 4);
pApprovalStatus.Value = spListItem["Approval Status"];
myCommand.Parameters.Add(pApprovalStatus);

SqlParameter pModifiedBy = new SqlParameter("@ModifiedBy", SqlDbType.VarChar , 50);
pModifiedBy.Value = spListItem["Modified By"];
myCommand.Parameters.Add(pModifiedBy); 

In the following code, we use “if-else” to send proper value to the database to avoid error. If “Approver Comments” are empty, it will generate an error. It is important to tackle this situation. We check the property for the null value, in case it contains null, we add comments of our own otherwise we leave the original comments in tact. This property will always contain null because “Approver Comments” are always null when a new document is added to the library. Approver can add his/her comments only at the time of approval. I used this property thinking that I would demonstrate it’s use in the “update” event.

if (spListItem["Approver Comments"]!=System.DBNull.Value)
{
     SqlParameter pApproverComments = new SqlParameter("@ApproverComments", SqlDbType.VarChar , 255);
     pApproverComments.Value = "No Comments";
}
else
{
     SqlParameter pApproverComments = new SqlParameter("@ApproverComments", SqlDbType.VarChar , 255);
     pApproverComments.Value = spListItem["Approver Comments"];
     myCommand.Parameters.Add(pApproverComments);
} 

Finally, open the connection, execute the stored procedure and close the connection.

// Open the connection and execute the Command 
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close(); }}

You can catch exceptions using “try-catch”. Exceptions caught are logged in the Windows Event Log.

catch ( System.Security.SecurityException ex ) 
{ 
    message = "Error: " + ex.Message; 
    writeToEventLog(message + ":" + ex.ToString()); 
} 
catch ( Exception ex ) 
{ 
    Message = "Error: " + ex.Message; 
    writeToEventLog(message + ":" + ex.ToString());
} } 

Comments

  1. 16 Feb 2009 at 05:39
    Hi, Your article caught me eye whilst I was browsing trying to learn about Sharepoint. I am BA not a developer and am trying to work out how to implement SharePoint. One of our directors was under the impression that SharePoint doucments are stored within the database rather than on a file store similar to Lotus Notes. I have not been able to find any information to verify this. My questions are: 1. Can you confirm where SharePoint stores the documents - database or network/file store directory? 2. How difficult is it to migrate/extract documents from SharePoint if you decide in the future to move to another product?
  2. 03 Oct 2008 at 18:56
    Hi, Great article. Is it possible to use the event handlers and copy the document to sql server? I need to take a document that is uploaded into a document library and copy the document to sql server for our external users to access through an asp.net web application.
  3. 30 Jun 2008 at 06:39

    Hi,

     

    I have one questsion, if you can reply. which format sql server store sharepoint files?

    second how sqlserver manage versions history?

    help will be appreciated.

    Thanks,

    Ars

  4. 27 Feb 2008 at 16:33

    Hello,

    I am new to SharePoint, I am reseraching for my company the option of useing SharePoint Shared Document library for our docmentation system.  We are a small company and need to create a standard shared docuemnt repository for our IT department.

    Can anyone answere the following questions?

     Thanks

     Is there icensing fee's for a share point shared document library?

     Can you create retention rules / periods on dcouments stored in the shared document library?

    Is the shared document library?

    What type of files can be stored in the shared document library? word, PDF, excell, powerpoint, onenote, miscrosoft project, visio?

     

  5. 30 May 2007 at 08:14

    Hi,

    This article is very useful for me as a beginner to Sharepoint.  I need a favour, there is a requirement to have a form that collects some input like description, remarks, expiry date etc and add a document to the library.  It requires edit feature and delete feature too.  Can you please guide me how to achieve in sharepoint, THANKS IN ADVANCE.

    Please mail at reachbaala@yahoo.com

    Thanks, Bala

     

     

  6. 01 Jan 1999 at 00:00

    This thread is for discussions of SharePoint, Document Library and SQL Server.

Leave a comment

Sign in or Join us (it's free).

S.S. Ahmed S.S. Ahmed is a senior IT Professional and works for a web and software development firm. Ahmed is a Microsoft Office SharePoint Server MVP. Ahmed specializes in creating database driven dynamic we...
AddThis

Related podcasts

  • Stack Overflow: Podcast #28

    This is the twenty-eighth episode of the StackOverflow podcast, where Joel and Jeff discuss Windows Azure, SQL Server 2008 full text search, Bayesian filtering, porn detection, and project management — among other things. Jeff met the inestimable Joey DeVilla aka Accordion Guy...

Events coming up

  • Dec 12

    SharePoint Saturday Kansas City

    Overland Park, United States

    Join SharePoint architects, developers, and other professionals that work with Microsoft Office SharePoint Server 2007 for ‘SharePoint Saturday’, on Saturday, December 12th, 2009.

We'd love to hear what you think! Submit ideas or give us feedback