Beispiel #1
0
        public bool RemoveDocumentByID(String recordID)
        {
            if (!IsOpen)
            {
                Open();
            }

            WBLogging.Debug("Call to RemoveDocumentByID with recordID = " + recordID + " for library: " + this.URL);

            SPListItem recordItem = WBUtils.FindItemByColumn(Site, List, WBColumn.RecordID, recordID);

            if (recordItem == null)
            {
                // There is currently no such item - so there is nothing to remove.
                return(false);
            }
            else
            {
                Records.UndeclareItemAsRecord(recordItem);
                recordItem.Delete();
                //libraryWeb.Update();

                return(true);
            }
        }
Beispiel #2
0
        public WBLink(String values)
        {
            if (String.IsNullOrEmpty(values))
            {
                IsOK = false;
                WBLogging.Debug("WBLink being created with blank or null values string:" + values);
                return;
            }

            String[] valueArray = values.Split('|');
            if (valueArray.Length == 5)
            {
                UsingTicksWhenVisited = true;
            }
            else if (valueArray.Length == 4)
            {
                UsingTicksWhenVisited = false;
            }
            else
            {
                IsOK = false;
                WBLogging.Debug("WBLink being created with values string with the wrong number of values: " + values);
                return;
            }

            Title     = WBUtils.PutBackDelimiterCharacters(valueArray[0]);
            URL       = WBUtils.PutBackDelimiterCharacters(valueArray[1]);
            UniqueID  = WBUtils.PutBackDelimiterCharacters(valueArray[2]);
            SPWebGUID = valueArray[3];

            if (UsingTicksWhenVisited)
            {
                TicksWhenVisitedString = valueArray[4];
            }
        }
Beispiel #3
0
 public void CopyColumns(WBItem itemToCopy, IEnumerable <WBColumn> columnsToCopy)
 {
     foreach (WBColumn column in columnsToCopy)
     {
         WBLogging.Debug("Copying column: " + column.DisplayName);
         this[column] = itemToCopy[column];
     }
 }
Beispiel #4
0
        public SPFolder GetMasterFolderByPath(String path)
        {
            String serverRelativePath = ProtectedMasterLibrary.Web.ServerRelativeUrl + "/" + ProtectedMasterLibrary.List.RootFolder.Name + "/" + path;

            WBLogging.Debug("Trying to find the SPFolder in the master library by way of the server relative path: " + serverRelativePath);

            SPFolder folder = ProtectedMasterLibrary.Web.GetFolder(serverRelativePath);

            return(folder);
        }
Beispiel #5
0
        public WBRecordsLibrary(WBRecordsLibraries libraries, String url, String protectiveZone)
        {
            WBLogging.Debug("In WBRecordsLibrary() constructor for: " + url);

            Libraries       = libraries;
            _url            = url;
            _protectiveZone = protectiveZone;

            WBLogging.Debug("Finished WBRecordsLibrary() constructor for: " + url);
        }
Beispiel #6
0
        public WBRecordsManager(String callingUserLogin)
        {
            WBLogging.Debug("In WBRecordsManager() constructor");

            _farm             = WBFarm.Local;
            _libraries        = new WBRecordsLibraries(this);
            _callingUserLogin = callingUserLogin;

            WBLogging.Debug("Finished WBRecordsManager() constructor");
        }
Beispiel #7
0
        public WBRecord GetRecordByPath(String path)
        {
            String serverRelativePath = ProtectedMasterLibrary.Web.ServerRelativeUrl + "/" + ProtectedMasterLibrary.List.RootFolder.Name + "/" + path;

            WBLogging.Debug("Trying to find the RecordID by way of the server relative path: " + serverRelativePath);

            SPListItem masterRecordItem = ProtectedMasterLibrary.Web.GetListItem(serverRelativePath);

            return(new WBRecord(this, masterRecordItem));
        }
Beispiel #8
0
        internal void PopulateWithFunctionalAreas(WBLocationTreeState treeState, TreeNodeCollection treeNodeCollection, String viewMode, WBTermCollection <WBTerm> teamFunctionalAreas)
        {
            bool expandNodes = true;

            if (teamFunctionalAreas.Count > 2)
            {
                expandNodes = false;
            }

            List <WBTerm> sortedTerms = new List <WBTerm>();

            foreach (WBTerm term in teamFunctionalAreas)
            {
                sortedTerms.Add(term);
            }
            sortedTerms = sortedTerms.OrderBy(o => o.Name).ToList();

            foreach (WBTerm functionalArea in sortedTerms)
            {
                SPFolder folder = null;

                if (viewMode != VIEW_MODE__NEW)
                {
                    folder = this.Libraries.GetMasterFolderByPath(functionalArea.Name);

                    if (folder == null)
                    {
                        WBLogging.Debug("Couldn't find folder for functional area: " + functionalArea.Name);
                        continue;
                    }
                }
                else
                {
                    WBLogging.Debug("View mode = " + viewMode);
                }


                WBFunctionalAreaTreeNode functionalAreaTreeNode = new WBFunctionalAreaTreeNode(functionalArea, folder);
                TreeNode node = functionalAreaTreeNode.AsTreeNode();

                node.Expanded         = expandNodes;
                node.PopulateOnDemand = false;
                node.SelectAction     = TreeNodeSelectAction.Expand;

                treeNodeCollection.Add(node);

                WBTaxonomy     recordsTypes = this.RecordsTypesTaxonomy;
                TermCollection terms        = recordsTypes.TermSet.Terms;

                PopulateWithRecordsTypes(treeState, node.ChildNodes, viewMode, folder, functionalArea, recordsTypes, terms);
            }
        }
Beispiel #9
0
        internal WBFolderTreeNode GetFolderTreeNode(String path)
        {
            List <String> steps          = WBUtils.GetPathStepsFromNormalisedPath(path);
            String        normalisedPath = String.Join("/", steps.ToArray());

            SPFolder folder = this.Libraries.GetMasterFolderByPath(normalisedPath);

            WBLogging.Debug("In GetFolderTreeNode(): steps.Count = " + steps.Count);
            if (folder == null)
            {
                WBLogging.Debug("In GetFolderTreeNode(): folder is NULL");
            }
            else
            {
                WBLogging.Debug("In GetFolderTreeNode(): folder = " + folder.Name);
            }

            if (steps.Count == 0)
            {
                return(null);
            }

            WBTerm functionalArea = this.FunctionalAreasTaxonomy.GetSelectedWBTermByPath(steps[0]);

            if (steps.Count == 1)
            {
                return(new WBFunctionalAreaTreeNode(functionalArea, folder));
            }

            // Now let's remove the functional area bit from the list of steps so that we just have a potential records type path:
            steps.RemoveAt(0);

            Term deepestRecordsTypeTerm = this.RecordsTypesTaxonomy.GetDeepestTermBySteps(steps);

            if (deepestRecordsTypeTerm == null)
            {
                return(null);
            }

            String deepestRecordsTypeLocationPath = functionalArea.Name + "/" + deepestRecordsTypeTerm.WBxFullPath();

            if (deepestRecordsTypeLocationPath == normalisedPath)
            {
                // OK so the path was to a records type - not a folder below the records type:
                return(new WBRecordsTypeTreeNode(functionalArea, new WBRecordsType(this.RecordsTypesTaxonomy, deepestRecordsTypeTerm), folder));
            }

            // Otherwise - if we've got here then the path is to an actual folder within the master records library:
            return(new WBFolderTreeNode(folder));
        }
Beispiel #10
0
        protected void ReturnJSONFromDialogOK(string returnValue)
        {
            int resultValue = OK_RESULT;

            WBLogging.Debug("Dialog returning with values: result = " + resultValue + " return = " + returnValue);

            //            if (Page.Request.QueryString["IsDlg"] != null)
            //              SPUtility.Redirect("/", SPRedirectFlags.UseSource, Context, "");


            returnValue = returnValue.Replace("\\", "\\\\"); // Need to double up the escaping so that it correctly survives this passback!

            Page.Response.Clear();
            Page.Response.Write(String.Format(CultureInfo.InvariantCulture, "<script type=\"text/javascript\">\n var returnVal = {1}; \n window.frameElement.commonModalDialogClose({0}, returnVal);</script>", new object[] { resultValue, String.IsNullOrEmpty(returnValue) ? "null" : String.Format("'{0}'", returnValue) }));
            Page.Response.End();
        }
Beispiel #11
0
        internal void PopulateTreeNode(WBLocationTreeState treeState, TreeNode node, String viewMode)
        {
            WBLogging.Debug("Looking for WBFolderTreeNode with path: " + node.ValuePath);

            WBFolderTreeNode folderTreeNode = this.GetFolderTreeNode(node.ValuePath);

            if (folderTreeNode == null)
            {
                WBLogging.Debug("Did not find WBFolderTreeNode at: " + node.ValuePath);
                return;
            }

            if (folderTreeNode is WBRecordsTypeTreeNode)
            {
                WBLogging.Debug("Expanding a records type node: " + node.Text);

                WBRecordsTypeTreeNode recordsTypeNode = (WBRecordsTypeTreeNode)folderTreeNode;
                WBRecordsType         recordsType     = recordsTypeNode.RecordsType;
                TermCollection        childTerms      = recordsType.Term.Terms;
                if (childTerms.Count > 0)
                {
                    PopulateWithRecordsTypes(treeState, node.ChildNodes, viewMode, recordsTypeNode.Folder, recordsTypeNode.FunctionalArea, recordsType.Taxonomy, childTerms);
                }
                else
                {
                    if (viewMode != VIEW_MODE__NEW)
                    {
                        PopulateWithSubFolders(treeState, node.ChildNodes, viewMode, recordsTypeNode.Folder);
                    }
                }
            }
            else if (folderTreeNode is WBFolderTreeNode)
            {
                WBLogging.Debug("Expanding a folder node: " + node.Text);

                // You shouldn't be here if the view mode was NEW !
                PopulateWithSubFolders(treeState, node.ChildNodes, viewMode, folderTreeNode.Folder);
            }
            else
            {
                WBLogging.Debug("NOT expanding an unrecognised node: " + node.Text + " of type: " + node.GetType());
            }
        }
Beispiel #12
0
        public bool MaybeCopyColumns(WBItem itemToCopy, IEnumerable <WBColumn> columnsToCopy)
        {
            // Let's pick up the item again before copying across the metadata:
            this.Reload();

            bool allCorrect = false;

            foreach (WBColumn column in columnsToCopy)
            {
                WBLogging.Debug("Copying column in MaybeCopyColumns(): " + column.DisplayName);
                if (this[column] != itemToCopy[column])
                {
                    allCorrect   = false;
                    this[column] = itemToCopy[column];
                }
            }

            return(allCorrect);
        }
Beispiel #13
0
        public static void WriteTrace(String categoryName, TraceSeverity traceSeverity, String message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            try
            {
                WBLogging service = Local;

                if (service != null)
                {
                    SPDiagnosticsCategory category = service.Areas[LOGGING_AREA_NAME].Categories[categoryName];
                    service.WriteTrace(1, category, traceSeverity, message);
                }
            }
            catch { }
        }
Beispiel #14
0
        public bool Open()
        {
            if (IsOpen)
            {
                return(false);
            }
            if (String.IsNullOrEmpty(_url))
            {
                WBLogging.RecordsTypes.Unexpected("You can't open a WBRecordsLibrary if the URL is null or empty");
                throw new Exception("You can't open a WBRecordsLibrary if the URL is null or empty");
            }

            WBLogging.Debug("In WBRecordsLibrary().Open() for: " + _url);

            _site = new SPSite(_url);
            _web  = _site.OpenWeb();

            // Let's check that we are running with the correct elevated priviledge user:
            if (_web.CurrentUser.ID != _site.SystemAccount.ID)
            {
                SPSite correctlyElevatedSite = new SPSite(_site.ID, _site.SystemAccount.UserToken);
                SPWeb  correctlyElevatedWeb  = correctlyElevatedSite.OpenWeb(_web.ID);

                _web.Dispose();
                _site.Dispose();

                _site = correctlyElevatedSite;
                _web  = correctlyElevatedWeb;
            }

            _list = _web.GetList(_url);

            _openedByThisObject = true;

            _site.AllowUnsafeUpdates = true;
            _web.AllowUnsafeUpdates  = true;

            _isOpen = true;

            WBLogging.Debug("Finished WBRecordsLibrary().Open() for: " + URL);
            return(true);
        }
Beispiel #15
0
        public void UpdateAs(String callingUserLogin)
        {
            switch (BackingType)
            {
            case BackingTypes.SPListItem:
            {
                bool before = _listItem.Web.AllowUnsafeUpdates;
                _listItem.Web.AllowUnsafeUpdates = true;

                SPUser callingUser = _listItem.Web.WBxEnsureUserOrNull(callingUserLogin);

                if (callingUser != null)
                {
                    WBLogging.Debug("Calling WBItem.Update() on item backed by callingUserLogin = "******" and SPUser = "******"Calling WBItem.Update() on item backed by callingUserLogin = "******" and SPUser = "******"Calling WBItem.Update() on item backed by SPListItem with no passed in user");
                    WBLogging.Debug("Calling WBItem.Update() on item backed by SPListItem with no passed in user");
                }

                _listItem.Update();

                _listItem.Web.AllowUnsafeUpdates = before;
                return;
            }

            case BackingTypes.Dictionary:
            {
                // At the moment there is nothing to do
                WBLogging.Debug("Called update on a WBItem derived class that is backed by a dictionary!");
                return;
            }

            default: throw new NotImplementedException("The backing type selected has no implementation for public Object this[WBColumn column]");
            }
        }
Beispiel #16
0
        public WBRecordsLibraries(WBRecordsManager manager)
        {
            WBLogging.Debug("In WBRecordsLibraries() constructor");


            WBFarm farm = WBFarm.Local;

            Manager = manager;

            if (String.IsNullOrEmpty(farm.ProtectedRecordsLibraryUrl))
            {
                WBLogging.RecordsTypes.Unexpected("The central, protected, master library has not been configured - so no records management is possible!");
                return;
            }

            ProtectedMasterLibrary = new WBRecordsLibrary(this, farm.ProtectedRecordsLibraryUrl, WBRecordsLibrary.PROTECTIVE_ZONE__PROTECTED);
            Add(ProtectedMasterLibrary);

            AddIfMissing(farm.PublicRecordsLibraryUrl, WBRecordsLibrary.PROTECTIVE_ZONE__PUBLIC);
            AddIfMissing(farm.PublicExtranetRecordsLibraryUrl, WBRecordsLibrary.PROTECTIVE_ZONE__PUBLIC_EXTRANET);

            WBSubjectTagsRecordsRoutings routings = farm.SubjectTagsRecordsRoutings(null);

            List <String> extraPublicLibraries = routings.AllPublicLibraries();

            foreach (String libraryURL in extraPublicLibraries)
            {
                AddIfMissing(libraryURL, WBRecordsLibrary.PROTECTIVE_ZONE__PUBLIC);
            }

            List <String> extraExtranetLibraries = routings.AllExtranetLibraries();

            foreach (String libraryURL in extraExtranetLibraries)
            {
                AddIfMissing(libraryURL, WBRecordsLibrary.PROTECTIVE_ZONE__PUBLIC_EXTRANET);
            }

            WBLogging.Debug("Finished WBRecordsLibraries() constructor");
        }
Beispiel #17
0
        internal void PopulateWithDocuments(WBLocationTreeState treeState, TreeNodeCollection treeNodeCollection, String viewMode, SPFolder folder)
        {
            WBLogging.Debug("In PopulateWithDocuments()");

            SPListItemCollection items = GetItemsRecursive(folder);

            WBLogging.Debug("In PopulateWithDocuments() items.Count = " + items.Count);

            List <SPListItem> sortedItems = new List <SPListItem>();

            foreach (SPListItem item in items)
            {
                sortedItems.Add(item);
            }
            sortedItems = sortedItems.OrderBy(o => o.Name).ToList();

            foreach (SPListItem item in items)
            {
                if (ItemCanBePicked(treeState, item))
                {
                    TreeNode node = new TreeNode();

                    node.Text             = item.Name;
                    node.Value            = item.Name;
                    node.Expanded         = true;
                    node.PopulateOnDemand = false;
                    node.SelectAction     = TreeNodeSelectAction.Select;


                    node.ImageUrl = SPUtility.ConcatUrls("/_layouts/images/",
                                                         SPUtility.MapToIcon(treeState.Web,
                                                                             SPUtility.ConcatUrls(treeState.Web.Url, node.Text), "", IconSize.Size16));

                    // No need to add this to the tree state as we'll never come looking for it:
                    treeNodeCollection.Add(node);
                }
            }
        }
Beispiel #18
0
        public WBSubjectTagRecordsRoutings(WBTaxonomy subjectTags, String values)
        {
            if (String.IsNullOrEmpty(values))
            {
                IsOK = false;
                WBLogging.Debug("WBSubjectTagRecordsRoutings being created with blank or null values string:" + values);
                return;
            }

            String[] valueArray = values.Split('|');
            if (valueArray.Length == 3)
            {
                SubjectTag               = new WBSubjectTag(subjectTags, WBUtils.PutBackDelimiterCharacters(valueArray[0]));
                PublicDocumentsLibrary   = WBUtils.PutBackDelimiterCharacters(valueArray[1]);
                ExtranetDocumentsLibrary = WBUtils.PutBackDelimiterCharacters(valueArray[2]);
            }
            else
            {
                IsOK = false;
                WBLogging.Debug("WBSubjectTagRecordsRoutings being created with values string with the wrong number of values: " + values);
                return;
            }
        }
Beispiel #19
0
        public TreeViewLocation(TreeViewLocation parent, WBRecordsManager manager, string mode, string minimumProtectiveZone, WBTerm functionalArea, WBRecordsType recordsType)
        {
            _type = LOCATION_TYPE__RECORDS_TYPE;

            _parent  = parent;
            _manager = manager;
            _mode    = mode;
            _minimumProtectiveZone = minimumProtectiveZone;

            _functionalArea = functionalArea;
            _recordsType    = recordsType;
            _name           = _recordsType.Name;
            _guidString     = _recordsType.Id.ToString();

            if (_mode != VIEW_MODE__NEW)
            {
                _folder = _parent._folder.WBxGetSubFolder(recordsType.Name);
                if (_folder == null)
                {
                    WBLogging.Debug("Did not find folder for: " + recordsType.Name);
                }
            }
        }
Beispiel #20
0
        private void UpdateWhichLibrariesNeedACopy()
        {
            WBLogging.Debug("In UpdateWhichLibrariesNeedACopy()");
            //WBTermCollection<WBSubjectTag> subjectTagsApplied = new WBTermCollection<WBSubjectTag>();

            _librariesNeedingACopy.Clear();
            _librariesMustNotHaveCopy.Clear();

            if (LiveOrArchived == "Live" && (RecordSeriesStatus == WBColumn.RECORD_SERIES_STATUS__LATEST || String.IsNullOrEmpty(RecordSeriesStatus)))
            {
                if (ProtectiveZone == WBRecordsType.PROTECTIVE_ZONE__PUBLIC)
                {
                    _librariesNeedingACopy.WBxAddIfNotNullOrEmpty(_farm.PublicRecordsLibraryUrl);

                    _librariesNeedingACopy.AddRange(Routings.PublicLibrariesToRouteTo(Metadata.SubjectTags));
                    _librariesMustNotHaveCopy.AddRange(Routings.AllPublicLibraries().Except(_librariesNeedingACopy));

                    _librariesMustNotHaveCopy.AddRange(Routings.AllExtranetLibraries());
                    _librariesMustNotHaveCopy.WBxAddIfNotNullOrEmpty(_farm.PublicExtranetRecordsLibraryUrl);
                }

                if (ProtectiveZone == WBRecordsType.PROTECTIVE_ZONE__PUBLIC_EXTRANET)
                {
                    _librariesNeedingACopy.WBxAddIfNotNullOrEmpty(_farm.PublicExtranetRecordsLibraryUrl);

                    _librariesNeedingACopy.AddRange(Routings.ExtranetLibrariesToRouteTo(Metadata.SubjectTags));
                    _librariesMustNotHaveCopy.AddRange(Routings.AllExtranetLibraries().Except(_librariesNeedingACopy));

                    _librariesMustNotHaveCopy.AddRange(Routings.AllPublicLibraries());
                    _librariesMustNotHaveCopy.WBxAddIfNotNullOrEmpty(_farm.PublicRecordsLibraryUrl);
                }
            }
            else
            {
                _librariesMustNotHaveCopy.WBxAddIfNotNullOrEmpty(_farm.PublicRecordsLibraryUrl);
                _librariesMustNotHaveCopy.WBxAddIfNotNullOrEmpty(_farm.PublicExtranetRecordsLibraryUrl);

                _librariesMustNotHaveCopy.AddRange(Routings.AllPublicLibraries());
                _librariesMustNotHaveCopy.AddRange(Routings.AllExtranetLibraries());
            }


            // Section of debug output:
            if (_librariesNeedingACopy.Count == 0)
            {
                WBLogging.Debug("Record ID = " + RecordID + " no public libraries need a copy");
            }

            foreach (String libraryURL in _librariesNeedingACopy)
            {
                WBLogging.Debug("Record ID = " + RecordID + " needs to be in: " + libraryURL);
            }

            if (_librariesMustNotHaveCopy.Count == 0)
            {
                WBLogging.Debug("Record ID = " + RecordID + " there are no public libraries that must NOT have a copy");
            }
            foreach (String libraryURL in _librariesMustNotHaveCopy)
            {
                WBLogging.Debug("Record ID = " + RecordID + " must NOT be in: " + libraryURL);
            }
        }
Beispiel #21
0
        public void PrecreateWorkBoxes()
        {
            int totalToHavePrecreated = Item.WBxGetColumnAsInt(WBColumn.PrecreateWorkBoxes, -1);

            // Is this template configured to precreate?
            if (totalToHavePrecreated <= 0)
            {
                return;
            }

            // Next let's just check that both of the lists for the precreation process are configured:
            String precreatedWorkBoxesListName = Item.WBxGetAsString(WBColumn.PrecreatedWorkBoxesList);

            if (String.IsNullOrEmpty(precreatedWorkBoxesListName))
            {
                return;
            }

            String requestPrecreatedWorkBoxListName = Item.WBxGetAsString(WBColumn.RequestPrecreatedWorkBoxList);

            if (String.IsNullOrEmpty(requestPrecreatedWorkBoxListName))
            {
                return;
            }

            bool previousWebAllowUnsafeUpdates = Collection.Web.AllowUnsafeUpdates;

            Collection.Web.AllowUnsafeUpdates = true;

            try
            {
                SPList precreatedWorkBoxesList      = Collection.Web.Lists[precreatedWorkBoxesListName];
                SPList requestPrecreatedWorkBoxList = Collection.Web.Lists[requestPrecreatedWorkBoxListName];

                // We only need to bring the two list's IDs into sync if there are no remaining precreated work boxes waiting to be used
                // if there are still waiting precreated work boxes, then we should be able to assume that the lists are still in sync
                if (precreatedWorkBoxesList.ItemCount == 0)
                {
                    MakeSureListsAreInSync(precreatedWorkBoxesList, requestPrecreatedWorkBoxList);
                }

                int safety       = 0;
                int safetyCutOut = 1000;

                int countPrecreated = precreatedWorkBoxesList.ItemCount;

                WBLogging.Debug("Current count of precreated: " + countPrecreated);
                WBLogging.Debug("Total target of precreated: " + totalToHavePrecreated);


                using (EventsFiringDisabledScope noevents = new EventsFiringDisabledScope())
                {
                    while (countPrecreated < totalToHavePrecreated && safety < safetyCutOut)
                    {
                        safety++;

                        SPListItem newItem    = Collection.List.AddItem();
                        WorkBox    newWorkBox = new WorkBox(Collection, newItem);
                        newWorkBox.Template = this;

                        // This update ensures that at the item is assigned an ID:
                        newItem.Update();

                        newWorkBox.Create("Precreated work box");

                        Collection.Web.AllowUnsafeUpdates = true;

                        SPListItem precreatedWorkBoxesListItem = precreatedWorkBoxesList.AddItem();
                        precreatedWorkBoxesListItem.WBxSet(WBColumn.WorkBoxListID, newItem.ID);
                        precreatedWorkBoxesListItem.WBxSet(WBColumn.Title, "Precreated work box: " + newWorkBox.Url);
                        precreatedWorkBoxesListItem.Update();

                        // We need to do this as precreatedWorkBoxesList.ItemCount does not get updated in the loop:
                        countPrecreated++;
                    }
                }

                if (safety >= safetyCutOut)
                {
                    throw new NotImplementedException("The precreation of work boxes loop appears to be out of control for: " + TemplateTitle);
                }
            }
            catch (Exception exception)
            {
                WBUtils.SendErrorReport(this.Collection.Web, "Work Box Precreation Error", "Something went wrong when trying to precreate a work box for: " + this.TemplateTitle + " Exception: " + exception.Message + " \n\n " + exception.StackTrace);
            }

            Collection.Web.AllowUnsafeUpdates = previousWebAllowUnsafeUpdates;
        }
Beispiel #22
0
        public String GetStandardHTMLTableRows()
        {
            SPListItem currentItem = this.CurrentItem;
            String     html        = "";

            if (this.ItemIDs.Count == 0)
            {
                WBLogging.Debug("process.ItemIDs.Count == 0");
                html += "<i>No documents selected!</i>";
            }
            else
            {
                int  numberOfDocuments = this.ItemIDs.Count;
                int  itemIndex         = -1;
                int  currentItemIndex  = -1;
                bool before            = true;
                foreach (String itemID in this.ItemIDs)
                {
                    itemIndex++;

                    String filename = this.MappedFilenames[itemID];

                    WBLogging.Debug("list through item with name: " + filename);
                    if (itemID == this.CurrentItemID)
                    {
                        currentItemIndex = itemIndex;
                        if (itemIndex != 0)
                        {
                            // OK so we've got to close the table row of the already published documents:
                            html += @"
    </td>
</tr>";
                        }

                        before = false;

                        if (this.PublishMode != PUBLISH_MODE__ALL_TOGETHER)
                        {
                            String originalFilename = "";
                            if (currentItem != null)
                            {
                                originalFilename = currentItem.WBxGetColumnAsString(WorkBox.COLUMN_NAME__ORIGINAL_FILENAME);
                            }

                            html += @"
<tr>
    <td class=""wbf-field-name-panel"">
        <div class=""wbf-field-name"">Publishing Document</div>
    </td>
    <td class=""wbf-field-value-panel"">
        <div class=""wbf-field-read-only-title"">
            <table border=""0"" cellpadding=""0"" cellspacing=""2px"">
                <tr>
                    <td rowspan=""2"" style=""padding-right: 10px; "">
                        <img src='" + WBUtils.DocumentIcon32(filename) + "' alt='Icon for file " + filename + @"'/>
                    </td>
                    <td>" + filename + @"</td>
                </tr>
                <tr>
                    <td>" + originalFilename + @"</td>
                </tr>
            </table>
        </div>
    </td>
</tr>
";
                        }
                        else
                        {
                            // So if we're here then we are publishing all together - so let's slightly change the layout:
                            html += @"
<tr>
    <td class=""wbf-field-name-panel"">
        <div class=""wbf-field-name"">Publishing Documents</div>
    </td>
    <td class=""wbf-field-value-panel"">
        <div>
            <img src='/_layouts/images/WorkBoxFramework/list-item-16.png' alt='Unpublished document'/>
            <img src='" + WBUtils.DocumentIcon16(filename) + "' alt='Icon for file " + filename + "'/> " + filename + @"
        </div>
";
                        }
                    }
                    else
                    {
                        if (before)
                        {
                            String statusIcon    = "/_layouts/images/WorkBoxFramework/green-tick-16.png";
                            String statusAltText = "Successfully published";
                            if (this.ItemStatus[itemID] == WBPublishingProcess.DOCUMENT_STATUS__ERROR)
                            {
                                statusIcon    = "/_layouts/images/WorkBoxFramework/red-cross-16.png";
                                statusAltText = "Failed to publish";
                            }

                            if (itemIndex == 0)
                            {
                                // OK so let's start the table row of the documents that have already been published:
                                html += @"
<tr>
    <td class=""wbf-field-name-panel"">
        <div class=""wbf-field-name""></div>
    </td>
    <td class=""wbf-field-name-panel"">
";
                            }

                            html += @"
        <div>
            <img src='" + statusIcon + "' alt='" + statusAltText + @"'/>
            <img src='" + WBUtils.DocumentIcon16(filename) + "' alt='Icon for file " + filename + "'/> " + filename + @"
        </div>
";
                        }
                        else
                        {
                            if (itemIndex == currentItemIndex + 1 && this.PublishMode != PUBLISH_MODE__ALL_TOGETHER)
                            {
                                html += @"
<tr>
    <td class=""wbf-field-name-panel"">
        <div class=""wbf-field-name""></div>
    </td>
    <td class=""wbf-field-name-panel"">
";
                            }

                            html += @"
        <div>
            <img src='/_layouts/images/WorkBoxFramework/list-item-16.png' alt='Unpublished document'/>
            <img src='" + WBUtils.DocumentIcon16(filename) + "' alt='Icon for file " + filename + "'/> " + filename + @"
        </div>
";

                            if (itemIndex == numberOfDocuments - 1)
                            {
                                html += @"
    </td>
</tr>";
                            }
                        }
                    }
                }
            }
            return(html);
        }
Beispiel #23
0
        public IHierarchicalEnumerable GetChildren()
        {
            if (_children == null)
            {
                _children = new TreeViewLocationCollection();

                switch (_type)
                {
                case LOCATION_TYPE__FUNCTIONAL_AREA: {
                    WBLogging.Debug("In GetChildren() for type Functional Area");
                    WBTaxonomy     recordsTypes = _manager.RecordsTypesTaxonomy;
                    TermCollection terms        = recordsTypes.TermSet.Terms;

                    foreach (Term childTerm in terms)
                    {
                        WBRecordsType recordsType      = new WBRecordsType(recordsTypes, childTerm);
                        bool          protectiveZoneOK = true;
                        //if (!String.IsNullOrEmpty(_minimumProtectiveZone))
                        //{
                        //   protectiveZoneOK = (recordsType.IsZoneAtLeastMinimum(_minimumProtectiveZone));
                        // }

                        if (recordsType.BranchCanHaveDocuments() && recordsType.IsRelevantToFunctionalArea(_functionalArea) && protectiveZoneOK)
                        {
                            TreeViewLocation newLocation = new TreeViewLocation(this, _manager, _mode, _minimumProtectiveZone, _functionalArea, recordsType);

                            // If we're looking for existing records then we'll only add this location if it has a real folder existing underneath it:
                            if (_mode == VIEW_MODE__NEW || newLocation._folder != null)
                            {
                                _children.Add(newLocation);
                            }
                        }
                        else
                        {
                            WBLogging.Debug("In GetChildren() excluded " + recordsType.Name + " because " + recordsType.BranchCanHaveDocuments() + " && " + protectiveZoneOK);
                        }
                    }

                    break;
                }

                case LOCATION_TYPE__RECORDS_TYPE: {
                    WBLogging.Debug("In GetChildren() for type Records Type");
                    WBTaxonomy recordsTypes = _manager.RecordsTypesTaxonomy;

                    TermCollection terms = _recordsType.Term.Terms;
                    if (terms.Count > 0)
                    {
                        foreach (Term childTerm in terms)
                        {
                            WBRecordsType recordsType      = new WBRecordsType(recordsTypes, childTerm);
                            bool          protectiveZoneOK = true;
                            if (!String.IsNullOrEmpty(_minimumProtectiveZone))
                            {
                                protectiveZoneOK = (recordsType.IsZoneAtLeastMinimum(_minimumProtectiveZone));
                            }

                            if (recordsType.BranchCanHaveDocuments() && recordsType.IsRelevantToFunctionalArea(_functionalArea) && protectiveZoneOK)
                            {
                                TreeViewLocation newLocation = new TreeViewLocation(this, _manager, _mode, _minimumProtectiveZone, _functionalArea, recordsType);

                                // If we're looking for existing records then we'll only add this location if it has a real folder existing underneath it:
                                if (_mode == VIEW_MODE__NEW || newLocation._folder != null)
                                {
                                    _children.Add(newLocation);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (_mode != VIEW_MODE__NEW)
                        {
                            // WBLogging.Debug("In view mode replace switching to folders part of tree");

                            string fullClassPath = WBUtils.NormalisePath(Path);

                            // WBLogging.Debug("Looking for starting folder = " + fullClassPath);

                            SPFolder protectedLibraryRootFolder = _manager.Libraries.ProtectedMasterLibrary.List.RootFolder;

                            // WBLogging.Debug("Got library root folder");

                            SPFolder recordsTypeFolder = protectedLibraryRootFolder.WBxGetFolderPath(fullClassPath);

                            // WBLogging.Debug("Got records type folder - definitely changed .. " + recordsTypeFolder);
                            if (recordsTypeFolder != null)
                            {
                                foreach (SPFolder child in recordsTypeFolder.SubFolders)
                                {
                                    _children.Add(new TreeViewLocation(this, _manager, _mode, _minimumProtectiveZone, child));
                                }
                            }
                            else
                            {
                                WBLogging.Debug("The master library doesn't have a folder with path: " + fullClassPath);
                            }

                            // WBLogging.Debug("Added children folders");
                        }
                    }

                    break;
                }

                case LOCATION_TYPE__FOLDER: {
                    WBLogging.Debug("In GetChildren() for type Folder");

                    if (_folder.SubFolders.Count > 0)
                    {
                        foreach (SPFolder child in _folder.SubFolders)
                        {
                            _children.Add(new TreeViewLocation(this, _manager, _mode, _minimumProtectiveZone, child));
                        }
                    }
                    else
                    {
                        if (_mode == VIEW_MODE__REPLACE)
                        {
                            SPListItemCollection items = GetItemsRecursive(_folder);
                            foreach (SPListItem item in items)
                            {
                                if (ItemCanBePicked(item))
                                {
                                    _children.Add(new TreeViewLocation(this, _manager, _mode, _minimumProtectiveZone, new WBDocument(_manager.Libraries.ProtectedMasterLibrary, item)));
                                }
                            }
                        }
                    }
                    break;
                }

                case LOCATION_TYPE__DOCUMENT: {
                    WBLogging.Debug("In GetChildren() for type Document");

                    break;
                }
                }
            }

            return(_children);
        }
Beispiel #24
0
        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);
        }
Beispiel #25
0
        internal void PopulateWithRecordsTypes(WBLocationTreeState treeState, TreeNodeCollection treeNodeCollection, String viewMode, SPFolder parentFolder, WBTerm functionalArea, WBTaxonomy recordsTypesTaxonomy, TermCollection recordsTypeTerms)
        {
            List <Term> sortedTerms = new List <Term>();

            foreach (Term term in recordsTypeTerms)
            {
                sortedTerms.Add(term);
            }
            sortedTerms = sortedTerms.OrderBy(o => o.Name).ToList();

            foreach (Term term in sortedTerms)
            {
                WBRecordsType recordsType = new WBRecordsType(recordsTypesTaxonomy, term);

                bool protectiveZoneOK = true;
                if (!String.IsNullOrEmpty(treeState.MinimumProtectiveZone))
                {
                    protectiveZoneOK = (recordsType.IsZoneAtLeastMinimum(treeState.MinimumProtectiveZone));
                }

                if (recordsType.BranchCanHaveDocuments() && recordsType.IsRelevantToFunctionalArea(functionalArea) && protectiveZoneOK)
                {
                    SPFolder folder = null;
                    if (viewMode != VIEW_MODE__NEW && parentFolder != null)
                    {
                        folder = parentFolder.WBxGetSubFolder(recordsType.Name);
                        if (folder == null)
                        {
                            WBLogging.Debug("Did not find folder for: " + recordsType.Name);
                        }
                    }

                    if (viewMode == VIEW_MODE__NEW || folder != null)
                    {
                        WBRecordsTypeTreeNode recordsTypeTreeNode = new WBRecordsTypeTreeNode(functionalArea, recordsType, folder);
                        TreeNode node = recordsTypeTreeNode.AsTreeNode();

                        if (recordsType.Term.TermsCount > 0 || viewMode != VIEW_MODE__NEW)
                        {
                            if (viewMode == VIEW_MODE__BROWSE_FOLDERS && recordsType.Term.TermsCount == 0)
                            {
                                node.SelectAction = TreeNodeSelectAction.Select;
                            }
                            else
                            {
                                node.SelectAction = TreeNodeSelectAction.Expand;
                            }
                            node.Expanded         = false;
                            node.PopulateOnDemand = true;
                        }
                        else
                        {
                            node.SelectAction     = TreeNodeSelectAction.Select;
                            node.Expanded         = true;
                            node.PopulateOnDemand = false;
                        }

                        treeNodeCollection.Add(node);
                    }
                }
            }
        }
Beispiel #26
0
        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);
        }
Beispiel #27
0
        private void MigrateOneDocumentToLibrary(
            WBMigrationMapping mapping,
            SPSite sourceSite,
            SPWeb sourceWeb,
            SPDocumentLibrary sourceLibrary,
            SPSite destinationSite,
            SPWeb destinationWeb,
            SPFolder destinationRootFolder,
            SPSite controlSite,
            SPWeb controlWeb,
            SPList controlList,
            SPView controlView,
            SPListItem migrationItem)
        {
            WBFarm farm = WBFarm.Local;

            //foreach (SPField field in migrationItem.Fields)
            //{
            //    WBLogging.Migration.Verbose("Field InternalName: " + field.InternalName + "  Field Title: " + field.Title +  " item[field.Title] : " + migrationItem[field.Title]);
            //}

            String sourceFilePath = migrationItem.WBxGetAsString(WBColumn.SourceFilePath);
            String mappingPath    = WBUtils.NormalisePath(migrationItem.WBxGetAsString(WBColumn.MappingPath));

            WBLogging.Migration.Verbose("Trying to migrate file      : " + sourceFilePath);
            WBLogging.Migration.Verbose("Migrating with mapping path : " + mappingPath);

            WBMappedPath mappedPath = mapping[mappingPath];

            SPListItem controlItem = migrationItem;
            SPListItem mappingItem = null;
            SPListItem subjectItem = null;

            String documentumSourceID = "";

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                documentumSourceID = controlItem.WBxGetAsString(WBColumn.SourceID);

                if (!String.IsNullOrEmpty(documentumSourceID))
                {
                    mappingItem = WBUtils.FindItemByColumn(controlSite, MigrationMappingList, WBColumn.SourceID, documentumSourceID);

                    subjectItem = WBUtils.FindItemByColumn(controlSite, MigrationSubjectsList, WBColumn.SourceID, documentumSourceID);
                }
            }



            if (mappedPath.InErrorStatus)
            {
                WBLogging.Migration.HighLevel("WBMigrationTimerJob.MigrateOneDocumentToLibrary(): There was an error with the mapped path: " + mappedPath.ErrorStatusMessage);
                return;
            }

            // OK so let's first get the various WBTerms from the mapped path so that if these
            // fail they fail before we copy the document!

            WBRecordsType                   recordsType    = null;
            WBTermCollection <WBTerm>       functionalArea = null;
            WBTermCollection <WBSubjectTag> subjectTags    = null;

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                string recordsTypePath = controlItem.WBxGetAsString(WBColumn.RecordsTypePath);
                if (String.IsNullOrEmpty(recordsTypePath) && mappingItem != null)
                {
                    recordsTypePath = mappingItem.WBxGetAsString(WBColumn.RecordsTypePath);
                }

                Term rterm = mapping.RecordsTypesTaxonomy.GetSelectedTermByPath(recordsTypePath);
                if (rterm != null)
                {
                    recordsType = new WBRecordsType(mapping.RecordsTypesTaxonomy, rterm);
                }


                string functionalAreaPath = controlItem.WBxGetAsString(WBColumn.FunctionalAreaPath);
                if (String.IsNullOrEmpty(functionalAreaPath) && mappingItem != null)
                {
                    functionalAreaPath = mappingItem.WBxGetAsString(WBColumn.FunctionalAreaPath);
                }

                if (!String.IsNullOrEmpty(functionalAreaPath))
                {
                    string[] paths = functionalAreaPath.Split(';');

                    List <WBTerm> fterms = new List <WBTerm>();

                    foreach (string path in paths)
                    {
                        WBLogging.Migration.Verbose("Trying to get a Functional Area by path with: " + path);

                        Term fterm = mapping.FunctionalAreasTaxonomy.GetOrCreateSelectedTermByPath(path);
                        if (fterm != null)
                        {
                            fterms.Add(new WBTerm(mapping.FunctionalAreasTaxonomy, fterm));
                        }
                        else
                        {
                            WBLogging.Debug("Coundn't find the functional area with path: " + path);
                        }
                    }

                    if (fterms.Count > 0)
                    {
                        functionalArea = new WBTermCollection <WBTerm>(mapping.FunctionalAreasTaxonomy, fterms);
                    }
                }


                string subjectTagsPaths = controlItem.WBxGetAsString(WBColumn.SubjectTagsPaths);
                if (String.IsNullOrEmpty(subjectTagsPaths) && mappingItem != null)
                {
                    subjectTagsPaths = mappingItem.WBxGetAsString(WBColumn.SubjectTagsPaths);
                }

                if (!String.IsNullOrEmpty(subjectTagsPaths))
                {
                    List <WBSubjectTag> sterms = new List <WBSubjectTag>();


                    // Note that it is not necessarily an error for the subject tags to be empty.
                    if (!String.IsNullOrEmpty(subjectTagsPaths) && subjectTagsPaths != "/")
                    {
                        string[] paths = subjectTagsPaths.Split(';');

                        foreach (string path in paths)
                        {
                            WBLogging.Migration.Verbose("Trying to get a Subject Tag by path with: " + path);

                            if (path != "/")
                            {
                                Term sterm = mapping.SubjectTagsTaxonomy.GetOrCreateSelectedTermByPath(path);
                                if (sterm != null)
                                {
                                    sterms.Add(new WBSubjectTag(mapping.SubjectTagsTaxonomy, sterm));
                                }
                                else
                                {
                                    WBLogging.Debug("Coundn't find the subject tag with path: " + path);
                                }
                            }
                        }
                    }

                    subjectTags = new WBTermCollection <WBSubjectTag>(mapping.SubjectTagsTaxonomy, sterms);
                }
            }
            else
            {
                recordsType    = mappedPath.RecordsType;
                functionalArea = mappedPath.FunctionalArea;
                subjectTags    = mappedPath.SubjectTags;
            }



            if (MigrationSubjectsList != null && MigrationSourceSystem == MIGRATION_SOURCE__HFI_INTRANET_DOCUMENTS)
            {
                //foreach (SPField field in migrationItem.Fields)
                //{
                //   WBLogging.Debug("Found field: " + field.Title + " field inner name: " + field.InternalName);
                //}

                subjectTags = AddAdditionalSubjectTags(controlSite, subjectTags, migrationItem.WBxGetAsString(WBColumn.SourceID));
            }


            if (recordsType == null)
            {
                MigrationError(migrationItem, "The records type for this item could not be found. Looked for: " + mappedPath.RecordsTypePath);
                return;
            }

            if (functionalArea == null || functionalArea.Count == 0)
            {
                MigrationError(migrationItem, "The functional area for this item could not be found. Looked for: " + mappedPath.FunctionalAreaPath);
                return;
            }

            // OK so we can start building up our information about the document we are going to declare:
            WBDocument document = new WBDocument();

            document.RecordsType    = recordsType;
            document.FunctionalArea = functionalArea;
            document.SubjectTags    = subjectTags;

            document[WBColumn.SourceFilePath] = sourceFilePath;

            string sourceSystem = migrationItem.WBxGetAsString(WBColumn.SourceSystem);

            if (String.IsNullOrEmpty(sourceSystem))
            {
                sourceSystem = farm.MigrationSourceSystem;
            }
            if (String.IsNullOrEmpty(sourceSystem))
            {
                sourceSystem = farm.MigrationControlListUrl;
            }
            document[WBColumn.SourceSystem] = sourceSystem;

            String sourceID = migrationItem.WBxGetAsString(WBColumn.SourceID);

            if (String.IsNullOrEmpty(sourceID) && MigrationSourceSystem != MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                sourceID = sourceFilePath;
            }
            document[WBColumn.SourceID] = sourceID;

            SPFile     sourceFile = null;
            SPListItem sourceItem = null;

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                if (String.IsNullOrEmpty(sourceID))
                {
                    sourceItem = sourceWeb.GetListItem(sourceFilePath);
                    document[WBColumn.SourceID]     = sourceFilePath;
                    document[WBColumn.SourceSystem] = "Initial SharePoint Web Docs";
                }
                else
                {
                    sourceItem = WBUtils.FindItemByColumn(sourceSite, (SPList)sourceLibrary, WBColumn.Source_ID, sourceID);
                }

                if (sourceItem == null)
                {
                    MigrationError(migrationItem, "Could not find the doc with source id = " + sourceFilePath);
                    return;
                }
                sourceFile = sourceItem.File;
            }



            if (migrationItem.WBxIsNotBlank(WBColumn.ReferenceDateString))
            {
                document.ReferenceDate = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ReferenceDateString));
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
            {
                document.Modified = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ModifiedDateString));
            }
            else
            {
                if (mappingItem != null)
                {
                    if (mappingItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
                    {
                        document.Modified = WBUtils.ParseDate(mappingItem.WBxGetAsString(WBColumn.ModifiedDateString));
                    }
                }
                else if (subjectItem != null)
                {
                    if (subjectItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
                    {
                        document.Modified = WBUtils.ParseDate(subjectItem.WBxGetAsString(WBColumn.ModifiedDateString));
                    }
                }
                else if (sourceItem != null)
                {
                    if (sourceItem.WBxHasValue(WBColumn.Modified))
                    {
                        document.Modified = (DateTime)sourceItem["Modified"];
                    }
                }
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.DeclaredDateString))
            {
                document.DeclaredRecord = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.DeclaredDateString));
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.ScanDateString))
            {
                document.ScanDate = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ScanDateString));
            }


            if (migrationItem.WBxIsNotBlank(WBColumn.OwningTeamPath) || !String.IsNullOrEmpty(mappedPath.OwningTeamPath))
            {
                WBTaxonomy teamsTaxonomy = mapping.TeamsTaxonomy;

                string owningTeamPath = migrationItem.WBxGetAsString(WBColumn.OwningTeamPath);
                if (owningTeamPath == "")
                {
                    owningTeamPath = mappedPath.OwningTeamPath;
                }
                WBTeam foundTeam = teamsTaxonomy.GetSelectedTeam(WBUtils.NormalisePath(owningTeamPath));

                if (foundTeam != null)
                {
                    WBLogging.Migration.Verbose("Found the owning team: " + foundTeam.Name);
                    document.OwningTeam = foundTeam;
                }
                else
                {
                    MigrationError(migrationItem, "Could not find the owning team at: " + owningTeamPath);
                    return;
                }
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.Title))
            {
                document[WBColumn.Title] = migrationItem.WBxGetAsString(WBColumn.Title);
            }


            if (MigrationSourceSystem == MIGRATION_SOURCE__HFI_INTRANET_DOCUMENTS)
            {
                document.Modified = File.GetLastWriteTime(sourceFilePath);
                WBLogging.Debug("Found the last modified date to be: " + document.Modified);
            }

            // We'll set the reference date for these imported files based on their existing declared date or modified date if it exists.
            if (!document.HasReferenceDate)
            {
                if (document.HasDeclaredRecord)
                {
                    document.ReferenceDate = document.DeclaredRecord;
                }
                else if (document.HasScanDate)
                {
                    document.ReferenceDate = document.ScanDate;
                }
                else if (document.HasModified)
                {
                    document.ReferenceDate = document.Modified;
                }
            }

            if (migrationItem.WBxHasValue(WBColumn.ReferenceID))
            {
                document.ReferenceID = migrationItem.WBxGetAsString(WBColumn.ReferenceID);
            }


            string protectiveZone = migrationItem.WBxGetAsString(WBColumn.ProtectiveZone);

            if (String.IsNullOrEmpty(protectiveZone))
            {
                protectiveZone = mappedPath.ProtectiveZone;
                if (String.IsNullOrEmpty(protectiveZone))
                {
                    protectiveZone = WBRecordsType.PROTECTIVE_ZONE__PROTECTED;
                }
            }
            document[WBColumn.ProtectiveZone] = protectiveZone;

            string liveOrArchived = migrationItem.WBxGetAsString(WBColumn.LiveOrArchived);

            if (String.IsNullOrEmpty(liveOrArchived))
            {
                liveOrArchived = mappedPath.LiveOrArchived;
                if (String.IsNullOrEmpty(liveOrArchived))
                {
                    liveOrArchived = WBColumn.LIVE_OR_ARCHIVED__LIVE;
                }
            }
            document[WBColumn.LiveOrArchived] = liveOrArchived;

            bool downloadFromWebSite = false;

            if (MigrationSourceSystem == MIGRATION_SOURCE__ALFRESCO_RECORDS)
            {
                downloadFromWebSite = true;
            }


            String originalFileName = migrationItem.WBxGetAsString(WBColumn.OriginalFilename).Trim();

            if (String.IsNullOrEmpty(originalFileName))
            {
                originalFileName = Path.GetFileName(sourceFilePath);
            }
            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                originalFileName = sourceFile.Name;
            }
            if (downloadFromWebSite)
            {
                originalFileName = HttpUtility.UrlDecode(originalFileName);
            }

            document.OriginalFilename = originalFileName;

            //String extension = Path.GetExtension(filename);


            WBItemMessages metadataErrors = recordsType.CheckMetadataIsOK(document);

            if (metadataErrors.Count > 0)
            {
                string message = "There were problems with the prepared metadata. ";
                foreach (WBColumn column in metadataErrors.Keys)
                {
                    message += "Error for column: " + column.DisplayName + " message: " + metadataErrors[column] + "  ";
                }
                MigrationError(migrationItem, message);
                return;
            }

            Stream fileStream = null;

            if (downloadFromWebSite)
            {
                WebClient webClient = new WebClient();

                if (!String.IsNullOrEmpty(farm.MigrationUserName) && !String.IsNullOrEmpty(farm.MigrationPassword))
                {
                    webClient.Credentials = new NetworkCredential(farm.MigrationUserName, farm.MigrationPassword);
                }

                string tempFile = @"C:\Temp\tmp.bin";
                if (farm.FarmInstance == WBFarm.FARM_INSTANCE__PROTECTED_INTERNAL_FARM)
                {
                    tempFile = @"E:\Temp\tmp.bin";
                }

                webClient.DownloadFile(sourceFilePath, tempFile);
                WBLogging.Migration.Verbose("Downloaded to local tmp file using webClient.DownloadFile() successfully");

                fileStream = File.OpenRead(tempFile);
                WBLogging.Migration.Verbose("Opened local tmp file using File.OpenRead() successfully");
            }
            else if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                fileStream = sourceFile.OpenBinaryStream();
                WBLogging.Migration.Verbose("Opened using sourceFile.OpenBinaryStream() successfully");
            }
            else
            {
                fileStream = File.OpenRead(sourceFilePath);
                WBLogging.Migration.Verbose("Opened using File.OpenRead() successfully");
            }

            SPListItem uploadedItem = null;

            try
            {
                uploadedItem = recordsType.PublishDocument(destinationWeb, destinationRootFolder, document, fileStream);
            }
            finally
            {
                fileStream.Close();
                fileStream.Dispose();
            }

            if (uploadedItem == null)
            {
                MigrationError(migrationItem, "There was a problem in the call to recordsType.PublishDocument() as the uploaded item is null.");
                return;
            }

            migrationItem.WBxSet(WBColumn.DateMigrated, DateTime.Now);
            migrationItem.WBxSet(WBColumn.MigratedToUrl, uploadedItem.WBxGet(WBColumn.EncodedAbsoluteURL));
            migrationItem.WBxSet(WBColumn.RecordID, uploadedItem.WBxGet(WBColumn.RecordID));
            migrationItem.WBxSet(WBColumn.MigrationStatus, WBColumn.MIGRATION_STATUS__DONE);

            migrationItem.Update();
        }