5,693,062 members and growing! (21,301 online)
Email Password   helpLost your password?
Enterprise Systems » SharePoint Server » General     Intermediate License: The Code Project Open License (CPOL)

Uploading Files to SharePoint Document Library and updating any Meta data columns

By Junaid Raza

Uploading Files to SharePoint Document Library and updating ant Meta data
VB 7.x, VB 8.0, VBWindows, .NET, .NET 1.1, .NET 2.0, WinXP, Win2003VS2005, Visual Studio, Dev

Posted: 23 Jul 2007
Updated: 10 Jun 2008
Views: 64,103
Bookmarked: 40 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 2.99 Rating: 3.54 out of 5
0 votes, 0.0%
1
2 votes, 28.6%
2
0 votes, 0.0%
3
3 votes, 42.9%
4
2 votes, 28.6%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

This article describes uploading files in a sequence to a SharePoint Document Library and then using CAML, updating each file's custom meta data. This article also also describes how to use DWS web service to create folders/subfolders in a Doc Lib and how to use List web service to upload/update files inside Doc Lib.

Background

In my organization, a large number of documents are scanned each day (.pdf) and we maintain an electronic complex system of approving documents and filtering/searching based on there respective meta data. Files are named in a specific manner, I had to write a Web Service named File Shunter in Vb.Net which contains two functions, 1 function takes the input folder and upload the files to server into a specific folder (this function also creates folders/subfolders based on rules in file name using SharePoint DWS Web service), the other function, for each document being uploaded, extracts all the required meta data from the file name and once the file has been uploaded, using CAML and List Web service (http://sp portal/subsite/_vti_bin/lists.asmx) updates the required meta data columns for that file. I use Web.config to store/retreive doc library name, portal name, user authentication etc... . This code uses web services, so it is not required to run the code on the server where portal is running (in case where SharePoint Object Model is used). Another feature is we have to maintain version history of each file since a file can be uploaded multiple times so we need to keep its revisions, for this purpose, if version history is enabled in document library and if a file's meta data is changed after it has been uploaded, it will become a new version while we need to access and update the current file without making anotehr version while updating it for this purpose the function bEnableVersion(True/false) is used, which is set true when uploading teh file so that if file already exists then a version is generated inside doc lib but when updating its meta data, version history is set to false (bEnableVersion(false)). Another good feature of a document library is that it can be used as a mapped drive inside file system (since its a web folder). Our documentation dept was used to of accessing files from a shared folder before, now after files are uploaded to SharePoint, we just mapped that document library as a shared folder for each user so there is no difference for them to work/access these files, Just enable the WebClient service on user's PC and map the doc lib (http://portal/site/doclib).

Using the code

There are two main functions: UploadDocument and WSSUpdateFile. The 1st function is passed Local file name (On file system) and remote file name (to be used inside doc lib. Once the file is uploaded, the other function is passed file name, and any meta data column values to be updated, for test purpose, i created a column named "TestCol" in my test document library and passed it "Test Value", but this function can be passed as many number of meta data column values as required, just add them in the xml batch inside the function with column name and the value. To update a file properties, normally its ID is required to access it and update its properties (even inside folders). I have used CAML (Access the recent uplaoded file and get its ID) then this ID is used in List Web service UpdateListItems function to update the properties of the file. Included is function "CreateFolder" which can be used to create any number of folder/subfolders within a Doc Lib. Most of the common required values like Portal URL, Doc Lib name, user, pwd, domain, folder name (where files reside to be uploaded) are set into Web.config for easy modification. Main function access these values to determine required data and authentication. To upload teh files lets say from D:\Test folder, in web.config under globalsharedpath key "<add key="GlobalSharedPath" value="D:\"/>" Pass only "D:\" and once the program is running, pass only "Test" in the input folder name. 1 thing to remember is that some of SharePoint web services are site specific, means u need to reference the exact site/subsite to play with it, for example if i have a subsite under http://portal/sitedirectory/site then list web servic erefernce should be like http://portal/sitedirectory/site/_vti_bin/lists.asmx.

//
Web.config
<configuration>
<appSettings>

<add key="SharePointServer" value=http://SP Portal/Site/>
<add key="DocLibrary" value="Doclib"/>
<add key="User" value="User"/>
<add key="Domain" value="Domain"/>
<add key="Pwd" value="Pwd"/>
<add key="GlobalSharedPath" value="D:\"/>
</appSettings>
//
Public Function UploadDocument(ByVal localFile As String, ByVal remoteFile As String) As String
        '// Read in the local file
        On Error GoTo handler
        Dim r As Byte()
        Dim Strm As System.IO.FileStream = New System.IO.FileStream(localFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)
        Dim reader As System.IO.BinaryReader = New System.IO.BinaryReader(Strm)
        Dim filecontents As Byte() = reader.ReadBytes(CInt(Strm.Length))
        reader.Close()
        Strm.Close()
        Dim sSPURL As String = ConfigurationManager.AppSettings("SharePointServer")
        Dim sDocLib As String = ConfigurationManager.AppSettings("DocLibrary")
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim sRemoteFileURL As String
        Dim NC As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
        sRemoteFileURL = sSPURL & "/" & sDocLib & "/" & Trim(LTrim(RTrim(remoteFile)))
       
        sRemoteFileURL = Replace(sRemoteFileURL, " ", "%20")
        sRemoteFileURL = Replace(sRemoteFileURL, "\", "/")
        Dim m_WC As WebClient = New WebClient
        m_WC.Credentials = NC
        r = m_WC.UploadData(sRemoteFileURL, "PUT", filecontents)
        Return "TRUE"
        Exit Function
handler:
        Return Err.Description
    End Function



Public Function WSSUpdateFile(ByVal sFileName As String, ByVal sSiteDoc As String, ByVal sTestCol As String) As String
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim sFileIDinList As String
        Dim strBatch As String = ""
        sSiteDoc = Replace(sSiteDoc, "%20", " ")
        sSiteDoc = Replace(sSiteDoc, "\", "/")
        Dim sFinalFilePath As String
        Dim sSPURL As String = ConfigurationManager.AppSettings("SharePointServer")
        Dim sDocLib As String = ConfigurationManager.AppSettings("DocLibrary")
        Try
            Dim netAccess As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
            Dim listService As New SPLists.Lists
            listService.Url = sSPURL & "/_vti_bin/lists.asmx"
            listService.Credentials = netAccess
            sFileIDinList = sGetID(listService.Url, sDocLib, sFileName)
            If sFileIDinList <> "" Then
                sFinalFilePath = sSPURL & "/" & sDocLib & "/" & sFileName
                'Now we have FileID so update the list
                strBatch = "<Method ID='1' Cmd='Update'>" + _
                    "<Field Name = 'ID'>" & sFileIDinList & "</Field>" + _
                    "<Field Name = 'FileRef'>" & sFinalFilePath & "</Field>" + _
                    "<Field Name = 'TestCol'>" & sTestCol & "</Field>" + _
                    "</Method>"
                Dim xmlDoc = New System.Xml.XmlDocument
                Dim elBatch As System.Xml.XmlElement = xmlDoc.createelement("Batch")
                elBatch.InnerXml = strBatch
                Dim ndreturn As System.Xml.XmlNode = listService.UpdateListItems(sDocLib, elBatch)
            End If
            Return "TRUE"
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function
Private Function sGetID(ByVal sURL As String, ByVal sListGUID As String, ByVal sFileName As String) As String
        Dim sUser As String = ConfigurationManager.AppSettings("User")
        Dim sPwd As String = ConfigurationManager.AppSettings("Pwd")
        Dim sDomain As String = ConfigurationManager.AppSettings("Domain")
        Dim netAccess As System.Net.NetworkCredential = New System.Net.NetworkCredential(sUser, sPwd, sDomain)
        Dim L As New SPLists.Lists
        L.Credentials = netAccess
        L.Url = sURL
        Dim xmldoc As XmlDocument = New XmlDocument
        Dim query As XmlNode = xmldoc.CreateNode(XmlNodeType.Element, "Query", "")
        query.InnerXml = "<OrderBy><FieldRef Name='Modified'  Ascending='False'></FieldRef></OrderBy>"""
        Try
            Dim caml As XmlNode = L.GetListItems(sListGUID, Nothing, query, Nothing, "1", Nothing)
            Dim id As String = caml.ChildNodes(1).ChildNodes(1).Attributes("ows_ID").Value
            Return id
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function


Points of Interest

Using Web services instead of OM Creating folders inside Doc Lib Enabling/Disabling Version History

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Junaid Raza


An IT graduate with 3 years experience in the area of software development, Database designing and administration, SharePoint/MOSS 2003/2007 development using its standard web services and Object Model and Network Programming. Currently working as Regional Database Manager with Nokia Siemens Networks (Telenor Project)Pakistan.
Occupation: Web Developer
Location: Pakistan Pakistan

Other popular SharePoint Server articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 72 (Total in Forum: 72) (Refresh)FirstPrevNext
Generalupdate business data column in document librarymemberCharu Agarwal19:33 30 Sep '08  
QuestionAssistance with solution?membertreesprite17:21 7 Jul '08  
GeneralHow to Rename a Folder copy folder or move foldermemberT.Ashraf8:48 18 Jun '08  
GeneralSpace in FileName or Document library NamememberAkthard1:35 12 Jun '08  
GeneralRe: Space in FileName or Document library NamememberJunaid Raza1:37 12 Jun '08  
Generaluploading search textmemberTroy Lee5:28 11 Jun '08  
GeneralHow to use only Web Service for this Update [modified]memberAkthard3:45 10 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberJunaid Raza10:46 10 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberAkthard22:02 10 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberJunaid Raza0:06 11 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberAkthard0:30 11 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberJunaid Raza0:35 11 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberAkthard0:39 11 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberAkthard0:40 11 Jun '08  
GeneralRe: How to use only Web Service for this UpdatememberAkthard1:08 11 Jun '08  
Generalgetting metadata from an xml filememberTroy Lee10:11 29 May '08  
GeneralRe: getting metadata from an xml filememberJunaid Raza19:49 29 May '08  
GeneralThe remote server returned an error: (401) Unauthorized.memberTroy Lee8:03 27 May '08  
GeneralRe: The remote server returned an error: (401) Unauthorized.memberJunaid Raza8:35 27 May '08  
GeneralRe: The remote server returned an error: (401) Unauthorized.memberTroy Lee10:20 27 May '08  
AnswerRe: The remote server returned an error: (401) Unauthorized.memberRAEdwards7420:28 1 Jul '08  
GeneralSPLists.ListsmemberTroy Lee11:42 19 May '08  
GeneralRe: SPLists.ListsmemberJunaid Raza3:47 20 May '08  
GeneralRe: SPLists.ListsmemberTroy Lee4:55 20 May '08  
GeneralRe: SPLists.ListsmemberTroy Lee5:18 20 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Jun 2008
Editor:
Copyright 2007 by Junaid Raza
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project