예제 #1
0
        public static SharePointFileManager SetupSharepoint(IConfiguration Configuration)
        {
            // add SharePoint.

            string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];
            string sharePointOdataUri       = Configuration["SHAREPOINT_ODATA_URI"];
            string sharePointWebname        = Configuration["SHAREPOINT_WEBNAME"];
            string sharePointAadTenantId    = Configuration["SHAREPOINT_AAD_TENANTID"];
            string sharePointClientId       = Configuration["SHAREPOINT_CLIENT_ID"];
            string sharePointCertFileName   = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"];
            string sharePointCertPassword   = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"];
            string ssgUsername             = Configuration["SSG_USERNAME"];
            string ssgPassword             = Configuration["SSG_PASSWORD"];
            string sharePointNativeBaseURI = Configuration["SHAREPOINT_NATIVE_BASE_URI"];

            var manager = new SharePointFileManager
                          (
                sharePointServerAppIdUri,
                sharePointOdataUri,
                sharePointWebname,
                sharePointAadTenantId,
                sharePointClientId,
                sharePointCertFileName,
                sharePointCertPassword,
                ssgUsername,
                ssgPassword,
                sharePointNativeBaseURI
                          );

            return(manager);
        }
        private async Task <List <ViewModels.FileSystemItem> > getFileDetailsListInFolder(string entityId, string entityName, string documentType)
        {
            List <ViewModels.FileSystemItem> fileSystemItemVMList = new List <ViewModels.FileSystemItem>();

            ValidateSession();


            if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType))
            {
                return(fileSystemItemVMList);
            }

            try
            {
                await CreateDocumentLibraryIfMissing(GetDocumentListTitle(entityName), GetDocumentTemplateUrlPart(entityName));

                string folderName = await GetFolderName(entityName, entityId, _dynamicsClient);;
                // Get the file details list in folder
                List <Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = null;
                SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
                try
                {
                    fileDetailsList = await _sharePointFileManager.GetFileDetailsListInFolder(GetDocumentTemplateUrlPart(entityName), folderName, documentType);
                }
                catch (SharePointRestException spre)
                {
                    _logger.LogError(spre, "Error getting SharePoint File List");
                    throw new Exception("Unable to get Sharepoint File List.");
                }

                if (fileDetailsList != null)
                {
                    foreach (Interfaces.SharePointFileManager.FileDetailsList fileDetails in fileDetailsList)
                    {
                        ViewModels.FileSystemItem fileSystemItemVM = new ViewModels.FileSystemItem()
                        {
                            // remove the document type text from file name
                            name = fileDetails.Name.Substring(fileDetails.Name.IndexOf("__") + 2),
                            // convert size from bytes (original) to KB
                            size = int.Parse(fileDetails.Length),
                            serverrelativeurl = fileDetails.ServerRelativeUrl,
                            timelastmodified  = DateTime.Parse(fileDetails.TimeLastModified),
                            documenttype      = fileDetails.DocumentType
                        };

                        fileSystemItemVMList.Add(fileSystemItemVM);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError("Error getting SharePoint File List");

                _logger.LogError(e.Message);
            }



            return(fileSystemItemVMList);
        }
        public override Task <UploadFileReply> UploadFile(UploadFileRequest request, ServerCallContext context)
        {
            var    result        = new UploadFileReply();
            string logFileName   = WordSanitizer.Sanitize(request.FileName);
            string logFolderName = WordSanitizer.Sanitize(request.FolderName);

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            CreateDocumentLibraryIfMissing(GetDocumentListTitle(request.EntityName), GetDocumentTemplateUrlPart(request.EntityName));

            try
            {
                string fileName = _sharePointFileManager.AddFile(GetDocumentTemplateUrlPart(request.EntityName),
                                                                 request.FolderName,
                                                                 request.FileName,
                                                                 request.Data.ToByteArray(), request.ContentType).GetAwaiter().GetResult();

                result.FileName     = fileName;
                result.ResultStatus = ResultStatus.Success;
            }
            catch (SharePointRestException ex)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in uploading file {logFileName} to folder {logFolderName}";
                _logger.LogError(ex, result.ErrorDetail);
            }
            catch (Exception e)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in uploading file {logFileName} to folder {logFolderName}";
                _logger.LogError(e, result.ErrorDetail);
            }

            return(Task.FromResult(result));
        }
예제 #4
0
 public FileController(IConfiguration configuration, ILoggerFactory loggerFactory, SharePointFileManager fileManager)
 {
     Configuration          = configuration;
     _loggerFactory         = loggerFactory;
     _sharePointFileManager = fileManager;
     _logger = loggerFactory.CreateLogger(typeof(TestController));
 }
예제 #5
0
 public WorkerUpdater(IConfiguration Configuration, ILoggerFactory loggerFactory, SharePointFileManager sharePointFileManager)
 {
     this.Configuration     = Configuration;
     _logger                = loggerFactory.CreateLogger(typeof(WorkerUpdater));
     _dynamics              = SpdUtils.SetupDynamics(Configuration);
     _sharePointFileManager = sharePointFileManager;
 }
        public async Task <IActionResult> DeleteFile([FromQuery] string serverRelativeUrl, [FromQuery] string documentType, [FromRoute] string entityId, [FromRoute] string entityName)
        {
            // get the file.
            if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(serverRelativeUrl) || string.IsNullOrEmpty(documentType))
            {
                return(BadRequest());
            }

            ValidateSession();

            var hasAccess = await CanAccessEntityFile(entityName, entityId, documentType, serverRelativeUrl);

            if (!hasAccess)
            {
                return(new NotFoundResult());
            }

            // Update modifiedon to current time
            UpdateEntityModifiedOnDate(entityName, entityId);
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
            var result = await _sharePointFileManager.DeleteFile(serverRelativeUrl);

            if (result)
            {
                return(new OkResult());
            }

            return(new NotFoundResult());
        }
예제 #7
0
        public override Task <DeleteFileReply> DeleteFile(DeleteFileRequest request, ServerCallContext context)
        {
            var result = new DeleteFileReply();

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            try
            {
                bool success = _sharePointFileManager.DeleteFile(request.ServerRelativeUrl).GetAwaiter().GetResult();

                if (success)
                {
                    result.ResultStatus = ResultStatus.Success;
                }
                else
                {
                    result.ResultStatus = ResultStatus.Fail;
                }
            }
            catch (SharePointRestException ex)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in deleting file {request.ServerRelativeUrl}";
                _logger.LogError(ex, result.ErrorDetail);
            }
            catch (Exception e)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in deleting file {request.ServerRelativeUrl}";
                _logger.LogError(e, result.ErrorDetail);
            }

            return(Task.FromResult(result));
        }
예제 #8
0
 public LegalEntitiesController(IConfiguration configuration, SharePointFileManager sharePointFileManager, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
 {
     _configuration       = configuration;
     _dynamicsClient      = dynamicsClient;
     _httpContextAccessor = httpContextAccessor;
     _encryptionKey       = _configuration["ENCRYPTION_KEY"];
     _logger = loggerFactory.CreateLogger(typeof(LegalEntitiesController));
 }
예제 #9
0
 public TiedHouseConnectionsController(IConfiguration configuration, SharePointFileManager sharePointFileManager, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
 {
     Configuration             = configuration;
     this._encryptionKey       = Configuration["ENCRYPTION_KEY"];
     this._httpContextAccessor = httpContextAccessor;
     this._dynamicsClient      = dynamicsClient;
     _logger = loggerFactory.CreateLogger(typeof(TiedHouseConnectionsController));
 }
예제 #10
0
 public AdoxioApplicationController(SharePointFileManager sharePointFileManager, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
 {
     Configuration          = configuration;
     _httpContextAccessor   = httpContextAccessor;
     _sharePointFileManager = sharePointFileManager;
     _dynamicsClient        = dynamicsClient;
     _logger = loggerFactory.CreateLogger(typeof(AdoxioApplicationController));
 }
        public override Task <CreateFolderReply> CreateFolder(CreateFolderRequest request, ServerCallContext context)
        {
            var result = new CreateFolderReply();

            var logFolder = WordSanitizer.Sanitize(request.FolderName);

            var listTitle = GetDocumentListTitle(request.EntityName);

            var _sharePointFileManager = new SharePointFileManager(_configuration);

            CreateDocumentLibraryIfMissing(listTitle, GetDocumentTemplateUrlPart(request.EntityName));

            var folderExists = false;

            try
            {
                var folder = _sharePointFileManager.GetFolder(listTitle, request.FolderName).GetAwaiter().GetResult();
                if (folder != null)
                {
                    folderExists = true;
                }
            }
            catch (SharePointRestException ex)
            {
                Log.Error(ex,
                          $"SharePointRestException creating sharepoint folder (status code: {ex.Response.StatusCode})");
                folderExists = false;
            }
            catch (Exception e)
            {
                Log.Error(e, "Generic Exception creating sharepoint folder");
                folderExists = false;
            }

            if (folderExists)
            {
                result.ResultStatus = ResultStatus.Success;
            }
            else
            {
                try
                {
                    _sharePointFileManager.CreateFolder(GetDocumentListTitle(request.EntityName), request.FolderName)
                    .GetAwaiter().GetResult();
                    var folder = _sharePointFileManager.GetFolder(listTitle, request.FolderName).GetAwaiter()
                                 .GetResult();
                    if (folder != null)
                    {
                        result.ResultStatus = ResultStatus.Success;
                    }
                }
                catch (SharePointRestException ex)
                {
                    result.ResultStatus = ResultStatus.Fail;
                    result.ErrorDetail  = $"ERROR in creating folder {logFolder}";
                    Log.Error(ex, result.ErrorDetail);
                }
            }
예제 #12
0
 public AccountController(IConfiguration configuration, SharePointFileManager sharePointFileManager, IHttpContextAccessor httpContextAccessor, BCeIDBusinessQuery bceid, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
 {
     Configuration          = configuration;
     _bceid                 = bceid;
     _dynamicsClient        = dynamicsClient;
     _httpContextAccessor   = httpContextAccessor;
     _sharePointFileManager = sharePointFileManager;
     _logger                = loggerFactory.CreateLogger(typeof(AccountController));
 }
예제 #13
0
 public ContactController(SharePointFileManager sharePointFileManager, IConfiguration configuration, IDynamicsClient dynamicsClient, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IHostingEnvironment env)
 {
     Configuration        = configuration;
     _dynamicsClient      = dynamicsClient;
     _httpContextAccessor = httpContextAccessor;
     _logger = loggerFactory.CreateLogger(typeof(ContactController));
     _env    = env;
     _sharePointFileManager = sharePointFileManager;
 }
예제 #14
0
 public AdoxioApplicationController(Interfaces.Microsoft.Dynamics.CRM.System context, SharePointFileManager sharePointFileManager, IConfiguration configuration, IDistributedCache distributedCache, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
 {
     Configuration               = configuration;
     this._system                = context;
     this._httpContextAccessor   = httpContextAccessor;
     this._sharePointFileManager = sharePointFileManager;
     //this._distributedCache = null;
     this._dynamicsClient = dynamicsClient;
     _logger = loggerFactory.CreateLogger(typeof(AdoxioLegalEntityController));
 }
        private async Task CreateDocumentLibraryIfMissing(string listTitle, string documentTemplateUrl = null)
        {
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
            var exists = await _sharePointFileManager.DocumentLibraryExists(listTitle);

            if (!exists)
            {
                await _sharePointFileManager.CreateDocumentLibrary(listTitle, documentTemplateUrl);
            }
        }
        private void CreateDocumentLibraryIfMissing(string listTitle, string documentTemplateUrl = null)
        {
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
            var exists = _sharePointFileManager.DocumentLibraryExists(listTitle).GetAwaiter().GetResult();

            if (!exists)
            {
                _sharePointFileManager.CreateDocumentLibrary(listTitle, documentTemplateUrl).GetAwaiter().GetResult();
            }
        }
예제 #17
0
        public override Task <CreateFolderReply> CreateFolder(CreateFolderRequest request, ServerCallContext context)
        {
            var    result    = new CreateFolderReply();
            string listTitle = GetDocumentListTitle(request.EntityName);

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            CreateDocumentLibraryIfMissing(listTitle, GetDocumentTemplateUrlPart(request.EntityName));

            bool folderExists = false;

            try
            {
                var folder = _sharePointFileManager.GetFolder(listTitle, request.FolderName).GetAwaiter().GetResult();
                if (folder != null)
                {
                    folderExists = true;
                }
            }
            catch (Exception)
            {
                folderExists = false;
            }

            if (folderExists)
            {
                result.ResultStatus = ResultStatus.Success;
            }
            else
            {
                try
                {
                    _sharePointFileManager.CreateFolder(GetDocumentListTitle(request.EntityName), request.FolderName).GetAwaiter().GetResult();
                    var folder = _sharePointFileManager.GetFolder(listTitle, request.FolderName).GetAwaiter().GetResult();
                    if (folder != null)
                    {
                        result.ResultStatus = ResultStatus.Success;
                    }
                }
                catch (SharePointRestException ex)
                {
                    result.ResultStatus = ResultStatus.Fail;
                    result.ErrorDetail  = $"ERROR in creating folder {request.FolderName}";
                    _logger.LogError(ex, result.ErrorDetail);
                }
                catch (Exception e)
                {
                    result.ResultStatus = ResultStatus.Fail;
                    result.ErrorDetail  = $"ERROR in creating folder {request.FolderName}";
                    _logger.LogError(e, result.ErrorDetail);
                }
            }

            return(Task.FromResult(result));
        }
예제 #18
0
 public FederalReportingController(IConfiguration configuration, ILoggerFactory loggerFactory)
 {
     _configuration = configuration;
     if (_configuration["DYNAMICS_ODATA_URI"] != null)
     {
         _dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);
     }
     if (_configuration["SHAREPOINT_ODATA_URI"] != null)
     {
         _sharepoint = new SharePointFileManager(_configuration);
     }
     _logger = loggerFactory.CreateLogger(typeof(FederalReportingController));
 }
예제 #19
0
        /// <summary>
        /// Setup the test
        /// </summary>
        public SharePoint()
        {
            Configuration = new ConfigurationBuilder()
                                                        // The following line is the only reason we have a project reference for cllc-public-app.
                                                        // If you were to use this code on a different project simply add user secrets as appropriate to match the environment / secret variables below.
                            .AddUserSecrets <Startup>() // Add secrets from the cllc-public-app
                            .AddEnvironmentVariables()
                            .Build();

            serverAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];

            sharePointFileManager = new SharePointFileManager(Configuration);
        }
        public override Task <FolderFilesReply> FolderFiles(FolderFilesRequest request, ServerCallContext context)
        {
            var result = new FolderFilesReply();

            // Get the file details list in folder
            List <Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = null;
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            try
            {
                fileDetailsList = _sharePointFileManager.GetFileDetailsListInFolder(GetDocumentTemplateUrlPart(request.EntityName), request.FolderName, request.DocumentType).GetAwaiter().GetResult();
                if (fileDetailsList != null)

                {
                    // gRPC ensures that the collection has space to accept new data; no need to call a constructor
                    foreach (var item in fileDetailsList)
                    {
                        // Sharepoint API responds with dates in UTC format
                        var      utcFormat = DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal;
                        DateTime parsedCreateDate, parsedLastModified;
                        DateTime.TryParse(item.TimeCreated, CultureInfo.InvariantCulture, utcFormat, out parsedCreateDate);
                        DateTime.TryParse(item.TimeLastModified, CultureInfo.InvariantCulture, utcFormat, out parsedLastModified);

                        FileSystemItem newItem = new FileSystemItem()
                        {
                            DocumentType      = item.DocumentType,
                            Name              = item.Name,
                            ServerRelativeUrl = item.ServerRelativeUrl,
                            Size              = int.Parse(item.Length),
                            TimeCreated       = parsedCreateDate != null?Timestamp.FromDateTime(parsedCreateDate) : null,
                                                    TimeLastModified = parsedLastModified != null?Timestamp.FromDateTime(parsedLastModified) : null,
                        };

                        result.Files.Add(newItem);
                    }
                    result.ResultStatus = ResultStatus.Success;
                }
            }
            catch (SharePointRestException spre)
            {
                Log.Error(spre, "Error getting SharePoint File List");
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = "Error getting SharePoint File List";
            }

            return(Task.FromResult(result));
        }
예제 #21
0
        /// <summary>
        /// Setup the test
        /// </summary>
        public SharePoint()
        {
            Configuration = new ConfigurationBuilder()
                                                        // The following line is the only reason we have a project reference for cllc-public-app.
                                                        // If you were to use this code on a different project simply add user secrets as appropriate to match the environment / secret variables below.
                            .AddUserSecrets <Startup>() // Add secrets from the cllc-public-app
                            .AddEnvironmentVariables()
                            .Build();

            serverAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];
            string odataUri     = Configuration["SHAREPOINT_ODATA_URI"];
            string webname      = Configuration["SHAREPOINT_WEBNAME"];
            string aadTenantId  = Configuration["SHAREPOINT_AAD_TENANTID"];
            string clientId     = Configuration["SHAREPOINT_CLIENT_ID"];
            string certFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"];
            string certPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"];

            sharePointFileManager = new SharePointFileManager(serverAppIdUri, odataUri, webname, aadTenantId, clientId, certFileName, certPassword, null, null, serverAppIdUri);
        }
예제 #22
0
        private async Task <bool> FileUploadExists(string accountId, string accountName, string documentType)
        {
            _logger.LogDebug(LoggingEvents.Get, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.Get, "accountId: {accountId}, accountName: {accountName}, documentType: {documentType}");

            var exists           = false;
            var accountIdCleaned = accountId.ToUpper().Replace("-", "");
            var folderName       = $"{accountName}_{accountIdCleaned}";
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
            var fileDetailsList = await _sharePointFileManager.GetFileDetailsListInFolder(SharePointFileManager.DefaultDocumentListTitle, folderName, documentType);

            if (fileDetailsList != null)
            {
                exists = fileDetailsList.Count() > 0;
            }

            _logger.LogDebug(LoggingEvents.Get, "FileUploadExists: " + exists);
            return(exists);
        }
        public override Task <FileExistsReply> FileExists(FileExistsRequest request, ServerCallContext context)
        {
            var result = new FileExistsReply();

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            List <Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = null;

            try
            {
                fileDetailsList = _sharePointFileManager.GetFileDetailsListInFolder(GetDocumentTemplateUrlPart(request.EntityName), request.FolderName, request.DocumentType).GetAwaiter().GetResult();
                if (fileDetailsList != null)

                {
                    var hasFile = fileDetailsList.Any(f => f.ServerRelativeUrl == request.ServerRelativeUrl);

                    if (hasFile)
                    {
                        result.ResultStatus = FileExistStatus.Exist;
                    }
                    else
                    {
                        result.ResultStatus = FileExistStatus.NotExist;
                    }
                }
            }
            catch (SharePointRestException spre)
            {
                _logger.LogError(spre, "Error determining if file exists");
                result.ResultStatus = result.ResultStatus = FileExistStatus.Error;
                result.ErrorDetail  = "Error determining if file exists";
            }

            catch (Exception e)
            {
                result.ResultStatus = FileExistStatus.Error;
                result.ErrorDetail  = $"Error determining if file exists";
                _logger.LogError(e, result.ErrorDetail);
            }

            return(Task.FromResult(result));
        }
        public override Task <FolderFilesReply> FolderFiles(FolderFilesRequest request, ServerCallContext context)
        {
            var result = new FolderFilesReply();


            // Get the file details list in folder
            List <Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = null;
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            try
            {
                fileDetailsList = _sharePointFileManager.GetFileDetailsListInFolder(GetDocumentTemplateUrlPart(request.EntityName), request.FolderName, request.DocumentType).GetAwaiter().GetResult();
                if (fileDetailsList != null)

                {
                    // gRPC ensures that the collection has space to accept new data; no need to call a constructor
                    foreach (var item in fileDetailsList)
                    {
                        FileSystemItem newItem = new FileSystemItem()
                        {
                            DocumentType      = item.DocumentType,
                            Name              = item.Name,
                            ServerRelativeUrl = item.ServerRelativeUrl,
                            Size              = int.Parse(item.Length)
                        };

                        result.Files.Add(newItem);
                    }
                    result.ResultStatus = ResultStatus.Success;
                }
            }
            catch (SharePointRestException spre)
            {
                _logger.LogError(spre, "Error getting SharePoint File List");
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = "Error getting SharePoint File List";
            }

            return(Task.FromResult(result));
        }
        public async Task <IActionResult> DownloadFile(string entityId, string entityName, [FromQuery] string serverRelativeUrl, [FromQuery] string documentType)
        {
            // get the file.
            if (string.IsNullOrEmpty(serverRelativeUrl) || string.IsNullOrEmpty(documentType) || string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName))
            {
                return(BadRequest());
            }

            ValidateSession();

            var hasAccess = await CanAccessEntityFile(entityName, entityId, documentType, serverRelativeUrl);

            if (!hasAccess)
            {
                return(new NotFoundResult());
            }
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            byte[] fileContents = await _sharePointFileManager.DownloadFile(serverRelativeUrl);

            return(new FileContentResult(fileContents, "application/octet-stream")
            {
            });
        }
        public override Task <DownloadFileReply> DownloadFile(DownloadFileRequest request, ServerCallContext context)
        {
            var    result = new DownloadFileReply();
            string logUrl = WordSanitizer.Sanitize(request.ServerRelativeUrl);
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            try
            {
                byte[] data = _sharePointFileManager.DownloadFile(request.ServerRelativeUrl).GetAwaiter().GetResult();

                if (data != null)
                {
                    result.ResultStatus = ResultStatus.Success;
                    result.Data         = ByteString.CopyFrom(data);
                }
                else
                {
                    result.ResultStatus = ResultStatus.Fail;
                }
            }
            catch (SharePointRestException ex)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in downloading file {logUrl}";
                _logger.LogError(ex, result.ErrorDetail);
            }
            catch (Exception e)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in downloading file {logUrl}";
                _logger.LogError(e, result.ErrorDetail);
            }


            return(Task.FromResult(result));
        }
        public override Task <TruncatedFilenameReply> GetTruncatedFilename(TruncatedFilenameRequest request, ServerCallContext context)
        {
            var    result        = new TruncatedFilenameReply();
            string logFileName   = WordSanitizer.Sanitize(request.FileName);
            string logFolderName = WordSanitizer.Sanitize(request.FolderName);

            try
            {
                var _sharePointFileManager = new SharePointFileManager(_configuration);

                // Ask SharePoint whether this filename would be truncated upon upload
                var listTitle      = GetDocumentListTitle(request.EntityName);
                var maybeTruncated = _sharePointFileManager.GetTruncatedFileName(request.FileName, listTitle, request.FolderName);
                result.FileName     = maybeTruncated;
                result.ResultStatus = ResultStatus.Success;
            }
            catch (SharePointRestException ex)
            {
                result.ResultStatus = ResultStatus.Fail;
                result.ErrorDetail  = $"ERROR in getting truncated filename {logFileName} for folder {logFolderName}";
                Log.Error(ex, result.ErrorDetail);
            }
            return(Task.FromResult(result));
        }
예제 #28
0
        public void Execute(IConfiguration config, bool doRename)
        {
            // get a connection to Dynamics.
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(config);

            // get the list of application files.
            SharePointFileManager sharePoint = new SharePointFileManager(config);

            string[] orderby = { "adoxio_licencenumber" };
            string[] expand  = { "adoxio_licences_SharePointDocumentLocations" };
            //var licences = dynamicsClient.Licenceses.Get(expand: expand).Value;


            var customHeaders = new Dictionary <string, List <string> >();
            var preferHeader  = new List <string>();

            preferHeader.Add($"odata.maxpagesize=5000");

            customHeaders.Add("Prefer", preferHeader);
            var odataVersionHeader = new List <string>();

            odataVersionHeader.Add("4.0");

            customHeaders.Add("OData-Version", odataVersionHeader);
            customHeaders.Add("OData-MaxVersion", odataVersionHeader);
            string odataNextLink = "1";
            bool   firstTime     = true;
            int    totalCount    = 5000;
            int    currentCount  = 0;
            int    renameCount   = 0;
            HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection> licencesQuery = new HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection>();

            while (odataNextLink != null)
            {
                if (firstTime)
                {
                    firstTime     = false;
                    licencesQuery = dynamicsClient.Licenceses.GetWithHttpMessagesAsync(expand: expand, customHeaders: customHeaders, count: true, orderby: orderby).GetAwaiter().GetResult();
                }
                else
                {
                    odataNextLink = licencesQuery.Body.OdataNextLink;
                    if (odataNextLink != null)
                    {
                        licencesQuery = dynamicsClient.Licenceses.GetNextLink(odataNextLink, customHeaders);

                        totalCount += licencesQuery.Body.Value.Count;
                    }
                    else
                    {
                        licencesQuery = new HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection>();
                    }
                }
                Console.Out.WriteLine($"Currently on licence {currentCount} of {totalCount}");
                if (licencesQuery?.Body?.Value != null)
                {
                    var licences = licencesQuery.Body.Value;


                    foreach (var licence in licences)
                    {
                        bool isInRange     = false;
                        int  licenceNumber = -1;
                        int.TryParse(licence.AdoxioLicencenumber, out licenceNumber);

                        if (licenceNumber >= 1114 && licenceNumber <= 18573)
                        {
                            isInRange = true;
                            //Console.Out.WriteLine($"Licence #{licenceNumber}");
                        }
                        currentCount++;
                        string folderName = licence.GetDocumentFolderName();
                        if (licence.AdoxioLicencesSharePointDocumentLocations != null &&
                            licence.AdoxioLicencesSharePointDocumentLocations.Count > 0 &&
                            licence.AdoxioLicencesSharePointDocumentLocations[0].Relativeurl != null)
                        {
                            folderName = licence.AdoxioLicencesSharePointDocumentLocations[0].Relativeurl;
                        }

                        List <FileDetailsList> fileList = null;
                        try
                        {
                            fileList = sharePoint.GetFileDetailsListInFolder(SharePointFileManager.LicenceDocumentUrlTitle,
                                                                             folderName, null)
                                       .GetAwaiter().GetResult();
                        }
                        catch (Exception e)
                        {
                            // Console.WriteLine($"Folder not found [{folderName}]");
                        }

                        if (fileList != null && fileList.Count > 0)
                        {
                            //Console.WriteLine($"Found {fileList.Count} Files.");
                            foreach (var file in fileList)
                            {
                                if (isInRange)
                                {
                                    // Console.Out.WriteLine($"Current filename: {file.Name}");
                                }

                                if (IsSuspect(file.Name))
                                {
                                    string newName = FixName(file.Name);
                                    if (newName != null)
                                    {
                                        Console.Out.WriteLine($"Filename {file.Name} is suspect.");
                                        Console.Out.WriteLine($"New name is {newName}");

                                        string oldFileName =
                                            $"/{SharePointFileManager.LicenceDocumentUrlTitle}/{folderName}/{file.Name}";
                                        string newFileName = $"{SharePointFileManager.LicenceDocumentUrlTitle}/{folderName}/{newName}";
                                        Console.Out.WriteLine($"Rename File {oldFileName} to {newFileName}");
                                        byte[] data = sharePoint.DownloadFile(oldFileName).GetAwaiter().GetResult();
                                        if (data != null)
                                        {
                                            var success = sharePoint.UploadFile(newName,
                                                                                SharePointFileManager.LicenceDocumentUrlTitle, folderName, data, "application/pdf").GetAwaiter().GetResult();
                                            if (success != null)
                                            {
                                                // cleanup the old file.
                                                sharePoint.DeleteFile(oldFileName).GetAwaiter().GetResult();
                                                Console.Out.WriteLine($"Rename File Complete");
                                            }
                                        }

                                        renameCount++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Console.Out.WriteLine($"Licence count is {totalCount}");
            Console.Out.WriteLine($"Rename count is {renameCount}");
        }
        private async Task CreateSharepointDynamicsLink(MicrosoftDynamicsCRMadoxioWorker worker)
        {
            // create a SharePointDocumentLocation link
            string folderName = await FileController.GetFolderName("worker", worker.AdoxioWorkerid, _dynamicsClient);

            string name = worker.AdoxioWorkerid + " Files";

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            // Create the folder
            bool folderExists = await _sharePointFileManager.FolderExists(SharePointFileManager.WorkertDocumentUrlTitle, folderName);

            if (!folderExists)
            {
                try
                {
                    await _sharePointFileManager.CreateFolder(SharePointFileManager.WorkertDocumentUrlTitle, folderName);
                }
                catch (Exception e)
                {
                    _logger.LogError("Error creating Sharepoint Folder");
                    _logger.LogError($"List is: {SharePointFileManager.WorkertDocumentUrlTitle}");
                    _logger.LogError($"FolderName is: {folderName}");
                    throw e;
                }
            }

            // Create the SharePointDocumentLocation entity
            MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation()
            {
                Relativeurl = folderName,
                Description = "Worker Qualification",
                Name        = name
            };


            try
            {
                mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError("Error creating SharepointDocumentLocation");
                _logger.LogError("Request:");
                _logger.LogError(httpOperationException.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(httpOperationException.Response.Content);
                mdcsdl = null;
            }
            if (mdcsdl != null)
            {
                // add a regardingobjectid.
                string workerReference = _dynamicsClient.GetEntityURI("adoxio_workers", worker.AdoxioWorkerid);
                var    patchSharePointDocumentLocation = new MicrosoftDynamicsCRMsharepointdocumentlocation();
                patchSharePointDocumentLocation.RegardingobjectidWorkerApplicationODataBind = workerReference;
                // set the parent document library.
                string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL(SharePointFileManager.WorkertDocumentUrlTitle);
                patchSharePointDocumentLocation.ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference);

                try
                {
                    _dynamicsClient.Sharepointdocumentlocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocation);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError("Error adding reference SharepointDocumentLocation to application");
                    _logger.LogError("Request:");
                    _logger.LogError(httpOperationException.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(httpOperationException.Response.Content);
                    throw httpOperationException;
                }

                string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid);
                // update the sharePointLocationData.
                Odataid oDataId = new Odataid()
                {
                    OdataidProperty = sharePointLocationData
                };
                try
                {
                    _dynamicsClient.Workers.AddReference(worker.AdoxioWorkerid, "adoxio_worker_SharePointDocumentLocations", oDataId);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError("Error adding reference to SharepointDocumentLocation");
                    _logger.LogError("Request:");
                    _logger.LogError(httpOperationException.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(httpOperationException.Response.Content);
                    throw httpOperationException;
                }
            }
        }
예제 #30
0
        private async Task initializeSharepoint(MicrosoftDynamicsCRMadoxioApplication adoxioApplication)
        {
            // create a SharePointDocumentLocation link
            string folderName = GetApplicationFolderName(adoxioApplication);
            string name       = adoxioApplication.AdoxioJobnumber + " Files";
            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);
            // Create the folder
            bool folderExists = await _sharePointFileManager.FolderExists(ApplicationDocumentUrlTitle, folderName);

            if (!folderExists)
            {
                try
                {
                    await _sharePointFileManager.CreateFolder(ApplicationDocumentUrlTitle, folderName);
                }
                catch (SharePointRestException spre)
                {
                    _logger.LogError(spre, "Error creating Sharepoint Folder");
                    throw spre;
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Error creating Sharepoint Folder");
                    throw e;
                }
            }

            // Create the SharePointDocumentLocation entity
            MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation()
            {
                Relativeurl = folderName,
                Description = "Application Files",
                Name        = name
            };


            try
            {
                mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
            }
            catch (HttpOperationException httpOperationException)
            {
                string mdcsdlId = _dynamicsClient.GetCreatedRecord(httpOperationException, null);
                if (!string.IsNullOrEmpty(mdcsdlId))
                {
                    mdcsdl.Sharepointdocumentlocationid = mdcsdlId;
                }
                else
                {
                    _logger.LogError(httpOperationException, "Error creating SharepointDocumentLocation");
                    mdcsdl = null;
                }
            }
            if (mdcsdl != null)
            {
                // add a regardingobjectid.
                string applicationReference            = _dynamicsClient.GetEntityURI("adoxio_applications", adoxioApplication.AdoxioApplicationid);
                var    patchSharePointDocumentLocation = new MicrosoftDynamicsCRMsharepointdocumentlocation();
                patchSharePointDocumentLocation.RegardingobjectidAdoxioApplicationODataBind = applicationReference;
                // set the parent document library.
                string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL("adoxio_application");
                patchSharePointDocumentLocation.ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference);

                try
                {
                    _dynamicsClient.Sharepointdocumentlocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocation);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error adding reference SharepointDocumentLocation to application");
                }

                string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid);
                // update the sharePointLocationData.
                Odataid oDataId = new Odataid()
                {
                    OdataidProperty = sharePointLocationData
                };
                try
                {
                    _dynamicsClient.Applications.AddReference(adoxioApplication.AdoxioApplicationid, "adoxio_application_SharePointDocumentLocations", oDataId);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error adding reference to SharepointDocumentLocation");
                }
            }
        }