Advertisement
Guest User

Untitled

a guest
Jul 18th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.10 KB | None | 0 0
  1. #region
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Net;
  6. using Microsoft.SharePoint.Client;
  7. using Nuveen.DMG.Core.Services;
  8. using System.Configuration;
  9. using System.IO;
  10. using System.Linq;
  11.  
  12. #endregion
  13.  
  14. namespace Nuveen.DMG.Common.Services
  15. {
  16. public class SharePointService : IDocumentManagementService
  17. {
  18. private readonly ILogger _logger;
  19. private readonly string _sharePointRoot = ConfigurationManager.AppSettings["SharePointRoot"];
  20.  
  21. public SharePointService()
  22. {
  23. _logger = ServiceLocator.Current.GetInstance<ILogger>();
  24. }
  25.  
  26. #region Connection Methods()
  27.  
  28. /// <summary>
  29. /// Certifications the validation which will allow code to work for SSL enabled sites.
  30. /// </summary>
  31. private void CertificationValidation()
  32. {
  33. try
  34. {
  35. ServicePointManager.ServerCertificateValidationCallback +=
  36. (sender, certificate, chain, sslPolicyError) => true;
  37. }
  38. catch (Exception ex)
  39. {
  40. _logger.Error(ex.Message, ex);
  41. throw;
  42. }
  43. }
  44.  
  45. /// <summary>
  46. /// Networks the credential.
  47. /// </summary>
  48. /// <returns></returns>
  49. private NetworkCredential NetworkCredential()
  50. {
  51. try
  52. {
  53. var userName = ConfigurationManager.AppSettings["SharePointUsername"];
  54. var domain = ConfigurationManager.AppSettings["SharePointDomain"];
  55. var password = ConfigurationManager.AppSettings["SharePointPassword"];
  56.  
  57. var networkCredential = new NetworkCredential(userName, password, domain);
  58.  
  59. return networkCredential;
  60. }
  61. catch (Exception ex)
  62. {
  63. _logger.Error(ex.Message, ex);
  64. throw;
  65. }
  66.  
  67. }
  68.  
  69. /// <summary>
  70. /// Opens the connection to share point.
  71. /// </summary>
  72. /// <exception cref="System.ArgumentException">OpehConnectionString: + exception</exception>
  73. private ClientContext OpenConnectionToSharePoint()
  74. {
  75. try
  76. {
  77. CertificationValidation();
  78. var siteUrl = ConfigurationManager.AppSettings["SharePointUrl"];
  79.  
  80. using (var clientContext = new ClientContext(siteUrl))
  81. {
  82. //Comment code uses the local authentication from computer
  83.  
  84. //clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
  85. //clientContext.Credentials = CredentialCache.DefaultCredentials;
  86.  
  87. clientContext.Credentials = NetworkCredential();
  88. clientContext.ValidateOnClient = true;
  89. _logger.Info("Connection to SharePoint was successful.");
  90.  
  91. return clientContext;
  92. }
  93. }
  94. catch (Exception ex)
  95. {
  96. _logger.Error(ex.Message, ex);
  97. throw;
  98. }
  99.  
  100. }
  101.  
  102. #endregion
  103.  
  104. #region Main Methods()
  105.  
  106. /// <summary>
  107. /// Uploads the file as a stream to a sub-folder.
  108. /// If the sub-folder, (folderName) is not provided the file will be uploaded to the Root Folder.
  109. /// </summary>
  110. /// <param name="file">The file.</param>
  111. /// <param name="fileName">Name of the file.</param>
  112. /// <param name="folderName">Name of the folder.</param>
  113. /// <exception cref="System.Exception">Stream cannot be null</exception>
  114. public void UploadFile(Stream file, string fileName, string folderName)
  115. {
  116. try
  117. {
  118. using (var clientContext = OpenConnectionToSharePoint())
  119. {
  120. var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
  121.  
  122. clientContext.Load(list.RootFolder);
  123. clientContext.Load(list.RootFolder.Folders);
  124. clientContext.ExecuteQuery();
  125.  
  126. if (string.IsNullOrEmpty(folderName))
  127. {
  128. var webContext = clientContext.Web.Context;
  129.  
  130. if (file == null) throw new Exception("Stream cannot be null");
  131. if (webContext.HasPendingRequest) webContext.ExecuteQuery();
  132.  
  133. var rootFileUrl = Path.Combine(list.RootFolder.ServerRelativeUrl, fileName);
  134.  
  135. Microsoft.SharePoint.Client.File.SaveBinaryDirect(
  136. clientContext, rootFileUrl, file, true);
  137. }
  138. else
  139. {
  140. CreateFolderIfDoesNotExist(folderName);
  141.  
  142. var newFolder = Path.Combine(list.RootFolder.ServerRelativeUrl, folderName);
  143. var folder = list.RootFolder.Folders.Add(newFolder);
  144. clientContext.ExecuteQuery();
  145.  
  146. var fileUrl = Path.Combine(newFolder, fileName);
  147. clientContext.Load(folder.Files);
  148. clientContext.ExecuteQuery();
  149.  
  150. var existingFile = folder.Files.ToList().FirstOrDefault(x => x.Name == fileName);
  151.  
  152. if (existingFile != null)
  153. {
  154. clientContext.Load(existingFile);
  155. clientContext.ExecuteQuery();
  156. clientContext.Load(existingFile.LockedByUser);
  157. clientContext.ExecuteQuery();
  158. }
  159. else
  160. {
  161. Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, file, true);
  162. }
  163. }
  164. }
  165. }
  166. catch (Exception ex)
  167. {
  168. _logger.Error(ex.Message, ex);
  169. throw;
  170. }
  171.  
  172. }
  173.  
  174. /// <summary>
  175. /// Downloads all files.
  176. /// If the sub-folder, (folderName) is not provided -- will download all files from the Root Folder.
  177. /// Otherwise, will download all the files from a specific sub-folder.
  178. /// </summary>
  179. /// <returns></returns>
  180. public List<MemoryStream> DownloadFiles(string fileName, string folderName, bool downloadAllFile)
  181. {
  182. try
  183. {
  184. var memoryStreamCollection = new List<MemoryStream>();
  185. using (var clientContext = OpenConnectionToSharePoint())
  186. {
  187. var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
  188. clientContext.Load(list);
  189. clientContext.Load(list.RootFolder);
  190. clientContext.Load(list.RootFolder.Folders);
  191. clientContext.Load(list.RootFolder.Files);
  192. clientContext.ExecuteQuery();
  193. var folder = list.RootFolder;
  194. if (!string.IsNullOrEmpty(folderName))
  195. {
  196. var folders = list.RootFolder.Folders;
  197. folder = folders.First(f => f.Name == folderName);
  198. }
  199.  
  200. clientContext.Load(folder.Files);
  201. clientContext.ExecuteQuery();
  202. if (downloadAllFile)
  203. {
  204. foreach (var file in folder.Files)
  205. {
  206. var fileReference = file.ServerRelativeUrl;
  207. GetStream(fileReference, memoryStreamCollection, file.Name, folderName);
  208. }
  209. return memoryStreamCollection;
  210. }
  211. else
  212. {
  213. var fileNameCheck = folder.Files.First(f => f.Name == fileName);
  214. var fileReference = fileNameCheck.ServerRelativeUrl;
  215. GetStream(fileReference, memoryStreamCollection, fileName, folderName);
  216. return memoryStreamCollection;
  217. }
  218. }
  219. }
  220. catch (Exception ex)
  221. {
  222. _logger.Error(ex.Message, ex);
  223. throw;
  224. }
  225. }
  226.  
  227. /// <summary>
  228. /// Deletes a file from a Sub-folder that matches the fileName.
  229. /// If the sub-folder, (folderName) is not provided the file will be deleted from the Root Folder.
  230. /// </summary>
  231. /// <param name="fileName">Name of the file.</param>
  232. /// <param name="folderName">Name of the folder.</param>
  233. public void DeleteFile(List<string> fileName, string folderName)
  234. {
  235. try
  236. {
  237. using (var clientContext = OpenConnectionToSharePoint())
  238. {
  239. var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
  240. clientContext.Load(list.RootFolder);
  241. clientContext.Load(list.RootFolder.Folders);
  242. clientContext.Load(list.RootFolder.Files);
  243. clientContext.ExecuteQuery();
  244.  
  245. var files = list.RootFolder.Files;
  246.  
  247. if (string.IsNullOrEmpty(folderName))
  248. {
  249. foreach (var file in files)
  250. {
  251. if (fileName.Contains(file.Name))
  252. {
  253. file.DeleteObject();
  254. clientContext.ExecuteQuery();
  255. _logger.Info(string.Format("{0}: was deleted from the {1} folder.", fileName, _sharePointRoot));
  256. }
  257. else
  258. {
  259. _logger.Error(string.Format("{0}: was not found.", fileName.Contains(file.Name)));
  260. }
  261. }
  262. }
  263. else
  264. {
  265. var folders = list.RootFolder.Folders;
  266. var folder = folders.First(f => f.Name == folderName);
  267. clientContext.Load(folder.Files);
  268. clientContext.ExecuteQuery();
  269.  
  270. var folderFiles = folder.Files;
  271. foreach (var ff in folderFiles)
  272. {
  273. if (fileName.Contains(ff.Name))
  274. ff.DeleteObject();
  275. clientContext.ExecuteQuery();
  276.  
  277. _logger.Info(string.Format("{0}: was deleted from {1} folder.", fileName.Contains(ff.Name), folderName));
  278. }
  279. }
  280.  
  281. }
  282. }
  283. catch (Exception ex)
  284. {
  285. _logger.Error(ex.Message, ex);
  286. throw;
  287. }
  288. }
  289.  
  290. #endregion
  291.  
  292. #region Helper Method()
  293.  
  294. /// <summary>
  295. /// Creates a folder if the folder does not already exist.
  296. /// </summary>
  297. /// <param name="folderName">Name of the folder.</param>
  298. private void CreateFolderIfDoesNotExist(string folderName)
  299. {
  300. try
  301. {
  302. using (var clientContext = OpenConnectionToSharePoint())
  303. {
  304. var list = clientContext.Web.Lists.GetByTitle(_sharePointRoot);
  305. list.EnableFolderCreation = true;
  306.  
  307. clientContext.Load(list);
  308. clientContext.Load(list.RootFolder);
  309. clientContext.Load(list.RootFolder.Folders);
  310. clientContext.ExecuteQuery();
  311.  
  312. var folderCollection = list.RootFolder.Folders;
  313.  
  314. foreach (var folder in folderCollection)
  315. {
  316. if (folder.Name == folderName)
  317. {
  318. clientContext.Load(folder.Files);
  319. clientContext.ExecuteQuery();
  320. }
  321. else
  322. {
  323. var itemCreateInfo = new ListItemCreationInformation
  324. {
  325. UnderlyingObjectType = FileSystemObjectType.Folder,
  326. LeafName = folderName
  327. };
  328.  
  329. var newItem = list.AddItem(itemCreateInfo);
  330. newItem["Title"] = folderName;
  331. newItem.Update();
  332. }
  333. }
  334. }
  335. }
  336. catch (Exception ex)
  337. {
  338. _logger.Error(ex.Message, ex);
  339. throw;
  340. }
  341. }
  342.  
  343. /// <summary>
  344. /// Gets the stream.
  345. /// </summary>
  346. /// <param name="fileReference">The file reference.</param>
  347. /// <param name="memoryStreamCollection">The memory stream collection.</param>
  348. /// <param name="fileName">Name of the file.</param>
  349. /// <param name="folderName">Name of the folder.</param>
  350. /// <returns></returns>
  351. private void GetStream(string fileReference, ICollection<MemoryStream> memoryStreamCollection, string fileName, string folderName)
  352. {
  353. try
  354. {
  355. if (string.IsNullOrEmpty(folderName))
  356. {
  357. folderName = _sharePointRoot;
  358. }
  359. using (var clientContext = OpenConnectionToSharePoint())
  360. {
  361. var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileReference);
  362. var fileStream = new MemoryStream();
  363.  
  364. fileInfo.Stream.CopyTo(fileStream);
  365. memoryStreamCollection.Add(fileStream);
  366.  
  367. _logger.Info(string.Format("{0}: was downloaded successfully from {1} folder.", fileName, folderName));
  368. }
  369. }
  370. catch (Exception ex)
  371. {
  372. _logger.Error(ex);
  373. throw;
  374. }
  375. }
  376. #endregion
  377. }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement