Skip to content

Instantly share code, notes, and snippets.

@jaycdave88
Created July 18, 2016 20:53
Show Gist options
  • Save jaycdave88/e58e8234421e851b511670fff6b3036d to your computer and use it in GitHub Desktop.
Save jaycdave88/e58e8234421e851b511670fff6b3036d to your computer and use it in GitHub Desktop.
#region
using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.SharePoint.Client;
using Nuveen.DMG.Core.Services;
using System.Configuration;
using System.IO;
using System.Linq;
#endregion
namespace Nuveen.DMG.Common.Services
{
public class SharePointService : IDocumentManagementService
{
private readonly ILogger _logger;
private readonly string _sharePointRoot = ConfigurationManager.AppSettings["SharePointRoot"];
public SharePointService()
{
_logger = ServiceLocator.Current.GetInstance<ILogger>();
}
#region Connection Methods()
/// <summary>
/// Certifications the validation which will allow code to work for SSL enabled sites.
/// </summary>
private void CertificationValidation()
{
try
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyError) => true;
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
/// <summary>
/// Networks the credential.
/// </summary>
/// <returns></returns>
private NetworkCredential NetworkCredential()
{
try
{
var userName = ConfigurationManager.AppSettings["SharePointUsername"];
var domain = ConfigurationManager.AppSettings["SharePointDomain"];
var password = ConfigurationManager.AppSettings["SharePointPassword"];
var networkCredential = new NetworkCredential(userName, password, domain);
return networkCredential;
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
/// <summary>
/// Opens the connection to share point.
/// </summary>
/// <exception cref="System.ArgumentException">OpehConnectionString: + exception</exception>
private ClientContext OpenConnectionToSharePoint()
{
try
{
CertificationValidation();
var siteUrl = ConfigurationManager.AppSettings["SharePointUrl"];
using (var clientContext = new ClientContext(siteUrl))
{
//Comment code uses the local authentication from computer
//clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
//clientContext.Credentials = CredentialCache.DefaultCredentials;
clientContext.Credentials = NetworkCredential();
clientContext.ValidateOnClient = true;
_logger.Info("Connection to SharePoint was successful.");
return clientContext;
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
#endregion
#region Main Methods()
/// <summary>
/// Uploads the file as a stream to a sub-folder.
/// If the sub-folder, (folderName) is not provided the file will be uploaded to the Root Folder.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="folderName">Name of the folder.</param>
/// <exception cref="System.Exception">Stream cannot be null</exception>
public void UploadFile(Stream file, string fileName, string folderName)
{
try
{
using (var clientContext = OpenConnectionToSharePoint())
{
var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
clientContext.Load(list.RootFolder);
clientContext.Load(list.RootFolder.Folders);
clientContext.ExecuteQuery();
if (string.IsNullOrEmpty(folderName))
{
var webContext = clientContext.Web.Context;
if (file == null) throw new Exception("Stream cannot be null");
if (webContext.HasPendingRequest) webContext.ExecuteQuery();
var rootFileUrl = Path.Combine(list.RootFolder.ServerRelativeUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(
clientContext, rootFileUrl, file, true);
}
else
{
CreateFolderIfDoesNotExist(folderName);
var newFolder = Path.Combine(list.RootFolder.ServerRelativeUrl, folderName);
var folder = list.RootFolder.Folders.Add(newFolder);
clientContext.ExecuteQuery();
var fileUrl = Path.Combine(newFolder, fileName);
clientContext.Load(folder.Files);
clientContext.ExecuteQuery();
var existingFile = folder.Files.ToList().FirstOrDefault(x => x.Name == fileName);
if (existingFile != null)
{
clientContext.Load(existingFile);
clientContext.ExecuteQuery();
clientContext.Load(existingFile.LockedByUser);
clientContext.ExecuteQuery();
}
else
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, file, true);
}
}
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
/// <summary>
/// Downloads all files.
/// If the sub-folder, (folderName) is not provided -- will download all files from the Root Folder.
/// Otherwise, will download all the files from a specific sub-folder.
/// </summary>
/// <returns></returns>
public List<MemoryStream> DownloadFiles(string fileName, string folderName, bool downloadAllFile)
{
try
{
var memoryStreamCollection = new List<MemoryStream>();
using (var clientContext = OpenConnectionToSharePoint())
{
var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
clientContext.Load(list);
clientContext.Load(list.RootFolder);
clientContext.Load(list.RootFolder.Folders);
clientContext.Load(list.RootFolder.Files);
clientContext.ExecuteQuery();
var folder = list.RootFolder;
if (!string.IsNullOrEmpty(folderName))
{
var folders = list.RootFolder.Folders;
folder = folders.First(f => f.Name == folderName);
}
clientContext.Load(folder.Files);
clientContext.ExecuteQuery();
if (downloadAllFile)
{
foreach (var file in folder.Files)
{
var fileReference = file.ServerRelativeUrl;
GetStream(fileReference, memoryStreamCollection, file.Name, folderName);
}
return memoryStreamCollection;
}
else
{
var fileNameCheck = folder.Files.First(f => f.Name == fileName);
var fileReference = fileNameCheck.ServerRelativeUrl;
GetStream(fileReference, memoryStreamCollection, fileName, folderName);
return memoryStreamCollection;
}
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
/// <summary>
/// Deletes a file from a Sub-folder that matches the fileName.
/// If the sub-folder, (folderName) is not provided the file will be deleted from the Root Folder.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="folderName">Name of the folder.</param>
public void DeleteFile(List<string> fileName, string folderName)
{
try
{
using (var clientContext = OpenConnectionToSharePoint())
{
var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
clientContext.Load(list.RootFolder);
clientContext.Load(list.RootFolder.Folders);
clientContext.Load(list.RootFolder.Files);
clientContext.ExecuteQuery();
var files = list.RootFolder.Files;
if (string.IsNullOrEmpty(folderName))
{
foreach (var file in files)
{
if (fileName.Contains(file.Name))
{
file.DeleteObject();
clientContext.ExecuteQuery();
_logger.Info(string.Format("{0}: was deleted from the {1} folder.", fileName, _sharePointRoot));
}
else
{
_logger.Error(string.Format("{0}: was not found.", fileName.Contains(file.Name)));
}
}
}
else
{
var folders = list.RootFolder.Folders;
var folder = folders.First(f => f.Name == folderName);
clientContext.Load(folder.Files);
clientContext.ExecuteQuery();
var folderFiles = folder.Files;
foreach (var ff in folderFiles)
{
if (fileName.Contains(ff.Name))
ff.DeleteObject();
clientContext.ExecuteQuery();
_logger.Info(string.Format("{0}: was deleted from {1} folder.", fileName.Contains(ff.Name), folderName));
}
}
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
#endregion
#region Helper Method()
/// <summary>
/// Creates a folder if the folder does not already exist.
/// </summary>
/// <param name="folderName">Name of the folder.</param>
private void CreateFolderIfDoesNotExist(string folderName)
{
try
{
using (var clientContext = OpenConnectionToSharePoint())
{
var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
list.EnableFolderCreation = true;
clientContext.Load(list);
clientContext.Load(list.RootFolder);
clientContext.Load(list.RootFolder.Folders);
clientContext.ExecuteQuery();
var folderCollection = list.RootFolder.Folders;
foreach (var folder in folderCollection)
{
if (folder.Name == folderName)
{
clientContext.Load(folder.Files);
clientContext.ExecuteQuery();
}
else
{
var itemCreateInfo = new ListItemCreationInformation
{
UnderlyingObjectType = FileSystemObjectType.Folder,
LeafName = folderName
};
var newItem = list.AddItem(itemCreateInfo);
newItem["Title"] = folderName;
newItem.Update();
}
}
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
}
/// <summary>
/// Gets the stream.
/// </summary>
/// <param name="fileReference">The file reference.</param>
/// <param name="memoryStreamCollection">The memory stream collection.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="folderName">Name of the folder.</param>
/// <returns></returns>
private void GetStream(string fileReference, ICollection<MemoryStream> memoryStreamCollection, string fileName, string folderName)
{
try
{
if (string.IsNullOrEmpty(folderName))
{
folderName = _sharePointRoot;
}
using (var clientContext = OpenConnectionToSharePoint())
{
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileReference);
var fileStream = new MemoryStream();
fileInfo.Stream.CopyTo(fileStream);
memoryStreamCollection.Add(fileStream);
_logger.Info(string.Format("{0}: was downloaded successfully from {1} folder.", fileName, folderName));
}
}
catch (Exception ex)
{
_logger.Error(ex);
throw;
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment