/// <summary> /// Create a custom router for a web content organizer /// </summary> /// <param name="web">The web</param> /// <param name="routerName">Router name</param> /// <param name="routerAssemblyName">Router assembly name</param> /// <param name="routerClassName">Router class name in the assembly</param> public void CreateCustomRouter(SPWeb web, string routerName, string routerAssemblyName, string routerClassName) { var contentOrganizer = new EcmDocumentRoutingWeb(web); this.DeleteCustomRouter(web, routerName); contentOrganizer.AddCustomRouter(routerName, routerAssemblyName, routerClassName); }
/// <summary> /// Adds the new rule. /// </summary> /// <param name="url">The URL.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="libraryName">The library.</param> /// <param name="relativeFolderUrl">The relative folder URL.</param> /// <param name="contentTypeName">Name of the content type.</param> /// <param name="conditionFieldId">The condition field id.</param> /// <param name="conditionFieldInternalName">Name of the condition field internal.</param> /// <param name="conditionFieldTitle">The condition field title.</param> /// <param name="conditionOperator">The condition operator.</param> /// <param name="conditionFieldValue">The condition field value.</param> public void AddNewRule( string url, string name, string description, string libraryName, string relativeFolderUrl, string contentTypeName, string conditionFieldId, string conditionFieldInternalName, string conditionFieldTitle, string conditionOperator, string conditionFieldValue) { List <EcmDocumentRouterRule> ruleList = new List <EcmDocumentRouterRule>(); // Build the conditionSettings XML from the constants above. string conditionXml = String.Format( @"<Condition Column=""{0}|{1}|{2}"" Operator=""{3}"" Value=""{4}"" />", conditionFieldId, conditionFieldInternalName, conditionFieldTitle, conditionOperator, conditionFieldValue); string conditionsXml = String.Format("<Conditions>{0}</Conditions>", conditionXml); using (SPSite spSite = new SPSite(url)) using (SPWeb spWeb = spSite.OpenWeb()) { EcmDocumentRoutingWeb edrw = new EcmDocumentRoutingWeb(spWeb); SPContentType ruleContentType = spWeb.ContentTypes[contentTypeName]; SPList ruleLibrary = spWeb.Lists[libraryName]; if (ruleLibrary.ContentTypes.BestMatch(ruleContentType.Id) == null) { throw new ArgumentException(String.Format("Ensure that the library {0} contains content type {1} before creating the rule", libraryName, contentTypeName)); } // Create a blank rule. Configure the rule.. EcmDocumentRouterRule edrRule = new EcmDocumentRouterRule(spWeb) { Name = name, Description = description, ContentTypeString = ruleContentType.Name, RouteToExternalLocation = false, Priority = "5", TargetPath = spWeb.GetFolder(url + relativeFolderUrl).ServerRelativeUrl, ConditionsString = conditionsXml }; // Update the rule and commit changes. edrRule.Update(); ruleList.Add(edrRule); } }
/// <summary>Initializes a new instance of the <see cref="RecordLibraryManager"/> class.</summary> /// <param name="url">The URL.</param> public RecordLibraryManager(string url) { using (SPSite spSite = new SPSite(url)) using (SPWeb spWeb = spSite.OpenWeb()) { spWeb.AllowUnsafeUpdates = true; EcmDocumentRoutingWeb edrw = new EcmDocumentRoutingWeb(spWeb); this.DropOffLibUrl = edrw.DropOffZoneUrl; this.DropOffLibTitle = edrw.DropOffZone.Title; this.DropOffLibrary = spWeb.Lists.TryGetList(edrw.DropOffZone.Title); this.EnabledLibraries = this.ScreenLibraries(spWeb); } }
/// <summary> /// Delete a custom rule /// </summary> /// <param name="web">the web</param> /// <param name="ruleName">The rule name</param> public void DeleteCustomRule(SPWeb web, string ruleName) { var routingWeb = new EcmDocumentRoutingWeb(web); var organizerRules = routingWeb.RoutingRuleCollection; var ruleToDelete = (from EcmDocumentRouterRule rule in organizerRules where rule.Name.Equals(ruleName, StringComparison.Ordinal) select rule).FirstOrDefault(); if (ruleToDelete != null) { ruleToDelete.Delete(); } }
/// <summary> /// Registers the custom document router. /// </summary> /// <param name="absoluteSiteURL">The absolute site URL.</param> /// <param name="customRouterName">Name of the custom router.</param> /// <param name="customRouterAssemblyName">Name of the custom router assembly.</param> /// <param name="customRouterClassName">Name of the custom router class.</param> public void RegisterCustomDocumentRouter(string absoluteSiteURL, string customRouterName, string customRouterAssemblyName, string customRouterClassName) { absoluteSiteURL.RequireNotNullOrEmpty("absoluteSiteURL"); customRouterAssemblyName.RequireNotNullOrEmpty("customRouterAssemblyName"); customRouterClassName.RequireNotNullOrEmpty("customRouterClassName"); customRouterName.RequireNotNullOrEmpty("customRouterName"); using (SPSite site = new SPSite(absoluteSiteURL)) using (SPWeb web = site.OpenWeb()) { EcmDocumentRoutingWeb contentOrganizer = new EcmDocumentRoutingWeb(web); contentOrganizer.AddCustomRouter(customRouterName, customRouterAssemblyName, customRouterClassName); } }
protected void Page_Load(object sender, EventArgs e) { SPWeb web = SPContext.Current.Web; SPList dropOffLib = web.Lists["Drop Off Library"]; EcmDocumentRoutingWeb routingWeb = new EcmDocumentRoutingWeb(web); EcmDocumentRouter router = routingWeb.Router; string finalDestination; bool wasRoutedToOtherWeb; if (routingWeb.IsRoutingEnabled) //是否启用了传送 routing { foreach (SPListItem item in dropOffLib.Items) { Response.Write("Item: " + item.DisplayName); SPFile file = item.File; bool enableModeration = item.ParentList.EnableModeration; //是否启用审批 bool fileModified = false; //在传送之前需要先checkin和approve if (file.CheckOutType != SPFile.SPCheckOutType.None) { file.CheckIn(string.Empty); fileModified = true; } if (enableModeration && item.DoesUserHavePermissions(SPBasePermissions.ApproveItems)) { file.Approve(string.Empty); fileModified = true; } SPListItem newItem = item; if (fileModified) { newItem = web.GetListItem(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, item.Url)); } bool isApproved = true; if (enableModeration) { isApproved = (newItem.ModerationInformation != null) && (newItem.ModerationInformation.Status == SPModerationStatusType.Approved); } if (isApproved) //必须是approve的状态才可以传送 { bool success = router.RouteFileToFinalDestination(newItem, out finalDestination, out wasRoutedToOtherWeb); //输出传送的结果 Response.Write(string.Format("Route result: {0} ", success)); Response.Write(string.Format("finalDestination: {0} ", finalDestination)); Response.Write(string.Format("wasRoutedToOtherWeb: {0} ", wasRoutedToOtherWeb)); Response.Write("</br>"); } } } }
/// <summary>Initializes a new instance of the <see cref="RecordLibraryManager"/> class.</summary> /// <param name="url">The URL.</param> public RecordLibraryManager(string url) { UnifiedLoggingServer.LogMedium("--- " + this.GetType().Name + " 1@ ---"); UnifiedLoggingServer.LogMedium("-@1:" + url); using (SPSite spSite = new SPSite(url)) using (SPWeb spWeb = spSite.OpenWeb()) { spWeb.AllowUnsafeUpdates = true; EcmDocumentRoutingWeb edrw = new EcmDocumentRoutingWeb(spWeb); this.DropOffLibUrl = edrw.DropOffZoneUrl; this.DropOffLibTitle = edrw.DropOffZone.Title; this.DropOffLibrary = spWeb.Lists.TryGetList(edrw.DropOffZone.Title); this.EnabledLibraries = this.ScreenLibraries(spWeb); } }
public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb web = GetWeb(properties)) { /* Deactivate the custom routers for Vendor documents and Work Matter documents */ EcmDocumentRoutingWeb contentOrganizer = new EcmDocumentRoutingWeb(web); try { contentOrganizer.RemoveCustomRouter(workMatterDocumentsRouterName); contentOrganizer.RemoveCustomRouter(vendorDocumentsRouterName); } catch (Exception ex) { Util.LogError("RemoveCustomRouter failed with message: " + ex.Message); } } }
/// <summary>On SubmitFile.</summary> /// <param name="contentOrganizerWeb"> /// The content organizer web. Web site to which the document is being added. /// </param> /// <param name="recordSeries"> /// The record series. Content type of the document. /// </param> /// <param name="userName"> /// The user name. Login name of the user creating the file. /// </param> /// <param name="fileContent"> /// The file content. Content stream of the file being organized. /// </param> /// <param name="properties"> /// The properties. Metadata of the file being organized. /// </param> /// <param name="finalFolder"> /// The final folder. Final location configured for the document being organized. /// </param> /// <param name="resultDetails"> /// The result details. Any details that the custom router wants to furnish for logging purposes. /// </param> /// <returns>Custom RouterResult. Custom information that should be logged by the content organizer.</returns> public CustomRouterResult OnSubmitFile( EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { if (contentOrganizerWeb == null) { throw new ArgumentNullException("contentOrganizerWeb"); } // We should have a Content Organizer enabled web if (!contentOrganizerWeb.IsRoutingEnabled) { throw new ArgumentException("Invalid Content Organizer that invoked the custom router."); } if (String.IsNullOrEmpty(recordSeries)) { throw new ArgumentNullException("Invalid Content type of the document."); } if (String.IsNullOrEmpty(userName)) { throw new ArgumentNullException("Invalid Login name of the user creating the file."); } if (fileContent == null) { throw new IOException("Invalid Content stream of the file being organized."); } if (properties == null) { throw new SPFieldValidationException("Invalid Metadata of the file being organized."); } if (finalFolder == null) { throw new DirectoryNotFoundException("Invalid Final location configured for the document being organized."); } if (String.IsNullOrEmpty(resultDetails)) { throw new ArgumentNullException("Invalid Custom information that should be logged by the content organizer."); } return(CustomRouterResult.SuccessCancelFurtherProcessing); }
protected override void CreateChildControls() { base.CreateChildControls(); string uploadUrl = String.Empty; if (System.AppDomain.CurrentDomain.FriendlyName.Contains("Sandbox")) { uploadUrl = "grrrrr"; } else { SPWeb web = SPContext.Current.Web; EcmDocumentRoutingWeb ecmWeb = new EcmDocumentRoutingWeb(web); if (ecmWeb.IsRoutingEnabled) { SPList dropOffLibrary = ecmWeb.DropOffZone; if (dropOffLibrary != null) { uploadUrl = SPUtility.ConcatUrls(web.Url, dropOffLibrary.Forms[(int)Microsoft.SharePoint.PAGETYPE.PAGE_NEWFORM].Url); } } } if (!String.IsNullOrEmpty(uploadUrl)) { string clickScript = String.Format("Schaeflein.Community.ContentOrganizerLink.LaunchUpload('{0}','{1}');return false;", uploadUrl, this.LinkText); HyperLink contentOrganizerNewForm = new HyperLink(); contentOrganizerNewForm.ID = "contentOrganizerNewForm"; contentOrganizerNewForm.NavigateUrl = "#"; contentOrganizerNewForm.ImageUrl = "/_layouts/images/accesssetting.gif"; contentOrganizerNewForm.Text = "This is the text"; contentOrganizerNewForm.Attributes.Add("onclick", clickScript); Controls.Add(contentOrganizerNewForm); } }
/// <summary> /// Creates the router. /// </summary> /// <param name="author">The author.</param> /// <param name="openBinaryStream">The open binary stream.</param> public void CreateRouter(string author, Stream openBinaryStream) { using (SPSite spSite = new SPSite(this.AbsoluteSiteUrl)) using (SPWeb spWeb = spSite.OpenWeb()) { EcmDocumentRoutingWeb ecmDocumentRoutingWeb = new EcmDocumentRoutingWeb(spWeb); try { ecmDocumentRoutingWeb.RemoveCustomRouter(this.RouterName); } catch (Exception e) { UnifiedLoggingServer.LogHigh("EcmDocumentRoutingWeb<" + this.RouterName + "> DEL_ERR:" + e.Message); } UnifiedLoggingServer.LogMedium("---- CRM:ADD_ROUTER"); ecmDocumentRoutingWeb.AddCustomRouter(this.RouterName, this.AssemblyName, this.ClassName); // fetch corresponding folder into corresponding library UnifiedLoggingServer.LogMedium("---- CRM_DestPath=" + this.RouterPath); if (this.HasRouter) { string log = "---- CRM.OnSubmiting\n"; UnifiedLoggingServer.LogMedium("---- CRM.OnSubmiting_DestPath=" + this.RouterPath); this.CustomRouter.OnSubmitFile( ecmDocumentRoutingWeb, this.ContentTypeName, author, openBinaryStream, this.RecordsRepositoryProperties, this.RouterFolder, ref log); UnifiedLoggingServer.LogMedium("---- CRM.OnSubmitted_DestPath=" + this.RouterPath); UnifiedLoggingServer.LogMedium(log); } UnifiedLoggingServer.LogMedium("---- CRM_END_DestPath=" + this.RouterPath); } }
protected void createRuleButton_Click(object sender, EventArgs e) { SPWeb currentWeb = SPContext.Current.Web; //We must get the EcmDocumentRoutingWeb object that corresponds to the current SPWeb EcmDocumentRoutingWeb routingWeb = new EcmDocumentRoutingWeb(currentWeb); //Get handles on the Document content type and the Shared Documents list SPContentType contentTypeForRule = currentWeb.ContentTypes["Document"]; SPList listForRule = currentWeb.Lists["Shared Documents"]; SPFolder folderForRule = currentWeb.GetFolder(currentWeb.Url + "/Shared%20Documents/DocumentDestination"); //Check that the content type is included in that library if (listForRule.ContentTypes.BestMatch(contentTypeForRule.Id) == null) { resultsLabel.Text = "The Document content type is not available in the " + "Shared Documents folder so the rule cannot be created"; } else { //Create a rule object EcmDocumentRouterRule newRule = new EcmDocumentRouterRule(currentWeb); //Set the properties newRule.Name = "Move all Documents"; newRule.Description = "This rule was create by C# code."; newRule.ContentTypeString = contentTypeForRule.Name; newRule.RouteToExternalLocation = false; newRule.Priority = "5"; newRule.TargetPath = folderForRule.ServerRelativeUrl; //Commit your changes newRule.Update(); } //Tell the user what happened resultsLabel.Text = "Rule created successfully."; }
// CustomRouterResult ICustomRouter.OnSubmitFile( // public CustomRouterResult OnSubmitFile( /// <summary> /// The on submit file. /// </summary> /// <param name="contentOrganizerWeb">The content organizer web.</param> /// <param name="recordSeries">The record series.</param> /// <param name="userName">The user name.</param> /// <param name="fileContent">The file content.</param> /// <param name="properties">The properties.</param> /// <param name="finalFolder">The final folder.</param> /// <param name="resultDetails">The result details.</param> /// <returns> /// The Microsoft.Office.RecordsManagement.RecordsRepository.CustomRouterResult. /// </returns> public CustomRouterResult OnSubmitFile( EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { if (contentOrganizerWeb == null) { throw new ArgumentNullException("contentOrganizerWeb"); } // We should have a Content Organizer enabled web if (!contentOrganizerWeb.IsRoutingEnabled) { throw new ArgumentException("Invalid content organizer."); } if (String.IsNullOrEmpty(recordSeries)) { throw new ArgumentNullException("recordSeries"); } if (String.IsNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } if (fileContent.Length == 0) { throw new ArgumentNullException("fileContent"); } if (properties == null) { throw new ArgumentNullException("properties"); } if (!finalFolder.Exists) { throw new ArgumentNullException("finalFolder"); } UnifiedLoggingServer.LogMedium("---- CR.OnSubmitFile() 7@"); UnifiedLoggingServer.LogMedium("-@1:" + contentOrganizerWeb.GetType()); UnifiedLoggingServer.LogMedium("-@2:" + recordSeries); UnifiedLoggingServer.LogMedium("-@3:" + userName); UnifiedLoggingServer.LogMedium("-@4:" + fileContent.Length); UnifiedLoggingServer.LogMedium("-@5:" + properties.Length); UnifiedLoggingServer.LogMedium("-@6:" + finalFolder.Name); UnifiedLoggingServer.LogMedium("-@7:" + resultDetails); try { foreach (RecordsRepositoryProperty recordsRepositoryProperty in properties) { string s = "---- CR.Props [" + recordsRepositoryProperty.Name + "|" + recordsRepositoryProperty.Value + "]"; this.log += s + "\n"; UnifiedLoggingServer.LogMedium(s); } // Create a Hashtable of properties which forms the metadata for the file Hashtable fileProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties(properties, recordSeries); UnifiedLoggingServer.LogMedium("---- CR.OnSubmitFile().GetHashtableForRecordsRepositoryProperties:" + fileProperties.Count); resultDetails += this.log; UnifiedLoggingServer.LogMedium("-@FilNm_:" + this.FileName); UnifiedLoggingServer.LogMedium("-@FilPt_:" + this.FilePath); UnifiedLoggingServer.LogMedium("-@SPusr_:" + this.SpUser); // Save it to disk EcmDocumentRouter.SaveFileToFinalLocation( contentOrganizerWeb, finalFolder, fileContent, this.FileName, this.FilePath, fileProperties, this.SpUser, true, "CustomRouter CheckInComment"); } catch (Exception e) { UnifiedLoggingServer.LogHigh("---- CR:TryCatch savefiletofinallocation" + e.Message); return(CustomRouterResult.SuccessCancelFurtherProcessing); } return(CustomRouterResult.SuccessContinueProcessing); }
private void RouteItem(SPWeb web, SPListItem item) { bool routeSucceeded = false; EcmDocumentRoutingWeb routingWeb = new EcmDocumentRoutingWeb(web); string serverRelativeUrl = "Drop Off Library"; //EcmCommonUrls.GetServerRelativeUrl(SPContext.Current.Web, EcmCommonUrls.Id.DropOffZone, 需要多语言 bool targetNotFound = false; string specifiedTargetUrl = string.Empty; if (routingWeb.IsRoutingEnabled) { SPListItem routeItem = item; SPFile file = routeItem.File; bool enableModeration = routeItem.ParentList.EnableModeration; bool fileOperationClear = false; //flag3 if (file.CheckOutType != SPFile.SPCheckOutType.None) { file.CheckIn(string.Empty); fileOperationClear = true; } if (enableModeration && routeItem.DoesUserHavePermissions(SPBasePermissions.ApproveItems)) { file.Approve(string.Empty); fileOperationClear = true; } if (fileOperationClear) { routeItem = web.GetListItem(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, routeItem.Url)); file = routeItem.File; } string displayName = routeItem.DisplayName; string finalUrl = web.Site.MakeFullUrl(file.ServerRelativeUrl); string docIdFromListItem = routeItem[new Guid("AE3E2A36-125D-45d3-9051-744B513536A6")] as string; SPUser currentUser = SPContext.Current.Web.CurrentUser; string str5; string routeDestination = string.Empty; bool routedExternally = false; ExternalRoutingResultProperties externalRouteResult = new ExternalRoutingResultProperties(); bool flag4 = false; bool flag5 = true; if (enableModeration) { flag5 = (routeItem.ModerationInformation != null) && (routeItem.ModerationInformation.Status == SPModerationStatusType.Approved); } if (flag5) { flag4 = true; SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite site = new SPSite(web.Site.ID)) { using (SPWeb newWeb = site.OpenWeb(web.ID)) { EcmDocumentRoutingWeb newRoutingWeb = new EcmDocumentRoutingWeb(newWeb); try { string finalDestination; bool wasRoutedToOtherWeb; routeSucceeded = newRoutingWeb.Router.RouteFileToFinalDestination(routeItem, out finalDestination, out wasRoutedToOtherWeb); //newRoutingWeb.Router.RouteFileToFinalLocationNowAsSystem(routeItem, web, currentUser, string.Empty, out routeDestination, out externalRouteResult); routedExternally = externalRouteResult.IsExternalRouter; } catch (DirectoryNotFoundException exception) { routeSucceeded = false; specifiedTargetUrl = exception.Message; targetNotFound = !string.IsNullOrEmpty(specifiedTargetUrl); } } } }); } } }
/// <summary> /// Delete a custom router /// </summary> /// <param name="web">The web</param> /// <param name="routerName">The router name</param> public void DeleteCustomRouter(SPWeb web, string routerName) { var contentOrganizer = new EcmDocumentRoutingWeb(web); contentOrganizer.RemoveCustomRouter(routerName); }
CustomRouterResult ICustomRouter.OnSubmitFile(EcmDocumentRoutingWeb web, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { CustomRouterResult result = new CustomRouterResult(); try { if (web == null) { throw new ArgumentNullException("web"); } if (!web.IsRoutingEnabled) { throw new ArgumentException("Invalid content organizer."); } string submitterLoginName = Resource.DefaultAdminAccount; string submittingUserName = userName; if (string.IsNullOrEmpty(userName)) { submittingUserName = submitterLoginName; } using (SPSite site = new SPSite(web.DropOffZoneUrl)) { using (SPWeb rootWeb = site.OpenWeb()) { SPUser submittingUser = rootWeb.SiteUsers[submittingUserName]; Hashtable fileProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties(properties, recordSeries); fileProperties["Title"] = fileProperties["Name"]; string modifiedFileName = fileProperties["BaseName"] + " - " + fileProperties["Work_x0020_Matter"] + "." + fileProperties["File Type"]; // Check for an existing file, grab the existing document ID if it exists SPFile existingFile = rootWeb.GetFile(finalFolder.ServerRelativeUrl + "/" + modifiedFileName); if (existingFile.Exists) { if ((existingFile.Item.Fields.ContainsField("Work_x0020_Matter_x0020_Document_x003a__x0020_Status") && existingFile.Item["Work_x0020_Matter_x0020_Document_x003a__x0020_Status"].ToString() == "Final") || Records.IsRecord(existingFile.Item)) { result = CustomRouterResult.SuccessCancelFurtherProcessing; resultDetails = "There was an error processing this document. It has already been added to the specified work matter and has been marked as final. The file cannot be overwritten."; SPUtility.TransferToErrorPage(resultDetails); return(result); } fileProperties[Resource.FieldDocumentIDString] = existingFile.Item[Resource.FieldDocumentIDString]; } SPFile newFile = EcmDocumentRouter.SaveFileToFinalLocation(web, finalFolder, fileContent, modifiedFileName, "", fileProperties, submittingUser, false, ""); SPListItem newItem = newFile.Item; if (newFile.Name != modifiedFileName) { result = CustomRouterResult.SuccessCancelFurtherProcessing; resultDetails = "There was an error processing this document. It has already been added to the specified work matter and has been marked as final. The file cannot be overwritten."; // We shouldn't delete these things. Some documents are being deleted unnecessarily //using (DisabledEventsScope scope = new DisabledEventsScope()) //{ // newItem.Delete(); //} SPUtility.TransferToErrorPage(resultDetails); return(result); } newItem["Modified"] = DateTime.Now; newItem.UpdateOverwriteVersion(); result = CustomRouterResult.SuccessCancelFurtherProcessing; } } } catch (Exception ex) { Util.LogError("OnSubmitFile failed with message: " + ex.Message); } result = CustomRouterResult.SuccessCancelFurtherProcessing; return(result); }
/// <summary> /// Create a custom router for a web content organizer /// </summary> /// <param name="web">The web</param> /// <param name="routerName">Router name</param> /// <param name="routerAssemblyName">Router assembly name</param> /// <param name="routerClassName">Router class name in the assembly</param> public void CreateCustomRouter(SPWeb web, string routerName, string routerAssemblyName, string routerClassName) { var contentOrganizer = new EcmDocumentRoutingWeb(web); DeleteCustomRouter(web, routerName); contentOrganizer.AddCustomRouter(routerName, routerAssemblyName, routerClassName); }
/// <summary> /// OnSubmitFile method for the content organizer /// </summary> /// <param name="contentOrganizerWeb">The web.</param> /// <param name="recordSeries">Record series.</param> /// <param name="userName">Submitting user name.</param> /// <param name="fileContent">File content.</param> /// <param name="properties">File properties.</param> /// <param name="finalFolder">The final folder.</param> /// <param name="resultDetails">Result processing details.</param> /// <returns>The CustomRouterResult.</returns> public override CustomRouterResult OnSubmitFile(EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { this.ResolveDependencies(); var web = new SPSite(contentOrganizerWeb.DropOffZoneUrl).OpenWeb(); // Get routed document properties var documentProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties( properties, recordSeries); // Example: Get a conventional field (8553196d-ec8d-4564-9861-3dbe931050c8 = FileLeafRef) string originalFileName = documentProperties["8553196d-ec8d-4564-9861-3dbe931050c8"].ToString(); // EncodedAbsUrl field string originalFileUrl = documentProperties["7177cfc7-f399-4d4d-905d-37dd51bc90bf"].ToString(); // Example: Get the SharePoint user who perform the action var user = web.EnsureUser(userName); // Example: Deal with errors if (originalFileName.ToLower().Contains("error")) { // Display error message SPUtility.TransferToErrorPage( string.Format(CultureInfo.InvariantCulture, "This is an error message")); // Save the error file in the Drop Off Library this.SaveDocumentToDropOffLibrary( fileContent, documentProperties, contentOrganizerWeb.DropOffZone, originalFileName, contentOrganizerWeb, user); return CustomRouterResult.SuccessCancelFurtherProcessing; } // Here is the business logic // Example: get a taxonomy field from document properties string confidentialityTaxValue = documentProperties[MyFields.MyTaxField.InternalName].ToString(); string confidentiality = new TaxonomyFieldValue(confidentialityTaxValue).Label; // Example: Set a new field to the item var indexDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime( DateHelper.GetSharePointDateUtc(web, DateTime.Now)); // Be careful, if you want to add or modify some properties, use internal GUID instead of InternalName if (!documentProperties.ContainsKey(MyFields.MyIndexDate.ID.ToString())) { documentProperties.Add(MyFields.MyIndexDate.ID.ToString(), indexDate); } else { documentProperties[MyFields.MyIndexDate.ID.ToString()] = indexDate; } // Save the file in the final destination. You can get the newly created file here and apply further actions. var file = EcmDocumentRouter.SaveFileToFinalLocation( contentOrganizerWeb, finalFolder, fileContent, originalFileName, originalFileUrl, documentProperties, user, true, string.Empty); web.Dispose(); return CustomRouterResult.SuccessContinueProcessing; }
/// <summary> /// OnSubmitFile method for the content organizer /// </summary> /// <param name="contentOrganizerWeb">The web.</param> /// <param name="recordSeries">Record series.</param> /// <param name="userName">Submitting user name.</param> /// <param name="fileContent">File content.</param> /// <param name="properties">File properties.</param> /// <param name="finalFolder">The final folder.</param> /// <param name="resultDetails">Result processing details.</param> /// <returns>The CustomRouterResult.</returns> public abstract CustomRouterResult OnSubmitFile(EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails);
/// <summary>Initializes a new instance of the <see cref="CustomRecordListItems"/> class.</summary> /// <param name="url">The url.</param> /// <param name="sourceFolder">The source folder.</param> /// <param name="destinationFolder">The destination folder.</param> public CustomRecordListItems(string url, string sourceFolder, string destinationFolder) { if (String.IsNullOrEmpty(url)) { throw new ArgumentNullException(url, "Inavild url"); } if (String.IsNullOrEmpty(sourceFolder)) { throw new ArgumentNullException(sourceFolder, "Invalid folder"); } if (String.IsNullOrEmpty(destinationFolder)) { throw new ArgumentNullException(destinationFolder, "Invalid folder"); } this.DocumentsSourceFolder = sourceFolder; this.DocumentsFinalFolder = destinationFolder; using (SPSite spSite = new SPSite(url)) using (SPWeb spWeb = spSite.OpenWeb()) { // EcmDoc EcmDocumentRoutingWeb ecmDocumentRoutingWeb = new EcmDocumentRoutingWeb(spWeb); // current user specs this.LoginName = System.Threading.Thread.CurrentPrincipal.Identity.Name; this.DocumentsUser = SPContext.Current.Web.CurrentUser; // screening the source folder SPList spList = spWeb.Lists[sourceFolder]; this.DocumentsFields = spList.Fields; int fieldsLimit = spList.Fields.Count; // viewing all items in source folder SPView spView = spList.Views["All Items"]; // current view fields on all items in source folder this.DocumentsViewFields = spView.ViewFields; int viewFieldsLimit = spView.ViewFields.Count; // screening the item collection for each item this.DocumentsItems = spList.Items; foreach (SPListItem spListItem in this.DocumentsItems) { SPContentType spContentType = spListItem.ContentType; SPCopyFieldMask spCopyFieldMask = spListItem.CopyFieldMask; SPCopyDestinationCollection spCopyDestinationCollection = spListItem.CopyDestinations; string displayName = spListItem.DisplayName; SPBasePermissions spBasePermissions = spListItem.EffectiveBasePermissions; SPFieldCollection spFieldCollection = spListItem.Fields; SPFile spFile = spListItem.File; SPFolder spFolder = spListItem.Folder; SPFileLevel spFileLevel = spListItem.Level; string name = spListItem.Name; Hashtable properties = spListItem.Properties; string title = spListItem.Title; string strUrl = spListItem.Url; SPListItemVersionCollection spListItemVersionCollection = spListItem.Versions; string xml = spListItem.Xml; } } }
/// <summary> /// Save a document to the drop off library /// </summary> /// <param name="fileContent"> /// The file content /// </param> /// <param name="docProperties"> /// The document properties /// </param> /// <param name="dropOffLibrary"> /// Drop Off Library List instance /// </param> /// <param name="fileName"> /// The file name /// </param> /// <param name="web"> /// The content organizer web. /// </param> /// <param name="user"> /// The user who submit the file. /// </param> /// <returns> /// The <see cref="SPListItem"/>. /// </returns> protected SPListItem SaveDocumentToDropOffLibrary(Stream fileContent, Hashtable docProperties, SPList dropOffLibrary, string fileName, EcmDocumentRoutingWeb web, SPUser user) { // Check File name // IMPORTANT: You cannot use the orginal document name because it is currently processed (modified state) by the content organizer. Use a prefix or suffix for the file name. if (!fileName.Contains("(Error)")) { fileName = Path.GetFileNameWithoutExtension(fileName) + "_" + "(Error)" + "(1)" + Path.GetExtension(fileName); } else { // Match the (xx)_ in the file name var matchesCountString = Regex.Matches(fileName, "\\(\\d{0,2}\\)"); var countString = (from Match m in matchesCountString where m.Length > 0 select m.Value).First(); // Match the try count var matchesCount = Regex.Matches(countString, "\\d{0,2}"); var count = (from Match m in matchesCount where m.Length > 0 select m.Value).First(); int increment = int.Parse(count, CultureInfo.InvariantCulture); increment++; var newStringIncrement = "(" + increment.ToString(CultureInfo.InvariantCulture) + ")"; fileName = Regex.Replace(fileName, "\\(\\d{0,2}\\)", newStringIncrement); } // Save the file to the Drop Off Library // IMPORTANT (do not use dropOffLibrary.Update() to avoid "The settings for this list have been recently changed" error) var file = EcmDocumentRouter.SaveFileToFinalLocation( web, dropOffLibrary.RootFolder, fileContent, fileName, string.Empty, docProperties, user, true, string.Empty); return file.Item; }