Canarys | IT Services

Blogs

How to upload documents to SharePoint 2013

Date:
Author:
Share

Introduction

SharePoint is a browser-based collaboration, content management, and extensible platform from Microsoft. The latest release of the product is SharePoint 2013.

In this article I will explain about one of the frameworks used for development in SharePoint 2013,   Client-side object model (CSOM). I am going to add a document through code to a SharePoint document library. I am going to use SharePoint object model to add document.

SharePoint 2013 provides a new client object model that enables you to create SharePoint solutions that run remotely from the SharePoint server farm. For example, the client object model enables you to consume and manipulate SharePoint data in Windows Forms applications, Windows Presentation Framework application, console applications, Silverlight applications, and ASP.NET Web applications.

The concept of development using the Client Object model was introduced in SharePoint 2010 and has been carried to the new versions. With the introduction of client-side object model, developers have the ability to perform core SharePoint functionality by using C# (managed client object model), JavaScript and Silverlight.

Creating a Sample Website

Now let’s create a web form that illustrates the complete process in detail.

The prerequisites are that you have SharePoint 2013 and Visual Studio 2010 or 2013 installed in a development environment

Step1: Create a new ASP.Net web project, named SPUploadDocUsingCSOM

Step 2: Adding the Client Object Model references

2.1 Right click the “References” node and choose “Add Reference”

2.2 Choose “Browse”

2.2.1 Navigate to this folder:
C: Program FilesCommon FilesMicrosoft SharedWeb Server Extensions16ISAPI

Note: this path might differ from your share point server version.

3 Select these two files:

3.1 Microsoft.SharePoint.Client.dll

3.2 Microsoft.SharePoint.Client.Runtime.dll

4 Make sure they are included in the references of your project:

5 Add the following using-statement in your class:

using Microsoft.SharePoint.Client;

.SPRef

Step 3: The complete code of ShaePointUploader.aspx looks like this

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”ShaePointUploader.aspx.cs” Inherits=”SPUploadDocUsingCSOM.ShaePointUploader” %>

Here is the UI looks like at runtime:

SPUI

Step 4: The complete code of ShaePointUploader.aspx.cs looks like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Microsoft.SharePoint.Client;

using System.Net;

using System.IO;

using System.Text.RegularExpressions;

using System.Drawing;

namespace SPUploadDocUsingCSOM

{

    public partial class ShaePointUploader : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        public ClientContext SPClientContext { get; set; }

        public Web SPWeb { get; set; }

        public string SPErrorMsg { get; set; }

        protected void btnUpload_Click(object sender, EventArgs e)

        {

            string sURL = txtSharePointURL.Text;

            string sDocName = string.Empty;

            if(!string.IsNullOrWhiteSpace(sURL) && !string.IsNullOrWhiteSpace(txtLibraryName.Text) && (FileLocalPath.HasFile))

            {

                bool bbConnected = Connect(sURL, “UserName”, “PassWord”, “DomainName”);

                if (bbConnected)

                {

                    Uri uri = new Uri(sURL);

                    string sSPSiteRelativeURL = uri.AbsolutePath;

                    sDocName = UploadFile(FileLocalPath.FileContent, FileLocalPath.FileName, sSPSiteRelativeURL, txtLibraryName.Text);                 

  i                f(!string.IsNullOrWhiteSpace(sDocName))

                    {

                        lblMsg.Text = “The document ” + sDocName + ” has been uploaded successfully..”;

                        lblMsg.ForeColor = Color.Blue;

                    }

                    else

                    {

                        lblMsg.Text = SPErrorMsg;

                        lblMsg.ForeColor = Color.Red;

                    }

                }

            }

        }

        public bool Connect(string SPURL, string SPUserName, string SPPassWord, string SPDomainName)

        {

            bool bConnected = false;

            try

            {

                SPClientContext = new ClientContext(SPURL);

                SPClientContext.Credentials = new NetworkCredential(SPUserName, SPPassWord, SPDomainName);

                SPWeb = SPClientContext.Web;

                SPClientContext.Load(SPWeb);

                SPClientContext.ExecuteQuery();

                bConnected = true;

            }

            catch (Exception ex)

            {

                bConnected = false;

                SPErrorMsg = ex.Message;

            }

            return bConnected;

        }

        public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)

        {

            string sDocName = string.Empty;

            try

            {

                if (SPWeb != null)

                {

                    var sFileUrl = String.Format(“{0}/{1}/{2}”, sSPSiteRelativeURL, sLibraryName, sFileName);

                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);

                    sDocName = sFileName;

                }

            }

            catch (Exception ex)

            {

                sDocName = string.Empty;

                SPErrorMsg = ex.Message;

            }

            return sDocName;

        }

Notice Connect and UploadFile I will explain each one in below sections.

Connecting to remote SharePoint site:

In order to connect to SharePoint remotely, we need to use the ClientContext class. It represents the context for SharePoint objects and operations. Use the ClientContext class to return context information about such objects as the current web application, site, site collection, or server version.

SPClientContext = new ClientContext(SPURL); //SPURL is your share point site URL

We should create an instance of the ClientContext class and supply the authentication credentials through its Credentials property.

SPClientContext.Credentials =new NetworkCredential(SPUserName, SPPassWord, SPDomainName);

Please specify the correct user name and password of your site otherwise an Unauthorized Exception will be thrown.

Retrieving the web’s properties using the load() method

var SPWeb = SPClientContext.Web;

SPClientContext.Load(SPWeb);

ExecuteQuery() method executes the current request in the server and retrieves the data. In this case, it will connect to the SharePoint site and load the web site properties.

SPClientContext.ExecuteQuery();

Uploading file to the SharePoint portal:

static SaveBinaryDirect() method of File object uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call. It sends raw binary across the wire and does not increase the message size.

File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);

First Parameter requires a ClientContext object that represents the SharePoint site’s server context.

Second parameter expects a string that represents the server-relative URL of the file.

Third parameter is a Stream object that represents the file.

Last parameter is a Boolean value that specifies whether the file is overwritten if it already exists.

Summary

Client Object Model is a new feature available from SharePoint 2010. It provides features to program against a SharePoint site using .NET Managed Code. It provides client-side applications with access to a subset of the SharePoint Foundation server object model, including core objects such as site collections, sites, lists, and list items. The .NET managed client object model provides a larger subset of functionality for standalone client applications like windows form apps.

Leave a Reply

Your email address will not be published. Required fields are marked *

Reach Us

With Canarys,
Let’s Plan. Grow. Strive. Succeed.