/// <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();
                    }
                }
            }
        }
Exemplo n.º 2
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>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void _grdDocFiles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                if (row.Cells[0].FindControl("_linkEdit") != null)
                {
                    int rowId = ((GridViewRow)((LinkButton)(e.CommandSource)).NamingContainer).RowIndex;
                    int docId = Convert.ToInt32(_grdDocFiles.DataKeys[rowId].Values["Id"].ToString());

                    Session[SessionName.DocumentId] = docId;
                    Response.Redirect("~/DocumentManagement/ImportDocument.aspx", true);
                }
            }
            else if (e.CommandName == "reupload")
            {
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                if (row.Cells[0].FindControl("_linkReupload") != null)
                {
                    int rowId = ((GridViewRow)((LinkButton)(e.CommandSource)).NamingContainer).RowIndex;
                    int docId = Convert.ToInt32(_grdDocFiles.DataKeys[rowId].Values["Id"].ToString());

                    Session[SessionName.DocumentId] = docId;
                    Response.Redirect("~/DocumentManagement/ReuploadDocument.aspx", true);
                }
            }
            else if (e.CommandName == "fileDownload")
            {
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                if (row.Cells[0].FindControl("_linkFileDownload") != null)
                {
                    int rowId = ((GridViewRow)((LinkButton)(e.CommandSource)).NamingContainer).RowIndex;
                    int docId = Convert.ToInt32(_grdDocFiles.DataKeys[rowId].Values["Id"].ToString());

                    DocumentServiceClient _documentServiceClient = new DocumentServiceClient();
                    try
                    {
                        Guid ProjectId = DataConstants.DummyGuid;
                        StartDocumentDownloadReturnValue Header;
                        if (!string.IsNullOrEmpty(Convert.ToString(Session[SessionName.ProjectId])))
                        {
                            ProjectId = new Guid(Convert.ToString(Session[SessionName.ProjectId]));
                        }

                        #region Start Download
                        try
                        {
                            Header = _documentServiceClient.StartDocumentDownloadForMatter(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, ProjectId, docId);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        #endregion

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

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

                            long   BytesLeft          = Header.Size;
                            string downloadFolderPath = Path.Combine(Server.MapPath("."), "Download");
                            string FileName           = Path.Combine(downloadFolderPath, Header.FileName);

                            try
                            {
                                #region Download Chunk by Chunk
                                // Open the file
                                using (FileStream FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    while (BytesLeft > 0)
                                    {
                                        // Download a chunk
                                        DownloadChunkReturnValue Chunk = _documentServiceClient.DocumentDownloadChunk(
                                            ((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId, FileStream.Position);

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

                                        // Write the chunk to the file
                                        FileStream.Write(Chunk.Bytes, 0, Chunk.ChunkSize);

                                        BytesLeft -= Chunk.ChunkSize;
                                    }
                                }
                                #endregion

                                #region Download Complete

                                // Tell the service we have finished downloading
                                _documentServiceClient.DocumentDownloadComplete(((LogonReturnValue)Session[SessionName.LogonSettings]).LogonId, Header.TransferId);
                                #endregion

                                // Check the file size
                                if (new FileInfo(FileName).Length != Header.Size)
                                {
                                    throw new Exception("File download failed, file size is wrong");
                                }

                                // Make a hash of the file
                                byte[] LocalHash = FileTransferHash.CreateFileMD5Hash(FileName);

                                // Check the hash matches that from the server
                                if (!FileTransferHash.CheckHash(LocalHash, Header.Hash))
                                {
                                    throw new Exception("File download failed, document checksum does not match");
                                }

                                // Set the file modified date
                                File.SetLastWriteTime(FileName, Header.ModifiedDate);

                                try
                                {
                                    //string jscript = "HideProgress();window.open('DocumentView.aspx?file={0}&path={1}','FileDownload','height=200,width=400,status=no,toolbar=no,menubar=no,left=0,top=0');";
                                    string jscript = "HideProgress(); GetDocument('" + AppFunctions.GetASBaseUrl() + "/Pages/DocMgmt/DocumentView.aspx?file={0}&path={1}');";
                                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
                                                                        Guid.NewGuid().ToString(),
                                                                        string.Format(jscript, HttpUtility.UrlEncode(new FileInfo(FileName).Name), HttpUtility.UrlEncode(FileName)),
                                                                        true);
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                            catch
                            {
                                // Download failed so delete file being downloaded
                                File.Delete(FileName);
                                throw;
                            }
                        }
                    }
                    catch (System.ServiceModel.EndpointNotFoundException)
                    {
                        _lblError.Text     = DataConstants.WSEndPointErrorMessage;
                        _lblError.CssClass = "errorMessage";
                    }
                    catch (Exception ex)
                    {
                        _lblError.CssClass = "errorMessage";
                        _lblError.Text     = ex.Message;
                    }
                    finally
                    {
                        if (_documentServiceClient != null)
                        {
                            if (_documentServiceClient.State != System.ServiceModel.CommunicationState.Faulted)
                            {
                                _documentServiceClient.Close();
                            }
                        }
                    }
                }
            }
        }