Ejemplo n.º 1
0
        public static void ShowBuildMappingForm(SPDocumentLibrary docLib, MappingProfile mp)
        {
            if (docLib == null)
                return;
            frmBuildMapping f = new frmBuildMapping();

            //--populate cboTargetContentType
            List<string> inelligableContentTypes = new List<string>();
            //inelligableContentTypes.Add("Document");
            inelligableContentTypes.Add("Folder");
            foreach (SPContentType ct in docLib.ContentTypes)
            {
                if (!inelligableContentTypes.Contains(ct.Name)) 
                    f.cboTargetContentType.Items.Add(ct.Name);
            }

            //--
            f.lblTargetDocLib.Text = "Target Document Library: " + docLib.Title;
            f.m_targetDocLib = docLib;
            if (mp == null) //--create a new Mapping Profile
            {
                f.m_mpWorking = new MappingProfile("new profile","");
                f.m_mpWorking.MappingItems = new List<MappingItem>();
                f.txtProfileName.Text = "(New Mapping Profile)";
                f.Text = "New Mapping Profile";
                f.lnkDeleteProfile.Enabled = false;
                if (f.cboTargetContentType.Items.Count == 1)
                    f.cboTargetContentType.SelectedIndex = 0;
            }
            else //--edit existing Mapping Profile
            {
                f.m_editingMPindex = ActionMetaDataUtil.MappingProfiles.IndexOf(mp);
                MappingProfile ret = (MappingProfile)Util.DeepCopy(mp);
                if (ret == null)
                    return;
                f.m_mpWorking = ret;
                f.txtProfileName.Text = mp.ProfileName;
                f.cboTargetContentType.SelectedIndex = f.cboTargetContentType.FindStringExact(mp.TargetContentTypeName);
                f.Text = "Edit Mapping Profile";
                if (f.m_mpWorking.MappingItems == null)
                    f.m_mpWorking.MappingItems = new List<MappingItem>();
            }

            f.displayMappingProfileInRtb(null, null);
            f.Location = new Point(MainForm.DefInstance.Left +10 , MainForm.DefInstance.Top + 10);

            //--
            f.ShowDialog();
        }
        public static void ShowForm(SPDocumentLibrary docLib)
        {
            FrmAddContnetTypeToDocLib f = new FrmAddContnetTypeToDocLib();
            f.m_docLib = docLib;

            //--
            SPWeb rootWeb = docLib.ParentWeb.Site.RootWeb;
            foreach (SPContentType ct in rootWeb.ContentTypes)
            {
                if (ct.Parent.Name == "Document" && ct.Group != "_Hidden")
                    f.cboRootContentTypes.Items.Add(new ContentTypeHolder(ct));
            }

            f.Text = "Add Content Type to " + docLib.Title;
            f.lblAvailableCT.Text = "Content Types available to add from " + rootWeb.Url;
            f.Location = new Point(MainForm.DefInstance.Left + 10, MainForm.DefInstance.Top + 10);
            f.ShowDialog();
        }
Ejemplo n.º 3
0
        protected override void SaveAttributes(Document Document)
        {
            SPSite            site = null;
            SPWeb             web  = null;
            SPFile            file;
            SPDocumentLibrary doclib = null;

            using (site = new SPSite(Document.Storage.MainPath))
            {
                using (web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    doclib = web.Lists[Document.Storage.Name] as SPDocumentLibrary;
                    try
                    {
                        if (!string.IsNullOrEmpty(Document.StorageArea.Path))
                        {
                            file = doclib.RootFolder.SubFolders[Document.StorageArea.Path].Files[GetIdDocuemnt(Document) + Path.GetExtension(Document.Name)];
                        }
                        else
                        {
                            file = doclib.RootFolder.Files[GetIdDocuemnt(Document) + Path.GetExtension(Document.Name)];
                        }
                        foreach (DocumentAttributeValue item in Document.AttributeValues)
                        {
                            file.Item[item.Attribute.Name] = item.Value;
                        }
                    }
                    catch (Exception ex)
                    {
                        //Write the log
                        throw new FileNotUploaded_Exception("File not uploaded" + Environment.NewLine + ex.ToString());
                    }
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// accesses the document library at the path provided,
        /// loops through the learning packages
        /// located the library and reads the package Id from package manifest
        /// </summary>
        /// <param name="siteURL">web site url</param>
        /// <param name="documentLibraryName">document library name</param>
        /// <returns></returns>
        public Hashtable GetAllLearningResources(string siteURL, string documentLibraryName)
        {
            Hashtable         resources      = new Hashtable();
            SharePointV3      sharepoint     = new SharePointV3();
            SPWeb             documentLibWeb = sharepoint.OpenWeb(siteURL);
            SPDocumentLibrary docLibrary     = sharepoint.GetDocumentLibrary(documentLibraryName, documentLibWeb);

            Microsoft.SharePointLearningKit.SlkStore store = SlkStore.GetStore(documentLibWeb);
            foreach (SPListItem item in docLibrary.Items)
            {
                //if this list item is a file
                if (item.File != null)
                {
                    SharePointFileLocation fileLocation = new SharePointFileLocation(documentLibWeb, item.UniqueId, item.File.UIVersion);
                    string location = fileLocation.ToString();
                    try
                    {
                        PackageInformation info = store.GetPackageInformation(location);
                        XPathNavigator     manifestNavigator = info.ManifestReader.CreateNavigator();
                        Guid packageIdentifier = ManifestParser.ParseIndexXml(manifestNavigator);
                        if (packageIdentifier == Guid.Empty)
                        {
                            packageIdentifier = ManifestParser.ParseImsManifestXml(manifestNavigator);
                        }
                        if (packageIdentifier != Guid.Empty)
                        {
                            resources.Add(packageIdentifier.ToString(), location);
                        }
                    }
                    catch
                    {
                        //not a valid learning package, do nothing
                    }
                }
            }
            return(resources);
        }
Ejemplo n.º 5
0
        private void BuildReportTree(SPFolder spFolder, SPDocumentLibrary spDocumentLibrary, ref XElement parentElement)
        {
            var xElement = new XElement("Folder", new XAttribute("Name", spFolder.Name));

            foreach (SPListItem spListItem in spDocumentLibrary.GetItemsInFolder(spDocumentLibrary.DefaultView, spFolder))
            {
                if (spListItem.FileSystemObjectType == SPFileSystemObjectType.Folder)
                {
                    BuildReportTree(spListItem.Folder, spDocumentLibrary, ref xElement);
                }
                else if (spListItem.FileSystemObjectType == SPFileSystemObjectType.File && spListItem.File.Name.ToLower().EndsWith(".rdl"))
                {
                    SPFile spFile = spListItem.File;
                    string name   = spFile.Name;

                    string url = string.Empty;
                    string hasResourcesParam = string.Empty;

                    try
                    {
                        var web = SPContext.Current.Web.Site.RootWeb;
                        var sServerReelativeUrl = (web.ServerRelativeUrl == "/") ? "" : web.ServerRelativeUrl;

                        url = sServerReelativeUrl + "/_layouts/epmlive/SSRSReportRedirect.aspx?weburl=" + HttpUtility.UrlEncode(Web.Site.RootWeb.Url) +
                              "&itemurl=" + HttpUtility.UrlEncode(spListItem.Url);
                    }
                    catch (Exception ex) { }

                    var element = new XElement("Report", new XAttribute("Name", name.Substring(0, name.Length - 4)),
                                               new XAttribute("Url", url),
                                               new XAttribute("HasResourcesParam", hasResourcesParam));

                    xElement.Add(element);
                }
            }
            parentElement.Add(xElement);
        }
Ejemplo n.º 6
0
 internal void RetracSolution(Guid _usGuid)
 {
     try
     {
         Tracing.TraceEvent.TraceVerbose(90, "RetracSolution", String.Format("The solution {0} will be deleted from the SolutionCatalog", _usGuid));
         SPUserSolution _us = SiteCollection.Solutions[_usGuid];
         SiteCollection.Solutions.Remove(_us);
         SPDocumentLibrary solutionGallery = (SPDocumentLibrary)SiteCollection.GetCatalog(SPListTemplateType.SolutionCatalog);
         foreach (SPListItem _li in solutionGallery.Items)
         {
             if (_li.File.Name == _us.Name)
             {
                 solutionGallery.Items.DeleteItemById(_li.ID);
                 Tracing.TraceEvent.TraceInformation(90, "RetracSolution", String.Format("The solution {0} has been deleted from the SolutionCatalog", _us.Name));
                 return;
             }
         }
         Tracing.TraceEvent.TraceWarning(90, "RetracSolution", String.Format("The solution {0} has not been found in the SolutionCatalog", _us.Name));
     }
     catch (Exception ex)
     {
         throw new ApplicationException(String.Format(Resources.LastOperationFailed, ex.Message));
     }
 }
Ejemplo n.º 7
0
        protected override void OnLoad(EventArgs e)
        {
            try
            {
                if (Request.QueryString["items"] != null && Request.QueryString["source"] != null && Request.QueryString["sourceurl"] != null)
                {
                    string   source     = Request.QueryString["source"];
                    string[] items      = Request.QueryString["items"].ToString().Split('|');
                    string   currentWeb = Request.QueryString["sourceurl"].Replace("'", string.Empty);

                    lblItems.Text        = null;
                    lblInstructions.Text = "You have selected the following documents to move.<br><br>";
                    source = source.Substring(1, source.Length - 2).ToLower();
                    Guid sourceId = new Guid(source);

                    SPWeb             web = SPContext.Current.Web;
                    SPDocumentLibrary sourceDocLibrary = (SPDocumentLibrary)web.Lists[sourceId];
                    listFiles = new List <SPFile>();

                    //start at 1 due to items split containing a leading empty value
                    for (int i = 1; i < items.Length; i++)
                    {
                        SPListItem currentListItem = sourceDocLibrary.GetItemById(int.Parse(items[i]));
                        if (currentListItem.File != null)
                        {
                            listFiles.Add(currentListItem.File);
                            lblItems.Text += currentListItem.Name + "<br>";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("Error while loading documents for batch moving.", ex, DiagnosticsCategories.eCaseWeb);
            }
        }
Ejemplo n.º 8
0
    public override void ItemAdded(SPItemEventProperties properties)
    {
        SPFile sourceFile = properties.ListItem.File;
        SPFile destFile;

        // Copy file from source library to destination
        using (Stream stream = sourceFile.OpenBinaryStream())
        {
            SPDocumentLibrary destLib =
                (SPDocumentLibrary)properties.ListItem.Web.Lists["Destination"];
            destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
            stream.Close();
        }

        // Update item properties
        SPListItem destItem   = destFile.Item;
        SPListItem sourceItem = sourceFile.Item;

        destItem["Title"] = sourceItem["Title"];
        //...
        //... destItem["FieldX"] = sourceItem["FieldX"];
        //...
        destItem.UpdateOverwriteVersion();
    }
Ejemplo n.º 9
0
        private void loadFile(SPDocumentLibrary oDocLib, string sDocTmpltURL, string sNewFileName)
        {
            ServicePointManager.ServerCertificateValidationCallback +=
                delegate(
                    object sender,
                    X509Certificate certificate,
                    X509Chain chain,
                    SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var webClient = new WebClient())
                {
                    webClient.UseDefaultCredentials = true;

                    webClient.Headers.Add(HttpRequestHeader.Cookie, Request.Headers["Cookie"]);

                    var fileBytes = webClient.DownloadData(sDocTmpltURL);

                    newFile = oDocLib.RootFolder.Files.Add(sNewFileName + ".mpp", fileBytes);
                    try
                    {
                        newFile.ReleaseLock(newFile.LockId);
                    }
                    catch (Exception ex)
                    {
                        SystemTrace.WriteLine(ex.ToString());
                    }

                    filePath = newFile.ServerRelativeUrl;
                }
            });
        }
 public void AddFile(SPDocumentLibrary list, byte[] data, string fielName, IDictionary props)
 {
 }
 public SPFile UploadFromPath(SPDocumentLibrary library, string path, string fileName)
 {
     return SharePointUtilities.UploadFromPath(library, path, fileName);
 }
Ejemplo n.º 12
0
        private void CreatePOItem(object sender, EventArgs e)
        {
            string _spTitle     = default(string);
            string _newFileName = default(string);
            string _stt         = default(string);

            try
            {
                using (EntitiesDataContext _EDC = new EntitiesDataContext(m_WorkflowProperties.SiteUrl))
                {
                    _stt = "using";
                    Shipping _sp = (from idx in _EDC.Shipping
                                    where idx.Id == m_WorkflowProperties.ItemId
                                    select idx).First();
                    if (!_sp.IsOutbound.Value)
                    {
                        m_LogAfterCreateToHistoryList_HistoryDescription1 = "Document has not been created because it is not outbound shipment";
                        return;
                    }
                    _stt     = "Shipping";
                    _spTitle = _sp.Title;
                    SPDocumentLibrary _lib = (SPDocumentLibrary)m_WorkflowProperties.Web.Lists[CommonDefinition.FreightPOLibraryTitle];
                    _stt = "SPDocumentLibrary";
                    SPFile _teml    = m_WorkflowProperties.Web.GetFile(_lib.DocumentTemplateUrl);
                    string _fname   = String.Format("FREIGHTPOFileName".GetLocalizedString(), _sp.Id.ToString());
                    SPFile _docFile = OpenXMLHelpers.AddDocument2Collection(_teml, _lib.RootFolder.Files, _fname);
                    _newFileName = _docFile.Name;
                    _stt         = "_doc";
                    int       _docId = (int)_docFile.Item.ID;
                    FreightPO _fpo   = (from idx in _EDC.FreightPOLibrary
                                        where idx.Id == _docId
                                        select idx).First();
                    _stt = "FreightPO";
                    if (_sp.Shipping2RouteTitle != null)
                    {
                        Route _rt = _sp.Shipping2RouteTitle;
                        _fpo.FreightPOTransportCosts    = _rt.TransportCosts.GetValueOrDefault(0.0);
                        _fpo.FreightPOTransportUnitType = _sp.Shipping2TransportUnitType.Title();
                        _fpo.FreightPOCommodity         = _rt.Route2Commodity.Title();
                        _fpo.FreightPOCurrency          = _rt.CurrencyTitle.Title();
                        _fpo.FPOFreightPO = _rt.GoodsHandlingPO.NotAvailable();
                        _stt = "FreightPO0";
                        if (_rt.FreightPayerTitle != null)
                        {
                            _fpo.FreightPOPayerAddress           = _rt.FreightPayerTitle != null ? _rt.FreightPayerTitle.CompanyAddress : String.Empty.NotAvailable();
                            _fpo.FreightPOPayerNIP               = _rt.FreightPayerTitle.NIP.NotAvailable();
                            _fpo.FreightPOPayerName              = _rt.FreightPayerTitle.PayerName.NotAvailable();
                            _fpo.FreightPOSendInvoiceToMultiline = _rt.FreightPayerTitle.SendInvoiceToMultiline.NotAvailable();
                            _fpo.FreightPOPayerZip               = _rt.FreightPayerTitle.WorkZip.NotAvailable();
                            _fpo.FreightPOPayerCity              = _rt.FreightPayerTitle.WorkCity.NotAvailable();
                        }
                    }
                    _stt = "Route";
                    _fpo.FreightPOForwarder = _sp.PartnerTitle.Title();
                    _fpo.FreightPOCity      = _sp.Shipping2City.Title();
                    _fpo.FreightPOCountry   = _sp.Shipping2City == null?String.Empty.NotAvailable() : _sp.Shipping2City.CountryTitle.Title();

                    _fpo.FPODispatchDate = _sp.EndTime;
                    _fpo.EmailAddress    = _sp.PartnerTitle == null?String.Empty.NotAvailable() : _sp.PartnerTitle.EmailAddress.NotAvailable();

                    _fpo.FPOLoadingDate      = _sp.StartTime;
                    _fpo.Title               = String.Format("FREIGHT PURCHASE ORDER FPO-1{0, 5}", _fpo.Id.Value);
                    _fpo.FPOWarehouseAddress = _sp.Shipping2WarehouseTitle == null?String.Empty.NotAvailable() : _sp.Shipping2WarehouseTitle.WarehouseAddress.NotAvailable();

                    _stt = "WarehouseAddress ";
                    _sp.Shipping2FreightPOIndex = _fpo;
                    _EDC.SubmitChanges();
                };
                _stt = "SubmitChanges";
                m_LogAfterCreateToHistoryList_HistoryOutcome1     = "Item Created";
                m_LogAfterCreateToHistoryList_HistoryDescription1 = String.Format("File {0} containing purchase order for shipping {1} successfully created.", _newFileName, _spTitle);
            }
            catch (Exception _ex)
            {
                m_LogAfterCreateToHistoryList_HistoryOutcome1 = "Exception";
                string _frmt = "Creation of the PO failed in the \"{0}\" state because of the error {1}";
                m_LogAfterCreateToHistoryList_HistoryDescription1 = string.Format(_frmt, _stt, _ex.Message);
            }
        }
Ejemplo n.º 13
0
        public static XmlDocument QueryFormLibrary(string SiteURL, string FormLibraryTitle, string OptionalContentType, string OptionalCAMLFilter, string OptionalBooleanIncludeAttachments)
        {
            //declare variables
            string currentUser = "";

            try
            {
                //open site context
                using (SPSite site = new SPSite(SiteURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //initialize
                        Stopwatch watch     = new Stopwatch();
                        int       countItem = 0;
                        currentUser = web.CurrentUser.LoginName.ToString();
                        watch.Start();

                        //validate parameter - FormLibraryTitle
                        if (String.IsNullOrEmpty(FormLibraryTitle))
                        {
                            //missing Form Library name, try to find first one in current Web
                            foreach (SPList l in web.GetListsOfType(SPBaseType.DocumentLibrary))
                            {
                                if (l.BaseTemplate == SPListTemplateType.XMLForm)
                                {
                                    FormLibraryTitle = l.Title;
                                    break;
                                }
                            }

                            //unable to find one, return error
                            if (String.IsNullOrEmpty(FormLibraryTitle))
                            {
                                throw new System.NullReferenceException("Required parameter missing.  No form library provided and none exists on this site.");
                            }
                        }

                        //open Form Library
                        SPDocumentLibrary list = (SPDocumentLibrary)web.Lists[FormLibraryTitle];

                        //CAML filter to reduce number of items
                        SPListItemCollection items;
                        if (!String.IsNullOrEmpty(OptionalCAMLFilter))
                        {
                            SPQuery query = new SPQuery(list.DefaultView);
                            query.Query = OptionalCAMLFilter;
                            items       = list.GetItems(query);
                        }
                        else
                        {
                            items = list.Items;
                        }
                        countItem = items.Count;

                        //open XML documents with XSD schema
                        string result = "";
                        int    i      = 0;
                        foreach (SPListItem item in items)
                        {
                            if (item.File.Name.ToUpper().EndsWith(".XML"))
                            {
                                try
                                {
                                    //read file as XML
                                    byte[]       data   = item.File.OpenBinary();
                                    XmlDocument  xml    = new XmlDocument();
                                    MemoryStream stream = new MemoryStream();
                                    stream.Write(data, 0, data.Length);
                                    stream.Seek(0, SeekOrigin.Begin);
                                    XmlTextReader reader = new XmlTextReader(stream);
                                    xml.Load(reader);
                                    xml = RemoveXmlns(xml.OuterXml);

                                    //loop XML child nodes
                                    foreach (XmlNode n in xml.ChildNodes)
                                    {
                                        string outer = n.OuterXml.ToString();
                                        if (!outer.StartsWith("<?"))
                                        {
                                            string append = String.Format("<{0}>{1}</{0}>", n.Name, n.InnerXml.Replace(" xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", ""));
                                            result += append;
                                            break;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //unable to process file
                                    result += String.Format("<Exception><File>{0}</File><Message>{1}</Message><StackTrace>{2}</StackTrace></Exception>", item.File.Name, ex.Message, ex.StackTrace);
                                }
                            }
                            //increment item counter
                            i++;
                        }

                        //diagnostic
                        watch.Stop();
                        string durationMS = watch.ElapsedMilliseconds.ToString();

                        //return merged output
                        result = "<NewDataSet>" + result + String.Format("<Diagnostic><DurationMS>{0}</DurationMS><SPListItems>{1}</SPListItems></Diagnostic></NewDataSet>", durationMS, countItem);

                        //ULS and EventLog
                        InfoPathDBLog.writeLog(String.Format("Success\r\nDurationMS:{6}\r\nSPListItems:{5}\r\nSiteURL:{0}\r\nFormLibraryTitle:{1}\r\nOptionalContentType:{2}\r\nOptionalCAMLFilter:{3}\r\nOptionalBooleanIncludeAttachments:{4}", SPContext.Current.Web.Url, FormLibraryTitle, OptionalContentType, OptionalCAMLFilter, OptionalBooleanIncludeAttachments, countItem, durationMS));

                        //return
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(result);
                        return(doc);
                    }
                }
            }
            catch (System.Exception ex)
            {
                //error handling
                InfoPathDBLog.writeLog(ex);
                XmlDocument doc = new XmlDocument();
                doc.InnerXml = String.Format("<ERROR><Type>{0}</Type><Message>{1}</Message><Source>{2}</Source><StackTrace>{3}</StackTrace><TargetSite>{4}</TargetSite><InnerException>{5}</InnerException><HelpLink>{6}</HelpLink><User>{7}</User></ERROR>", cleanXml(ex.GetType()), cleanXml(ex.Message), cleanXml(ex.Source), cleanXml(ex.StackTrace), cleanXml(ex.TargetSite), cleanXml(ex.InnerException), cleanXml(ex.HelpLink), cleanXml(currentUser));
                return(doc);
            }
        }
Ejemplo n.º 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WBLogging.Generic.Verbose("In Page_Load for the self approval dialog");

            manager = new WBRecordsManager(SPContext.Current.Web.CurrentUser.LoginName);

            // If this is the initial call to the page then we need to load the basic details of the document we're publishing out:
            if (!IsPostBack)
            {
                process         = WBUtils.DeserializeFromCompressedJSONInURI <WBPublishingProcess>(Request.QueryString["PublishingProcessJSON"]);
                process.WorkBox = WorkBox;

//                WBLogging.Debug("Created the WBProcessObject");

                PublishingProcessJSON.Value = WBUtils.SerializeToCompressedJSONForURI(process);

                //             WBLogging.Debug("Serialized the WBProcessObject to hidden field");
            }
            else
            {
                process         = WBUtils.DeserializeFromCompressedJSONInURI <WBPublishingProcess>(PublishingProcessJSON.Value);
                process.WorkBox = WorkBox;
            }



            // Let's clear out all of the error messages text fields:
            ErrorMessageLabel.Text = "";


            //OK so we have the basic identity information for the document being published out so let's get the document item:

            Guid sourceListGuid            = new Guid(process.ListGUID);
            SPDocumentLibrary sourceDocLib = (SPDocumentLibrary)WorkBox.Web.Lists[sourceListGuid];

            sourceDocAsItem = sourceDocLib.GetItemById(int.Parse(process.CurrentItemID));
            sourceFile      = sourceDocAsItem.File;

            WBDocument sourceDocument = new WBDocument(WorkBox, sourceDocAsItem);

            fileTypeInfo = manager.GetFileTypeInfo(sourceDocument.FileType);

            if (fileTypeInfo != null)
            {
                Dictionary <String, String> checkBoxDetails = manager.GetCheckBoxDetailsForDocumentType(fileTypeInfo.WBxGetAsString(WBColumn.DocumentType));
                foreach (String checkBoxCode in checkBoxDetails.Keys)
                {
                    CheckBoxes.Controls.Add(CreateCheckBoxDiv(checkBoxCode, checkBoxDetails[checkBoxCode]));
                }

                CheckBoxesCodes.Value = String.Join(";", checkBoxDetails.Keys.ToArray <string>());
            }

            if (!IsPostBack)
            {
                DocumentsBeingPublished.Text = process.GetStandardHTMLTableRows();

                String typeText = null;

                if (fileTypeInfo != null)
                {
                    typeText = fileTypeInfo.WBxGetAsString(WBColumn.DocumentType) + " (" + fileTypeInfo.WBxGetAsString(WBColumn.FileTypePrettyName) + ")";
                }
                if (String.IsNullOrEmpty(typeText))
                {
                    typeText = sourceDocument.FileType + " " + sourceDocument.Name;
                }
                DocumentType.Text = typeText;
                WBLogging.Debug("The file type of the record is: " + typeText);

                IAO.Text = "<none found>";
                if (!String.IsNullOrEmpty(process.OwningTeamsIAOAtTimeOfPublishing))
                {
                    SPUser owningTeamIAO = SPContext.Current.Web.WBxEnsureUserOrNull(process.OwningTeamsIAOAtTimeOfPublishing);
                    if (owningTeamIAO != null)
                    {
                        IAO.Text = owningTeamIAO.Name;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private void DocLibRecursive(SPWeb web)
        {
            Logger.Instance.Info(String.Format("Batch Copy/Move - Executing DocLibRecursive For Web: {0}", web.Url),
                                 DiagnosticsCategories.eCaseWeb);
            List <SPDocumentLibrary> docLibList = new List <SPDocumentLibrary>();

            string strWebTemplate = web.WebTemplate;
            string strcurrWeb     = currWeb.Title.ToString();
            string strWeb         = web.Title.ToString();

            if (!strWebTemplate.Contains("SEARCH")) // Don't show search site libraries
            {
                if (web.DoesUserHavePermissions(SPBasePermissions.Open))
                {
                    var parentNode = new TreeNode(web.Title.ToString());
                    parentNode.SelectAction = TreeNodeSelectAction.None;
                    treeView.Nodes.Add(parentNode);

                    foreach (SPList list in web.Lists)
                    {
                        if (DoesUserHavePermissions(web, list.Title) && list.BaseType == SPBaseType.DocumentLibrary && !list.IsApplicationList && !list.Hidden && list.Title != "Form Templates" && list.Title != "Customized Reports" && list.Title != "Site Collection Documents" && list.Title != "Site Collection Images" && list.Title != "Images")
                        {
                            SPDocumentLibrary docLib = (SPDocumentLibrary)list;
                            if (docLib.IsCatalog == false)
                            {
                                Logger.Instance.Info(String.Format("Batch Copy/Move - DocLibRecursive - Building Tree Node For Library: {0}",
                                                                   docLib.RootFolder.Url), DiagnosticsCategories.eCaseWeb);
                                TreeNode tn    = new TreeNode();
                                TreeNode child = new TreeNode();

                                tn.ImageUrl = docLib.ImageUrl;
                                tn.Text     = docLib.Title;
                                tn.Value    = web.Url + "/" + docLib.RootFolder.Url;
                                if (docLib.Folders.Count > 0)
                                {
                                    var childItems = docLib.Folders;
                                    foreach (SPListItem childItem in childItems)
                                    {
                                        child          = new TreeNode();
                                        child.ImageUrl = tn.ImageUrl;;
                                        child.Text     = childItem.Name;
                                        child.Value    = web.Url + "/" + childItem.Url;
                                        tn.ChildNodes.Add(child);
                                        child = null;
                                    }
                                }
                                tn.ChildNodes.Add(tn);
                                parentNode.ChildNodes.Add(tn);
                                tn = null;
                            }
                        }
                    }

                    // Collapse all except current site
                    if (strWeb == strcurrWeb)
                    {
                        parentNode.ExpandAll();
                    }
                    else
                    {
                        parentNode.CollapseAll();
                    }

                    //This fails if the user has the ability to open the web, but not enough rights to view the subwebs.
                    foreach (SPWeb subWeb in web.GetSubwebsForCurrentUser())
                    {
                        DocLibRecursive(subWeb);
                        subWeb.Dispose();
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            WBLogging.Generic.Verbose("In Page_Load for the public doc metadata dialog");

            // Creating the taxonomy objects for later use:
            recordsTypeTaxonomy     = WBTaxonomy.GetRecordsTypes(WorkBox.Site);
            teamsTaxonomy           = WBTaxonomy.GetTeams(recordsTypeTaxonomy);
            seriesTagsTaxonomy      = WBTaxonomy.GetSeriesTags(recordsTypeTaxonomy);
            subjectTagsTaxonomy     = WBTaxonomy.GetSubjectTags(recordsTypeTaxonomy);
            functionalAreasTaxonomy = WBTaxonomy.GetFunctionalAreas(recordsTypeTaxonomy);

            // If this is the initial call to the page then we need to load the basic details of the document we're publishing out:
            if (!IsPostBack)
            {
                ListGUID.Value = Request.QueryString["ListGUID"];
                ItemID.Value   = Request.QueryString["ItemID"];

                // The following variable has its name due to a strange compliation error with the name 'DestinationType'
                TheDestinationType.Value = Request.QueryString["DestinationType"];
                DestinationURL.Value     = Request.QueryString["DestinationURL"];
                DestinationTitle.Text    = Request.QueryString["DestinationTitle"] + " (" + Request.QueryString["DestinationType"] + ")";

                WBLogging.Generic.Verbose("DestinationType = " + TheDestinationType.Value);
                WBLogging.Generic.Verbose("DestinationURL = " + DestinationURL.Value);
            }

            // Now do a check that we do at this stage have the basic details of the document:
            if (ListGUID.Value == null || ListGUID.Value == "")
            {
                errorMessage += "ListGUID hasn't been set. ";
            }

            if (ItemID.Value == null || ItemID.Value == "")
            {
                errorMessage += "ItemID hasn't been set. ";
            }

            if (TheDestinationType.Value == null || TheDestinationType.Value == "")
            {
                errorMessage += "DestinationType hasn't been set. ";
            }

            if (errorMessage.Length > 0)
            {
                ErrorMessageLabel.Text = errorMessage;
                return;
            }

            // Let's clear out all of the error messages text fields:
            ErrorMessageLabel.Text          = "";
            RecordsTypeFieldMessage.Text    = "";
            FunctionalAreaFieldMessage.Text = "";
            ProtectiveZoneMessage.Text      = "";
            ReferenceIDMessage.Text         = "";
            ReferenceDateMessage.Text       = "";
            SeriesTagFieldMessage.Text      = "";
            ScanDateMessage.Text            = "";
            OwningTeamFieldMessage.Text     = "";
            InvolvedTeamsFieldMessage.Text  = "";


            //OK so we have the basic identity information for the document being published out so let's get the document item:

            Guid sourceListGuid            = new Guid(ListGUID.Value);
            SPDocumentLibrary sourceDocLib = (SPDocumentLibrary)WorkBox.Web.Lists[sourceListGuid];

            sourceDocAsItem = sourceDocLib.GetItemById(int.Parse(ItemID.Value));
            sourceFile      = sourceDocAsItem.File;

            generatingFilename = WorkBox.RecordsType.GeneratePublishOutFilenames;

            // Now, if this is the first time we might need to load up the default metadata values for the document:
            if (!IsPostBack)
            {
                WorkBox.Web.AllowUnsafeUpdates = true;
                WorkBox.ApplyPublishOutDefaults(sourceDocAsItem);
                WorkBox.Web.AllowUnsafeUpdates = false;

                // Let's now re-load the item as it's name may have changed:
                sourceDocAsItem       = null;
                sourceDocAsItem       = sourceDocLib.GetItemById(int.Parse(ItemID.Value));
                sourceFile            = sourceDocAsItem.File;
                pageRenderingRequired = true;
            }
            else
            {
                WBLogging.Debug("Setting the subject tags: " + SubjectTagsField.Text);
                sourceDocAsItem.WBxSetMultiTermColumn(WorkBox.COLUMN_NAME__SUBJECT_TAGS, SubjectTagsField.Text);


                // If this is a post back - then let's check if the records type has been modified:
                if (NewRecordsTypeUIControlValue.Value != "")
                {
                    WBLogging.Generic.Unexpected("The returned value was: " + NewRecordsTypeUIControlValue.Value);

                    WBRecordsType oldRecordsType = sourceDocAsItem.WBxGetSingleTermColumn <WBRecordsType>(recordsTypeTaxonomy, WorkBox.COLUMN_NAME__RECORDS_TYPE);
                    WBRecordsType newRecordsType = new WBRecordsType(recordsTypeTaxonomy, NewRecordsTypeUIControlValue.Value);

                    RecordsTypeUIControlValue.Value = NewRecordsTypeUIControlValue.Value;
                    RecordsType.Text      = newRecordsType.Name;
                    pageRenderingRequired = true;

                    // These are now being done in CaptureAsDocument()
                    // sourceDocAsItem.WBxSetSingleTermColumn(WorkBox.COLUMN_NAME__RECORDS_TYPE, NewRecordsTypeUIControlValue.Value);
                    // sourceDocAsItem.WBxSet(WBColumn.Title, this.TitleField.Text);

                    // This is now being done in CaptureAsDocument()
                    // WorkBox.GenerateFilename(newRecordsType, sourceDocAsItem);

                    // If either the old or new records type have an uneditable functional area, then we'll update it to the new default area.
                    if (!oldRecordsType.IsFunctionalAreaEditable || !newRecordsType.IsFunctionalAreaEditable)
                    {
                        WBLogging.Debug("Setting the functional area as it's not editable: " + newRecordsType.DefaultFunctionalAreaUIControlValue);
                        this.FunctionalAreaField.Text = newRecordsType.DefaultFunctionalAreaUIControlValue;
                        sourceDocAsItem.WBxSetMultiTermColumn(WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, newRecordsType.DefaultFunctionalAreaUIControlValue);
                    }

/* This is now being done in CaptureAsDocument()
 *                  else
 *                  {
 *                      WBLogging.Debug("Saving the current functional area selection: " + this.FunctionalAreaField.Text);
 *                      sourceDocAsItem.WBxSetMultiTermColumn(WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, this.FunctionalAreaField.Text);
 *                  }
 */

                    WBDocument document = CaptureAsDocument(sourceDocAsItem, newRecordsType);
                    document.Update();

                    // Let's now re-load the item as it's name may have changed:
                    sourceDocAsItem = null;
                    sourceDocAsItem = sourceDocLib.GetItemById(int.Parse(ItemID.Value));
                    sourceFile      = sourceDocAsItem.File;
                }
                else
                {
                    // Otherwise we are in a normal post back call.
                    pageRenderingRequired = false;
                }
            }



            // Now load up some of the basic details:
            documentRecordsType = sourceDocAsItem.WBxGetSingleTermColumn <WBRecordsType>(recordsTypeTaxonomy, WorkBox.COLUMN_NAME__RECORDS_TYPE);

            destinationType = TheDestinationType.Value;

            // Which of the metadata fields are being used in the form (or will need to be processed in any postback) :
            showReferenceID   = documentRecordsType.DocumentReferenceIDRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN;
            showReferenceDate = documentRecordsType.DocumentReferenceDateRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN;
            showSubjectTags   = true; // documentRecordsType.DocumentSubjectTagsRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN;
            showSeriesTag     = documentRecordsType.DocumentSeriesTagRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN;
            showScanDate      = documentRecordsType.DocumentScanDateRequirement != WBRecordsType.METADATA_REQUIREMENT__HIDDEN;

            if (pageRenderingRequired)
            {
                renderPage();
            }
        }
 internal DocumentLibraryIncomingProcessor(SPDocumentLibrary library, SEMessage message, ConfigProvider config)
 {
 }
 public SPFile UploadStream(SPDocumentLibrary library, Stream stream, string fileName)
 {
     return SharePointUtilities.UploadStream(library, stream, fileName);
 }
Ejemplo n.º 19
0
        private void AddItemsFromDocLib(SPDocumentLibrary docLib)
        {
            if (Param.IncludeSubFolders)
            {
                AddItemsFromList(docLib.Items);
            }
            else
            {
                SPQuery q = new SPQuery();
                q.Folder = docLib.RootFolder;

                AddItemsFromList(docLib.GetItems(q));
            }
        }
Ejemplo n.º 20
0
		private void PopulateListOfItems(SPDocumentLibrary lib, SPQuery query, ref List<Item> items)
		{
			SPListItemCollection listItems = lib.GetItems(query);
			PopulateListOfItems(listItems, ref items);
		}
 //获得文件在文档库的索引
 private static int GetFileIndex(SPDocumentLibrary docLib, string fileName)
 {
     for (int i = 0; i < docLib.RootFolder.Files.Count; i++)
     {
         if (docLib.RootFolder.Files[i].Name == fileName)
         {
             return i;
         }
     }
     return -1;//找不到文件
 }
Ejemplo n.º 22
0
        private void processReports(SPWeb web)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string username = "";
                string password = "";
                EPMLiveCore.ReportAuth _chrono = SPContext.Current.Site.WebApplication.GetChild <EPMLiveCore.ReportAuth>("ReportAuth");
                if (_chrono != null)
                {
                    username = _chrono.Username;
                    password = EPMLiveCore.CoreFunctions.Decrypt(_chrono.Password, "KgtH(@C*&@Dhflosdf9f#&f");
                }

                bool reportingIntegratedMode = true;
                bool.TryParse(EPMLiveCore.CoreFunctions.getWebAppSetting(SPContext.Current.Site.WebApplication.Id, "ReportsUseIntegrated"), out reportingIntegratedMode);

                if (!reportingIntegratedMode)
                {
                    Guid fieldsFeature = new Guid("acdb86be-bfa5-41c7-91a8-7682d7edffa5");
                    if (web.Features[fieldsFeature] == null)
                    {
                        web.Features.Add(fieldsFeature);
                    }

                    Guid receiversFeature = new Guid("a8ebe311-83e1-48a4-ab31-50f237398f44");

                    if (web.Features[receiversFeature] == null)
                    {
                        web.Features.Add(receiversFeature);
                    }

                    string dataSourceString = String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <DataSourceDefinition xmlns=""http://schemas.microsoft.com/sqlserver/reporting/2006/03/reportdatasource"">
                      <Extension>SQL</Extension>
                      <ConnectString>Data Source={0};Initial Catalog={1};</ConnectString>
                      <CredentialRetrieval>Store</CredentialRetrieval>
                      <WindowsCredentials>{2}</WindowsCredentials>
                      <ImpersonateUser>False</ImpersonateUser>
                      <Enabled>True</Enabled>
                    </DataSourceDefinition>", txtReportServer.Text, txtReportDatabase.Text, chkWindows.Checked);

                    SPDocumentLibrary doclib = web.Lists["Report Library"] as SPDocumentLibrary;
                    web.AllowUnsafeUpdates   = true;
                    SPFile file = doclib.RootFolder.Files.Add(doclib.RootFolder.Url + "/Data Sources/EPMLiveReportDB.rsds", Encoding.ASCII.GetBytes(dataSourceString), new Hashtable {
                        { "Datasource Credentials", String.Format("{0}:{1}", txtReportUsername.Text, hdnReportPassword.Value == "" ? hdnSaveReportPassword.Value : hdnReportPassword.Value) }
                    }, true);

                    web.AllowUnsafeUpdates = false;
                }
                else
                {
                    SSRS2006.ReportingService2006 SSRS = new SSRS2006.ReportingService2006();
                    SSRS.Url = ssrsurl + "/ReportService2006.asmx";
                    SSRS.UseDefaultCredentials = true;


                    if (password != "")
                    {
                        SSRS.UseDefaultCredentials = false;
                        if (username.Contains("\\"))
                        {
                            SSRS.Credentials = new System.Net.NetworkCredential(username.Substring(username.IndexOf("\\") + 1), password, username.Substring(0, username.IndexOf("\\")));
                        }
                        else
                        {
                            SSRS.Credentials = new System.Net.NetworkCredential(username, password);
                        }
                    }


                    /*System.Web.HttpCookie tCookie = System.Web.HttpContext.Current.Response.Cookies["WSS_KeepSessionAuthenticated"];
                     *
                     * System.Net.Cookie oC = new System.Net.Cookie();
                     *
                     * // Convert between the System.Net.Cookie to a System.Web.HttpCookie...
                     * oC.Domain = System.Web.HttpContext.Current.Request.Url.Host;
                     * oC.Expires = tCookie.Expires;
                     * oC.Name = tCookie.Name;
                     * oC.Path = tCookie.Path;
                     * oC.Secure = tCookie.Secure;
                     * oC.Value = tCookie.Value;
                     *
                     * SSRS.CookieContainer = new System.Net.CookieContainer();
                     *
                     * SSRS.CookieContainer.Add(oC);
                     */

                    try
                    {
                        var authCookie       = HttpContext.Current.Request.Cookies["FedAuth"];
                        var fedAuth          = new Cookie(authCookie.Name, authCookie.Value, authCookie.Path, string.IsNullOrEmpty(authCookie.Domain) ? HttpContext.Current.Request.Url.Host : authCookie.Domain);
                        SSRS.CookieContainer = new CookieContainer();
                        SSRS.CookieContainer.Add(fedAuth);
                    }
                    catch { }

                    SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Report Library"];

                    SPListItemCollection folders = list.GetItemsInFolder(list.DefaultView, list.RootFolder);

                    try
                    {
                        foreach (SPListItem li in folders)
                        {
                            if (li.FileSystemObjectType == SPFileSystemObjectType.Folder && li.Name == "Data Sources")
                            {
                                SSRS2006.DataSourceDefinition dsd = new SSRS2006.DataSourceDefinition();
                                dsd.ConnectString       = "Data Source=" + txtReportServer.Text + ";Initial Catalog=" + txtReportDatabase.Text + ";";
                                dsd.CredentialRetrieval = SSRS2006.CredentialRetrievalEnum.Store;
                                dsd.UserName            = txtReportUsername.Text;
                                if (hdnReportPassword.Value == "")
                                {
                                    dsd.Password = hdnSaveReportPassword.Value;
                                }
                                else
                                {
                                    dsd.Password = hdnReportPassword.Value;
                                }

                                if (chkWindows.Checked)
                                {
                                    dsd.WindowsCredentials = chkWindows.Checked;
                                }

                                dsd.Enabled   = true;
                                dsd.Extension = "SQL";

                                SSRS.CreateDataSource("EPMLiveReportDB.rsds", web.Url + "/" + li.Url, true, dsd, null);
                            }
                        }

                        SSRS2006.DataSourceReference dsr = new SSRS2006.DataSourceReference();
                        dsr.Reference = web.Url + "/Report Library/Data Sources/EPMLiveReportDB.rsds";

                        foreach (SPListItem li in folders)
                        {
                            processRDL(SSRS, web, li, dsr, list);
                        }
                    }
                    catch
                    {
                        pnlMessage.Visible = true;
                    }
                }
            });
        }
Ejemplo n.º 23
0
        public override bool Perform()
        {
            storeurl = CoreFunctions.getFarmSetting("workenginestore");

            solutions = (SPDocumentLibrary)base.SPWeb.Site.GetCatalog(SPListTemplateType.ListTemplateCatalog);

            LogMessage("Activating List Features");

            SPSite.Features.Add(new Guid("e08e676e-81fb-497e-9590-9d1c2673b85c"), true);


            //==============================================================
            LogMessage("Removing old settings list");

            try
            {
                SPList settings = SPWeb.Lists.TryGetList("EPM Live Settings");

                if (settings != null)
                {
                    settings.Delete();
                }
            }
            catch (Exception ex)
            {
                LogMessage("", ex.Message, 3);
            }

            //==============================================================

            LogMessage("Downloading and Installing List Templates");

            DownloadAndInstallList("Departments", "Departments", "Departments");
            DownloadAndInstallList("HolidaySchedules", "HolidaySchedules", "Holiday Schedules");
            DownloadAndInstallList("Holidays", "Holidays", "Holidays");

            if (base.bIsPfe)
            {
                DownloadAndInstallList("EPM Live Settings", "pfe epm live settings", "EPM Live Settings");
            }
            else
            {
                DownloadAndInstallList("EPM Live Settings", "epm live settings", "EPM Live Settings");
            }

            DownloadAndInstallList("Roles", "Roles", "Roles");
            DownloadAndInstallList("WorkHours", "WorkHours", "Work Hours");
            DownloadAndInstallList("Time Off", "TimeOff", "Time Off");
            //==============================================================


            LogMessage("Checking Holidays Lookup");

            SPList oHolidays         = SPWeb.Lists.TryGetList("Holidays");
            SPList oHolidaySchedules = SPWeb.Lists.TryGetList("Holiday Schedules");
            SPList oResourcePool     = SPWeb.Lists.TryGetList("Resources");

            if (oHolidays == null)
            {
                LogMessage("", "Holidays list missing", 3);
            }
            else if (oHolidaySchedules == null)
            {
                LogMessage("", "Holiday Schedules list missing", 3);
            }
            else
            {
                SPField oField = null;
                try
                {
                    oField = oHolidays.Fields.GetFieldByInternalName("HolidaySchedule");
                }
                catch { }

                if (oField == null)
                {
                    LogMessage("\tCreating Holidays Lookup");

                    oField       = oHolidays.Fields.GetFieldByInternalName(oHolidays.Fields.AddLookup("HolidaySchedule", oHolidaySchedules.ID, true));
                    oField.Title = "Holiday Schedule";
                    oField.Update();

                    var spFieldLookup = (SPFieldLookup)oField;
                    spFieldLookup.LookupField = "Title";
                    spFieldLookup.Update();
                }
                else
                {
                    LogMessage("\tUpdating Holidays Lookup");

                    SPFieldLookup oLookup = (SPFieldLookup)oField;
                    if (new Guid(oLookup.LookupList) != oHolidaySchedules.ID)
                    {
                        oField.Delete();
                        oHolidays.Update();
                        oField       = oHolidays.Fields.GetFieldByInternalName(oHolidays.Fields.AddLookup("HolidaySchedule", oHolidaySchedules.ID, true));
                        oField.Title = "Holiday Schedule";
                        oField.Update();

                        var spFieldLookup = (SPFieldLookup)oField;
                        spFieldLookup.LookupField = "Title";
                        spFieldLookup.Update();
                    }
                }

                oHolidays.Update();
            }

            //Fixing Department Lookup

            SPList oDepartments = SPWeb.Lists.TryGetList("Departments");

            if (oDepartments == null)
            {
                LogMessage("", "Departments list missing", 3);
            }
            else
            {
                LogMessage("Departments list lookups");

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("RBS");
                    if (new Guid(lookup.LookupList) != oDepartments.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("RBS", oDepartments.ID, false);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("RBS");



                        lookup.LookupField = "DisplayName";
                        lookup.Title       = "Parent Department";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField RBS");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field RBS: " + ex.Message, 3);
                }

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Managers");
                    if (new Guid(lookup.LookupList) != oResourcePool.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("Managers", oResourcePool.ID, true);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Managers");



                        lookup.LookupField = "Title";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField Managers");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field Managers: " + ex.Message, 3);
                }

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Executives");
                    if (new Guid(lookup.LookupList) != oResourcePool.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("Executives", oResourcePool.ID, false);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Executives");

                        lookup.LookupField = "Title";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField Executives");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field Executives: " + ex.Message, 3);
                }
            }


            LogMessage("Processing Time Off Temp Data");

            SPList oNonWork = SPWeb.Lists.TryGetList("Non Work");
            SPList oTimeOff = SPWeb.Lists.TryGetList("Time Off");

            if (oNonWork == null)
            {
                LogMessage("", "Non Work list missing", 3);
            }
            else if (oTimeOff == null)
            {
                LogMessage("", "Time Off list missing", 3);
            }
            else
            {
                if (!oTimeOff.Fields.ContainsFieldWithInternalName("TempType"))
                {
                    oTimeOff.Fields.Add("TempType", SPFieldType.Text, false);
                    oTimeOff.Update();

                    try
                    {
                        SPField oField = oTimeOff.Fields.GetFieldByInternalName("TempType");
                        oField.ShowInDisplayForm = false;
                        oField.ShowInEditForm    = false;
                        oField.ShowInNewForm     = false;
                        oField.Update();
                    }
                    catch { }
                }

                SPField oTimeOffType = null;
                try
                {
                    oTimeOffType = oTimeOff.Fields.GetFieldByInternalName("TimeOffType");
                }
                catch { }

                if (oTimeOffType != null && oTimeOffType.Type == SPFieldType.Choice)
                {
                    LogMessage("\tProcessing Temp Items");

                    foreach (SPListItem li in oTimeOff.Items)
                    {
                        try
                        {
                            li["TempType"] = li[oTimeOffType.Id].ToString();
                            li.Update();
                        }
                        catch (Exception ex)
                        {
                            LogMessage("\t", li.Title + ": " + ex.Message, 3);
                        }
                    }
                }

                SPField oWorkDetail = null;
                try
                {
                    oWorkDetail = oTimeOff.Fields.GetFieldByInternalName("WorkDetail");
                }
                catch { }

                if (oWorkDetail == null)
                {
                    try
                    {
                        oTimeOff.Fields.AddFieldAsXml(@"<Field Type=""DaysHoursBreakdownField"" DisplayName=""WorkDetail"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" StaticName=""WorkDetail"" Name=""WorkDetail"" ><Customization><ArrayOfProperty><Property><Name>StartDateField</Name><Value xmlns:q1=""http://www.w3.org/2001/XMLSchema"" p4:type=""q1:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">StartDate</Value></Property><Property><Name>FinishDateField</Name><Value xmlns:q2=""http://www.w3.org/2001/XMLSchema"" p4:type=""q2:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">DueDate</Value></Property><Property><Name>HoursField</Name><Value xmlns:q3=""http://www.w3.org/2001/XMLSchema"" p4:type=""q3:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Work</Value></Property><Property><Name>HolidaySchedulesField</Name><Value xmlns:q4=""http://www.w3.org/2001/XMLSchema"" p4:type=""q4:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">HolidaySchedule</Value></Property><Property><Name>ResourcePoolList</Name><Value xmlns:q5=""http://www.w3.org/2001/XMLSchema"" p4:type=""q5:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Resources</Value></Property><Property><Name>WorkHoursList</Name><Value xmlns:q6=""http://www.w3.org/2001/XMLSchema"" p4:type=""q6:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Work Hours</Value></Property><Property><Name>HolidaysList</Name><Value xmlns:q7=""http://www.w3.org/2001/XMLSchema"" p4:type=""q7:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Holidays</Value></Property></ArrayOfProperty></Customization></Field>");
                        SPField oField = oTimeOff.Fields.GetFieldByInternalName("WorkDetail");
                        oField.Title = "Work Detail";
                        oField.Update();

                        LogMessage("\tAdd Work Detail Field");
                    }
                    catch (Exception ex)
                    {
                        LogMessage("", "Add Work Detail: " + ex.Message, 3);
                    }
                }
            }

            try
            {
                if (!oResourcePool.Fields.ContainsFieldWithInternalName("EXTID"))
                {
                    oResourcePool.Fields.Add("EXTID", SPFieldType.Text, false);
                    SPField oField = oResourcePool.Fields.GetFieldByInternalName("EXTID");
                    oField.Hidden = true;
                    oField.Update();

                    LogMessage("Add EXTID Field to Resources");
                }
            }
            catch (Exception ex)
            {
                LogMessage("", "Add EXTID Field to Resources: " + ex.Message, 3);
            }

            //Process dept event

            LogMessage("Processing Department Events");

            try
            {
                bool badding   = false;
                bool bupdating = false;
                bool bdeleted  = false;

                string sClass    = "EPMLiveCore.DepartmentEvent";
                string sAssembly = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5";

                foreach (SPEventReceiverDefinition e in oDepartments.EventReceivers)
                {
                    if (e.Assembly == sAssembly && e.Class == sClass)
                    {
                        if (e.Type == SPEventReceiverType.ItemAdding)
                        {
                            badding = true;
                        }
                        else if (e.Type == SPEventReceiverType.ItemUpdating)
                        {
                            bupdating = true;
                        }
                        else if (e.Type == SPEventReceiverType.ItemDeleted)
                        {
                            bdeleted = true;
                        }
                    }
                }

                if (!badding)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemAdding, sAssembly, sClass);
                    oDepartments.Update();
                }

                if (!bupdating)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemUpdating, sAssembly, sClass);
                    oDepartments.Update();
                }
                if (!bdeleted)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemDeleted, sAssembly, sClass);
                    oDepartments.Delete();
                }
            }
            catch (Exception ex)
            {
                LogMessage("", ex.Message, 3);
            }

            LogMessage("Mapping Reporting lists.");

            var       reportData = new ReportData(SPSite.ID);
            DataTable dbMappings = reportData.GetDbMappings();

            if (!dbMappings.Select(string.Format("SiteId = '{0}'", SPSite.ID)).Any())
            {
                LogMessage("", "Reporting is not configured.", 2);
            }
            else
            {
                try
                {
                    var reportBiz = new ReportBiz(SPSite.ID, SPSite.WebApplication.Id);

                    reportBiz.GetDatabaseMappings();

                    foreach (var list in new[] { "Work Hours", "Holiday Schedules", "Holidays", "Time Off" })
                    {
                        try
                        {
                            LogMessage("Mapping " + list + " list to Reporting.");

                            SPList spList = SPWeb.Lists[list];

                            ListBiz listBiz = reportBiz.CreateListBiz(spList.ID);

                            if (string.IsNullOrEmpty(listBiz.ListName))
                            {
                                reportBiz.CreateListBiz(spList.ID);
                                LogMessage("", "Mapped successfully.", 1);
                            }
                            else
                            {
                                LogMessage("", "Already mapped.", 2);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMessage("", ex.Message, 3);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", ex.Message, 3);
                }
            }

            return(true);
        }
Ejemplo n.º 24
0
 private void processRDL(SSRS2006.ReportingService2006 SSRS, SPWeb web, SPListItem folder, SSRS2006.DataSourceReference dsr, SPDocumentLibrary list)
 {
     foreach (SPListItem li in list.GetItemsInFolder(list.DefaultView, folder.Folder))
     {
         if (li.FileSystemObjectType == SPFileSystemObjectType.Folder)
         {
             processRDL(SSRS, web, li, dsr, list);
         }
         else
         {
             try
             {
                 SSRS2006.DataSource[] dsstl = SSRS.GetItemDataSources(web.Url + "/" + li.Url);
                 for (int i = 0; i < dsstl.Length; i++)
                 {
                     if (dsstl[i].Name == "EPMLiveReportDB")
                     {
                         dsstl[i].Item = dsr;
                     }
                 }
                 SSRS.SetItemDataSources(web.Url + "/" + li.Url, dsstl);
             }
             catch { }
         }
     }
 }
 public static SPFile UploadStream(SPDocumentLibrary library, Stream stream, string fileName)
 {
     library.RequireNotNull("library");
     stream.RequireNotNull("stream");
     fileName.RequireNotNullOrEmpty("fileName");
     SPFolder rootFolder = library.RootFolder;
     SPFile spFile = rootFolder.Files.Add(fileName, stream);
     library.Update();
     return spFile;
 }
 protected abstract void PopulateTree(SPListItemCollection listItems, SPDocumentLibrary doc, TreeNode treeNode);
Ejemplo n.º 27
0
        private void InspectLibrary(SPList list)
        {
            if (!(list is SPDocumentLibrary))
            {
                return;
            }

            SPDocumentLibrary docLib = (SPDocumentLibrary)list;

            foreach (Microsoft.SharePoint.SPCheckedOutFile file in docLib.CheckedOutFiles)
            {
                var details = new SPCheckedOutFile()
                {
                    FileWithNoCheckIn = file,
                    File              = null,
                    Url               = list.ParentWeb.Site.MakeFullUrl(SPUrlUtility.CombineUrl(list.ParentWeb.ServerRelativeUrl, file.Url)),
                    SiteId            = list.ParentWeb.Site.ID,
                    WebId             = list.ParentWeb.ID,
                    ListId            = list.ID,
                    ListItemId        = file.ListItemId,
                    CheckedOutBy      = file.CheckedOutBy,
                    CheckedOutByEmail = file.CheckedOutByEmail,
                    CheckedOutById    = file.CheckedOutById,
                    CheckedOutByName  = file.CheckedOutByName,
                    DirName           = file.DirName,
                    ImageUrl          = file.ImageUrl,
                    LeafName          = file.LeafName,
                    Length            = file.Length,
                    TimeLastModified  = file.TimeLastModified
                };
                WriteObject(details);
            }
            foreach (SPListItem item in docLib.Items)
            {
                if (!Utilities.IsCheckedOut(item))
                {
                    continue;
                }
                if (docLib.CheckedOutFiles.Any(f => f.ListItemId == item.ID))
                {
                    continue;
                }

                SPFile file    = item.File;
                var    details = new SPCheckedOutFile()
                {
                    FileWithNoCheckIn = null,
                    File              = file,
                    Url               = list.ParentWeb.Site.MakeFullUrl(SPUrlUtility.CombineUrl(list.ParentWeb.ServerRelativeUrl, file.Url)),
                    SiteId            = list.ParentWeb.Site.ID,
                    WebId             = list.ParentWeb.ID,
                    ListId            = list.ID,
                    ListItemId        = item.ID,
                    CheckedOutBy      = file.CheckedOutByUser,
                    CheckedOutByEmail = file.CheckedOutByUser.Email,
                    CheckedOutById    = file.CheckedOutByUser.ID,
                    CheckedOutByName  = file.CheckedOutByUser.Name,
                    DirName           = file.ParentFolder.Url,
                    ImageUrl          = "/_layouts/images/" + SPUtility.MapToIcon(list.ParentWeb, file.Name, string.Empty),
                    LeafName          = file.Name,
                    Length            = file.Length,
                    TimeLastModified  = file.TimeLastModified
                };
                WriteObject(details);
            }
        }
Ejemplo n.º 28
0
        private void lnkAddNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SPDocumentLibrary docLib = (SPList)cboDocLibs.SelectedItem as SPDocumentLibrary;

            frmBuildMapping.ShowBuildMappingForm(docLib, null);
        }
Ejemplo n.º 29
0
		private void PopulateListOfItems(SPDocumentLibrary lib, SPFolder folder, SPView view, ref List<Item> items)
		{
			SPList list = lib.Lists[folder.ParentListId];
			SPQuery query = new SPQuery(view);
			query.Folder = folder;
			SPListItemCollection listItems = list.GetItems(query);

			PopulateListOfItems(listItems, ref items);
		}
Ejemplo n.º 30
0
        /// <summary>
        /// Processes the specified request for CFD content and returns the alternatePresentation string of HTML to deliver to the client.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="webId">The web id.</param>
        /// <param name="listId">The list id.</param>
        /// <param name="type">The type of request - Open or Save</param>
        /// <param name="location">The location within the web</param>
        /// <param name="url">The URL of the entire request</param>
        /// <param name="largeListThrottled">The parameter is not used.</param>
        /// <param name="lcid">The lcid for the culture of the request</param>
        /// <param name="userAgent">The browser user agent string</param>
        /// <param name="webProperties">The properties for the Web</param>
        /// <param name="defaultPresentation">The default presentation through the OOB page</param>
        /// <param name="alternatePresentation">The alternate presentation which will be delivered to the client</param>
        public void Process(Guid siteId, Guid webId, Guid listId, WffRequestType type, string location, string url, bool largeListThrottled, int lcid, string userAgent, Hashtable webProperties, string defaultPresentation, ref string alternatePresentation)
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(defaultPresentation) || string.IsNullOrEmpty(userAgent))
            {
                return;
            }

            NameValueCollection queryString = HttpUtility.ParseQueryString(url.Substring(url.IndexOf("?", StringComparison.OrdinalIgnoreCase)));
            string extensions = string.Empty;
            //identify whether this is a request from outlook or not
            bool outlook = false;

            if (!string.IsNullOrEmpty(queryString["Extensions"]))
            {
                extensions = queryString["Extensions"].ToLowerInvariant();
                outlook    = true;
            }

            if (extensions.Contains("oob"))
            {
                alternatePresentation = defaultPresentation.Replace("</h1>", "</h1>(Custom dialog turned off due to querystring)");
                return;
            }
            else
            {
                try
                {
                    //is the user trying to open a document or save one
                    string action = "Open";
                    if (type == WffRequestType.Save)
                    {
                        action = "Save";
                    }

                    using (SPSite site = new SPSite(siteId))
                    {
                        using (SPWeb web = site.OpenWeb(webId))
                        {
                            List <string> filters = CustomFileDialogPostProcessor.ParseFileFormatFilterString(queryString["filedialogfiltervalue"]);
                            XmlDocument   content = null;
                            Data          data    = new Data();
                            //If we have an id we are currently looking at a list
                            if (listId.CompareTo(Guid.Empty) != 0)
                            {
                                SPDocumentLibrary library = web.Lists[listId] as SPDocumentLibrary;
                                SPFolder          folder  = web.GetFolder(location);
                                //get a data representation for that list
                                content = data.GetListData(library, folder, outlook, action, "Modified", filters);
                                //transform the list into Html for the cfd
                            }
                            else //assume website
                            {
                                content = data.GetSiteData(web, outlook, action, "Modified", filters);
                            }

                            XsltArgumentList args = new XsltArgumentList();
                            foreach (string key in queryString.AllKeys)
                            {
                                if (!string.IsNullOrEmpty(key))
                                {
                                    args.AddParam("qs-" + key.ToLowerInvariant(), string.Empty, queryString[key]);
                                }
                            }

                            string xsltPath = RootSiteFromAny(web.Url) + "/Style%20Library/SingleAndMultiselect.xslt";

                            alternatePresentation = GetTransformedData(content, xsltPath, args);
                        }
                    }



                    // alternatePresentation = XmlHelpers.GetTransformedData(content, Concat(SharePointPathManipulation.RootSiteFromAny(pd.SiteUrl), stylesheet), args);
                }
                catch (Exception ex)
                {
                    alternatePresentation = defaultPresentation.Replace("</h1>", "</h1>(Custom dialog not available due to an error.  You can try to navigate using the standard dialog below.  If you see this message repeatedly, try closing and reopening your editing application (e.g. Word))<!--" + ex.Message + ex.StackTrace + "-->");
                }
            }
        }
Ejemplo n.º 31
0
        private void RunOneMigrationCycle()
        {
            WBFarm farm = WBFarm.Local;

            WBMigrationMapping mapping = new WBMigrationMapping(farm.MigrationMappingListUrl, farm.MigrationMappingListView);

            using (SPSite controlSite = new SPSite(farm.MigrationControlListUrl))
                using (SPWeb controlWeb = controlSite.OpenWeb())
                {
                    SPList controlList = controlWeb.GetList(farm.MigrationControlListUrl);
                    SPView controlView = null;
                    SPListItemCollection migrationItems = null;

                    MigrationMappingList = controlWeb.GetList(farm.MigrationMappingListUrl);

                    if (!String.IsNullOrEmpty(farm.MigrationSubjectsListUrl))
                    {
                        MigrationSubjectsList = controlWeb.GetList(farm.MigrationSubjectsListUrl);
                    }

                    if (String.IsNullOrEmpty(farm.MigrationControlListView))
                    {
                        migrationItems = controlList.Items;
                    }
                    else
                    {
                        controlView    = controlList.Views[farm.MigrationControlListView];
                        migrationItems = controlList.GetItems(controlView);
                    }

                    int total = migrationItems.Count;

                    int itemsPerCycle = Convert.ToInt32(farm.MigrationItemsPerCycle);
                    if (itemsPerCycle <= 0)
                    {
                        itemsPerCycle = total;
                    }

                    int count = 0;

                    // Now let's get the additional subjects list if it is defined:



                    /*
                     *
                     *   Now opening the SPSite and SPWeb objects that can be re-used for each migrated item (where appropriate).
                     *
                     */

                    SPSite   destinationSite       = null;
                    SPWeb    destinationWeb        = null;
                    SPFolder destinationRootFolder = null;

                    SPSite            sourceSite    = null;
                    SPWeb             sourceWeb     = null;
                    SPDocumentLibrary sourceLibrary = null;

                    switch (farm.MigrationType)
                    {
                    case WBFarm.MIGRATION_TYPE__MIGRATE_IZZI_PAGES:
                    {
                        // nothing at the moment
                        break;
                    }

                    case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_LIBRARY:
                    {
                        destinationSite       = new SPSite(farm.ProtectedRecordsLibraryUrl);
                        destinationWeb        = destinationSite.OpenWeb();
                        destinationRootFolder = destinationWeb.GetFolder(farm.ProtectedRecordsLibraryUrl);

                        mapping.ConnectToSite(destinationSite);


                        if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
                        {
                            if (farm.FarmInstance == WBFarm.FARM_INSTANCE__DEVELOPMENT_FARM)
                            {
                                sourceSite    = new SPSite("http://sharepointhub/records");
                                sourceWeb     = sourceSite.OpenWeb();
                                sourceLibrary = sourceWeb.Lists["Source Library"] as SPDocumentLibrary;
                            }
                            else
                            {
                                sourceSite    = new SPSite("http://stagingweb/publicrecords");
                                sourceWeb     = sourceSite.OpenWeb();
                                sourceLibrary = sourceWeb.Lists["Documents"] as SPDocumentLibrary;

                                foreach (SPField field in sourceLibrary.Fields)
                                {
                                    WBLogging.Generic.Verbose("Field found: " + field.Title + " internal: " + field.InternalName + " type: " + field.Type.ToString());
                                }
                            }
                        }



                        break;
                    }

                    case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_WORK_BOXES:
                    {
                        // nothing at the moment
                        break;
                    }
                    }

                    try
                    {
                        foreach (SPListItem migrationItem in migrationItems)
                        {
                            count++;
                            if (count > itemsPerCycle)
                            {
                                break;
                            }

                            string progressString = String.Format("Migrating item {0} of {1} in a cycle of {2} items using control list: {3}", count, total, itemsPerCycle, farm.MigrationControlListUrl);

                            try
                            {
                                switch (farm.MigrationType)
                                {
                                case WBFarm.MIGRATION_TYPE__MIGRATE_IZZI_PAGES:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start izzi Page Migration Cycle. " + progressString);

                                    MigrateOneWebPage(mapping, controlSite, controlWeb, controlList, controlView, migrationItem);

                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End izzi Page Migration Cycle.");
                                    break;
                                }

                                case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_LIBRARY:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start Documents To Library Migration Cycle. " + progressString);

                                    if (migrationItem.WBxGetAsString(WBColumn.FileOrFolder) == WBColumn.FILE_OR_FOLDER__FOLDER)
                                    {
                                        AddSubFilesAndFolders(mapping,
                                                              controlSite, controlWeb, controlList, controlView,
                                                              migrationItem);
                                    }
                                    else
                                    {
                                        MigrateOneDocumentToLibrary(mapping,
                                                                    sourceSite, sourceWeb, sourceLibrary,
                                                                    destinationSite, destinationWeb, destinationRootFolder,
                                                                    controlSite, controlWeb, controlList, controlView,
                                                                    migrationItem);
                                    }


                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End Documents To Library Migration Cycle.");
                                    break;
                                }

                                case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_WORK_BOXES:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start Documents To Work Boxes Migration Cycle. " + progressString);

                                    MigrateOneDocumentToWorkBox(mapping, controlSite, controlWeb, controlList, controlView, migrationItem);

                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End Documents To Work Boxes Migration Cycle.");
                                    break;
                                }

                                default:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): No migration setup to run - doing nothing.");
                                    break;
                                }
                                }
                            }
                            catch (Exception itemLevelException)
                            {
                                string messageSoFar = migrationItem.WBxGetAsString(WBColumn.MigrationMessage);

                                migrationItem.WBxSet(WBColumn.MigrationStatus, WBColumn.MIGRATION_STATUS__ERROR);
                                migrationItem.WBxSet(WBColumn.MigrationMessage, messageSoFar + "Exception Thrown: " + itemLevelException.Message);
                                migrationItem.Update();

                                WBLogging.Migration.Unexpected("An item level exception has occurred:");
                                WBLogging.Migration.Unexpected(itemLevelException);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        WBLogging.Migration.Unexpected(exception);
                    }
                    finally
                    {
                        if (destinationWeb != null)
                        {
                            destinationWeb.Dispose();
                        }
                        if (destinationSite != null)
                        {
                            destinationSite.Dispose();
                        }

                        if (sourceWeb != null)
                        {
                            sourceWeb.Dispose();
                        }
                        if (sourceSite != null)
                        {
                            sourceSite.Dispose();
                        }
                    }
                }
        }
        protected void publishButton_OnClick(object sender, EventArgs e)
        {
            WBLogging.Debug("In publishButton_OnClick()");

            Hashtable metadataProblems = checkMetadataState();

            string protectiveZone = "";


            if (metadataProblems.Count > 0)
            {
                RecordsTypeFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__RECORDS_TYPE].WBxToString();

                FunctionalAreaFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__FUNCTIONAL_AREA].WBxToString();
                ProtectiveZoneMessage.Text      = metadataProblems[WorkBox.COLUMN_NAME__PROTECTIVE_ZONE].WBxToString();

                //               SubjectTagsMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__SUBJECT_TAGS].WBxToString();
                ReferenceIDMessage.Text    = metadataProblems[WorkBox.COLUMN_NAME__REFERENCE_ID].WBxToString();;
                ReferenceDateMessage.Text  = metadataProblems[WorkBox.COLUMN_NAME__REFERENCE_DATE].WBxToString();;
                SeriesTagFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__SERIES_TAG].WBxToString();
                ScanDateMessage.Text       = metadataProblems[WorkBox.COLUMN_NAME__SCAN_DATE].WBxToString();

                OwningTeamFieldMessage.Text    = metadataProblems[WorkBox.COLUMN_NAME__OWNING_TEAM].WBxToString();
                InvolvedTeamsFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__INVOLVED_TEAMS].WBxToString();

                pageRenderingRequired = true;
            }
            else
            {
                pageRenderingRequired = false;
            }

            if (pageRenderingRequired)
            {
                WBLogging.Debug("In publishButton_OnClick(): Page render required - not publishing at this point");
                renderPage();
            }
            else
            {
                WBLogging.Debug("In publishButton_OnClick(): No page render required - so moving to publish");

                // The event should only be processed if there is no other need to render the page again

                // First let's update the item with the new metadata values submitted:
                SPDocumentLibrary sourceDocLib    = (SPDocumentLibrary)SPContext.Current.Web.Lists[new Guid(ListGUID.Value)];
                SPListItem        sourceDocAsItem = sourceDocLib.GetItemById(int.Parse(ItemID.Value));

                WBDocument document = CaptureAsDocument(sourceDocAsItem, documentRecordsType);

                document.Update();

                /*
                 *
                 *   OK So now we actually publish out the document:
                 *
                 */


                SPFile sourceFile   = sourceDocAsItem.File;
                string errorMessage = "";

                string successMessage = "<h3>Successfully Published Out</h3> <table cellpadding='5'>";
                if (TheDestinationType.Value.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__WORK_BOX))
                {
                    using (WorkBox workBox = new WorkBox(DestinationURL.Value))
                    {
                        string selectedFolderPath = Request.QueryString["SelectedFolderPath"];
                        if (string.IsNullOrEmpty(selectedFolderPath))
                        {
                            selectedFolderPath = "/";
                        }

                        string destinationRootFolderUrl = DestinationURL.Value + "/" + workBox.DocumentLibrary.RootFolder.Url + selectedFolderPath;

                        errorMessage = sourceFile.WBxCopyTo(destinationRootFolderUrl, new List <String>());

                        if (errorMessage == "")
                        {
                            successMessage += "<tr><td>Filename</td><td><b>" + sourceFile.Name + "</b></td></tr><tr><td>Published out to:</td><td><a href=\"" + destinationRootFolderUrl + "\"><b>" + destinationRootFolderUrl + "</b></a></td></tr>";
                        }
                    }
                }
                else
                {
                    // WBRecordsType recordsType = new WBRecordsType(recordsTypeTaxonomy, document[WBColumn.RecordsType].WBxToString());

                    using (WBRecordsManager manager = new WBRecordsManager(SPContext.Current.Web.CurrentUser.LoginName))
                    {
                        try
                        {
                            WBLogging.Debug("In publishButton_OnClick(): About to try to publish");

                            manager.PublishDocument(WorkBox, document);

                            WBLogging.Debug("In publishButton_OnClick(): Should have finished the publishing");

                            //recordsType.PublishDocument(document, sourceFile.OpenBinaryStream());

                            string fullClassPath = "Just a test"; //  WBUtils.NormalisePath(document.FunctionalArea.Names() + "/" + recordsType.FullPath);

                            successMessage += "<tr><td>Published out to location:</td><td>" + fullClassPath + "</td></tr>\n";


                            if (document.ProtectiveZone == WBRecordsType.PROTECTIVE_ZONE__PUBLIC)
                            {
                                successMessage += "<tr><td>To public records library</td><td><a href=\"http://stagingweb/publicrecords\">Our public library</a></td></tr>\n";
                            }

                            if (document.ProtectiveZone == WBRecordsType.PROTECTIVE_ZONE__PUBLIC_EXTRANET)
                            {
                                successMessage += "<tr><td>To public extranet records library</td><td><a href=\"http://stagingextranets/records\">Our public extranet library</a></td></tr>\n";
                            }

                            successMessage += "<tr><td>To internal records library</td><td><a href=\"http://sp.izzi/library/Pages/ViewByFunctionThenType.aspx\">Our internal library</a></td></tr>\n";
                        }
                        catch (Exception exception)
                        {
                            errorMessage = "An error occurred when trying to publish: " + exception.Message;
                            WBLogging.Generic.Unexpected(exception);
                        }
                    }
                }

/*
 *              WBFarm farm = WBFarm.Local;
 *              string destinationRootFolderUrl = farm.ProtectedRecordsLibraryUrl;
 *              List<String> filingPath = null;
 *
 *
 *              filingPath = documentRecordsType.FilingPathForItem(sourceDocAsItem);
 *
 *              string filingPathString = string.Join("/", filingPath.ToArray());
 *
 *              WBLogging.Generic.Verbose("The file is: " + sourceFile.Url);
 *              WBLogging.Generic.Verbose("The destination is: " + destinationRootFolderUrl);
 *              WBLogging.Generic.Verbose("The destination filing path is: " + filingPathString);
 *
 *
 *              string errorMessage = sourceFile.WBxCopyTo(destinationRootFolderUrl, filingPath);
 *
 *              if (errorMessage == "")
 *              {
 *                  successMessage += "<tr><td>Filename</td><td><b>" + sourceFile.Name + "</b></td></tr><tr><td>Published out to:</td><td><a href=\"" + destinationRootFolderUrl + "\"><b>" + destinationRootFolderUrl + "</b></a></td></tr><tr><td>Filing path:</td><td><a href=\"" + destinationRootFolderUrl + "/" + filingPathString + "\"><b>" + filingPathString + "</b></td></tr>";
 *              }
 *
 *              WBLogging.Generic.Verbose("Protective zone was set to be: " + protectiveZone);
 *
 *
 *              if (!TheDestinationType.Value.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__WORK_BOX)
 *                  && protectiveZone.Equals(WBRecordsType.PROTECTIVE_ZONE__PUBLIC))
 *              {
 *                  // OK so we're going to copy this to the public library as well:
 *              WBLogging.Generic.Verbose("The file is: " + sourceFile.Url);
 *              WBLogging.Generic.Verbose("The destination is: " + farm.PublicRecordsLibraryUrl);
 *              WBLogging.Generic.Verbose("The destination filing path is: " + filingPathString);
 *
 *                  string errorMessagePublic = sourceFile.WBxCopyTo(farm.PublicRecordsLibraryUrl, filingPath);
 *
 *                  if (errorMessagePublic == "")
 *                  {
 *                      successMessage += "<tr><td colspan='2'><b>And also published to the public library.</b></td></tr>";
 *                  }
 *              }
 *
 *              if (!TheDestinationType.Value.Equals(WorkBox.PUBLISHING_OUT_DESTINATION_TYPE__WORK_BOX)
 *                  && protectiveZone.Equals(WBRecordsType.PROTECTIVE_ZONE__PUBLIC_EXTRANET))
 *              {
 *                  // OK so we're going to copy this to the public extranet library as well:
 *                  WBLogging.Generic.Verbose("The file is: " + sourceFile.Url);
 *                  WBLogging.Generic.Verbose("The destination is: " + farm.PublicExtranetRecordsLibraryUrl);
 *                  WBLogging.Generic.Verbose("The destination filing path is: " + filingPathString);
 *
 *                  string errorMessagePublicExtranet = sourceFile.WBxCopyTo(farm.PublicExtranetRecordsLibraryUrl, filingPath);
 *
 *                  if (errorMessagePublicExtranet == "")
 *                  {
 *                      successMessage += "<tr><td colspan='2'><b>And also published to the public extranet library.</b></td></tr>";
 *                  }
 *              }
 */
                successMessage += "</table>";

                if (errorMessage == "")
                {
                    //returnFromDialogOKAndRefresh();
                    GoToGenericOKPage("Publishing Out Success", successMessage);
                }
                else
                {
                    GoToGenericOKPage("Publishing Out Error", errorMessage);

                    //returnFromDialogOK("An error occurred during publishing: " + errorMessage);
                }
            }
        }
Ejemplo n.º 33
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();
        }
 public static SPFile UploadFromPath(SPDocumentLibrary library, string path, string fileName)
 {
     library.RequireNotNull("library");
     path.RequireNotNullOrEmpty("path");
     fileName.RequireNotNullOrEmpty("fileName");
     using (Stream stream = File.OpenRead(path))
     {
         return UploadStream(library, stream, fileName);
     }
 }
Ejemplo n.º 35
0
        private void m_CreatePO_ExecuteCode(object sender, EventArgs e)
        {
            string _spTitle     = default(string);
            string _newFileName = default(string);
            string _stt         = "Starting";

            try
            {
                _stt = "using";
                using (EntitiesDataContext _EDC = new EntitiesDataContext(workflowProperties.SiteUrl))
                {
                    Shipping _sp = (from idx in _EDC.Shipping
                                    where idx.Id == workflowProperties.ItemId
                                    select idx).First();
                    if (!_sp.IsOutbound.Value)
                    {
                        m_AfterCreationLogToHistoryList_HistoryDescription1 = "Document has not been created because it is not outbound shipment";
                        return;
                    }
                    _stt     = "Shipping";
                    _spTitle = _sp.Title;
                    SPDocumentLibrary _lib = (SPDocumentLibrary)workflowProperties.Web.Lists[CommonDefinition.SealProtocolLibraryTitle];
                    _stt = "SPDocumentLibrary";
                    SPFile _teml    = workflowProperties.Web.GetFile(_lib.DocumentTemplateUrl);
                    string _fname   = String.Format("SealProtocolFileName".GetLocalizedString(), _sp.Id.ToString());
                    SPFile _docFile = OpenXMLHelpers.AddDocument2Collection(_teml, _lib.RootFolder.Files, _fname);
                    _newFileName = _docFile.Name;
                    _stt         = "_doc";
                    int          _docId = (int)_docFile.Item.ID;
                    SealProtocol _sprt  = (from idx in _EDC.SealProtocolLibrary
                                           where idx.Id == _docId
                                           select idx).First();
                    Dictionary <TeamMembers, string> _team = GetTeamData(_EDC, _sp);
                    _sprt.SealProtocol1stDriver          = _team[TeamMembers._1stDriver];
                    _sprt.SealProtocol2ndDriver          = _team[TeamMembers._2ndDriver];
                    _sprt.SealProtocol1stEscort          = _team[TeamMembers._1stEscort];
                    _sprt.SealProtocol2ndEscort          = _team[TeamMembers._2ndEscort];
                    _sprt.SealProtocolDispatchDateActual = _sp.StartTime;
                    _sprt.SealProtocolCity                   = _sp.Shipping2City.Title();
                    _sprt.SealProtocolContainersNo           = _sp.ContainerNo.NotAvailable();
                    _sprt.SealProtocolCountry                = _sp.Shipping2City == null ? String.Empty : _sp.Shipping2City.CountryTitle.Title();
                    _sprt.SealProtocolDispatchDate           = _sp.StartTime;
                    _sprt.SealProtocolDriverPhone            = _team[TeamMembers.DriverSPhone];
                    _sprt.SealProtocolEscortCarNo            = _team[TeamMembers.EscortCarNo];
                    _sprt.SealProtocolEscortPhone            = _team[TeamMembers.EscortPhone];
                    _sprt.SealProtocolForwarder              = _sp.PartnerTitle.Title();
                    _sprt.SealProtocolSecurityEscortProvider = _sp.Shipping2PartnerTitle.Title();
                    _sp.SecuritySealProtocolIndex            = _sprt;
                    _sprt.SealProtocolTrailerNo              = _team[TeamMembers.TrailerNo];
                    _sprt.SealProtocolTruckNo                = _team[TeamMembers.TruckNo];
                    _sprt.Title = String.Format("Security Seal & Signature Protocol SSP-3{0, 5}", _sprt.Id);
                    _sprt.SealProtocolWarehouse = _sp.Shipping2WarehouseTitle == null?String.Empty.NotAvailable() : _sp.Shipping2WarehouseTitle.WarehouseAddress.NotAvailable();

                    _stt = "WarehouseAddress ";
                    _EDC.SubmitChanges();
                }
                m_AfterCreationLogToHistoryList_HistoryOutcome1     = "Item Created";
                m_AfterCreationLogToHistoryList_HistoryDescription1 = String.Format("File {0} containing purchase order for shipping {1} successfully created.", _newFileName, _spTitle);
            }
            catch (Exception _ex)
            {
                m_AfterCreationLogToHistoryList_HistoryOutcome1 = "Exception";
                string _frmt = "Creation of the Seal Protocol failed in the \"{0}\" state because of the error {1}";
                m_AfterCreationLogToHistoryList_HistoryDescription1 = string.Format(_frmt, _stt, _ex.Message);
            }
        }
Ejemplo n.º 36
0
 // can only get folder creation to work with Document Libraries
 private SPFolder CreateFolderPath(SPDocumentLibrary list, string path)
 {
     return(CreateFolderPathRecursive(list.RootFolder, path.Split('/').ToList()));
 }
Ejemplo n.º 37
0
    public XmlDocument GetWFTasks(string sSiteURL, string sDocLibName, string sFolder, string sDocName, string sUser)
    {
        //temp debugging code:
        if (sUser.ToLower() == @"basexp\admin")
        {
            sUser = @"mossrtm\administrator";
        }
        sUser = @"mossrtm\administrator";
        //end temp debugging code

        string      sTaskName = string.Empty;
        string      sTaskURL  = string.Empty;
        XmlDocument xDoc      = new XmlDocument();
        XmlElement  xElem     = null;
        XmlText     xText     = null;
        XmlNode     xNode     = null;
        //SPUser usr = new SPUser(
        //this.User.
        SPSite            site   = new SPSite(sSiteURL);
        SPWeb             web    = site.OpenWeb();
        SPDocumentLibrary doclib = (SPDocumentLibrary)web.Lists[sDocLibName];
        SPListItem        item   = null;

        foreach (SPListItem itemTemp in doclib.Items)
        {
            if (sFolder == string.Empty)
            {
                if (itemTemp.File.Name.ToLower() == sDocName.ToLower())
                {
                    item = itemTemp;
                    break;
                }
            }
            else
            {
                if ((itemTemp.Folder.Name == sFolder) &&
                    (itemTemp.File.Name.ToLower() == sDocName.ToLower())
                    )
                {
                    item = itemTemp;
                    break;
                }
            }
        }
        //string sCurrentUser = this.User.Identity.Name.ToLower();

        string sTaskAssignedTo = string.Empty;

        for (int i = 0; i < item.Workflows.Count; i++)
        {
            SPWorkflow wf = item.Workflows[i];
            if (!wf.IsCompleted)
            {
                wf.TaskFilter = new SPWorkflowFilter(SPWorkflowState.Running, SPWorkflowState.None);
                for (int j = 0; j < wf.Tasks.Count; j++)
                {
                    SPWorkflowTask task = item.Workflows[i].Tasks[j];
                    sTaskAssignedTo = task["AssignedTo"].ToString();
                    sTaskAssignedTo = sTaskAssignedTo.Substring(sTaskAssignedTo.IndexOf('#') + 1);
                    if (sUser.ToLower() == sTaskAssignedTo.ToLower())
                    {
                        sTaskName = task.DisplayName;

                        sTaskURL = sSiteURL.TrimEnd('/') + "/Lists/" + wf.TaskList.Title + "/DispForm.aspx?ID=" + task.ID.ToString();
                        break;
                    }
                }
            }
        }

        xNode = xDoc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);
        xDoc.AppendChild(xNode);
        xElem = xDoc.CreateElement("WorkFlowTask");
        xDoc.AppendChild(xElem);
        xElem = xDoc.CreateElement("TaskName");
        xText = xDoc.CreateTextNode(sTaskName);
        xElem.AppendChild(xText);
        xDoc.ChildNodes.Item(1).AppendChild(xElem);
        xElem = xDoc.CreateElement("TaskURL");
        xText = xDoc.CreateTextNode(sTaskURL);
        xElem.AppendChild(xText);
        xDoc.ChildNodes.Item(1).AppendChild(xElem);

        return(xDoc);
    }
Ejemplo n.º 38
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SPWeb             web     = SPContext.Current.Site.RootWeb;
                SPDocumentLibrary library = (SPDocumentLibrary)web.Lists.TryGetList(this.ListDataSource);
                if (library != null)
                {
                    var query = new SPQuery()
                    {
                        Query = String.Format(@"
                            <OrderBy>
                                <FieldRef Name='Ordem'  Ascending='True' />
                            </OrderBy>
                            <Where>
                                <And>
                                    <Leq>
                                        <FieldRef Name='DataInicio' />
                                        <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value>
                                    </Leq>
                                    <And>
                                        <Gt>
                                            <FieldRef Name='DataFim' />
                                            <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value>
                                        </Gt>
                                        <Eq>
                                            <FieldRef Name='_ModerationStatus' />
                                            <Value Type='ModStat'>0</Value>
                                        </Eq>
                                    </And>
                                </And>
                            </Where>",
                                              SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now))
                    };

                    SPListItemCollection items = library.GetItems(query);

                    int num = 1;
                    foreach (SPListItem item in items)
                    {
                        if (this.TVFlashHtml != null)
                        {
                            this.TVFlashHtml = this.TVFlashHtml + ", ";
                        }

                        var link = string.Format("{0}", Convert.ToString(item["Url"]).Replace("&", "{}"));



                        this.TVFlashHtml += this.cliptemplate
                                            .Replace("{url}", web.Site.MakeFullUrl(item.Url))
                                            .Replace("{text}", num++.ToString())

                                            .Replace("{linkurl}", link)

                                            //.Replace("{destino}", (string)item["Destino"] ?? "")
                                            .Replace("{Posicao}", double.Parse((item["Posicao"] ?? "0").ToString()).ToString())
                                            .Replace("{Duracao}", double.Parse((item["Duracao"] ?? "5").ToString()).ToString());
                    }
                }
            }
        }
Ejemplo n.º 39
0
        private void TreeViewItemsNodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                if (e.Node.Tag != null)
                {
                    string tag = e.Node.Tag.ToString();

                    switch (tag)
                    {
                    case "ContentType Event Handlers":
                    {
                        SPContentType item = (SPContentType)e.Node.Parent.Tag;
                        foreach (SPEventReceiverDefinition er in item.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class + " (" + er.Type.ToString() + ")");
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    case "Web Event Handlers":
                    {
                        SPWeb item = (SPWeb)e.Node.Parent.Tag;
                        foreach (SPEventReceiverDefinition er in item.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class + " (" + er.Type.ToString() + ")");
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    case "Lib Event Handlers":
                    {
                        SPDocumentLibrary item = (SPDocumentLibrary)e.Node.Parent.Tag;
                        foreach (SPEventReceiverDefinition er in item.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class + " (" + er.Type.ToString() + ")");
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    case "Files":
                    {
                        SPDocumentLibrary item = (SPDocumentLibrary)e.Node.Parent.Tag;
                        foreach (SPListItem listItem in item.Items)
                        {
                            TreeNode node = e.Node.Nodes.Add(listItem.File.Name);
                            node.Tag                = listItem.File;
                            node.ImageIndex         = 3;
                            node.SelectedImageIndex = 3;
                            TreeNode evNode = node.Nodes.Add("Event Handlers");
                            evNode.Tag = "File Event Handlers";
                        }
                        break;
                    }

                    case "List Event Handlers":
                    {
                        SPList item = (SPList)e.Node.Parent.Tag;
                        foreach (SPEventReceiverDefinition er in item.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class + " (" + er.Type.ToString() + ")");
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    case "Items":
                    {
                        SPList item = (SPList)e.Node.Parent.Tag;
                        foreach (SPListItem listItem in item.Items)
                        {
                            TreeNode node = e.Node.Nodes.Add(listItem.Title);
                            node.Tag                = listItem;
                            node.ImageIndex         = 5;
                            node.SelectedImageIndex = 5;
                            TreeNode evNode = node.Nodes.Add("Event Handlers");
                            evNode.Tag = "Item Event Handlers";
                        }
                        break;
                    }

                    case "Item Event Handlers":
                    {
                        SPListItem item = (SPListItem)e.Node.Parent.Tag;
                        SPList     list = item.ParentList;

                        foreach (SPEventReceiverDefinition er in list.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class + " (" + er.Type.ToString() + ")");
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    case "File Event Handlers":
                    {
                        SPFile item = (SPFile)e.Node.Parent.Tag;
                        foreach (SPEventReceiverDefinition er in item.EventReceivers)
                        {
                            TreeNode node = e.Node.Nodes.Add(er.Class);
                            node.Tag                = er;
                            node.ImageIndex         = 10;
                            node.SelectedImageIndex = 10;
                        }
                        break;
                    }

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger(ex.ToString(), Color.LightBlue);
            }
        }
Ejemplo n.º 40
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                SPWeb web     = SPContext.Current.Web;
                SPWeb rootWeb = SPContext.Current.Site.RootWeb;

                foreach (SPList list in web.Lists)
                {
                    if (list.BaseType == SPBaseType.DocumentLibrary)
                    {
                        SPDocumentLibrary docLib = (SPDocumentLibrary)list;

                        if (docLib.IsCatalog == false && !list.IsApplicationList && !list.IsSiteAssetsLibrary && ContainsWebSitePageTypes(list))
                        {
                            ListItem item = new ListItem(list.Title, list.ID.ToString());

                            if (!this.ddl_library.Items.Contains(item))
                            {
                                this.ddl_library.Items.Add(item);
                            }
                        }
                    }
                }


                //TODO ListId queryparam
                try
                {
                    this.ddl_library.SelectedValue = Request.Params["list"].ToString();
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }

                SPContentTypeCollection availableContentTypes = rootWeb.AvailableContentTypes;


                foreach (SPContentType contenttype in availableContentTypes)
                {
                    if (!this.ddl_contentgroup.Items.Contains(new ListItem(contenttype.Group)))
                    {
                        this.ddl_contentgroup.Items.Add(contenttype.Group);
                    }
                }

                this.ddl_contentgroup.Items.Remove("_Hidden");
                this.ddl_contentgroup.SelectedValue = "Publishing Content Types";

                foreach (SPContentType contenttype in availableContentTypes)
                {
                    if (contenttype.Group == this.ddl_contentgroup.SelectedValue)
                    {
                        List <PageLayout> check = servicePageLayouts.GetPageLayouts(contenttype.Id);
                        if (check.Count > 0)
                        {
                            ListItem item = new ListItem(contenttype.Name, contenttype.Id.ToString());
                            this.ddl_contentname.Items.Add(item);
                        }
                    }
                }

                if (this.ddl_contentname.Items.Count > 0)
                {
                    this.ddl_contentname.SelectedIndex = 0;;
                    SPContentTypeId contenttypeid = new SPContentTypeId(this.ddl_contentname.SelectedValue);

                    List <PageLayout> layouts = servicePageLayouts.GetPageLayouts(contenttypeid);
                    //layouts.AddRange(servicePageLayouts.GetPageLayouts(contenttypeid.Parent));

                    foreach (PageLayout layout in layouts)
                    {
                        ListItem item = new ListItem(layout.Title, layout.UniqueId.ToString());
                        if (!this.ddl_pagelayout.Items.Contains(item))
                        {
                            this.ddl_pagelayout.Items.Add(item);
                        }
                    }

                    if (this.ddl_pagelayout.Items.Count > 0)
                    {
                        PageLayout layout = servicePageLayouts.GetPageLayout(new Guid(this.ddl_pagelayout.Items[0].Value));
                        this.lbl_description.Text = layout.Description;
                    }
                }
            }
        }
        public SPFile GetFile(SPDocumentLibrary lib, int id)
        {
            SPListItem item = lib.GetItemById(id) ;

            return item.File;
        }
Ejemplo n.º 42
0
        public SPLicense.LicenseFile.SPLicenseFile GetLicense(Type type, object instance, bool allowExceptions)
        {
            try
            {
                TestLicense   test    = new TestLicense();
                SPLicenseFile license = test.Create(type, instance, allowExceptions);
                string        key     = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString();

                SPAdministrationWebApplication centralWebApp = SPAdministrationWebApplication.Local;
                SPSite lowSite = centralWebApp.Sites[0];

                SPUserToken oSysToken = GetSysToken(lowSite.ID);
                using (SPSite centralSite = new SPSite(lowSite.ID, oSysToken))
                {
                    centralSite.AllowUnsafeUpdates = true;


                    using (SPWeb centralWeb = centralSite.OpenWeb())
                    {
                        bool     availableList = true;
                        SPFile   licenseFile   = null;
                        SPFolder licenseFolder = null;

                        centralWeb.AllowUnsafeUpdates = true;
                        try
                        {
                            SPList            LicenseList    = centralWeb.Lists["Hemrika License Files"];
                            SPDocumentLibrary LicenseLibrary = (SPDocumentLibrary)LicenseList;
                            licenseFolder = centralWeb.Folders["Hemrika License Files"];


                            /*
                             * if (!Farmbag.Contains("Hemrika_Encryption_Key"))
                             * {
                             *  Farmbag["Hemrika_Encryption_Key"] = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString();
                             * }
                             *
                             * encrypt = Farmbag["Hemrika_Encryption_Key"];
                             */

                            SPQuery oQuery = new SPQuery();
                            oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">" + type.Assembly.FullName + "</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>");
                            SPListItemCollection colListItems = LicenseLibrary.GetItems(oQuery);

                            foreach (SPListItem licenseItem in colListItems)
                            {
                                licenseFile = licenseItem.File;
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            availableList = false;
                        }

                        MemoryStream lic = null; //= new MemoryStream();
                        XmlDocument  xml = new XmlDocument();

                        if (licenseFile == null)
                        {
                            lic = new MemoryStream();
                            xml.LoadXml(license.ToXmlString());

                            SPLicenseFile.SaveFile(license, lic, false, String.Empty, false);

                            if (availableList && licenseFolder != null)
                            {
                                licenseFile = licenseFolder.Files.Add(type.Assembly.FullName + ".lic", lic, true);

                                licenseFile.Update();
                                licenseFile.Item.Update();
                            }
                        }

                        if (lic != null)
                        {
                            lic.Close();
                            //lic.Dispose();
                        }

                        if (licenseFile != null)
                        {
                            //byte[] bytes = licenseFile.OpenBinary();
                            //lic = new MemoryStream();
                            //lic.Read(bytes, 0, bytes.Length);

                            license = SPLicenseFile.LoadFile(licenseFile.OpenBinaryStream(), type, false, String.Empty);// true, key);
                        }

                        /*
                         * if (lic != null)
                         * {
                         *  lic.Close();
                         *  //lic.Dispose();
                         * }
                         */
                        centralWeb.AllowUnsafeUpdates = false;
                    }
                    centralSite.AllowUnsafeUpdates = false;
                }

                return(license);
            }
            catch (Exception ex)
            {
                throw new LicenseException(type, instance, ex.Message, ex);
            }
        }
 public void UpdateFile(SPDocumentLibrary list, byte[] data, string fielName, IDictionary props , int id )
 {
 }