Sharepoint can be one of those tricky pain points for most asp.net web developers whose primary focus is the web space and not necessarily as a sharepoint developer. It seems like there is no one go to place to find exactly what you need for your specific solution when it comes to Sharepoint.

Luckily for me, I had the opportunity to investigate several ways of performing a simple task within sharepoint. Everything is documented below. If there are any questions please shoot me a message on twitter @mobilizecloud

The Problem

Our backend MVC C# web application that serves as a portal for all our customers has multiple online document repositories. What we found was that everytime we needed to change out a document, ous staff was having to do it in two places, in the web application and also within sharepoint.

So our goal was to figure out the easiest way possible to synchronize Sharepoint and the web application.

The Solution

To solve our problem we investigated doing direct uploads and manipulations of the files on SharePoint from our web application. We looked into using the sharepoint web services but ran into issues when trying to delete files. So we eventually choose to go with the client object model.

Step 1 - Downloading SharePoint DLLs

You will need to download the following dlls to your web application project. Download them using the links below or using the nuget package manager and search for "SharePoint" then download "Microsoft SharePoint Foundation 2010 Client Object Model"

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll
Step 2 - Uploading a file

The code snippet below shows how we take a file that recently has been uploaded to an mvc controller and upload it to sharepoint at the same time. Several functions have been consolidated for reuse throughout the project.

        public ActionResult Create(SomeVM Model)
        {
            var ValidFileName = GenerateValidFileName(Model.FileUploaded.FileName);
            var UniqueFileName = CommonFunctions.GetUniqueFilename("~/Uploads/" + ValidFileName, ValidFileName);
            var SavedPath = "~/Uploads/" + UniqueFileName;
            Model.FileUploaded.SaveAs(Server.MapPath(SavedPath));

            //Create a Dictionary for any meta data fields that need to be passed to sharepoint with the file.
            var MetaData = new Dictionary<string, string>();
            MetaData.Add("Title", "Title Value");
            MetaData.Add("Manufacturer", "Manufacturer Value");

            //Returns the SharepointURL location of the recently uploaded file. Will be used later to delete the file on sharepoint if needed.
            var SharepointURL = UploadSharePointFile(Server.MapPath(PriceFile.PDFUploadLocation), "/sales", "ActiveDocs", MetaData);
        }

        public string GenerateValidFileName(string name)
        {
            string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
            string invalidReStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);
            return System.Text.RegularExpressions.Regex.Replace(name, invalidReStr, "_");
        }

        public string GenerateUniqueFilename(string Path, string postedFileName)
        {
            string fileExtension = postedFileName.Substring(postedFileName.LastIndexOf('.') + 1);
            int index = 2;

            while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(Path)))
            {
                var OriginalName = postedFileName;
                postedFileName = string.Format("{0} ({1}).{2}", postedFileName.Substring(0, postedFileName.LastIndexOf('.')), index, fileExtension);
                Path = Path.Replace(OriginalName, postedFileName);
                index++;
            }

            return postedFileName;
        }

        public string UploadSharePointFile(string UploadFile, string Location, string Library, Dictionary<string, string> MetaData)
        {
            using (ClientContext clientContext = new ClientContext("http://default.sharepoint.url" + Location))
            {
                //Use your sharepoint credentials
                var Username = "username";
                var Password = "password";
                var Domain = "domain";
                clientContext.Credentials = new NetworkCredential(Username, Password, Domain);

                //Get Document List
                List documentsList = clientContext.Web.Lists.GetByTitle(Library);

                var fileCreationInformation = new FileCreationInformation();
                //Assign to content byte[] i.e. documentStream

                fileCreationInformation.Content = System.IO.File.ReadAllBytes(UploadFile);
                //Allow owerwrite of document

                fileCreationInformation.Overwrite = true;
                //Upload URL

                fileCreationInformation.Url = "http://default.sharepoint.url" + Location + "/" + Library + "/" + Path.GetFileName(UploadFile);
                Microsoft.SharePoint.Client.File UploadedFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
                clientContext.Load(UploadedFile);

                ListItem item = UploadedFile.ListItemAllFields;
                clientContext.Load(item);
                foreach (var data in MetaData)
                {
                    item[data.Key] = data.Value;
                }
                item.Update();     

                clientContext.ExecuteQuery();

            }
            return "";
        }