public DocumentReturnValue GetDocumentDetails(Guid logonId, Guid projectId, int docId)
        {
            DocumentReturnValue returnValue = new DocumentReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!SrvMatterCommon.WebAllowedToAccessMatter(projectId))
                                throw new Exception("Access denied");

                            // Must check that document belongs to the matter
                            // (otherwise any docId could be passed and the matter security check above is meaningless)
                            this.CheckDocumentBelongsToMatter(projectId, docId);

                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    DocumentSearchItem docDetails = new DocumentSearchItem();

                    SrvDocument srvDoc = new SrvDocument();
                    srvDoc.Load(docId);

                    docDetails.Id = srvDoc.Id;
                    docDetails.CreatedDate = srvDoc.CreationDate;
                    docDetails.FeeEarnerId = srvDoc.FeeEarnerId;
                    docDetails.FileName = Path.Combine(srvDoc.VolumeLocation, srvDoc.FileName);
                    docDetails.TypeId = srvDoc.TypeId;
                    docDetails.FileDescription = srvDoc.Description;
                    docDetails.Notes = srvDoc.Notes;
                    docDetails.IsPublic = srvDoc.IsPublic;
                    docDetails.UseVersioning = srvDoc.IsUsedVersioning;
                    docDetails.IsEncrypted = srvDoc.IsEncrypted;
                    docDetails.IsLocked = srvDoc.IsLocked;

                    returnValue.Document = docDetails;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// Get documents for deep search
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="fileListToSearch"></param>
        /// <returns></returns>
        public DocumentSearchReturnValue GetMatterDocumentForDeepSearch(Guid logonId, Guid projectId, DocumentSearchCriteria criteria)
        {
            DocumentSearchReturnValue returnValue = new DocumentSearchReturnValue();
            SrvFileSearcher srvFileSearcher = new SrvFileSearcher();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            //Can search for documents
                            if (!SrvMatterCommon.WebAllowedToAccessMatter(projectId))
                                throw new Exception("Access denied");

                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    DataList<DocumentSearchItem> docs = this.MatterDocumentSearchInternal(projectId);

                    string[] listOfDocuments = null;
                    string fileInfo;
                    string searchFilePath;

                    listOfDocuments = new string[docs.Rows.Count];
                    for (int i = 0; i < docs.Rows.Count; i++)
                    {
                        fileInfo = string.Empty;
                        fileInfo = docs.Rows[i].FilePath;
                        if (fileInfo != string.Empty)
                        {
                            fileInfo += "^" + docs.Rows[i].FileDescription + "^" +
                                docs.Rows[i].Id + "^" +
                                Convert.ToString(docs.Rows[i].CreatedDate.ToString("dd/MM/yyyy")) +
                                "^" + Convert.ToString(docs.Rows[i].FeeEarnerRef);
                            listOfDocuments[i] = fileInfo;
                        }
                    }

                    srvFileSearcher.IgnoreCase = !criteria.IsMatchCase;
                    srvFileSearcher.SearchSubFolders = criteria.IsSubFolderSearch;
                    srvFileSearcher.SearchInFiles = criteria.IsDeepSearch;
                    srvFileSearcher.SearchFilesOfType = (SrvFileSearcher.AvailableFileTypes)criteria.DocumentType;

                    if (string.IsNullOrEmpty(criteria.SearchString))
                    {
                        criteria.SearchString = string.Empty;
                    }

                    srvFileSearcher.SearchSetPaths(listOfDocuments, criteria.SearchString);

                    List<FileInfo> filesFound = srvFileSearcher.FilesFound;
                    DataList<DocumentSearchItem> listDocuments = new DataList<DocumentSearchItem>();
                    foreach (FileInfo info in filesFound)
                    {
                        searchFilePath = string.Empty;

                        DocumentSearchItem item = new DocumentSearchItem();
                        item.FileName = info.Name;

                        string fileDescription = SrvDocumentCommon.GetDocumentDescription(info.Name);

                        item.FileDescription = fileDescription;
                        item.FilePath = info.FullName;

                        foreach (string element in listOfDocuments)
                        {
                            searchFilePath = string.Empty;
                            if (element.Contains("^"))
                            {
                                searchFilePath = element.Split('^')[0];
                                if (info.FullName == searchFilePath)
                                {
                                    item.Id = Convert.ToInt32(element.Split('^')[2]);
                                    item.CreatedDate = Convert.ToDateTime(Convert.ToString(element.Split('^')[3]));
                                    item.FeeEarnerRef = Convert.ToString(Convert.ToString(element.Split('^')[4]));
                                }
                            }
                        }

                        listDocuments.Rows.Add(item);
                    }
                    returnValue.Document = listDocuments;
                    returnValue.Message = srvFileSearcher.ErrorMessage;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = srvFileSearcher.ErrorMessage + "<br />" + ex.Message;
            }

            return returnValue;
        }
        private DataList<DocumentSearchItem> MatterDocumentSearchInternal(Guid projectId)
        {
            bool? GetPublicDocs = null;

            switch (UserInformation.Instance.UserType)
            {
                case DataConstants.UserType.Staff:
                    // Can do everything
                    break;
                case DataConstants.UserType.Client:
                case DataConstants.UserType.ThirdParty:
                    GetPublicDocs = true;

                    break;
                default:
                    throw new Exception("Access denied");
            }

            // Get list of Project Documents
            DataList<DocumentSearchItem> docs = new DataList<DocumentSearchItem>();

            DsProjectDocs dsProjectDocs = SrvDocumentLookup.GetProjectDocuments(projectId, GetPublicDocs);

            DataView dvProjectDocs = new DataView(dsProjectDocs.Tables[0]);
            string filter = string.Empty;
            filter = " (DocDescription <> 'PLACEHOLDER_FOLDER')";

            dvProjectDocs.RowFilter = filter;

            dvProjectDocs.Sort = "DocCreated desc";

            #region fill in additional docattributes we need
            //while (idx < dvProjectDocs.Tables[0].Rows.Count)
            foreach (DataRowView drv in dvProjectDocs)
            {
                // Don't display module documents attached to matter
                if (drv.Row["DocDescription"].ToString().Trim() != "PLACEHOLDER_FOLDER")
                {
                    string emailOwner = string.Empty;
                    bool isFound = false;
                    string imgName = string.Empty;
                    //
                    DocumentSearchItem docItem = new DocumentSearchItem();
                    docItem.Id = Convert.ToInt32(drv.Row["DocID"]);
                    docItem.ProjectId = (Guid)drv.Row["ProjectId"];
                    docItem.FileName = drv.Row["DocFileName"].ToString();
                    docItem.FileDescription = drv.Row["DocDescription"].ToString();
                    docItem.Notes = drv.Row["DocNotes"].ToString();
                    docItem.UseVersioning = Convert.ToBoolean(drv.Row["DocUseVersioning"]);
                    docItem.CreatedDate = Convert.ToDateTime(drv.Row["DocCreated"]);
                    docItem.LastModified = Convert.ToDateTime(drv.Row["DocLastModified"]);
                    docItem.IsEncrypted = Convert.ToBoolean(drv.Row["DocIsEncrypted"]);
                    docItem.IsLocked = Convert.ToBoolean(drv.Row["DocIsLocked"]);
                    docItem.CreatedBy = drv.Row["DocCreatedByUserName"].ToString();
                    docItem.IsPublic = Convert.ToBoolean(drv.Row["DocIsPublic"]);

                    #region Get Attributes for each Doc

                    DsDocAttributes dsDocAttr = SrvDocumentLookup.GetDocumentAttributes(docItem.Id);

                    for (int i = 0; i < dsDocAttr.DocAttributes.Count; i++)
                    {
                        if (dsDocAttr.DocAttributes[i].DocAttributeTypeID == 6)
                        {
                            IRIS.Law.PmsCommonData.DsEarnerDetails dsEarnerDetails = SrvEarnerLookup.GetEarnerDetails(new Guid(dsDocAttr.DocAttributes[i].DocAttributeValue));
                            if (dsEarnerDetails.Earners.Count > 0)
                                docItem.FeeEarnerRef = dsEarnerDetails.Earners[0].feeRef;
                        }

                        if (dsDocAttr.DocAttributes[i].DocAttributeTypeID == 22)
                        {
                            emailOwner = dsDocAttr.DocAttributes[i].DocAttributeValue.ToString().Trim();
                        }
                    }
                    #endregion

                    #region Get Document Path for each doc

                    docItem.FilePath = SrvDocumentCommon.GetDocumentPath(docItem.Id);

                    #endregion

                    bool hasVersions = false;

                    if (Convert.ToBoolean(docItem.UseVersioning))
                    {
                        hasVersions = SrvDocumentCommon.CheckIfHasVersions(docItem.Id);
                    }

                    #region Setup the tooltip
                    string toolTip = string.Empty;
                    if (docItem.IsEncrypted)
                    {
                        toolTip += Environment.NewLine + "Document is Encrypted.";
                    }
                    if (docItem.IsLocked)
                    {
                        toolTip += Environment.NewLine + "Document is Locked.";
                    }
                    if (hasVersions)
                    {
                        toolTip += Environment.NewLine + "Document is Versioned.";
                    }
                    if (!string.IsNullOrEmpty(toolTip))
                    {
                        docItem.ToolTip = toolTip + Environment.NewLine;
                    }
                    #endregion

                    // Get Email Attachment
                    #region Get Email Attachment
                    string emailHasAttachment = string.Empty;
                    if (!string.IsNullOrEmpty(emailOwner))
                    {
                        SrvDocument srvDocument = new SrvDocument();
                        srvDocument.Load(docItem.Id);

                        if (srvDocument.EmailHasAttachement)
                        {
                            emailHasAttachment = "Yes";
                        }
                        else
                        {
                            emailHasAttachment = string.Empty;
                        }
                    }
                    #endregion

                    // Set ImageName on document attributes
                    #region Set ImageName on doc Attributes
                    if (hasVersions)
                    {
                        imgName = "documents.png";
                        isFound = true;
                    }

                    if (docItem.IsEncrypted)
                    {
                        imgName = "shield1.png";
                        isFound = true;
                    }

                    if (docItem.IsLocked)
                    {
                        imgName = "lock.png";
                        isFound = true;
                    }
                    #endregion

                    // Get Image file according to the File Extension.
                    #region Get Image File

                    if (isFound == false)
                    {
                        // Default ImageName to PMS.gif
                        imgName = "pms.png";

                        // Get File Extension
                        #region Get File Extension
                        string fileExtension = string.Empty;
                        try
                        {
                            fileExtension = Path.GetExtension(docItem.FileName).ToUpper();
                        }
                        catch
                        {
                        }

                        switch (fileExtension)
                        {
                            case ".DOC":
                            case ".DOCX":
                            case ".RTF":
                                imgName = "word.gif";
                                break;
                            case ".PDF":
                                imgName = "pdf.gif";
                                break;
                            case ".XLS":
                            case ".XLSX":
                            case ".XLSM":
                                imgName = "excel.gif";
                                break;
                            case ".TXT":
                                imgName = "text.gif";
                                break;
                            case ".PPT":
                            case ".PPS":
                                imgName = "powerPoint.gif";
                                break;
                            case ".MSG":
                                if (emailHasAttachment == "Yes")
                                {
                                    imgName = "paperclip.png";
                                }
                                else
                                {
                                    imgName = "mail.png";
                                }
                                break;
                            case ".GIF":
                            case ".JPG":
                            case ".CSV":
                            case ".JIF":
                            case ".PEG":
                            case ".PCT":
                            case ".PSP":
                            case ".PNG":
                            case ".TIF":
                            case ".IFF":
                            case ".BMP":
                            case ".PCX":
                            case ".WMF":
                            case ".TIFF":
                            case ".LFM":
                            case ".XFD":
                            case ".LPW":
                                 imgName = "pms.png";
                                break;
                            default:
                                imgName = "pms.png";
                                break;
                        }
                        #endregion
                    }
                    #endregion

                    docItem.ImgfileName = imgName;
                    docs.Rows.Add(docItem);
                }
            }
            #endregion

            return docs;
        }
        /// <summary>
        /// Save Document to document server and also save details to the database
        /// This method requires to work with actual files, the reason is
        /// If the existing document is not encrypted, and if user updates the document details by setting
        /// Encryption flag to true, then the actual document is to be encrypted.
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="docSearchItem"></param>
        /// <returns></returns>
        public DocumentReturnValue EditMatterDocumentDetails(Guid logonId, DocumentSearchItem docSearchItem)
        {
            DocumentReturnValue returnValue = new DocumentReturnValue();
            string errorMessage = string.Empty;

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Check permission
                            if (!UserSecuritySettings.GetUserSecuitySettings(9))
                                throw new Exception("You do not have sufficient permissions to carry out this request");
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    returnValue.Success = false;

                    SrvDocument srvDoc = new SrvDocument();
                    srvDoc.Id = docSearchItem.Id;
                    // If document details is edited then Load default values in SrvDocument
                    srvDoc.Load(docSearchItem.Id);

                    srvDoc.DocumentModuleId = docSearchItem.ProjectId;
                    byte[] bytesToUpdate = new byte[0];
                    srvDoc.BytesToUpdate = bytesToUpdate;

                    // Hardcoded
                    srvDoc.Type = DmEnums.DmPMSDocType.Project;
                    srvDoc.ApplicationId = (int)DataConstants.Application.PMS;
                    srvDoc.FolderName = "Documents";

                    srvDoc.TypeId = docSearchItem.TypeId;
                    srvDoc.Description = docSearchItem.FileDescription;
                    srvDoc.Notes = docSearchItem.Notes;

                    srvDoc.IsPublic=docSearchItem.IsPublic;
                    srvDoc.IsUsedVersioning = docSearchItem.UseVersioning;
                    srvDoc.CreationDate = docSearchItem.CreatedDate;
                    srvDoc.IsLocked = docSearchItem.IsLocked;
                    srvDoc.FeeEarnerId = docSearchItem.FeeEarnerId;

                    // Don't set it while Editing Document
                    srvDoc.VolumeId = 0;

                    #region File Encryption
                    if (!srvDoc.IsEncrypted && docSearchItem.IsEncrypted)
                    {
                        // Encrypt the file and save to the document server
                        if (!string.IsNullOrEmpty(srvDoc.VolumeLocation))
                        {
                            DmEncryptionWeb dmEncryption = new DmEncryptionWeb();
                            string tempDocPath = string.Empty;

                            string savedDocPath = Path.Combine(srvDoc.VolumeLocation, srvDoc.FileName);
                            tempDocPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(srvDoc.FileName));

                            dmEncryption.CopyAndEncryptFile(savedDocPath, tempDocPath, false);

                            File.Copy(tempDocPath, savedDocPath, true);
                            File.Delete(tempDocPath);
                        }
                        else
                        {
                            throw new Exception("Upload document failed on the server.");
                        }
                        srvDoc.IsEncrypted = docSearchItem.IsEncrypted;
                    }
                    #endregion

                    returnValue.Success = srvDoc.Save(out errorMessage);

                    docSearchItem.Id = srvDoc.Id;
                    docSearchItem.FileName = srvDoc.FileName;

                    returnValue.Document = docSearchItem;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// Start New Document Upload for the specific organisation
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="ModifiedDate"></param>
        /// <param name="Size"></param>
        /// <param name="Hash"></param>
        /// <param name="docSearchItem"></param>
        /// <returns></returns>
        public StartDocumentUploadReturnValue StartNewDocumentUploadForOrganisation(Guid logonId,
            DateTime ModifiedDate, long Size, byte[] Hash, DocumentSearchItem docSearchItem)
        {
            StartDocumentUploadReturnValue ReturnValue = new StartDocumentUploadReturnValue();

            docSearchItem.ProjectId = Guid.Empty;
            docSearchItem.MemberId = Guid.Empty;

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!ApplicationSettings.Instance.IsUser(DataConstants.DummyGuid, docSearchItem.OrganisationId) || !UserSecuritySettings.GetUserSecuitySettings(274))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    // Check File Type before upload
                    this.CheckFileTypeBeforeUpload(Path.GetFileName(docSearchItem.FileName));

                    DocumentStorageData documentStorageData = Host.GetDocumentStorageData(logonId);

                    #region Load Associate Data to DocumentStorageData

                    documentStorageData.ExitingDocument = false;
                    documentStorageData.DocDetails = docSearchItem;

                    SrvDocument srvDoc = new SrvDocument();
                    // If New document is being uploaded, Get the volume location which will help to upload document on documentuploadcomplete
                    srvDoc.ApplicationId = (int)DataConstants.Application.PMS;
                    srvDoc.FileName = docSearchItem.FileName;
                    srvDoc.DocumentModuleId = docSearchItem.OrganisationId;
                    srvDoc.Type = DmEnums.DmPMSDocType.Org;

                    bool isVoumeCreated = false;
                    Common commonFunction = new Common();
                    isVoumeCreated = commonFunction.GetVolumeLocation(ref srvDoc);

                    if (!isVoumeCreated)
                    {
                        throw new Exception("Upload document failed on the server.");
                    }
                    else
                    {
                        documentStorageData.VolumeLocation = srvDoc.VolumeLocation;
                        documentStorageData.VolumeId = srvDoc.VolumeId;
                        documentStorageData.FileName = srvDoc.FileName;
                    }

                    #endregion

                    ReturnValue.MaxChunkSize = Host.FileTransferChunkSize;

                    ReturnValue.TransferId = FileTransfer.StartFileUpload(logonId, Path.GetFileName(docSearchItem.FileName), ModifiedDate, Size, Hash, documentStorageData);
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                ReturnValue.Success = false;
                ReturnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                ReturnValue.Success = false;
                ReturnValue.Message = ex.Message;
            }

            return ReturnValue;
        }
        /// <summary>
        /// Reupload document, upload updated document to the original document server location
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="docSearchItem"></param>
        /// <returns></returns>
        private DocumentReturnValue DocumentReuploaded(DocumentSearchItem docSearchItem)
        {
            DocumentReturnValue returnValue = new DocumentReturnValue();
            string errorMessage = string.Empty;

            try
            {

                SrvDocument srvDoc = new SrvDocument();
                srvDoc.Id = docSearchItem.Id;

                if (docSearchItem.ProjectId != Guid.Empty)
                {
                    srvDoc.DocumentModuleId = docSearchItem.ProjectId;
                    srvDoc.Type = DmEnums.DmPMSDocType.Project;
                }
                else if (docSearchItem.MemberId != Guid.Empty)
                {
                    srvDoc.DocumentModuleId = docSearchItem.MemberId;
                    srvDoc.Type = DmEnums.DmPMSDocType.Member;
                }
                else if (docSearchItem.OrganisationId != Guid.Empty)
                {
                    srvDoc.DocumentModuleId = docSearchItem.OrganisationId;
                    srvDoc.Type = DmEnums.DmPMSDocType.Org;
                }

                // If document details is edited then Load default values in SrvDocument
                srvDoc.Load(docSearchItem.Id);

                // Don't set it while Editing Document
                srvDoc.VolumeId = 0;

                // Hardcoded
                srvDoc.ApplicationId = (int)DataConstants.Application.PMS;
                srvDoc.FolderName = "Documents";

                if (!srvDoc.IsUsedVersioning)
                    throw new Exception("Unable to reupload document as versioning is disabled. You may rename your document and retry.");

                srvDoc.Notes = docSearchItem.Notes;

                if (returnValue.Success)
                {
                    //FileStreamCreator fileStreamCreator = new FileStreamCreator();
                    if (!File.Exists(docSearchItem.FileName))
                    {
                        throw new Exception("Document is not uploaded.");
                    }
                    Common dmCommon = new Common();

                    try
                    {
                        string collection = dmCommon.GetOriginalDocFilePath(docSearchItem.Id);
                        string originalFilePath = GetValueOnIndexFromArray(collection, 0);
                        bool isEncrypted = Convert.ToBoolean(GetValueOnIndexFromArray(collection, 1));
                        bool local = Convert.ToBoolean(GetValueOnIndexFromArray(collection, 2));

                        if (!string.IsNullOrEmpty(originalFilePath))
                        {
                            // Reupload Document
                            // If existing document is in encrypted form, then the upadted doc will also be saved in encrypted format
                            if (dmCommon.ReuploadDoc(docSearchItem.Id, docSearchItem.FileName, isEncrypted, local))
                            {
                                FileInfo file = new FileInfo(docSearchItem.FileName);
                                if (File.Exists(originalFilePath))
                                {
                                    // Attempt to copy the file.
                                    file.CopyTo(originalFilePath, true);
                                }
                                // Save Document Details
                                returnValue.Success = srvDoc.Save(out errorMessage);
                            }
                            else
                            {
                                returnValue.Success = false;
                                returnValue.Message = "Reupload failed.";
                            }
                        }
                        else
                        {
                            returnValue.Success = false;
                            returnValue.Message = "System cannot able to find original file path location to reupload.";
                        }
                    }
                    catch (Exception ex)
                    {
                        returnValue.Success = false;
                        returnValue.Message = ex.Message;
                    }
                }
            }
            finally
            {
                if (!string.IsNullOrEmpty(docSearchItem.FileName))
                {
                    // Delete the temp file which was created when uploaded from client
                    if (File.Exists(docSearchItem.FileName))
                    {
                        File.Delete(docSearchItem.FileName);
                    }
                }
            }

            return returnValue;
        }
Example #7
0
        /// <summary>
        /// Import Button Click Event
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">Event arguments</param>
        protected void _btnSave_Click(object sender, EventArgs e)
        {
            DocumentServiceClient _documentServiceClient = new DocumentServiceClient();

            try
            {
                string fileName = string.Empty;
                if (_editMode == false)
                {
                    #region Upload File to Application Server
                    if (_fileName.PostedFile != null)
                    {
                        if (!string.IsNullOrEmpty(_fileName.PostedFile.FileName))
                        {
                            if (!CheckFileTypeExtension())
                            {
                                _lblError.Text = UploadFileTypesErrorMessage;
                                return;
                            }

                            if (!Directory.Exists(Path.Combine(Server.MapPath("."), "Upload")))
                            {
                                Directory.CreateDirectory(Path.Combine(Server.MapPath("."), "Upload"));
                            }

                            _fileName.PostedFile.SaveAs(Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1));

                            fileName = Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1);
                        }
                        else
                        {
                            _lblError.Text = "Please select document.";
                            return;
                        }
                    }
                    #endregion
                }

                #region Load Details
                DocumentSearchItem             docDetails     = new DocumentSearchItem();
                DocumentReturnValue            docReturnValue = null;
                StartDocumentUploadReturnValue Header;

                docDetails.ProjectId = (Guid)Session[SessionName.ProjectId];
                // Document Type is General
                docDetails.TypeId          = 1;
                docDetails.FileDescription = _txtDocument.Text;
                docDetails.Notes           = _txtNotes.Text;
                if (!string.IsNullOrEmpty(_ddlFeeEarner.SelectedValue))
                {
                    docDetails.FeeEarnerId = new Guid(GetValueOnIndexFromArray(_ddlFeeEarner.SelectedValue, 1));
                }
                else
                {
                    docDetails.FeeEarnerId = DataConstants.DummyGuid;
                }
                docDetails.IsPublic      = _chkPublic.Checked;
                docDetails.UseVersioning = _chkUseVersioning.Checked;
                docDetails.IsEncrypted   = _chkEncryptFile.Checked;
                docDetails.IsLocked      = _chkLockDocument.Checked;
                #endregion

                if (_editMode == false)
                {
                    if (string.IsNullOrEmpty(fileName))
                    {
                        _lblError.Text = "Please select document.";
                        return;
                    }

                    docDetails.FileName     = fileName;
                    docDetails.CreatedDate  = DateTime.Now;
                    docDetails.ModifiedDate = docDetails.CreatedDate;
                    docDetails.Id           = 0;

                    FileInfo FInfo = new FileInfo(fileName);
                    // Create a hash of the file
                    byte[] LocalHash = FileTransferHash.CreateFileMD5Hash(fileName);

                    #region Start Upload
                    try
                    {
                        Header = _documentServiceClient.StartNewDocumentUploadForMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId,
                                                                                        // Strip off the path as this is irrelavent
                                                                                        FInfo.LastWriteTime, FInfo.Length, LocalHash, docDetails);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    if (Header != null)
                    {
                        if (!Header.Success)
                        {
                            _lblError.CssClass = "errorMessage";
                            _lblError.Text     = Header.Message;
                            return;
                        }
                    }
                    #endregion

                    #region Upload Chunk by Chunk
                    long BytesLeft = FInfo.Length;

                    // Open the file
                    using (FileStream FileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        while (BytesLeft > 0)
                        {
                            byte[] Bytes = new byte[Header.MaxChunkSize];

                            long Position = FileStream.Position;

                            // Read at most MaxChunkSize bytes
                            int ChunkSize = FileStream.Read(Bytes, 0, (int)Math.Min(BytesLeft, Header.MaxChunkSize));

                            // Upload the chunk
                            ReturnValue Result = _documentServiceClient.DocumentUploadChunk(
                                ((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId, Position, ChunkSize, Bytes);

                            if (!Result.Success)
                            {
                                throw new Exception("File upload failed: " + Result.Message);
                            }

                            BytesLeft -= ChunkSize;
                        }
                    }
                    #endregion

                    #region Upload Complete
                    // Tell the service we have finished the upload
                    docReturnValue = _documentServiceClient.DocumentUploadComplete(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId);
                    #endregion

                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                }
                else
                {
                    docDetails.Id = Convert.ToInt32(Session[SessionName.DocumentId]);
                    if (_ccCreatedDate.DateText.Length > 0)
                    {
                        docDetails.CreatedDate = Convert.ToDateTime(_ccCreatedDate.DateText);
                    }

                    try
                    {
                        docReturnValue = _documentServiceClient.EditMatterDocumentDetails(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, docDetails);
                    }
                    catch (System.ServiceModel.EndpointNotFoundException)
                    {
                        _lblError.Text = DataConstants.WSEndPointErrorMessage;
                    }
                    catch (Exception ex)
                    {
                        _lblError.Text = ex.Message;
                    }
                }

                if (docReturnValue != null)
                {
                    if (docReturnValue.Success)
                    {
                        if (docReturnValue.Document != null)
                        {
                            if (_editMode == false)
                            {
                                Session[SessionName.DocumentId] = docReturnValue.Document.Id;
                                _editMode = true;
                            }

                            DisplayDocumentDetails();

                            _lblError.Text     = "Document information saved successfully.";
                            _lblError.CssClass = "successMessage";

                            _btnSave.Enabled   = false;
                            _btnImport.Enabled = true;
                        }
                    }
                    else
                    {
                        _lblError.Text     = "Document information not saved.<br />" + docReturnValue.Message;
                        _lblError.CssClass = "errorMessage";
                    }
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                _lblError.Text = DataConstants.WSEndPointErrorMessage;
            }
            catch (Exception ex)
            {
                _lblError.Text = ex.Message;
            }
            finally
            {
                if (_documentServiceClient != null)
                {
                    if (_documentServiceClient.State != System.ServiceModel.CommunicationState.Faulted)
                    {
                        _documentServiceClient.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Start existing Document Upload for the specific organisation
        /// </summary>
        /// <param name="logonId"></param>
        /// <param name="ModifiedDate"></param>
        /// <param name="Size"></param>
        /// <param name="Hash"></param>
        /// <param name="docSearchItem"></param>
        /// <returns></returns>
        public StartDocumentUploadReturnValue StartExistingDocumentUploadForOrganisation(Guid logonId,
            DateTime ModifiedDate, long Size, byte[] Hash, DocumentSearchItem docSearchItem)
        {
            StartDocumentUploadReturnValue ReturnValue = new StartDocumentUploadReturnValue();

            docSearchItem.ProjectId = Guid.Empty;
            docSearchItem.MemberId = Guid.Empty;

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                            if (!ApplicationSettings.Instance.IsUser(DataConstants.DummyGuid, docSearchItem.OrganisationId))
                                throw new Exception("Access denied");

                            this.CheckDocumentBelongsToOrganisation(docSearchItem.OrganisationId, docSearchItem.Id);

                            // if user is client and the document is not public, throw an access denied exception
                            SrvDocument srvDoc = new SrvDocument();
                            srvDoc.Load(docSearchItem.Id);

                            if (!srvDoc.IsPublic)
                                throw new Exception("Access denied");

                            break;
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    // Check File Type before upload
                    this.CheckFileTypeBeforeUpload(Path.GetFileName(docSearchItem.FileName));

                    DocumentStorageData documentStorageData = Host.GetDocumentStorageData(logonId);

                    documentStorageData.DocDetails = docSearchItem;

                    documentStorageData.ExitingDocument = true;

                    // Saving this data is not required here, hence commented out
                    // This information will not be requiring in UploadDocumentComplete
                    // as we are calling Reupload method & this method is handling all type of file handling
                    // like, versioning, encryption etc
                    // Reupload method gets this information using DocumentId
                    // SrvDocument srvDoc = new SrvDocument();
                    //srvDoc.Load(docSearchItem.Id);
                    //documentStorageData.VolumeLocation = srvDoc.VolumeLocation;
                    //documentStorageData.VolumeId = 0;
                    //documentStorageData.FileName = srvDoc.FileName;

                    ReturnValue.MaxChunkSize = Host.FileTransferChunkSize;

                    ReturnValue.TransferId = FileTransfer.StartFileUpload(logonId, Path.GetFileName(docSearchItem.FileName), ModifiedDate, Size, Hash, documentStorageData);
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                ReturnValue.Success = false;
                ReturnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                ReturnValue.Success = false;
                ReturnValue.Message = ex.Message;
            }

            return ReturnValue;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void _btnSaveReupload_Click(object sender, EventArgs e)
        {
            string fileName = string.Empty;
            DocumentServiceClient _documentServiceClient = new DocumentServiceClient();

            try
            {
                DocumentSearchItem docDetails = new DocumentSearchItem();

                #region Upload File to Application Server
                if (_fileName.PostedFile != null)
                {
                    if (!string.IsNullOrEmpty(_fileName.PostedFile.FileName))
                    {
                        if (!CheckFileTypeExtension())
                        {
                            _lblErrorReupload.Text = UploadFileTypesErrorMessage;
                            return;
                        }

                        if (string.IsNullOrEmpty(_hdnDocFileName.Value))
                        {
                            _lblErrorReupload.Text = "Existing file name to compare does not exists.";
                            return;
                        }

                        if (Convert.ToString(_hdnDocFileName.Value) != _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1))
                        {
                            _lblErrorReupload.Text = "File should be uploaded with the file name '" + _hdnDocFileName.Value + "'";
                            return;
                        }

                        if (!Directory.Exists(Path.Combine(Server.MapPath("."), "Upload")))
                        {
                            Directory.CreateDirectory(Path.Combine(Server.MapPath("."), "Upload"));
                        }

                        _fileName.PostedFile.SaveAs(Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1));

                        docDetails.FileName = Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        _lblErrorReupload.Text = "Please select document.";
                        return;
                    }
                }
                #endregion

                DocumentReturnValue            docReturnValue = null;
                StartDocumentUploadReturnValue Header;

                #region Load Data
                docDetails.ProjectId = (Guid)Session[SessionName.ProjectId];
                // Document Type is General
                docDetails.TypeId = 1;
                docDetails.Id     = Convert.ToInt32(Session[SessionName.DocumentId]);
                docDetails.Notes  = _txtNotes.Text;
                fileName          = docDetails.FileName;
                #endregion

                if (string.IsNullOrEmpty(fileName))
                {
                    _lblErrorReupload.Text = "Please select document.";
                    return;
                }

                FileInfo FInfo = new FileInfo(fileName);
                // Create a hash of the file
                byte[] LocalHash = FileTransferHash.CreateFileMD5Hash(fileName);

                #region Start Upload File
                try
                {
                    Header = _documentServiceClient.StartExistingDocumentUploadForMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId,
                                                                                         // Strip off the path as this is irrelavent
                                                                                         FInfo.LastWriteTime, FInfo.Length, LocalHash, docDetails);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                if (Header != null)
                {
                    if (!Header.Success)
                    {
                        _lblErrorReupload.CssClass = "errorMessage";
                        _lblErrorReupload.Text     = Header.Message;
                        return;
                    }
                }
                #endregion

                #region Upload Chunk
                long BytesLeft = FInfo.Length;

                // Open the file
                using (FileStream FileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    while (BytesLeft > 0)
                    {
                        byte[] Bytes = new byte[Header.MaxChunkSize];

                        long Position = FileStream.Position;

                        // Read at most MaxChunkSize bytes
                        int ChunkSize = FileStream.Read(Bytes, 0, (int)Math.Min(BytesLeft, Header.MaxChunkSize));

                        // Upload the chunk
                        ReturnValue Result = _documentServiceClient.DocumentUploadChunk(
                            ((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId, Position, ChunkSize, Bytes);

                        if (!Result.Success)
                        {
                            throw new Exception("File upload failed: " + Result.Message);
                        }

                        BytesLeft -= ChunkSize;
                    }
                }
                #endregion

                #region Upload Complete
                // Tell the service we have finished the upload & Save Document Details
                docReturnValue = _documentServiceClient.DocumentUploadComplete(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId);
                #endregion

                if (docReturnValue != null)
                {
                    if (docReturnValue.Success)
                    {
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }

                        if (docReturnValue.Success)
                        {
                            _lblErrorReupload.Text     = "Document information saved successfully.";
                            _lblErrorReupload.CssClass = "successMessage";
                        }
                        else
                        {
                            _lblErrorReupload.Text     = docReturnValue.Message;
                            _lblErrorReupload.CssClass = "errorMessage";
                        }
                    }
                    else
                    {
                        _lblErrorReupload.Text     = "Document information not saved.<br />" + docReturnValue.Message;
                        _lblErrorReupload.CssClass = "errorMessage";
                    }
                }
            }
            catch (Exception ex)
            {
                _lblErrorReupload.Text     = ex.Message;
                _lblErrorReupload.CssClass = "errorMessage";
            }
            finally
            {
                if (_documentServiceClient != null)
                {
                    if (_documentServiceClient.State != System.ServiceModel.CommunicationState.Faulted)
                    {
                        _documentServiceClient.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Import Button Click Event
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">Event arguments</param>
        protected void _btnSave_Click(object sender, EventArgs e)
        {
            DocumentServiceClient _documentServiceClient = new DocumentServiceClient();
            try
            {
                string fileName = string.Empty;
                if (_editMode == false)
                {
                    #region Upload File to Application Server
                    if (_fileName.PostedFile != null)
                    {
                        if (!string.IsNullOrEmpty(_fileName.PostedFile.FileName))
                        {
                            if (!CheckFileTypeExtension())
                            {
                                _lblError.Text = UploadFileTypesErrorMessage;
                                return;
                            }

                            if (!Directory.Exists(Path.Combine(Server.MapPath("."), "Upload")))
                            {
                                Directory.CreateDirectory(Path.Combine(Server.MapPath("."), "Upload"));
                            }

                            _fileName.PostedFile.SaveAs(Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1));

                            fileName = Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1);

                        }
                        else
                        {
                            _lblError.Text = "Please select document.";
                            return;
                        }
                    }
                    #endregion
                }

                #region Load Details
                DocumentSearchItem docDetails = new DocumentSearchItem();
                DocumentReturnValue docReturnValue = null;
                StartDocumentUploadReturnValue Header;

                docDetails.ProjectId = (Guid)Session[SessionName.ProjectId];
                // Document Type is General
                docDetails.TypeId = 1;
                docDetails.FileDescription = _txtDocument.Text;
                docDetails.Notes = _txtNotes.Text;
                if (!string.IsNullOrEmpty(_ddlFeeEarner.SelectedValue))
                {
                    docDetails.FeeEarnerId = new Guid(GetValueOnIndexFromArray(_ddlFeeEarner.SelectedValue, 1));
                }
                else
                {
                    docDetails.FeeEarnerId = DataConstants.DummyGuid;
                }
                docDetails.IsPublic = _chkPublic.Checked;
                docDetails.UseVersioning = _chkUseVersioning.Checked;
                docDetails.IsEncrypted = _chkEncryptFile.Checked;
                docDetails.IsLocked = _chkLockDocument.Checked;
                #endregion

                if (_editMode == false)
                {
                    if (string.IsNullOrEmpty(fileName))
                    {
                        _lblError.Text = "Please select document.";
                        return;
                    }

                    docDetails.FileName = fileName;
                    docDetails.CreatedDate = DateTime.Now;
                    docDetails.ModifiedDate = docDetails.CreatedDate;
                    docDetails.Id = 0;

                    FileInfo FInfo = new FileInfo(fileName);
                    // Create a hash of the file
                    byte[] LocalHash = FileTransferHash.CreateFileMD5Hash(fileName);

                    #region Start Upload
                    try
                    {
                        Header = _documentServiceClient.StartNewDocumentUploadForMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId,
                            // Strip off the path as this is irrelavent
                        FInfo.LastWriteTime, FInfo.Length, LocalHash, docDetails);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    if (Header != null)
                    {
                        if (!Header.Success)
                        {
                            _lblError.CssClass = "errorMessage";
                            _lblError.Text = Header.Message;
                            return;
                        }
                    }
                    #endregion

                    #region Upload Chunk by Chunk
                    long BytesLeft = FInfo.Length;

                    // Open the file
                    using (FileStream FileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        while (BytesLeft > 0)
                        {
                            byte[] Bytes = new byte[Header.MaxChunkSize];

                            long Position = FileStream.Position;

                            // Read at most MaxChunkSize bytes
                            int ChunkSize = FileStream.Read(Bytes, 0, (int)Math.Min(BytesLeft, Header.MaxChunkSize));

                            // Upload the chunk
                            ReturnValue Result = _documentServiceClient.DocumentUploadChunk(
                                ((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId, Position, ChunkSize, Bytes);

                            if (!Result.Success)
                                throw new Exception("File upload failed: " + Result.Message);

                            BytesLeft -= ChunkSize;
                        }
                    }
                    #endregion

                    #region Upload Complete
                    // Tell the service we have finished the upload
                    docReturnValue = _documentServiceClient.DocumentUploadComplete(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId);
                    #endregion

                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                }
                else
                {
                    docDetails.Id = Convert.ToInt32(Session[SessionName.DocumentId]);
                    if (_ccCreatedDate.DateText.Length > 0)
                    {
                        docDetails.CreatedDate = Convert.ToDateTime(_ccCreatedDate.DateText);
                    }

                    try
                    {
                        docReturnValue = _documentServiceClient.EditMatterDocumentDetails(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, docDetails);
                    }
                    catch (System.ServiceModel.EndpointNotFoundException)
                    {
                        _lblError.Text = DataConstants.WSEndPointErrorMessage;
                    }
                    catch (Exception ex)
                    {
                        _lblError.Text = ex.Message;
                    }
                }

                if (docReturnValue != null)
                {
                    if (docReturnValue.Success)
                    {
                        if (docReturnValue.Document != null)
                        {
                            if (_editMode == false)
                            {
                                Session[SessionName.DocumentId] = docReturnValue.Document.Id;
                                _editMode = true;
                            }

                            DisplayDocumentDetails();

                            _lblError.Text = "Document information saved successfully.";
                            _lblError.CssClass = "successMessage";

                            _btnSave.Enabled = false;
                            _btnImport.Enabled = true;
                        }
                    }
                    else
                    {
                        _lblError.Text = "Document information not saved.<br />" + docReturnValue.Message;
                        _lblError.CssClass = "errorMessage";
                    }
                }

            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                _lblError.Text = DataConstants.WSEndPointErrorMessage;
            }
            catch (Exception ex)
            {
                _lblError.Text = ex.Message;
            }
            finally
            {
                if (_documentServiceClient != null)
                {
                    if (_documentServiceClient.State != System.ServiceModel.CommunicationState.Faulted)
                        _documentServiceClient.Close();
                }
            }
        }
        /// <summary>
        /// Save Document to document server and also save details to the database
        /// This method requires to work with actual files, the reason is
        /// If the existing document is not encrypted, and if user updates the document details by setting
        /// Encryption flag to true, then the actual document is to be encrypted.
        /// </summary>
        /// <param name="oHostSecurityToken"></param>
        /// <param name="docSearchItem"></param>
        /// <returns></returns>
        public DocumentReturnValue EditMatterDocumentDetails(HostSecurityToken oHostSecurityToken, DocumentSearchItem docSearchItem)
        {
            DocumentReturnValue ReturnValue = null;

            if (Functions.ValidateIWSToken(oHostSecurityToken))
            {
                oDocumentService = new DocumentService();
                ReturnValue      = oDocumentService.EditMatterDocumentDetails(Functions.GetLogonIdFromToken(oHostSecurityToken), docSearchItem);
            }
            else
            {
                ReturnValue         = new DocumentReturnValue();
                ReturnValue.Success = false;
                ReturnValue.Message = "Invalid Token";
            }
            return(ReturnValue);
        }
        /// <summary>
        /// Start existing Document Upload for the specific Organisation
        /// </summary>
        /// <param name="oHostSecurityToken"></param>
        /// <param name="projectId"></param>
        /// <param name="FileName"></param>
        /// <param name="ModifiedDate"></param>
        /// <param name="Size"></param>
        /// <param name="Hash"></param>
        /// <param name="docId"></param>
        /// <returns></returns>
        public StartDocumentUploadReturnValue StartExistingDocumentUploadForOrganisation(HostSecurityToken oHostSecurityToken,
                                                                                         DateTime ModifiedDate, long Size, byte[] Hash, DocumentSearchItem docSearchItem)
        {
            StartDocumentUploadReturnValue ReturnValue = null;

            if (Functions.ValidateIWSToken(oHostSecurityToken))
            {
                oDocumentService = new DocumentService();
                ReturnValue      = oDocumentService.StartExistingDocumentUploadForOrganisation(Functions.GetLogonIdFromToken(oHostSecurityToken), ModifiedDate, Size, Hash, docSearchItem);
            }
            else
            {
                ReturnValue         = new StartDocumentUploadReturnValue();
                ReturnValue.Success = false;
                ReturnValue.Message = "Invalid Token";
            }
            return(ReturnValue);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void _btnSaveReupload_Click(object sender, EventArgs e)
        {
            string fileName = string.Empty;
            DocumentServiceClient _documentServiceClient = new DocumentServiceClient();
            try
            {
                DocumentSearchItem docDetails = new DocumentSearchItem();

                #region Upload File to Application Server
                if (_fileName.PostedFile != null)
                {
                    if (!string.IsNullOrEmpty(_fileName.PostedFile.FileName))
                    {
                        if (!CheckFileTypeExtension())
                        {
                            _lblErrorReupload.Text = UploadFileTypesErrorMessage;
                            return;
                        }

                        if (string.IsNullOrEmpty(_hdnDocFileName.Value))
                        {
                            _lblErrorReupload.Text = "Existing file name to compare does not exists.";
                            return;
                        }

                        if (Convert.ToString(_hdnDocFileName.Value) != _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1))
                        {
                            _lblErrorReupload.Text = "File should be uploaded with the file name '" + _hdnDocFileName.Value + "'";
                            return;
                        }

                        if (!Directory.Exists(Path.Combine(Server.MapPath("."), "Upload")))
                        {
                            Directory.CreateDirectory(Path.Combine(Server.MapPath("."), "Upload"));
                        }

                        _fileName.PostedFile.SaveAs(Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1));

                        docDetails.FileName = Server.MapPath(".") + "/Upload/" + _fileName.PostedFile.FileName.Substring(_fileName.PostedFile.FileName.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        _lblErrorReupload.Text = "Please select document.";
                        return;
                    }
                }
                #endregion

                DocumentReturnValue docReturnValue = null;
                StartDocumentUploadReturnValue Header;

                #region Load Data
                docDetails.ProjectId = (Guid)Session[SessionName.ProjectId];
                // Document Type is General
                docDetails.TypeId = 1;
                docDetails.Id = Convert.ToInt32(Session[SessionName.DocumentId]);
                docDetails.Notes = _txtNotes.Text;
                fileName = docDetails.FileName;
                #endregion

                if (string.IsNullOrEmpty(fileName))
                {
                    _lblErrorReupload.Text = "Please select document.";
                    return;
                }

                FileInfo FInfo = new FileInfo(fileName);
                // Create a hash of the file
                byte[] LocalHash = FileTransferHash.CreateFileMD5Hash(fileName);

                #region Start Upload File
                try
                {
                    Header = _documentServiceClient.StartExistingDocumentUploadForMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId,
                        // Strip off the path as this is irrelavent
                    FInfo.LastWriteTime, FInfo.Length, LocalHash, docDetails);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                if (Header != null)
                {
                    if (!Header.Success)
                    {
                        _lblErrorReupload.CssClass = "errorMessage";
                        _lblErrorReupload.Text = Header.Message;
                        return;
                    }
                }
                #endregion

                #region Upload Chunk
                long BytesLeft = FInfo.Length;

                // Open the file
                using (FileStream FileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    while (BytesLeft > 0)
                    {
                        byte[] Bytes = new byte[Header.MaxChunkSize];

                        long Position = FileStream.Position;

                        // Read at most MaxChunkSize bytes
                        int ChunkSize = FileStream.Read(Bytes, 0, (int)Math.Min(BytesLeft, Header.MaxChunkSize));

                        // Upload the chunk
                        ReturnValue Result = _documentServiceClient.DocumentUploadChunk(
                            ((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId, Position, ChunkSize, Bytes);

                        if (!Result.Success)
                            throw new Exception("File upload failed: " + Result.Message);

                        BytesLeft -= ChunkSize;
                    }
                }
                #endregion

                #region Upload Complete
                // Tell the service we have finished the upload & Save Document Details
                docReturnValue = _documentServiceClient.DocumentUploadComplete(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId);
                #endregion

                if (docReturnValue != null)
                {
                    if (docReturnValue.Success)
                    {
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }

                        if (docReturnValue.Success)
                        {
                            _lblErrorReupload.Text = "Document information saved successfully.";
                            _lblErrorReupload.CssClass = "successMessage";
                        }
                        else
                        {
                            _lblErrorReupload.Text = docReturnValue.Message;
                            _lblErrorReupload.CssClass = "errorMessage";
                        }
                    }
                    else
                    {
                        _lblErrorReupload.Text = "Document information not saved.<br />" + docReturnValue.Message;
                        _lblErrorReupload.CssClass = "errorMessage";
                    }
                }
            }
            catch (Exception ex)
            {
                _lblErrorReupload.Text = ex.Message;
                _lblErrorReupload.CssClass = "errorMessage";
            }
            finally
            {
                if (_documentServiceClient != null)
                {
                    _documentServiceClient.Close();
                }
                if (DocReUpload != null) { OnDocReUpload(e); }
            }
        }