コード例 #1
0
        /// <summary>
        ///     WE ARE ADDING A NEW DOC VERSION
        /// </summary>
        /// <param name="document"> The document. </param>
        public AddDocumentVersionModel(Document document, AddEditDocumentVersionDialog view)
        {
            DialogView = view;
            ProgressBarView = view as IProgressBarView;

            mDocument = document;
            mDocumentId = document.Id;
            mCurrentEditMode = EditMode.Add;
            mDocumentVersion = new DocumentVersion { DocumentId = document.Id };
            mDocumentVersion.Date = DateTime.Now;

            OkButtonCommand = new DelegateCommand<object>(OkButtonHandler, CanExecuteOkButtonHandler);
            CancelButtonCommand = new DelegateCommand<object>(CancelButtonHander, CanExecuteOkButtonHandler);
            OpenFileDialogCommand = new DelegateCommand<object>(OpenFileDialogButtonHander, CanExecuteOkButtonHandler);

            mLatestVersion = (from x in document.DocumentVersions orderby x.Version descending select x).Take(1).FirstOrDefault();

            if (mLatestVersion != null)
            {
                Version = mLatestVersion.Version;
                AutoIncrementVersion = false;
                RaisePropertyChanged("AutoIncrementVersion");
            }

            if (DataModelLoaded != null)
            {
                DataModelLoaded();
            }
        }
コード例 #2
0
        public AddEditDocumentVersionDialog(Document document, DocumentVersion documentVersion)
        {
            // Required to initialize variables
            InitializeComponent();

            Title = "Edit Document Version";
            mInEditMode = true;

            mModel = new AddDocumentVersionModel(document, documentVersion);
            mModel.DialogView = this;
            DataContext = mModel;

            mModel.OKButtonClicked += ModelOkButtonClicked;
            mModel.CancelButtonClicked += ModelCancelButtonClicked;
            mModel.TransferCompleted += () =>
                {
                    //busyIndicator.IsBusy = false;
                    this.Close();
                };

            mModel.ErrorOccurred += (message) =>
            {
                //busyIndicator.IsBusy = false;
                List<string> errors = new List<string>();
                errors.Add(message);
                this.ValidationPopup.Show(Utils.BuildValidationResultFromServerErrors("", errors));
            };
        }
コード例 #3
0
 public DocumentVersionPreview(DocumentVersion documentVersion)
 {
     InitializeComponent();
     //busyIndicator.IsBusy = true;
     DocumentVersionPreviewModel model = new DocumentVersionPreviewModel(documentVersion, this);
     this.DataContext = model;
 }
コード例 #4
0
ファイル: DocumentViewModel.cs プロジェクト: barrett2474/CMS2
        public DocumentViewModel(Document document)
        {
            if (document == null) throw new ArgumentNullException("document");

            CompositionInitializer.SatisfyImports(this);

            mDocument = document;

            SaveButtonCommand = new DelegateCommand<object>(SaveButtonHandler, CanExecuteOkButtonHandler);
            RemoveButtonCommand = new DelegateCommand<object>(RemoveButtonHandler, CanExecuteDeleteButtonHandler);

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetDocumentTypesCompleted += cmsWebServiceClient_GetDocumentTypesCompleted;
            cmsWebServiceClient.GetDocumentTypesAsync();

            Areas = new ObservableCollection<Area>(from x in CMS.Cache.Areas where x.IsActive && x.SiteId == CMS.AppSetting.DefaultSiteId select x);

            cmsWebServiceClient.GetDocumentAuthorsCompleted += cmsWebServiceClient_GetDocumentAuthorsCompleted;
            cmsWebServiceClient.GetDocumentAuthorsAsync();

            cmsWebServiceClient.GetDocumentDisciplinesCompleted += (s, e) =>
                {
                    DocumentDisciplines = new ObservableCollection<DocumentDiscipline>(e.Result);
                    mDisciplinesLoaded = true;
                    OnDataSourceLoaded();
                };
            cmsWebServiceClient.GetDocumentDisciplinesAsync();

            cmsWebServiceClient.GetDocumentPurchaseOrdersCompleted += (s, e) =>
            {
                DocumentPurchaseOrders = new ObservableCollection<DocumentPurchaseOrder>(e.Result);
                DocumentPurchaseOrders.Insert(0, new DocumentPurchaseOrder { Name = BLANK, Id = -1 });
                mPurchaseOrdersLoaded = true;
                OnDataSourceLoaded();
            };
            cmsWebServiceClient.GetDocumentPurchaseOrdersAsync();

            if (mDocument.DocumentVersions != null && mDocument.DocumentVersions.Count > 0)
            {
                mSelectedVersion = Document.DocumentVersions[0];
            }
        }
コード例 #5
0
        private void SetPdfViewerDataSource(DocumentVersion documentVersion)
        {
            try
            {
                CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                cmsWebServiceClient.GetDocumentVersionContentCompleted += (s1, e1) =>
                    {
                        //mView.busyIndicator.IsBusy = false;

                        if (!e1.Result.HasErrors)
                        {
                            byte[] bytes = e1.Result.EntityResult;

                            if (bytes.Length == 0)
                            {
                                return;
                            }

                            MemoryStream ms = new MemoryStream(bytes);
                            FixedDocumentStreamSource fdss = new PdfDocumentSource(ms);
                            mView.pdfViewer.DocumentSource = fdss;
                            mView.pdfViewer.Visibility=Visibility.Visible;

                        }
                        else
                        {
                            mView.WarningPopup.Show(Utils.BuildValidationResultFromServerErrors(MESSAGE, e1.Result.ServerErrorMessages));
                        }
                    };
                cmsWebServiceClient.GetDocumentVersionContentAsync(documentVersion);

            }
            catch (Exception ex)
            {
                //mView.busyIndicator.IsBusy = false;
                mView.WarningPopup.Show(Utils.BuildValidationResultFromServerErrors(MESSAGE, new List<string> { ex.Message }));
            }
        }
コード例 #6
0
        private void InsertDocVersion(DocumentVersion documentVersion)
        {
            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
            cmsWebServiceClient.AddDocumentVersionCompleted += (s1, e1) => FinishedDocumentVersionInsert(documentVersion);

            cmsWebServiceClient.AddDocumentVersionAsync(documentVersion, false, CMS.User.Id);
        }
コード例 #7
0
        /// <summary>
        ///   Gets the user.
        ///   Tries with username, then First LastName, then with Id.
        /// </summary>
        /// <param name="userName"> Name of the user. </param>
        /// <param name="documentVersion"> The document version. </param>
        /// <param name="i"> The i. </param>
        /// <returns> </returns>
        private bool GetUserFailed(string userName, DocumentVersion documentVersion, int i)
        {
            if (string.IsNullOrEmpty(userName))
            {
                RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Line '{1}': User Name is empty. Skipping this row.", WorkSheetName, i));
                return true;
            }

            bool found = false;

            using (CmsEntities context = new CmsEntities(5000))
            {

                User user = (from x in context.Users where string.Compare(x.UserName, userName, true, CultureInfo.CurrentCulture) == 0 select x).FirstOrDefault();
                if (user == null)
                {
                    user = (from x in context.Users where string.Compare(x.FirstName + " " + x.LastName, userName, true, CultureInfo.CurrentCulture) == 0 select x).FirstOrDefault();

                    if (user == null)
                    {
                        int result;
                        if (int.TryParse(userName, out result))
                        {
                            user = (from x in context.Users where x.Id == result select x).FirstOrDefault();

                            if (user != null)
                            {
                                found = true;
                            }
                        }
                    }
                    else
                    {
                        found = true;
                    }
                }
                else
                {
                    found = true;
                }

                if (found)
                {
                    documentVersion.UserId = user.Id;
                    return false;
                }

                RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1}': Could not match  User '{2}'. Skipping this row.",
                    WorkSheetName, i + 1, userName));
                return true;
            }
        }
コード例 #8
0
        private bool CheckNotDuplicateFailed(DocumentVersion documentVersion, IEnumerable<DocumentVersion> candidates)
        {
            using (CmsEntities context = new CmsEntities(5000))
            {

                int countDups = (from x in context.DocumentVersions
                                 where x.Version == documentVersion.Version
                                       && x.DocumentId == documentVersion.DocumentId
                                       && x.Native == documentVersion.Native
                                 select x).Count();

                if (countDups > 0)
                {
                    RaiseMessage(CommonUtils.MessageType.Error, string.Format("The Version using the file name '{0}' already exists in the Database for: Document ID '{1}', Version '{2}',  & Native '{3}'.", documentVersion.Filename, documentVersion.DocumentId, documentVersion.Version.ToString(), documentVersion.Native));

                    log.Info(string.Format("raised message MessageType.AlreadyExists for filename '{0}'.", documentVersion.Filename));
                    RaiseMessage(CommonUtils.MessageType.AlreadyExists, documentVersion.Filename);
                    return true;
                }

                countDups = (from x in candidates
                             where x.Version == documentVersion.Version
                                   && x.DocumentId == documentVersion.DocumentId
                                   && x.Native == documentVersion.Native
                             select x).Count();

                if (countDups > 0)
                {
                    RaiseMessage(CommonUtils.MessageType.Error, string.Format("The Canidate Version using the file name '{0}' already exists in the list of candidates to save: Document ID '{1}', Version '{2}', & Native '{3}'.", documentVersion.Filename, documentVersion.DocumentId, documentVersion.Version.ToString(), documentVersion.Native));
                    return true;
                }

                return false;
            }
        }
コード例 #9
0
        public DbOperationResult<DocumentVersion> DeleteDocumentVersion(DocumentVersion documentVersion, int userId)
        {
            DbOperationResult<DocumentVersion> dbOperationResult = new DbOperationResult<DocumentVersion>();

            try
            {
                using (CmsEntities cee = new CmsEntities())
                {
                    DocumentVersion toBeDeleted = (from x in cee.DocumentVersions
                                                   where x.Id == documentVersion.Id &&
                                                         x.Path.ToLower() == documentVersion.Path.ToLower()
                                                   select x).FirstOrDefault();

                    if (toBeDeleted == null)
                    {
                        dbOperationResult.ServerWarningMessages.Add("That File Version did not 'physically' exist. The database record will be cleaned up when Saved.");
                    }
                    else
                    {
                        //First try to delete the file from HDD

                        string settingValue = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.UploadedDocumentsPathRoot);
                        string folderPath = String.Format(@"{0}\{1}", settingValue, toBeDeleted.Path);

                        if (!Directory.Exists(folderPath))
                        {
                            dbOperationResult.ServerWarningMessages.Add("Folder Path does not exist.");
                        }
                        else
                        {
                            string[] files = Directory.GetFiles(folderPath);

                            if (files.Length == 0)
                            {
                                string message = string.Format("No Files exists in Folder Path {0}", folderPath);

                                log.Warning("", message);
                                dbOperationResult.ServerWarningMessages.Add(message);
                            }

                            foreach (var file in Directory.GetFiles(folderPath))
                            {
                                File.Delete(file);
                            }

                            Directory.Delete(folderPath, true);
                        }

                        BuildRevisonHistoryForDeletedDocumentVersion(documentVersion.DocumentId, cee, userId, toBeDeleted);

                        //Delete from database
                        cee.DocumentVersions.Remove(toBeDeleted);
                        cee.SaveChanges();
                        dbOperationResult.ServerInformationMessages.Add("File Version Deleted Sucessfully");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());
                dbOperationResult.ServerErrorMessages = BuildOperationalErrorResults(ex).ServerErrorMessages;
                return dbOperationResult;
            }

            return dbOperationResult;
        }
コード例 #10
0
        private DocumentVersion AddDocumentVersion(DocumentVersion newDocumentVersion, CmsEntities cee, bool autoIncrementVersion)
        {
            IncrementVersionNumber(newDocumentVersion, cee, autoIncrementVersion);

            newDocumentVersion.Date = DateTime.Now;

            //detach user
            //User tempUser = newDocumentVersion.User;
            int userId = newDocumentVersion.UserId;
            newDocumentVersion.User = null;
            newDocumentVersion.UserId = userId;

            int? checkoutUserId = newDocumentVersion.CheckoutByUserId;
            newDocumentVersion.CheckoutByUser = null;
            newDocumentVersion.CheckoutByUserId = checkoutUserId;

            cee.DocumentVersions.Add(newDocumentVersion);

            var documentRevisionHistory = new DocumentRevisionHistory
            {
                Description = string.Format("Document Version {0} Added. Filename = '{1}'", TryConvertToAplphaVerion(newDocumentVersion.Version), newDocumentVersion.Filename),
                Date = DateTime.Now,
                UserId = userId,
                DocumentId = newDocumentVersion.DocumentId,
                IsSystemMessage = true
            };

            var latestPrh = (from x in cee.DocumentRevisionHistories
                             where x.DocumentId == newDocumentVersion.DocumentId
                             select x.Revision).ToList();

            if (latestPrh.Count > 0)
            {
                documentRevisionHistory.Revision = latestPrh.AsQueryable().Max() + VERSIONINCREMENT;
            }
            else
            {
                documentRevisionHistory.Revision = VERSIONINCREMENT;
            }

            cee.DocumentRevisionHistories.Add(documentRevisionHistory);

            return newDocumentVersion;
        }
コード例 #11
0
        private void RaiseTransferComplete(DocumentVersion documentVersion)
        {
            mDocumentVersion = documentVersion;

            //if (!mTransferFailed && DocumentVersionAdded != null)
            //{
            //    DocumentVersionAdded(documentVersion);
            //}

            if (TransferCompleted != null)
            {
                TransferCompleted();
            }
        }
コード例 #12
0
        private void GetDocumentVersionCompleted(object sender, GetDocumentVersionCompletedEventArgs e)
        {
            mDocumentVersion = e.Result;

            RaisePropertyChanged("CurrentLocation");
            RaisePropertyChanged("CheckoutUser");
            RaisePropertyChanged("CheckoutDate");
        }
コード例 #13
0
        public void TransferDroppedFiles(IProgressBarView view, int documentId, IEnumerable<FileInfo> fileInfos)
        {
            //we need to control the version increment on the client becuase of the async nature of WCF.

            ProgressBarView = view;

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetLatestDocumentVersionsCompleted
                += (s, e) =>
                    {
                        List<DocumentVersion> latest = e.Result;

                        decimal latestVersion;

                        if (latest != null && latest.Count == 1)
                        {
                            latestVersion = latest[0].Version;
                        }
                        else
                        {
                            latestVersion = new decimal(0.99); //will increment to 1.000
                        }

                        //start loop
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            if (latestVersion < 0)
                            {
                                latestVersion += mAlphaIncrediment;

                                if (latestVersion == 0)
                                {
                                    //int the rare case we are incrementing from a 'Z' version, we would end up as 0.  so if so, we will bump it up to 0.01.
                                    latestVersion = new decimal(0.00) + mDeciamlIncrediment;
                                }

                            }
                            else
                            {
                                latestVersion += mDeciamlIncrediment;
                            }

                            mDocumentVersion = new DocumentVersion
                               {
                                   Path = Guid.NewGuid().ToString(),
                                   DocumentId = documentId,
                                   UserId = CMS.User.Id,
                                   Date = DateTime.Now,
                                   Filename = fileInfo.Name,
                                   Version = latestVersion
                               };

                            mFileInfo = fileInfo;

                            //TransferFile(fileInfo, documentVersion);
                            DoInsert();
                        } //end loop
                    };

            cmsWebServiceClient.GetLatestDocumentVersionsAsync(new List<int> { documentId });
        }
コード例 #14
0
 public DocumentVersionPreviewModel(DocumentVersion documentVersion, DocumentVersionPreview view)
 {
     mView = view;
     SetPdfViewerDataSource(documentVersion);
 }
コード例 #15
0
        public DbOperationResult<DocumentVersion> SaveDocumentVersion(DocumentVersion documentVersion, int userId)
        {
            DbOperationResult<DocumentVersion> result = new DbOperationResult<DocumentVersion>();

            using (CmsEntities cee = new CmsEntities())
            {
                DocumentVersion originalObject = (from x in cee.DocumentVersions where x.Id == documentVersion.Id select x).FirstOrDefault();

                if (originalObject != null)
                {

                    cee.Entry(originalObject).CurrentValues.SetValues(documentVersion);

                    if (documentVersion.AutoIncrement)
                    {
                        IncrementVersionNumber(originalObject, cee, true);
                        originalObject.AutoIncrement = false; // keeping this false so next time the contro is loaded it is re-set to false by default. the property has done it's job already.
                    }

                    cee.SaveChanges();

                    result.EntityResult = (from x in cee.DocumentVersions.Include("User") where x.Id == documentVersion.Id select x).FirstOrDefault();
                }
            }

            return result;
        }
コード例 #16
0
        private static void BuildRevisonHistoryForDeletedDocumentVersion(int documentId, CmsEntities cee, int userId, DocumentVersion documentVersion)
        {
            DocumentRevisionHistory rh = new DocumentRevisionHistory();

            rh.Description = string.Format("Document Version {0} Deleted. Filename = '{1}'", TryConvertToAplphaVerion(documentVersion.Version), documentVersion.Filename );

            rh.DocumentId = documentId;
            rh.Date = DateTime.Now;
            rh.UserId = userId;
            rh.IsSystemMessage = true;

            var latestPrh = (from x in cee.DocumentRevisionHistories
                             where x.DocumentId == documentId
                             select x.Revision).ToList();

            if (latestPrh.Count > 0)
            {
                rh.Revision = latestPrh.AsQueryable().Max() + VERSIONINCREMENT;
            }
            else
            {
                rh.Revision = VERSIONINCREMENT;
            }
            cee.DocumentRevisionHistories.Add(rh);
        }
コード例 #17
0
        private bool TransferFile(FileInfo fileInfo, DocumentVersion documentVersion)
        {
            long fileSize = fileInfo.Length;

            ProgressBarView.ProgressBar.Maximum = fileSize;
            ProgressBarView.ProgressBar.Minimum = 0;
            ProgressBarView.ProgressBar.Visibility = Visibility.Visible;
            ProgressBarView.ProgressBar.Value = 0;

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
            try
            {
                Stream stream = fileInfo.OpenRead();

                if (stream.Length > int.MaxValue)
                {
                    var errors = Utils.BuildValidationResultFromServerErrors("Upload Failed.", new List<string> { string.Format("File [{0}] can not be bigger than 2GB.", fileInfo.Name) });

                    if (DialogView != null)
                    {
                        DialogView.ValidationPopup.Show(errors);
                        RaiseTransferFailed();
                        return false;
                    }

                    mDocumentVersionsControl.ValidationPopup.Show(errors);
                    RaiseTransferFailed();
                    return false;
                }

                int transferChunkSize = Utils.GetTransferChunkSize(stream);
                CommonUploadFile file = new CommonUploadFile { Name = fileInfo.Name, Size = stream.Length, Path = documentVersion.Path };

                if (stream.Position > -1 && stream.Position < stream.Length)
                {
                    int chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);

                    byte[] fileBytes = new byte[chunkSize];
                    stream.Read(fileBytes, 0, chunkSize);

                    cmsWebServiceClient.UploadFileCompleted +=
                        (s1, e1) =>
                        {
                            if (stream.Position > -1 && stream.Position < stream.Length)
                            {
                                chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);

                                fileBytes = new byte[chunkSize];
                                stream.Read(fileBytes, 0, chunkSize);
                                cmsWebServiceClient.UploadFileAsync(file.Name, fileBytes, CMS.AppSetting.DocumentsRootUrl, file.Path, true);

                                if (DialogView != null)
                                {
                                    DialogView.RadProgressBar1.Value = DialogView.RadProgressBar1.Value + chunkSize;
                                }

                                ProgressBarView.ProgressBar.Value = ProgressBarView.ProgressBar.Value + chunkSize;

                            }
                            else
                            {
                                //Close the stream when all files are uploaded
                                stream.Close();

                                if (e1.Result.EntityResult.WrittenByteArraySize != fileSize)
                                {
                                    Dictionary<string, List<ValidationResult>> errors = Utils.BuildValidationResultFromServerErrors("Upload Failed.", new List<string> { "There was a loss of information while attempting to transfer the file.  Please try again." });
                                    if (DialogView != null)
                                    {
                                        DialogView.ValidationPopup.Show(errors);
                                        RaiseTransferFailed();
                                        return;
                                    }

                                    mDocumentVersionsControl.ValidationPopup.Show(errors);
                                    RaiseTransferFailed();
                                    return;
                                }

                                RaiseTransferComplete(documentVersion);

                                ProgressBarView.ProgressBar.Visibility = Visibility.Collapsed;

                            }
                        };

                    cmsWebServiceClient.UploadFileAsync(file.Name, fileBytes, CMS.AppSetting.DocumentsRootUrl, file.Path, false);
                }
            }
            catch (IOException)
            {
                OnErrorOccurred(string.Format("Cannot upload the file '{0}' because it is currently open. Please close the file and try again", fileInfo.Name));
                return false;

            }
            catch (SecurityException)
            {
                OnErrorOccurred(string.Format("Cannot upload the file '{0}' because it is currently open. Please close the file and try again", fileInfo.Name));
                return false;
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ex.Message);
                return false;
            }

            return true;
        }
コード例 #18
0
        private void IncrementVersionNumber(DocumentVersion newDocumentVersion, CmsEntities cee, bool autoIncrementVersion)
        {
            List<decimal> latestVersions = (from x in cee.DocumentVersions
                                            where x.DocumentId == newDocumentVersion.DocumentId
                                            select x.Version).ToList();

            decimal max = 0;

            if (latestVersions.Count > 0)
            {
                max = latestVersions.AsQueryable().Max();
            }

            if (newDocumentVersion.Version >= 0)
            {
                const decimal incrediment = 0.01m; //was changed from 3 decimal places.

                if (autoIncrementVersion)
                {
                    newDocumentVersion.Version = max + incrediment;
                }
            }
            else
            {
                const decimal alphaIncrediment = 1.00m; //was changed from 3 decimal places.
                if (autoIncrementVersion)
                {
                    newDocumentVersion.Version = max + alphaIncrediment;
                }
            }

            if (newDocumentVersion.Version < max)
            {
                log.Info(string.Format("Version number passed '{0}' in is less than current max revision number '{1}'.", newDocumentVersion.Version, max));
            }
        }
コード例 #19
0
        /// <summary>
        ///     WE ARE EDITING AN EXISTING DOC VERSION
        /// </summary>
        /// <param name="document"> The document. </param>
        /// <param name="documentVersion"> The document version. </param>
        public AddDocumentVersionModel(Document document, DocumentVersion documentVersion)
        {
            mDocument = document;
            mDocumentId = documentVersion.DocumentId;
            mCurrentEditMode = EditMode.Edit;
            mDocumentVersion = documentVersion;
            mOriginalVersionNumber = documentVersion.Version;

            mLatestVersion = (from x in document.DocumentVersions orderby x.Version descending select x).Take(1).FirstOrDefault();

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetDocumentVersionCompleted += GetDocumentVersionCompleted;
            cmsWebServiceClient.GetDocumentVersionAsync(documentVersion.Id);

            OkButtonCommand = new DelegateCommand<object>(OkButtonHandler, CanExecuteOkButtonHandler);
            CancelButtonCommand = new DelegateCommand<object>(CancelButtonHander, CanExecuteOkButtonHandler);
            OpenFileDialogCommand = new DelegateCommand<object>(OpenFileDialogButtonHander, CanExecuteOkButtonHandler);

            if (DataModelLoaded != null)
            {
                DataModelLoaded();
            }
        }
コード例 #20
0
        public DbOperationResult<byte[]> GetDocumentVersionContent(DocumentVersion documentVersion)
        {
            DbOperationResult<byte[]> result = new DbOperationResult<byte[]>();

            if (documentVersion == null)
            {
                documentVersion = new DocumentVersion();
                documentVersion.Filename = "NO.VERSIONS.EXIST.pdf";
                documentVersion.Path = string.Empty;
            }

            string settingValue = GetAppSettingValue(CommonUtils.AppSettingKey.UploadedDocumentsPathRoot);

            if (string.IsNullOrEmpty(settingValue))
            {
                result.ServerErrorMessages.Add("Could not find app setting for UploadedDocumentsPathRoot");
                return result;
            }

            string fullFilePath = Path.Combine(settingValue, documentVersion.Path, documentVersion.Filename);

            if (!File.Exists(fullFilePath))
            {
                documentVersion = new DocumentVersion();
                documentVersion.Filename = "FILE.NOT.FOUND.pdf";
                documentVersion.Path = string.Empty;
                fullFilePath = Path.Combine(settingValue, documentVersion.Path, documentVersion.Filename);
            }

            byte[] fileContent = File.ReadAllBytes(fullFilePath);

            if (fileContent.Length == 0)
            {
                result.ServerErrorMessages.Add("file contents were empty. byte array is zero length.");
                return result;
            }

            result.ServerInformationMessages.Add(documentVersion.Filename);
            result.EntityResult = fileContent;
            return result;
        }
コード例 #21
0
ファイル: ImporterPlugin.cs プロジェクト: barrett2474/CMS2
            internal static IImporter CreateImporter(ImportFileMetaData metaData, DocumentVersion documentVersion = null, BaseAttachmentDto attachmentDto = null)
            {
                switch (metaData.ImportType)
                {
                    case CommonUtils.ImportType.CreateRelatedDocuments:
                        return new RelatedDocumentImporter(metaData);

                    case CommonUtils.ImportType.CreateIssue:
                    case CommonUtils.ImportType.UpdateIssue:
                        return new IssueImporter(metaData);
                    case CommonUtils.ImportType.CreateMilestones:
                        return new MilestoneImporter(metaData);

                    case CommonUtils.ImportType.CreateUpdateFinancial:
                        return new FinancialImporter(metaData);

                    case CommonUtils.ImportType.CreateIssueReferences:
                    case CommonUtils.ImportType.UpdateIssueReferences:
                        return new IssueSystemReferencesImporter(metaData);

                    case CommonUtils.ImportType.Cji3:
                        return new Cji3Importer(metaData);

                    case CommonUtils.ImportType.Cji5:
                        return new Cji5Importer(metaData);

                    case CommonUtils.ImportType.CreatePipe:
                    case CommonUtils.ImportType.UpdatePipe:
                        return new PipeImporter(metaData);
                    case CommonUtils.ImportType.CreatePipeComponent:
                    case CommonUtils.ImportType.UpdatePipeComponent:
                        return new PipeComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateMechanical:
                    case CommonUtils.ImportType.UpdateMechanical:
                        return new MechanicalImporter(metaData);
                    case CommonUtils.ImportType.CreateMechanicalComponent:
                    case CommonUtils.ImportType.UpdateMechanicalComponent:
                        return new MechanicalComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateElectrical:
                    case CommonUtils.ImportType.UpdateElectrical:
                        return new ElectricalImporter(metaData);
                    case CommonUtils.ImportType.CreateElectricalComponent:
                    case CommonUtils.ImportType.UpdateElectricalComponent:
                        return new ElectricalComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateInstrument:
                    case CommonUtils.ImportType.UpdateInstrument:
                        return new InstrumentImporter(metaData);
                    case CommonUtils.ImportType.CreateInstrumentComponent:
                    case CommonUtils.ImportType.UpdateInstrumentComponent:
                        return new InstrumentComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateCalibrationComponent:
                    case CommonUtils.ImportType.UpdateCalibrationComponent:
                        return new CalibrationComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateMobilePlant:
                    case CommonUtils.ImportType.UpdateMobilePlant:
                        return new MobilePlantImporter(metaData);

                    case CommonUtils.ImportType.CreateMobilePlantComponent:
                    case CommonUtils.ImportType.UpdateMobilePlantComponent:
                        return new MobilePlantComponentImporter(metaData);

                    case CommonUtils.ImportType.CreateDocument:
                    case CommonUtils.ImportType.UpdateDocument:
                        return new DocumentImporter(metaData);

                    case CommonUtils.ImportType.CreateDocumentVersionStep1:
                    case CommonUtils.ImportType.UpdateDocumentVersion: //we don't need the file
                        return new DocumentVersionImporter(metaData);

                    case CommonUtils.ImportType.CreateDocumentLocations:
                        return new DocumentLocationImporter(metaData);

                    case CommonUtils.ImportType.CreateAttachmentDtoStep1:
                    case CommonUtils.ImportType.UpdateAttachment: //we don't need the file
                        return new AttachmentImporter(metaData);

                    case CommonUtils.ImportType.LinkRelatedEquipmentDocument:
                        return new DocumentEquipmentImporter(metaData);

                    //CONTROL SYSTEM
                    case CommonUtils.ImportType.CreateControlsSystems:
                    case CommonUtils.ImportType.UpdateControlSystems:
                        return new ControlSystemImporter(metaData);
                    case CommonUtils.ImportType.CreateControlComponents:
                    case CommonUtils.ImportType.UpdateControlComponents:
                        return new ControlComponentImporter(metaData);
                    case CommonUtils.ImportType.CreateEngineeringProperties:
                    case CommonUtils.ImportType.UpdateEngineeringProperties:
                        return new EngineeringPropertiesImporter(metaData);
                    case CommonUtils.ImportType.CreateTuningProperties:
                    case CommonUtils.ImportType.UpdateTuningProperties:
                        return new TuningPropertiesImporter(metaData);
                    case CommonUtils.ImportType.CreateInterlocks:
                    case CommonUtils.ImportType.UpdateInterlocks:
                        return new InterlockImporter(metaData);
                    case CommonUtils.ImportType.CreateInterlockRisks:
                    case CommonUtils.ImportType.UpdateInterlockRisks:
                        return new InterlockRiskImporter(metaData);

                    //ALARMS
                    case CommonUtils.ImportType.CreateAlarms:
                    case CommonUtils.ImportType.UpdateAlarms:
                        return new AlarmImporter(metaData);

                    //Testing
                    case CommonUtils.ImportType.CreateComponentTestingProperties:
                    case CommonUtils.ImportType.UpdateComponentTestingProperties:
                        return new ComponentTestingPropertiesImporter(metaData);

                }

                return null;
            }
コード例 #22
0
        private List<DocumentVersion> BuildStep1Result(IList<DocumentVersionDataAdapter> importData)
        {
            List<DocumentVersion> candidates = new List<DocumentVersion>();

            if (importData.Count == 0)
            {
                RaiseMessage(CommonUtils.MessageType.Warning, NoDataFoundForWorkSheetMessage());
                log.Debug(NoDataFoundForWorkSheetMessage());
                return candidates;
            }

            log.Debug(string.Format("entering BuildStep1Result to build {0} candidates", importData.Count));

            for (int i = 0; i < importData.Count; i++)
            {
                DocumentVersion documentVersion = new DocumentVersion();

                DocumentVersionDataAdapter adapter = importData[i];

                if (!adapter.IsValid())
                {
                    foreach (string message in adapter.ErrorMessages)
                    {
                        RaiseMessage(CommonUtils.MessageType.Error, message);
                        log.Debug(message);
                    }
                    continue;
                }

                //check for blanks
                if (string.IsNullOrEmpty(adapter.DocumentName))
                {
                    mSkipBlankNameCount++;

                    if (mSkipBlankNameCount > 3)
                    {
                        string msg = string.Format("Step 1: Aborted Sheet - Too Many Blank Names. '{0}'.", WorkSheetName);
                        RaiseMessage(CommonUtils.MessageType.Error, msg);
                        log.Debug(msg);
                        return candidates;
                    }

                    continue;
                }

                if (GetDocumentFailed(adapter.DocumentName, documentVersion, i))
                {
                    string msg = string.Format("Step 1: Failed to get Document {0} for the Version: ' {1} '.", adapter.DocumentName, adapter.Version.ToString());
                    log.Debug(msg);
                    RaiseMessage(CommonUtils.MessageType.Error, msg);
                    continue;
                }

                if (adapter.User == mUserNamePreviouslyChecked && mUserIdOfUserNamePreviouslyChecked != 0)
                {
                    documentVersion.UserId = mUserIdOfUserNamePreviouslyChecked;
                }
                else
                {
                    if (GetUserFailed(adapter.User, documentVersion, i))
                    {
                        string msg = string.Format("failed  to Get User with username '{0}'.", adapter.User);
                        RaiseMessage(CommonUtils.MessageType.Error, msg);
                        log.Debug(msg);
                        return candidates;
                    }
                    else
                    {
                        mUserNamePreviouslyChecked = adapter.User;
                        mUserIdOfUserNamePreviouslyChecked = documentVersion.UserId;
                    }
                }

                documentVersion.Filename = adapter.FileName;
                documentVersion.Version = adapter.Version;
                documentVersion.Date = adapter.Date;
                documentVersion.Description = adapter.Description;
                documentVersion.ApprovedBy = adapter.ApprovedBy;

                documentVersion.Native = adapter.Native;

                if (MetaData.ImportType == CommonUtils.ImportType.CreateDocumentVersionStep1)
                {
                    if (CheckNotDuplicateFailed(documentVersion, candidates))
                    {
                        continue;
                    }
                }

                candidates.Add(documentVersion);

            }

            if (candidates.Count == 0)
            {
                string msg = string.Format("Step 1: No  Document Versions were added from from worksheet {0}.", WorkSheetName);
                log.Debug(msg);
                RaiseMessage(CommonUtils.MessageType.Warning, msg);
            }

            return candidates;
        }
コード例 #23
0
ファイル: DocumentUploader.cs プロジェクト: barrett2474/CMS2
        private bool BuildFilePathAndCopyFile(BackgroundWorker worker, DocumentVersion canidateVersion, FileInfo[] files, string settingValue, int count)
        {
            //NEW PATH
            string guidFolder = Guid.NewGuid().ToString();
            canidateVersion.Path = guidFolder;
            string fullPath = Path.Combine(settingValue, guidFolder, canidateVersion.Filename);

            if (CopyFile(worker, canidateVersion, files, settingValue, guidFolder, fullPath))
            {
                mImportCount++;

                FileProcessedState fileProcessedState = new FileProcessedState { ProgressCount = string.Format("{0}/{1}", mImportCount, count) };
                worker.ReportProgress(mImportCount / count, fileProcessedState);

                return true;
            }

            return false;
        }
コード例 #24
0
        private bool GetDocumentFailed(string docName, DocumentVersion documentVersion, int i)
        {
            if (string.IsNullOrEmpty(docName))
            {
                RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Line '{1}': documentVersion name is empty. Skipping this row.", WorkSheetName, i));
                return true;
            }

            using (CmsEntities context = new CmsEntities(5000))
            {
                Document document = (from x in context.Documents where string.Compare(x.Name, docName, true, CultureInfo.CurrentCulture) == 0 select x).FirstOrDefault();
                if (document == null)
                {
                    RaiseMessage(CommonUtils.MessageType.Error, string.Format("WorkSheet '{0}' Row '{1}': Could not match documentVersion name '{2}'. Skipping this row.",
                        WorkSheetName, i, docName));
                    return true;
                }

                documentVersion.DocumentId = document.Id;
                return false;
            }
        }
コード例 #25
0
ファイル: DocumentUploader.cs プロジェクト: barrett2474/CMS2
        private bool CopyFile(BackgroundWorker worker, DocumentVersion documentVersion, FileInfo[] files, string settingValue, string guidFolder, string fullFilePath)
        {
            FileInfo fi;
            if (documentVersion.Native)
            {
                DocumentVersion version = documentVersion;
                fi = (from x in files
                      where
                          x.Name.Equals(version.Filename, StringComparison.CurrentCultureIgnoreCase)
                          && !x.Extension.Equals(PDF, StringComparison.CurrentCultureIgnoreCase)
                      select x).FirstOrDefault();
            }
            else
            {
                fi = (from x in files
                      where
                          x.Name.Equals(documentVersion.Filename, StringComparison.CurrentCultureIgnoreCase)
                          && x.Extension.Equals(PDF, StringComparison.CurrentCultureIgnoreCase)
                      select x).FirstOrDefault();
            }

            if (fi == null)
            {
                worker.ReportProgress(0, new FileState { Message = (string.Format("File '{0}' not found. Skipping...", documentVersion.Filename)), Type = Common.ImporterMessageType.Error });
                return false;
            }

            if (fi.Length == 0)
            {
                worker.ReportProgress(0, new FileState { Message = (string.Format("File '{0}' has zero file size. Skipping...", fi.Name)), Type = Common.ImporterMessageType.Error });
                return false;
            }

            if (fi.Length > int.MaxValue)
            {
                worker.ReportProgress(0, new FileState { Message = (string.Format("File {0} is larger than max of 2GB. Skipping...", fi.Name)), Type = Common.ImporterMessageType.Error });
                return false;
            }

            if (!Directory.Exists(Path.Combine(settingValue, guidFolder)))
            {
                Directory.CreateDirectory(Path.Combine(settingValue, guidFolder));
            }

            File.Copy(fi.FullName, fullFilePath);

            mMovedFiles.Add(fi);

            if (File.Exists(fullFilePath))
            {
                File.Delete(fullFilePath);
            }

            return true;
        }
コード例 #26
0
        private void TransferSingleDocumentVersionFile(FileInfo fileInfo, DocumentVersion documentVersion)
        {
            long sentFileSize = fileInfo.Length;
            long writtenFileSize = 0;

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
            try
            {
                Stream stream = fileInfo.OpenRead();

                if (stream.Length > int.MaxValue)
                {
                    DbImportResult r = new DbImportResult();
                    r.ErrorMessages = new List<string>();
                    r.ErrorMessages.Add(string.Format("File [{0}] can not be bigger than 2GB. ", fileInfo.Name));
                    FileTransferFailed(r);
                    return;
                }

                int transferChunkSize = Utils.GetTransferChunkSize(stream);
                CommonUploadFile file = new CommonUploadFile { Name = fileInfo.Name, Size = stream.Length, Path = documentVersion.Path };

                if (stream.Position > -1 && stream.Position < stream.Length)
                {
                    int chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);

                    byte[] fileBytes = new byte[chunkSize];
                    stream.Read(fileBytes, 0, chunkSize);

                    cmsWebServiceClient.UploadFileCompleted +=
                        (s1, e1) =>
                        {
                            if (stream.Position > -1 && stream.Position < stream.Length)
                            {
                                chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);

                                fileBytes = new byte[chunkSize];
                                stream.Read(fileBytes, 0, chunkSize);
                                writtenFileSize += e1.Result.EntityResult.WrittenByteArraySize;

                                cmsWebServiceClient.UploadFileAsync(file.Name, fileBytes, CMS.AppSetting.DocumentsRootUrl, file.Path, true);
                            }
                            else
                            {
                                //Close the stream when all files are uploaded
                                stream.Close();

                                writtenFileSize += e1.Result.EntityResult.WrittenByteArraySize;

                                if (writtenFileSize < sentFileSize)
                                {
                                    DbImportResult r = new DbImportResult();
                                    r.ErrorMessages = new List<string>();
                                    r.ErrorMessages.Add("There was a loss of information while attempting to transfer the file.  Please try again. ");
                                    FileTransferFailed(r);
                                    return;
                                }

                                BeginDocumentVersionInsert(documentVersion);
                            }
                        };

                    cmsWebServiceClient.UploadFileAsync(file.Name, fileBytes, CMS.AppSetting.DocumentsRootUrl, file.Path, false);
                }
            }
            catch (Exception ex)
            {
                mGlobalImportResult.ErrorMessages.Add(ex.Message);
            }
        }
コード例 #27
0
        public DocumentVersion AddDocumentVersion(DocumentVersion newDocumentVersion, bool autoIncrementVersion, int userId)
        {
            using (CmsEntities cee = new CmsEntities())
            {
                newDocumentVersion = AddDocumentVersion(newDocumentVersion, cee, autoIncrementVersion);
                cee.SaveChanges();

                NotifyFavouriteSaved(new NotificationInformation
                {
                    DocumentId = newDocumentVersion.DocumentId,
                    DocumentVersionId = newDocumentVersion.Id,
                    FavouriteType = CommonUtils.FavouriteType.Document, //don't use doc version fav type
                    SavedByUserId = userId
                });

                DocumentVersion version = (from x in cee.DocumentVersions.Include("User") where x.Id == newDocumentVersion.Id select x).FirstOrDefault();
                return version;
            }
        }
コード例 #28
0
ファイル: MainPage.xaml.cs プロジェクト: barrett2474/CMS2
        private void OpenDocumentVersionPreview(DocumentVersion documentVersion)
        {
            const string HEADERLABEL = "Document Version Preview";

            bool found = false;
            RadTabItem foundTabItem = null;

            foreach (RadTabItem tabItem in MainTabControl.Items)
            {
                var content = tabItem.Content as DocumentVersionPreview;
                if (content != null)
                {
                    foundTabItem = tabItem;
                    found = true;
                    break;
                }
            }

            if (found)
            {
                foundTabItem.Content = new DocumentVersionPreview(documentVersion);
            }
            else
            {
                var ti = new RadTabItem();
                var th = new TabHeader(ti, this);
                th.headerLabel.Content = string.Format(HEADERLABEL);
                ti.Header = th;
                ti.Content = new DocumentVersionPreview(documentVersion); //
                ti.IsSelected = true;
                ti.DropDownContent = th.headerLabel.Content.ToString();
                MainTabControl.Items.Add(ti);
            }
        }
コード例 #29
0
 private void ModelOkButtonClicked(DocumentVersion documentVersion)
 {
     //busyIndicator.IsBusy = true;
     if (OKButtonClicked != null)
     {
         OKButtonClicked(documentVersion, mInEditMode);
         OKButton.IsEnabled = false;
         CancelButton.IsEnabled = false;
     }
 }