Showing posts with label Front Page Server Extensions. Show all posts
Showing posts with label Front Page Server Extensions. Show all posts

Thursday, July 3, 2008

Programatically Manage Remote Documents with the FrontPage RPC Library

We've rolled up some of the ideas in previous posts about FrontPage Server Extensions RPC methods into a free CC licensed c# code library.

You can download the source code along with a demo copy of HubKey's SharePoint Client API from HubKey's website - click here for details.

Documentation about the members exposed through the HubKey.Net.FrontPageRPC.WebClient class can be found online here.

Features of the class include:


  • Upload or download many documents in one web request using the 'get documents' and 'put documents' methods.

  • True file streaming (without pre-loading to memory) for faster uploads.

  • Asynchronous methods including an asynchronous MoveDocuments method.

  • Auto detection of FrontPage dll paths and versions.



The following FrontPage Server Extensions RPC Methods are included in the library:


  • checkin document method - remotely check-in a document to source control.

  • checkout document method - remotely check-out a document from source control.

  • getDocsMetaInfo method - download document metadata to a client machine.

  • get document method - remotely download a document with metadata from a web folder or SharePoint document library. Includes an asynchronous method.

  • get documents method - programatically download documents with metadata from a web folder or SharePoint document library in one web request. Includes an asynchronous method.

  • list documents method - obtains a list of files and folders on the web or SharePoint server. Sorts the results into a tree structure to allow for use in a TreeView control.

  • list versions method - retrieves metadata for all the versions of the specified document.

  • move document method - programatically move (rename) or copy a file or folder. Allows for moves between webs or even servers by downloading and then uploading the file.

  • open service method - list service meta information.

  • put document method - programatically upload a file to a SharePoint document library or web server with meta info. Includes an asynchronous method.

  • put documents method - remotely upload files to a SharePoint document library or web server with meta info. Includes a method to asynchronously upload large files. Allows true streaming (without loading into memory first) for large file uploads.

  • remove documents method - delete files or folders from a SharePoint document library or web server.

  • setDocsMetaInfo method - update document meta data from a client computer.

  • uncheckout document method - revert a document to the version before it was checked out.

  • url to web url method - break a url into its web and web relative components.



A very brief code example follows - we'll cover an in depth sample application in a future post:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace HubKey.Net.FrontPageRPC
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient webClient = new WebClient();
 
            //upload a document and check it in
 
            MetaInfoCollection meta = new MetaInfoCollection();
            meta.Add("vti_title", "My Title");
            UploadDocumentResponse uploadDocumentResponse = webClient.UploadDocument("https://localhost/Docs1/test.txt", @"C:\test.txt", meta);
            if (uploadDocumentResponse.Document.IsCheckedOut)
                webClient.CheckInDocument(uploadDocumentResponse.Document, "uploaded via RPC");
 
            //move a document between servers
 
            MoveDocumentResponse moveDocumentResponse = webClient.MoveDocument("http://localhost/Docs2/test.txt", "https://remoteserver/Docs2/test.txt");
        }
    }
}

Wednesday, November 14, 2007

Upload a File to a SharePoint Document Library - Part II

In Part I I posted code that used the SharePoint lists service to help in uploading files with meta data to a sharepoint document library. Here is another variation, this time using FrontPage Server Extensions and RPC. Note that this code won't create more than one new folder - if this is a problem you may want to ensure the full folder path with code like that from the first article.

Update: You can download a comprehensive c# class library to automate RPC calls - including uploading files to a SharePoint document library. See this blog post for more information.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
 
namespace DevHoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, object> properties = new Dictionary<string, object>();
            properties.Add("Title", "Test Title");
            //Create or overwrite text file test.txt in 'Docs' document library creating folder 'Test Folder' as required.
            DocLibHelper.Upload("http://localhost/Docs/Test Folder/test.txt", System.Text.Encoding.ASCII.GetBytes("Test text."), properties);
        }
    }
 
    static class DocLibHelper
    {
        static string EncodeMetaInfo(Dictionary<string, object> metaInfo)
        {
            if (metaInfo == null) return "";
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, object> kvp in metaInfo)
            {
                if (kvp.Value != null)
                {
                    string fieldName = kvp.Key; // note: field names are case sensitive
                    switch (fieldName)
                    {
                        case "Title":
                            fieldName = "vti_title";
                            break;
                    }
                    string data = EscapeVectorChars(kvp.Value.ToString());
                    string dataTypeCode = "S";
                    switch (kvp.Value.GetType().FullName)
                    {
                        case "System.Boolean":
                            dataTypeCode = "B";
                            break;
                        case "System.DateTime":
                            data = ((DateTime)kvp.Value).ToString("s") + "Z";
                            break;
                    }
                    sb.AppendFormat("{0};{1}W|{2};", fieldName, dataTypeCode, data);
                }
            }
            return HttpUtility.UrlEncode(sb.ToString().TrimEnd(';'));
        }
 
        static string EscapeVectorChars(string value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in value)
            {
                switch (c)
                {
                    case ';':
                    case '|':
                    case '[':
                    case ']':
                    case '\\':
                        sb.Append("\\");
                        break;
                }
                sb.Append(c);
            }
            return sb.ToString();
        }
 
        public static string GetWebURL(string url)
        {
            try
            {
                url = url.Substring(0, url.LastIndexOf("/"));
                try
                {
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Credentials = CredentialCache.DefaultCredentials;
                        webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
                        webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
                        byte[] data = Encoding.UTF8.GetBytes("method=open+service%3a12.0.4518.1016&service_name=%2f");
                        string result = Encoding.UTF8.GetString(webClient.UploadData(url + "/_vti_bin/_vti_aut/author.dll", "POST", data));
                        if (result.IndexOf("\n<li>status=327684") == -1)
                            return url;
                        throw new Exception();
                    }
                }
                catch
                {
                    return GetWebURL(url);
                }
            }
            catch
            {
                return null;
            }
        }
 
        public static bool Upload(string destinationUrl, byte[] bytes, Dictionary<string, object> metaInfo)
        {
            string result = "";
            string webUrl = GetWebURL(destinationUrl);
            string documentName = destinationUrl.Substring(webUrl.Length + 1);
            return Upload(webUrl, documentName, bytes, metaInfo, out result);
        }
 
        public static bool Upload(string webUrl, string documentName, byte[] bytes, Dictionary<string, object> metaInfo, out string result)
        {
            string putOption = "overwrite,createdir,migrationsemantics"// see http://msdn2.microsoft.com/en-us/library/ms455325.aspx
            string comment = null;
            bool keepCheckedOut = false;
            string method = "method=put+document%3a12.0.4518.1016&service_name=%2f&document=[document_name={0};meta_info=[{1}]]&put_option={2}&comment={3}&keep_checked_out={4}\n";
            method = String.Format(method, documentName, EncodeMetaInfo(metaInfo), putOption, HttpUtility.UrlEncode(comment), keepCheckedOut.ToString().ToLower());
            List<byte> data = new List<byte>();
            data.AddRange(Encoding.UTF8.GetBytes(method));
            data.AddRange(bytes);
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Credentials = CredentialCache.DefaultCredentials;
                    webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded");
                    webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
                    result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll", "POST", data.ToArray()));
                    if (result.IndexOf("\n<p>message=successfully") < 0)
                        throw new Exception(result);
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return false;
            }
            return true;
        }
    }
}