示例#1
0
        /// <summary>
        /// Method to upload document to SPO library
        /// </summary>
        /// <param name="uploadDocumentRequest">Request Model format for Upload functionality</param>
        /// <param name="LoggerId">MessageId used for logging information</param>
        /// <returns></returns>
        public UploadDocumentResponse DDMSUpload(UploadDocumentRequest uploadDocumentRequest, string LoggerId)
        {
            UploadDocumentResponse uploadDocumentResponse = new UploadDocumentResponse();

            try
            {
                Log.DebugFormat("In DDMSUpload method for MessageId - {0}", LoggerId);
                if (uploadDocumentRequest.DocumentId != Guid.Empty)
                {
                    //if documentid is passed in request, an existing document will be updated
                    uploadDocumentResponse = UpdateDocument(uploadDocumentRequest, LoggerId);
                }
                else
                {
                    //if documentid is empty or not passed in request, a new document is uploaded
                    uploadDocumentResponse = UploadDocument(uploadDocumentRequest, LoggerId);
                }
                Log.DebugFormat("Out of DDMSUpload method for MessageId - {0}", LoggerId);
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Exception in DDMSUpload method :{0}", e.Message);
                uploadDocumentResponse.ErrorMessage = e.Message;
            }
            return(uploadDocumentResponse);
        }
示例#2
0
        public void Should_Split_A_File_In_Chunks_For_Writing()
        {
            var mockDataService = new Mock <IFlowDocsOperations>();
            var sut             = new FlowDocsDocument(mockDataService.Object);

            sut.ChunkSize = 10;

            var doc = "this is the document to send!."; //30 chars

            var docBytes = Encoding.Unicode.GetBytes(doc);

            var oid            = Guid.NewGuid();
            var uploadResponse = new UploadDocumentResponse {
                OidDocument = oid
            };

            mockDataService.Setup(x => x.UploadDocument(Moq.It.IsAny <UploadDocumentRequest>()))
            .Returns(uploadResponse);

            var info = new DocumentInfo {
                DocumentName = "Name", Path = "path", Description = "desc", Owner = "owner", Version = 1
            };

            sut.UploadDocument(info, docBytes, DocumentUploadMode.NewVersion);

            mockDataService.Verify(x => x.UploadDocument(Moq.It.IsAny <UploadDocumentRequest>()), Times.Exactly(6));
        }
        public static UploadDocumentResponse Unmarshall(UnmarshallerContext context)
        {
            UploadDocumentResponse uploadDocumentResponse = new UploadDocumentResponse();

            uploadDocumentResponse.HttpResponse  = context.HttpResponse;
            uploadDocumentResponse.RequestId     = context.StringValue("UploadDocument.RequestId");
            uploadDocumentResponse.ProjectId     = context.StringValue("UploadDocument.ProjectId");
            uploadDocumentResponse.TotalCount    = context.IntegerValue("UploadDocument.TotalCount");
            uploadDocumentResponse.FileDataCount = context.IntegerValue("UploadDocument.FileDataCount");
            uploadDocumentResponse.JsonDataCount = context.IntegerValue("UploadDocument.JsonDataCount");

            return(uploadDocumentResponse);
        }
示例#4
0
        public IHttpActionResult UploadDocument([FromBody] UploadDocumentRequest uploadDocumentRequest)
        {
            Guid messageId;
            Dictionary <string, dynamic> keyValuePairs;


            //Retrieve the header parameters from request object
            RetrieveHeaders(out keyValuePairs, out messageId);
            UploadDocumentResponse uploadDocumentResponse = new UploadDocumentResponse();

            try
            {
                Log.DebugFormat("In api/UploadDocument, before calling DDMSUpload method for MessageId - {0}", messageId.ToString());
                // Upload or update the document to SPO library
                uploadDocumentResponse = ddmsUploadDocument.DDMSUpload(uploadDocumentRequest, messageId.ToString());
                Log.DebugFormat("In api/UploadDocument, after calling DDMSUpload method for MessageId - {0}", messageId.ToString());
                if (string.IsNullOrEmpty(uploadDocumentResponse.ErrorMessage))
                {
                    keyValuePairs.Add(HeaderConstants.ErrorCode, (int)HttpStatusCode.OK);
                    keyValuePairs.Add(HeaderConstants.Status, HeaderValueConstants.Success);
                    foreach (var field in keyValuePairs)
                    {
                        if (!string.IsNullOrEmpty(field.Value.ToString()) && !string.IsNullOrWhiteSpace(field.Value.ToString()))
                        {
                            HttpContext.Current.Response.Headers.Add(field.Key, field.Value.ToString());
                        }
                    }
                    return(Content(HttpStatusCode.OK, uploadDocumentResponse));
                }
                //If file is not found during update
                if (uploadDocumentResponse.ErrorMessage == ErrorMessage.FileNotFound)
                {
                    AddErrorResponseHeaders(keyValuePairs, (int)HttpStatusCode.NotFound, ErrorMessage.FileNotFound);
                    return(Content(HttpStatusCode.NotFound, uploadDocumentResponse));
                }
                else
                {
                    AddErrorResponseHeaders(keyValuePairs, (int)HttpStatusCode.InternalServerError, uploadDocumentResponse.ErrorMessage);
                    return(Content(HttpStatusCode.InternalServerError, uploadDocumentResponse));
                }
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Error in api/UploadDocument DDMSUpload method for MessageId - {0} :{1}", messageId.ToString(), ex.Message);
                uploadDocumentResponse.ErrorMessage = ex.Message;
                AddErrorResponseHeaders(keyValuePairs, (int)HttpStatusCode.InternalServerError, uploadDocumentResponse.ErrorMessage);
                return(Content(HttpStatusCode.InternalServerError, uploadDocumentResponse));
            }
        }
示例#5
0
        /// <summary>
        /// AUTHOR: Ashok Kolwal
        /// COMPANY: VITRANA
        /// Version: 1.0
        /// Description: This method is used for upload the document with it's content in documentum.
        /// Last Modified date: 11 Jul,2017
        /// </summary>
        /// <param name="request">Local drive document input folder path</param>
        /// <returns>document and it's idfID</returns>

        public UploadDocumentResponse UploadDocuments(UploadDocumentRequest request)
        {
            UploadDocumentResponse response = new UploadDocumentResponse();

            response.Status  = 1;
            response.Message = "SUCCESS";
            try
            {
                response.Result = new DocBrockerServiceUtility().UploadDoc(request.DocInputFolderPath);
            }
            catch (Exception ex)
            {
                response.Status  = 0;
                response.Message = ServiceBase.GetExceptionMessage(ex);
            }
            return(response);
        }
示例#6
0
        public string UploadDocument(string fileName, string docType, string tradeKey, string tradingSystem, string formatInd, byte[] stream)
        {
            UploadDocumentRequest request = new UploadDocumentRequest
            {
                DocumentKey       = tradeKey,
                DocumentType      = docType,
                FeedType          = "CONTRACTS",//fixed as this works for only the confirms now.
                ObjectFormatInd   = formatInd,
                ObjectStream      = stream,
                TradingSystemCode = tradingSystem,
                FileName          = tradeKey + "_" + tradingSystem + "_" + docType + "." + formatInd//fileName,
            };

            UploadDocumentResponse response = _client.UploadDocument(request);

            return(String.Format("Status:{0} ,URL :{1}", response.Status, response.URL));
        }
示例#7
0
        public string UploadDocument(string fileName, string docType, string tradeKey, string tradingSystem, byte[] stream)
        {
            UploadDocumentRequest request = new UploadDocumentRequest
            {
                DocumentKey       = tradeKey,
                DocumentType      = docType,
                FeedType          = "Manual",
                FileName          = fileName,
                ObjectFormatInd   = "Bytes",
                ObjectStream      = stream,
                TradingSystemCode = tradingSystem
            };

            UploadDocumentResponse response = _client.UploadDocument(request);

            return(String.Format("Status:{0} ,URL :{1}", response.Status, response.URL));
        }
示例#8
0
        /// <summary>
        /// Upload
        /// </summary>
        /// <param name="document">Document</param>
        /// <param name="reader">Reader</param>
        /// <param name="mode">Mode</param>
        /// <returns>Guid</returns>
        private Guid Upload(DocumentInfo document, Stream reader, DocumentUploadMode mode)
        {
            var  chunkTotal = (int)Math.Ceiling((decimal)reader.Length / GetChunkSize());
            var  chunkSize  = GetChunkSize();
            var  counter    = 0;
            Guid oid        = Guid.Empty;

            foreach (byte[] c in SplitIntoChunks(reader, chunkSize))
            {
                var request = new UploadDocumentRequest
                {
                    OidDocument  = oid,
                    DocumentName = document.DocumentName,
                    Description  = document.Description,
                    Owner        = document.Owner,
                    Path         = document.Path,
                    Version      = document.Version,
                    DataField    = c,
                    ChunkNumber  = counter++,
                    ChunkTotal   = chunkTotal,
                    ChunkSize    = chunkSize,
                    MimeType     = document.MimeType,
                    FileHash     = Md5Hash.CreateMd5Hash(c),
                    FileSize     = reader.Length,
                    Mode         = mode,
                    PreviousOid  = document.PreviousOid
                };

                UploadDocumentResponse response = null;
                if (_flowDocsService == null)
                {
                    using (var docsProxy = new FlowDocsOperations())
                    {
                        response = docsProxy.UploadDocument(request);
                    }
                }
                else
                {
                    response = _flowDocsService.UploadDocument(request);
                }

                oid = response.OidDocument;
            }

            return(oid);
        }
示例#9
0
        public async Task <(string documentId, string file1, string file2)> UploadDocument(string applicantId, byte[] side1, byte[] side2,
                                                                                           DocumentType documentType, string fileType, string documentId)
        {
            var frontResponse = await UploadFile <UploadDocumentResponse>($"{KycAidBaseUrl}files", side1, fileType);

            UploadDocumentResponse rearResponse = null;

            if (side2 != null && side2.Length > 0)
            {
                rearResponse = await UploadFile <UploadDocumentResponse>($"{KycAidBaseUrl}files", side2, fileType);
            }

            var documentResponse = string.IsNullOrWhiteSpace(documentId)
                ? await CreateDocument(applicantId, frontResponse.FileId, rearResponse?.FileId, documentType)
                : await UpdateDocument(documentId, frontResponse.FileId, rearResponse?.FileId, documentType);

            return(documentResponse, frontResponse.FileId, rearResponse?.FileId);
        }
示例#10
0
        /// <summary>
        /// Upload Document. It calls the abstract method to perform the operation
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Response</returns>
        public UploadDocumentResponse UploadDocument(UploadDocumentRequest request)
        {
            if (request.OidDocument != Guid.Empty && request.ChunkNumber == 0)
            {
                throw new ArgumentException("OidDocument should be empty");
            }

            if (request.ChunkNumber > 0 && request.OidDocument == Guid.Empty)
            {
                throw new ArgumentException("OidDocument should not be empty");
            }

            var response = new UploadDocumentResponse
            {
                OidDocument = request.OidDocument == Guid.Empty ? Guid.NewGuid() : request.OidDocument
            };

            UploadChunk(response.OidDocument, request);

            return(response);
        }
示例#11
0
        /// <summary>
        /// Method to upload a new document
        /// </summary>
        /// <param name="uploadDocumentRequest">Request Model format for Upload functionality</param>
        /// <param name="LoggerId">MessageId  used for logging information</param>
        /// <returns></returns>
        private UploadDocumentResponse UploadDocument(UploadDocumentRequest uploadDocumentRequest, string LoggerId)
        {
            UploadDocumentResponse uploadDocumentResponse = new UploadDocumentResponse();
            SecureString           secureString           = null;
            Random random = new Random();

            try
            {
                Log.DebugFormat("In UploadDocument method for MessageId - {0}", LoggerId);
                //If document content is not null and in permissible limits
                if (uploadDocumentRequest.DocumentContent != null && uploadDocumentRequest.DocumentContent.Length > 0 && uploadDocumentRequest.DocumentContent.Length <= Convert.ToInt32(ConfigurationManager.AppSettings.Get(SpoConstants.MaxFileSize)))
                {
                    using (ClientContext clientContext = new ClientContext(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOSiteURL)))
                    {
                        //Get SPO Credentials for authentication
                        secureString = new NetworkCredential("", CommonHelper.Decrypt(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPassword),
                                                                                      ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPasswordKey),
                                                                                      ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPasswordIv))).SecurePassword;
                        //Decrypt the user name and password information
                        String username = CommonHelper.Decrypt(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserName),
                                                               ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserNameKey),
                                                               ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserNameIv));

                        clientContext.Credentials = new SharePointOnlineCredentials(username, secureString);
                        //Check if file with same name already exists
                        //if (TryGetFileByServerRelativeUrl(clientContext, uploadDocumentRequest, LoggerId))
                        //{
                        Log.DebugFormat("In UploadDocument method FileName already exists renaming the file for MessageId - {0}", LoggerId);

                        //If file exists with same name, rename based on current time stamp and add random number
                        uploadDocumentRequest.DocumentName = string.Concat(System.IO.Path.GetFileNameWithoutExtension(uploadDocumentRequest.DocumentName), DateTime.Now.ToString("yyyyMMddhhmmss"), random.Next(1000, 9999), System.IO.Path.GetExtension(uploadDocumentRequest.DocumentName));
                        Log.DebugFormat("In UploadDocument method after renaming the file for MessageId - {0} :{1}", LoggerId, uploadDocumentRequest.DocumentName);
                        //}
                        //Get the document library to upload
                        Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOSiteURL)
                                                                                       + "/"
                                                                                       + ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOFolder));

                        //Create file creation information for new upload
                        FileCreationInformation fileCreationInformation = new FileCreationInformation
                        {
                            ContentStream = new System.IO.MemoryStream(uploadDocumentRequest.DocumentContent),
                            Url           = uploadDocumentRequest.DocumentName,
                            Overwrite     = false
                        };
                        File file = folder.Files.Add(fileCreationInformation);
                        clientContext.Load(folder);
                        //Load the required fields
                        clientContext.Load(file, i => i.Name,
                                           i => i.UniqueId,
                                           i => i.UIVersionLabel,
                                           i => i.ServerRelativeUrl,
                                           i => i.ListId,
                                           i => i.Exists);
                        clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                            Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                            LoggerId);

                        if (file.Exists)
                        {
                            //assign the documentid to response model
                            uploadDocumentResponse.DocumentId = file.UniqueId;
                            //assign the version number to response model
                            uploadDocumentResponse.Version = file.UIVersionLabel;
                            Log.DebugFormat("In UploadDocument method for MessageId - {0} - after uploading file to SPO DocumentId :{1} Version:{2}", LoggerId, uploadDocumentResponse.DocumentId, uploadDocumentResponse.Version);
                            //Check if metadata is passed in request object
                            if (ValidateMetadata(uploadDocumentRequest))
                            {
                                Log.DebugFormat("In UploadDocument method - validate metadata success, calling SaveOrUpdateMetaData method for MessageId - {0}", LoggerId);
                                //Calls the methods to update metadata
                                if (!SaveOrUpdateMetaData(clientContext, file, uploadDocumentRequest, uploadDocumentResponse, SpoConstants.OverRideExistingVersion, LoggerId))
                                {
                                    uploadDocumentResponse.DocumentId = Guid.Empty;
                                    uploadDocumentResponse.Version    = string.Empty;
                                }
                            }
                        }
                    }
                }
                else
                {
                    Log.DebugFormat("In UploadDocument method for MessageId - {0} - {1}", LoggerId, ErrorMessage.MaxFileSizeContentReached);
                    uploadDocumentResponse.ErrorMessage = ErrorMessage.MaxFileSizeContentReached;
                }
            }
            catch (WebException e) when(e.Status == WebExceptionStatus.NameResolutionFailure)
            {
                Log.ErrorFormat("Error in UploadDocument method for MessageId - {0} :{1}", LoggerId, e.Message);
                uploadDocumentResponse.ErrorMessage = ErrorMessage.RemoteName;
            }
            catch (ServerException ex)
            {
                Log.ErrorFormat("ServerException in UploadDocument method for MessageId - {0} :{1}", LoggerId, ex.Message);
                if (ex.ServerErrorTypeName == ErrorException.SystemIoFileNotFound)
                {
                    uploadDocumentResponse.ErrorMessage = ErrorMessage.FileNotFound;
                }
                else
                {
                    uploadDocumentResponse.ErrorMessage = ex.Message;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Exception in UploadDocument method for MessageId - {0} :{1}", LoggerId, ex.Message);
                uploadDocumentResponse.ErrorMessage = ex.Message;
            }
            return(uploadDocumentResponse);
        }
示例#12
0
        /// <summary>
        /// Method to update the metadata for a file
        /// </summary>
        /// <param name="clientContext">SPO client context object</param>
        /// <param name="folder">SPO Document library</param>
        /// <param name="file">New file uploaded to document library</param>
        /// <param name="uploadDocumentRequest"> Request model for Upload Document</param>
        /// <param name="uploadDocumentResponse">Response model for Upload Document</param>
        /// <param name="overRideExistingVersion">boolean value to override existing version</param>
        /// <param name="LoggerId">MessageId for logging information</param>
        /// <returns></returns>
        private bool SaveOrUpdateMetaData(ClientContext clientContext, File file, UploadDocumentRequest uploadDocumentRequest, UploadDocumentResponse uploadDocumentResponse, bool overRideExistingVersion, string LoggerId)
        {
            bool bReturnvalue = false;

            try
            {
                Log.DebugFormat("In SaveOrUpdateMetaData method for MessageId - {0}", LoggerId);
                List objList = clientContext.Web.Lists.GetById(file.ListId);
                //Fetch the document based on SPO Unique ID
                ListItem objListItem = objList.GetItemByUniqueId(file.UniqueId);

                //Update dealer number if request parameter has a value
                if (!string.IsNullOrWhiteSpace(uploadDocumentRequest.DealerNumber))
                {
                    objListItem[SpoConstants.DealerNumber] = uploadDocumentRequest.DealerNumber;
                }
                //Update request user  if request parameter has a value
                if (!string.IsNullOrWhiteSpace(uploadDocumentRequest.RequestUser))
                {
                    objListItem[SpoConstants.RequestUser] = uploadDocumentRequest.RequestUser;
                }
                //Overrides existing version
                if (overRideExistingVersion)
                {
                    objListItem.UpdateOverwriteVersion();
                }
                else
                {
                    //Creates a new version of document
                    objListItem.Update();
                }

                clientContext.Load(file, i => i.Name,
                                   i => i.UniqueId,
                                   i => i.UIVersionLabel,
                                   i => i.ServerRelativeUrl,
                                   i => i.ListId,
                                   i => i.Exists);
                clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                    Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                    LoggerId);
                //Retrieve the unique document id after upload
                uploadDocumentResponse.DocumentId = file.UniqueId;
                //Retrieve the version number
                uploadDocumentResponse.Version = file.UIVersionLabel;
                Log.DebugFormat("In SaveOrUpdateMetaData method for MessageId - {0} DocumentId :{1} Version :{2}", LoggerId, uploadDocumentResponse.DocumentId, uploadDocumentResponse.Version);
                bReturnvalue = true;
                Log.DebugFormat("Out of SaveOrUpdateMetaData method for MessageId - {0}", LoggerId);
            }
            catch (WebException e) when(e.Status == WebExceptionStatus.NameResolutionFailure)
            {
                Log.ErrorFormat("WebException in SaveOrUpdateMetaData method for MessageId - {0} :{1}", LoggerId, e.Message);
                bReturnvalue = false;
                uploadDocumentResponse.ErrorMessage = ErrorMessage.RemoteName;
            }
            catch (ServerException ex)
            {
                Log.ErrorFormat("ServerException in SaveOrUpdateMetaData method for MessageId - {0} :{1}", LoggerId, ex.Message);
                bReturnvalue = false;
                if (ex.ServerErrorTypeName == ErrorException.SystemIoFileNotFound)
                {
                    uploadDocumentResponse.ErrorMessage = ErrorMessage.FileNotFound;
                }
                if (ex.ServerErrorTypeName == ErrorException.ArgumentException)
                {
                    uploadDocumentResponse.ErrorMessage = ex.Message;
                }
                if (ex.ServerErrorTypeName == ErrorException.SpFieldValueException)
                {
                    uploadDocumentResponse.ErrorMessage = ex.ServerErrorValue + ErrorMessage.FieldValueNotValid;
                }
                else
                {
                    uploadDocumentResponse.ErrorMessage = ex.Message;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Exception in SaveOrUpdateMetaData method for MessageId - {0} :{1}", LoggerId, ex.Message);
                uploadDocumentResponse.ErrorMessage = ex.Message;
            }
            return(bReturnvalue);
        }
示例#13
0
        /// <summary>
        /// Method to update an existing document
        /// </summary>
        /// <param name="uploadDocumentRequest">Request model for Update document</param>
        /// <param name="LoggerId">MessageId  used for logging information</param>
        /// <returns></returns>
        private UploadDocumentResponse UpdateDocument(UploadDocumentRequest uploadDocumentRequest, string LoggerId)
        {
            UploadDocumentResponse uploadDocumentResponse = new UploadDocumentResponse();
            SecureString           secureString           = null;

            try
            {
                Log.DebugFormat("In UpdateDocument method for MessageId - {0} DocumentId :{1}", LoggerId, uploadDocumentRequest.DocumentId.ToString());
                using (ClientContext clientContext = new ClientContext(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOSiteURL)))
                {
                    //Get SPO Credentials for authentication
                    secureString = new NetworkCredential("", CommonHelper.Decrypt(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPassword),
                                                                                  ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPasswordKey),
                                                                                  ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOPasswordIv))).SecurePassword;
                    //Decrypt the user name and password information
                    String username = CommonHelper.Decrypt(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserName),
                                                           ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserNameKey),
                                                           ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOUserNameIv));

                    clientContext.Credentials = new SharePointOnlineCredentials(username, secureString);

                    //Retrieve the existing document based on DocumentId
                    File file = clientContext.Web.GetFileById(uploadDocumentRequest.DocumentId);
                    //Load the required field values
                    clientContext.Load(file, i => i.Name,
                                       i => i.UniqueId,
                                       i => i.UIVersionLabel,
                                       i => i.ServerRelativeUrl,
                                       i => i.ListId,
                                       i => i.Exists);
                    clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                        Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                        LoggerId);

                    //Fetch the folder path of the file which exists in SPO library
                    Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOSiteURL)
                                                                                   + "/"
                                                                                   + System.IO.Path.GetDirectoryName(file.ServerRelativeUrl));
                    clientContext.Load(folder);
                    clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                        Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                        LoggerId);

                    if (uploadDocumentRequest.DocumentContent != null && uploadDocumentRequest.DocumentContent.Length > 0 && uploadDocumentRequest.DocumentContent.Length <= Convert.ToInt32(ConfigurationManager.AppSettings.Get(SpoConstants.MaxFileSize)))
                    {
                        //Check if the file extension in request is same as the file in SPO library
                        if (System.IO.Path.GetExtension(file.Name).ToUpper() == System.IO.Path.GetExtension(uploadDocumentRequest.DocumentName).ToUpper())
                        {
                            Log.DebugFormat("File Extension validation success for MessageId - {0} - Same file extension provided", LoggerId);
                            //Check if filename in request object is same as filename in document library
                            if (System.IO.Path.GetFileNameWithoutExtension(file.Name).ToUpper() != System.IO.Path.GetFileNameWithoutExtension(uploadDocumentRequest.DocumentName).ToUpper())
                            {
                                uploadDocumentRequest.DocumentName = file.Name;
                            }
                            //Create the file creation information object
                            FileCreationInformation fileCreationInformation = new FileCreationInformation
                            {
                                ContentStream = new System.IO.MemoryStream(uploadDocumentRequest.DocumentContent),
                                Url           = uploadDocumentRequest.DocumentName,
                                Overwrite     = true
                            };
                            //Add the file to the library
                            file = folder.Files.Add(fileCreationInformation);
                            clientContext.Load(folder);
                            //Load the metadata after update - version will be updated
                            clientContext.Load(file, i => i.Name,
                                               i => i.UniqueId,
                                               i => i.UIVersionLabel,
                                               i => i.ServerRelativeUrl,
                                               i => i.ListId,
                                               i => i.Exists);
                            //Update an existing document
                            clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                                Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                                LoggerId);
                            uploadDocumentResponse.DocumentId = file.UniqueId;
                            uploadDocumentResponse.Version    = file.UIVersionLabel;
                            Log.DebugFormat("In UpdateDocument method after updating the document in SPO for MessageId - {0} DocumentId :{1} Version{2}", LoggerId, uploadDocumentResponse.DocumentId, uploadDocumentResponse.Version);
                            if (ValidateMetadata(uploadDocumentRequest))
                            {
                                Log.DebugFormat("In UpdateDocument method - validate metadata success, calling SaveOrUpdateMetaData method for MessageId - {0}", LoggerId);
                                //Calls the methods to update metadata
                                if (!SaveOrUpdateMetaData(clientContext, file, uploadDocumentRequest, uploadDocumentResponse, SpoConstants.OverRideExistingVersion, LoggerId))
                                {
                                    uploadDocumentResponse.DocumentId   = Guid.Empty;
                                    uploadDocumentResponse.Version      = string.Empty;
                                    uploadDocumentResponse.ErrorMessage = ErrorMessage.UpdateFailed;
                                }
                            }
                        }
                        else
                        {
                            //If file extension in request object is different, throw an error
                            uploadDocumentResponse.DocumentId   = Guid.Empty;
                            uploadDocumentResponse.Version      = string.Empty;
                            uploadDocumentResponse.ErrorMessage = ErrorMessage.DifferentFileExtension;
                        }
                    }
                    else
                    {
                        if (uploadDocumentRequest.DocumentContent == null || uploadDocumentRequest.DocumentContent.Length == 0)
                        {
                            Log.DebugFormat("In UpdateDocument method - DocumentContent is null or DocumentContent length is zero for MessageId - {0}", LoggerId);
                            Log.DebugFormat("In UpdateDocument method - Update only MetaData for MessageId - {0}", LoggerId);
                            //If document content is null and only metadata is passed in request object
                            if (ValidateMetadata(uploadDocumentRequest))
                            {
                                Log.DebugFormat("In UpdateDocument method - validate metadata success, calling SaveOrUpdateMetaData method for MessageId - {0}", LoggerId);
                                //Calls the methods to update metadata
                                if (!SaveOrUpdateMetaData(clientContext, file, uploadDocumentRequest, uploadDocumentResponse, !SpoConstants.OverRideExistingVersion, LoggerId))
                                {
                                    Log.DebugFormat("In UpdateDocument method for MessageId - {0} - Update only MetaData failed :{1}", LoggerId, uploadDocumentResponse.ErrorMessage);
                                    uploadDocumentResponse.DocumentId   = Guid.Empty;
                                    uploadDocumentResponse.Version      = string.Empty;
                                    uploadDocumentResponse.ErrorMessage = ErrorMessage.UpdateFailed;
                                }
                            }
                        }

                        //Check if document content is not null and in permissible limits
                        if (uploadDocumentRequest.DocumentContent != null && uploadDocumentRequest.DocumentContent.Length > 0 && uploadDocumentRequest.DocumentContent.Length > Convert.ToInt32(ConfigurationManager.AppSettings.Get(SpoConstants.MaxFileSize)))
                        {
                            Log.DebugFormat("In UpdateDocument method for MessageId - {0} - {1}", LoggerId, ErrorMessage.MaxFileSizeContentReached);
                            uploadDocumentResponse.ErrorMessage = ErrorMessage.MaxFileSizeContentReached;
                            uploadDocumentResponse.DocumentId   = Guid.Empty;
                            uploadDocumentResponse.Version      = string.Empty;
                        }
                    }
                }
            }
            catch (WebException e) when(e.Status == WebExceptionStatus.NameResolutionFailure)
            {
                Log.ErrorFormat("WebException in UpdateDocument method for MessageId - {0} :{1}", LoggerId, e.Message);
                uploadDocumentResponse.ErrorMessage = ErrorMessage.RemoteName;
            }
            catch (ServerException ex)
            {
                Log.ErrorFormat("ServerException in UpdateDocument method for MessageId - {0} :{1}", LoggerId, ex.Message);
                if (ex.ServerErrorTypeName == ErrorException.SystemIoFileNotFound)
                {
                    uploadDocumentResponse.ErrorMessage = ErrorMessage.FileNotFound;
                }
                else
                {
                    uploadDocumentResponse.ErrorMessage = ex.Message;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Exception in UpdateDocument method for MessageId - {0} :{1}", LoggerId, ex.Message);
                uploadDocumentResponse.ErrorMessage = ex.Message;
            }
            return(uploadDocumentResponse);
        }