public WBRecord DeclareNewRecord(WBTaskFeedback feedback, String callingUserLogin, WBDocument document, WBRecord recordToReplace, String replacingAction, WBItem extraMetadata) { WBTerm functionalArea = document.FunctionalArea[0]; WBRecordsType recordsType = document.RecordsType; string fullClassPath = WBUtils.NormalisePath(functionalArea.Name + "/" + recordsType.FullPath); WBLogging.RecordsTypes.HighLevel("Declaring a document to the library with path: " + fullClassPath); string datePath = "NO DATE SET"; string dateForName = "YYYY-MM-DD"; string oldDateFormat = "YYYYMMDD-"; // If nothing else we'll use the time now (which will be roughly the date / time declared as the date for the naming convention: DateTime referenceDate = DateTime.Now; if (document.HasReferenceDate && recordsType.DocumentReferenceDateRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN) { referenceDate = document.ReferenceDate; } else { document.ReferenceDate = referenceDate; } int year = referenceDate.Year; int month = referenceDate.Month; if (month >= 4) { datePath = String.Format("{0}-{1}", year.ToString("D4"), (year + 1).ToString("D4")); } else { datePath = String.Format("{0}-{1}", (year - 1).ToString("D4"), year.ToString("D4")); } dateForName = String.Format("{0}-{1}-{2}", referenceDate.Year.ToString("D4"), referenceDate.Month.ToString("D2"), referenceDate.Day.ToString("D2")); oldDateFormat = String.Format("{0}{1}{2}-", referenceDate.Year.ToString("D4"), referenceDate.Month.ToString("D2"), referenceDate.Day.ToString("D2")); string fullFilingPath = String.Join("/", recordsType.FilingPathForDocument(document).ToArray()); WBLogging.Debug("The original filename is set as: " + document.OriginalFilename); String extension = Path.GetExtension(document.OriginalFilename); String filename = WBUtils.RemoveDisallowedCharactersFromFilename(document.OriginalFilename); String titleForFilename = document[WBColumn.Title].WBxToString(); String referenceID = document.ReferenceID; // We don't want to use a title that is too long: if (String.IsNullOrEmpty(titleForFilename) || titleForFilename.Length > 50) { titleForFilename = ""; } if (String.IsNullOrEmpty(titleForFilename) && String.IsNullOrEmpty(referenceID)) { titleForFilename = Path.GetFileNameWithoutExtension(filename); // Let's now remove the old date format if the date is the same as the one // that is going to be used for the new date format: titleForFilename = titleForFilename.Replace(oldDateFormat, ""); } if (String.IsNullOrEmpty(referenceID)) { filename = "(" + dateForName + ") " + titleForFilename + extension; } else { if (String.IsNullOrEmpty(titleForFilename)) { filename = "(" + dateForName + ") " + referenceID + extension; } else { filename = "(" + dateForName + ") " + referenceID + " - " + titleForFilename + extension; } } filename = WBUtils.RemoveDisallowedCharactersFromFilename(filename); SPContentType classFolderType = null; SPContentType filePartFolderType = null; try { classFolderType = ProtectedMasterLibrary.Site.RootWeb.ContentTypes[WBRecordsType.RECORDS_LIBRARY__CLASS_FOLDER_CONTENT_TYPE]; filePartFolderType = ProtectedMasterLibrary.Site.RootWeb.ContentTypes[WBRecordsType.RECORDS_LIBRARY__FILE_PART_FOLDER_CONTENT_TYPE]; } catch (Exception exception) { WBLogging.RecordsTypes.Unexpected("Couldn't find the class and/or file part folder content types."); throw new Exception("Couldn't find the class and/or file part folder content types.", exception); } if (classFolderType == null) { classFolderType = ProtectedMasterLibrary.Site.RootWeb.ContentTypes[WBRecordsType.RECORDS_LIBRARY__FALL_BACK_FOLDER_CONTENT_TYPE]; } if (filePartFolderType == null) { filePartFolderType = ProtectedMasterLibrary.Site.RootWeb.ContentTypes[WBRecordsType.RECORDS_LIBRARY__FALL_BACK_FOLDER_CONTENT_TYPE]; } SPFolder protectedLibraryRootFolder = ProtectedMasterLibrary.List.RootFolder; protectedLibraryRootFolder.WBxGetOrCreateFolderPath(fullClassPath, classFolderType.Id); SPFolder actualDestinationFolder = protectedLibraryRootFolder.WBxGetOrCreateFolderPath(fullFilingPath, filePartFolderType.Id); /* * // This next bit is all because we've been having problems when new folders had to be created: * if (actualDestinationFolder == null) * { * WBLogging.RecordsTypes.HighLevel("We have to create part of the folder path: " + fullFilingPath); * actualDestinationFolder = protectedLibraryRootFolder.WBxGetOrCreateFolderPath(fullFilingPath, filePartFolderType.Id); * * WBLogging.RecordsTypes.HighLevel("Now we're going to add a dummy first file:"); * * MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("Please ignore this file.")); * SPFile dummyFile = actualDestinationFolder.Files.Add("FirstFile.txt", memoryStream); * * WBLogging.RecordsTypes.HighLevel("Now we're going to try to update the file"); * try * { * dummyFile.Item.Update(); * } * catch (Exception e) * { * WBLogging.RecordsTypes.Unexpected("And exception did occur while updating the dummy item", e); * } * * memoryStream.Dispose(); * * WBLogging.RecordsTypes.HighLevel("Now re-opening the whole ProtectedMasterLibrary object"); * * ProtectedMasterLibrary.ReOpen(); * * WBLogging.RecordsTypes.HighLevel("Have re-opened the whole ProtectedMasterLibrary object - now re-getting the SPFolder:"); * * protectedLibraryRootFolder = ProtectedMasterLibrary.List.RootFolder; * actualDestinationFolder = protectedLibraryRootFolder.WBxGetFolderPath(fullFilingPath); * } */ if (ProtectedMasterLibrary.Web.WBxFileExists(actualDestinationFolder, filename)) { filename = ProtectedMasterLibrary.Web.WBxMakeFilenameUnique(actualDestinationFolder, filename); } SPFile uploadedFile = actualDestinationFolder.Files.Add(filename, document.OpenBinaryStream()); SPListItem uploadedItem = uploadedFile.Item; if (extraMetadata == null) { extraMetadata = new WBItem(); } if (!extraMetadata.IsUsingColumn(WBColumn.DatePublished)) { extraMetadata[WBColumn.DatePublished] = DateTime.Now; } if (!extraMetadata.IsUsingColumn(WBColumn.PublishedBy) && SPContext.Current != null) { extraMetadata[WBColumn.PublishedBy] = SPContext.Current.Web.CurrentUser; } WBRecord newRecord = new WBRecord(this, uploadedItem, uploadedItem.ID.ToString(), document, extraMetadata); if (feedback != null) { String urlToFolder = newRecord.ProtectedMasterRecord.AbsoluteURL.Replace(newRecord.Name, ""); feedback.AddFeedback("Uploaded file to protected, master records library"); feedback.AddFeedback("Master record: <a href='" + newRecord.ProtectedMasterRecord.AbsoluteURL + "' target='_blank'>" + newRecord.ProtectedMasterRecord.AbsoluteURL + "</a>"); feedback.AddFeedback("In folder: <a href='" + urlToFolder + "' target='_blank'>" + urlToFolder + "</a>"); } if (recordToReplace != null) { // OK so actually we need to do the replacement actions with elevated priviledges: //bool digestOK = SPContext.Current.Web.ValidateFormDigest(); //if (digestOK) //{ SPSecurity.RunWithElevatedPrivileges(delegate() { using (WBRecordsManager manager = new WBRecordsManager(callingUserLogin)) { WBRecord elevatedRecordToReplace = manager.Libraries.GetRecordByID(recordToReplace.RecordID); if (replacingAction == WBPublishingProcess.REPLACE_ACTION__ARCHIVE_FROM_IZZI) { elevatedRecordToReplace.LiveOrArchived = WBColumn.LIVE_OR_ARCHIVED__ARCHIVED; elevatedRecordToReplace.RecordSeriesStatus = WBColumn.RECORD_SERIES_STATUS__ARCHIVED; } else { elevatedRecordToReplace.RecordSeriesStatus = WBColumn.RECORD_SERIES_STATUS__RETIRED; } elevatedRecordToReplace.Update(callingUserLogin, "Record was " + elevatedRecordToReplace.RecordSeriesStatus + " because it was replaced through publishing process"); if (feedback != null) { feedback.AddFeedback("Archived record being replaced"); } WBLogging.Debug("WBRecordsLibraries.DeclareNewRecord(): Archived the record being replaced Record ID = " + recordToReplace.RecordID); } }); newRecord.ReplacesRecordID = recordToReplace.RecordID; newRecord.RecordSeriesID = recordToReplace.RecordSeriesID; newRecord.RecordSeriesIssue = "" + (recordToReplace.RecordSeriesIssue.WBxToInt() + 1); newRecord.RecordSeriesStatus = WBColumn.RECORD_SERIES_STATUS__LATEST; } else { newRecord.ReplacesRecordID = null; newRecord.RecordSeriesID = newRecord.RecordID; newRecord.RecordSeriesIssue = "1"; newRecord.RecordSeriesStatus = WBColumn.RECORD_SERIES_STATUS__LATEST; } newRecord.LiveOrArchived = WBColumn.LIVE_OR_ARCHIVED__LIVE; newRecord.UpdateMasterAndCreateCopies(feedback, callingUserLogin); bool beforeForDocument = document.Web.AllowUnsafeUpdates; document.Web.AllowUnsafeUpdates = true; // And now just copy back to the original document any metadata changes: document.MaybeCopyColumns(newRecord.Metadata, WBRecord.DefaultColumnsToCopy); // And let's make sure that the original document is using the work box document content type: if (document.IsSPListItem) { SPContentType workBoxDocumentType = document.Item.ParentList.ContentTypes[WBFarm.Local.WorkBoxDocumentContentTypeName]; if (workBoxDocumentType != null) { document.Item["ContentTypeId"] = workBoxDocumentType.Id; } } document.Update(); // uploadedItem.Update(); // uploadedFile.Update(); bool beforeForUploadedFile = uploadedFile.Web.AllowUnsafeUpdates; uploadedFile.Web.AllowUnsafeUpdates = true; if (uploadedFile.CheckOutType != SPFile.SPCheckOutType.None) { uploadedFile.WBxCheckInAs("Declared new major version of record.", SPCheckinType.MajorCheckIn, callingUserLogin); } else { WBLogging.Migration.Verbose("There was no need to check in file: " + uploadedFile.Name); } uploadedFile.Web.AllowUnsafeUpdates = beforeForUploadedFile; document.Web.AllowUnsafeUpdates = beforeForDocument; return(newRecord); }
public WBDocument GetOrCreateRecordCopy(WBTaskFeedback feedback, WBRecord record) { WBDocument masterRecordDocument = record.ProtectedMasterRecord; WBDocument recordCopyDocument = GetDocumentByID(record.RecordID); if (recordCopyDocument == null) { Web.AllowUnsafeUpdates = true; bool forPublicWeb = true; if (ProtectiveZone == WBRecordsLibrary.PROTECTIVE_ZONE__PROTECTED) { forPublicWeb = false; } List <String> path = masterRecordDocument.Item.WBxGetFolderPath(); SPFolder rootFolder = List.RootFolder; SPFolder actualDestinationFolder = rootFolder.WBxGetOrCreateFolderPath(path, forPublicWeb); string filename = masterRecordDocument.Item.Name; if (forPublicWeb) { filename = WBUtils.PrepareFilenameForPublicWeb(filename); } if (Web.WBxFileExists(actualDestinationFolder, filename)) { throw new Exception("The file being copied already exists in the library - this should never happen!"); } SPFile copiedFile = null; using (Stream stream = masterRecordDocument.OpenBinaryStream()) { copiedFile = actualDestinationFolder.Files.Add(filename, stream); stream.Close(); } recordCopyDocument = new WBDocument(this, copiedFile.Item); recordCopyDocument.MaybeCopyColumns(record.Metadata, WBRecord.DefaultColumnsToCopy); recordCopyDocument.Item.UpdateOverwriteVersion(); // If the new file is checked out by this creation process - then check it in: if (copiedFile.CheckOutType != SPFile.SPCheckOutType.None) { copiedFile.CheckIn("Document published here from a workbox. The original source URL was: " + masterRecordDocument.AbsoluteURL, SPCheckinType.MajorCheckIn); } Web.AllowUnsafeUpdates = false; recordCopyDocument.DebugName = "Copy of " + record.RecordID + " for: " + this.URL; if (feedback != null) { String folderURL = recordCopyDocument.AbsoluteURL.Replace(recordCopyDocument.Name, ""); feedback.Created("Created copy: <a href='" + recordCopyDocument.AbsoluteURL + "' target='_blank'>" + recordCopyDocument.AbsoluteURL + "</a>"); feedback.Created("In folder: <a href='" + folderURL + "' target='_blank'>" + folderURL + "</a>"); } } return(recordCopyDocument); }
public WBPublishingProcess PublishDocument(WBPublishingProcess process) { SPListItem currentItem = process.CurrentItem; WBDocument document = new WBDocument(process.WorkBox, currentItem); WBTaskFeedback feedback = new WBTaskFeedback(WBTaskFeedback.TASK_TYPE__PUBLISH, process.CurrentItemID); feedback.PrettyName = document.Name; process.LastTaskFeedback = feedback; // Just check that the IAO at time of publishing is captured: process.AddExtraMetadata(WBColumn.IAOAtTimeOfPublishing, process.OwningTeamsIAOAtTimeOfPublishing); if (SPContext.Current != null) { process.AddExtraMetadataIfMissing(WBColumn.PublishedBy, SPContext.Current.Web.CurrentUser); } process.AddExtraMetadataIfMissing(WBColumn.DatePublished, DateTime.Now); if (process.ProtectiveZone != WBRecordsType.PROTECTIVE_ZONE__PROTECTED) { // If the document is going on the public or public extranet zones then let's set a review date for 2 years from now: process.AddExtraMetadataIfMissing(WBColumn.ReviewDate, DateTime.Now.AddYears(2)); } if (process.RecordsTypeTaxonomy == null) { WBLogging.Debug("Yeah - the process.RecordsTypeTaxonomy == null !! "); } else { WBLogging.Debug("No - the process.RecordsTypeTaxonomy was NOT null !! "); } try { // Setting the various keys metadata values on the document to be published: WBRecordsType recordsType = new WBRecordsType(process.RecordsTypeTaxonomy, process.RecordsTypeUIControlValue); document.RecordsType = recordsType; document.FunctionalArea = new WBTermCollection <WBTerm>(process.FunctionalAreasTaxonomy, process.FunctionalAreaUIControlValue); document.SubjectTags = new WBTermCollection <WBSubjectTag>(process.SubjectTagsTaxonomy, process.SubjectTagsUIControlValue); document.OwningTeam = new WBTeam(process.TeamsTaxonomy, process.OwningTeamUIControlValue); document.InvolvedTeams = new WBTermCollection <WBTeam>(process.TeamsTaxonomy, process.InvolvedTeamsUIControlValue); document.ProtectiveZone = process.ProtectiveZone; document.Title = process.CurrentShortTitle; WBLogging.Debug("Set document.Title = " + document.Title); document.Update(); document.Reload(); process.WorkBox.GenerateAndSetFilename(recordsType, document); document.Update(); document.Reload(); process.ReloadCurrentItem(); } catch (Exception e) { feedback.Failed("It was not possible to save the metadata to the document before publishing it", e); WBLogging.Debug("It was not possible to save the metadata to the document before publishing it"); process.CurrentItemFailed(); return(process); } WBLogging.Debug("Starting WBRecordsManager.PublishDocument()"); if (!document.IsSPListItem) { feedback.Failed("You can currently only publish SPListItem backed WBDocument objects"); WBLogging.Debug("WBRecordsManager.PublishDocument(): WBDocument wasn't a list item"); process.CurrentItemFailed(); return(process); } WBRecord recordToReplace = null; if (!String.IsNullOrEmpty(process.ToReplaceRecordID)) { WBLogging.Debug("WBRecordsManager.PublishDocument(): Replacing record with id: " + process.ToReplaceRecordID); recordToReplace = Libraries.GetRecordByID(process.ToReplaceRecordID); if (recordToReplace == null) { feedback.Failed("Couldn't find the record that is meant to be replaced with Record ID = " + process.ToReplaceRecordID); WBLogging.Debug("WBRecordsManager.PublishDocument(): Couldn't find the record that is meant to be replaced with Record ID = " + process.ToReplaceRecordID); process.CurrentItemFailed(); return(process); } } WBLogging.Debug("WBRecordsManager.PublishDocument(): About to declare new record"); WBRecord newRecord = null; try { newRecord = Libraries.DeclareNewRecord(feedback, _callingUserLogin, document, recordToReplace, process.ReplaceAction, process.ExtraMetadata); } catch (Exception e) { feedback.AddFeedback("Something went wrong with first attempt to publish document"); feedback.AddException(e); WBLogging.RecordsTypes.Unexpected("Something went wrong with first attempt to publish document", e); } if (newRecord == null) { WBLogging.RecordsTypes.Unexpected("Making a second attempt to publish document"); try { newRecord = Libraries.DeclareNewRecord(feedback, _callingUserLogin, document, recordToReplace, process.ReplaceAction, process.ExtraMetadata); } catch (Exception e) { feedback.Failed("Something went wrong with the second attempt to publish document", e); WBLogging.RecordsTypes.Unexpected("Something went wrong with the second attempt to publish document", e); process.CurrentItemFailed(); return(process); } } WBLogging.Debug("WBRecordsManager.PublishDocument(): Declared new record"); feedback.Success(); process.CurrentItemSucceeded(); if (newRecord != null && newRecord.ProtectiveZone != WBRecordsType.PROTECTIVE_ZONE__PROTECTED) { String documentType = GetDocumentType(newRecord.ProtectedMasterRecord); bool needsEmailToIAONow = (documentType == WBColumn.DOCUMENT_TYPE__SPREADSHEET); bool needsEmailToWebteamNow = !String.IsNullOrEmpty(process.WebPageURL); if (needsEmailToIAONow || needsEmailToWebteamNow) { //WBLogging.Debug("WBRecordsManager.PublishDocument(): process.WebPageURL has been set - so creating or updating alert email"); SPUser publisehdByUser = newRecord.ProtectedMasterRecord[WBColumn.PublishedBy] as SPUser; String publishedByString = "Published by: <unknown>"; if (publisehdByUser != null) { publishedByString = "Published by: " + publisehdByUser.Name; } List <SPUser> approvedByUsers = newRecord.ProtectedMasterRecord[WBColumn.PublishingApprovedBy] as List <SPUser>; String approvedByString = "Approved by: <unknown>"; if (approvedByUsers != null) { approvedByString = "Approved by: " + approvedByUsers.WBxToPrettyString(); } if (needsEmailToWebteamNow && String.IsNullOrEmpty(process.WebteamEmailAlertMessage)) { process.WebteamEmailAlertMessage = @"<p>Dear Webteam,</p> <p>One or more documents have been published to the Public Records Library that should be put on a web page.</p> <p>Web page URL: " + process.WebPageURL + @"</p> <p>Please find details of the published documents below.</p> <p>" + publishedByString + "<br/>\n" + approvedByString + "</p>\n\n<p><b>Published Documents:</b></p>\n\n"; } if (needsEmailToIAONow && String.IsNullOrEmpty(process.IAOEmailAlertMessage)) { process.IAOEmailAlertMessage = @"<p>Dear Information Asset Owner,</p> <p>An Excel document has been published to the Public Records Library by a member of your team.</p> <p>As the responsible Information Asset Owner for this document, please find details of the publication below along with a link.</p> <p>" + publishedByString + "<br/>\n" + approvedByString + "</p>\n\n<p><b>Published Documents:</b></p>\n\n"; } String functionalAreaString = ""; if (newRecord.FunctionalArea.Count > 0) { functionalAreaString = newRecord.FunctionalArea[0].FullPath; } if (needsEmailToWebteamNow) { process.WebteamEmailAlertMessage += "<p><a href=\"" + newRecord.ProtectedMasterRecord.AbsoluteURL + "\">" + newRecord.ProtectedMasterRecord.Name + "</a><br/>\n(" + newRecord.ProtectiveZone + "): " + functionalAreaString + "/" + newRecord.RecordsType.FullPath + "</p>\n"; } if (needsEmailToIAONow) { process.IAOEmailAlertMessage += "<p><a href=\"" + newRecord.ProtectedMasterRecord.AbsoluteURL + "\">" + newRecord.ProtectedMasterRecord.Name + "</a><br/>\nLocation: (" + newRecord.ProtectiveZone + "): " + functionalAreaString + "/" + newRecord.RecordsType.FullPath + "</p>\n"; } if (process.PublishMode != WBPublishingProcess.PUBLISH_MODE__ALL_TOGETHER || !process.HasMoreDocumentsToPublish) { if (needsEmailToWebteamNow) { WBLogging.Debug("WBRecordsManager.PublishDocument(): Webteam Email Alert Message: " + process.WebteamEmailAlertMessage); StringDictionary headers = new StringDictionary(); headers.Add("to", WBFarm.Local.PublicWebsiteTeamEmail); headers.Add("cc", WBFarm.Local.PublicDocumentEmailAlertsTo); headers.Add("content-type", "text/html"); headers.Add("bcc", WBFarm.Local.SendErrorReportEmailsTo); headers.Add("subject", "New documents published for a web page"); WBUtils.SendEmail(Libraries.ProtectedMasterLibrary.Web, headers, process.WebteamEmailAlertMessage); } process.WebteamEmailAlertMessage = null; WBLogging.Debug("WBRecordsManager.PublishDocument(): Webteam Email Alert Message: " + process.WebteamEmailAlertMessage); if (needsEmailToIAONow) { StringDictionary headers = new StringDictionary(); SPUser teamsIAO = Libraries.ProtectedMasterLibrary.Web.WBxEnsureUserOrNull(process.OwningTeamsIAOAtTimeOfPublishing); if (teamsIAO != null) { headers.Add("to", teamsIAO.Email); headers.Add("cc", WBFarm.Local.PublicDocumentEmailAlertsTo); } else { headers.Add("to", WBFarm.Local.PublicDocumentEmailAlertsTo); } headers.Add("content-type", "text/html"); headers.Add("bcc", WBFarm.Local.SendErrorReportEmailsTo); headers.Add("subject", "New Excel documents published for which you are IAO"); WBUtils.SendEmail(Libraries.ProtectedMasterLibrary.Web, headers, process.IAOEmailAlertMessage); process.IAOEmailAlertMessage = null; } } } } else { WBLogging.Debug("WBRecordsManager.PublishDocument(): Either publishing failed - or web page URL was not set"); } return(process); }