Пример #1
0
        private static FileNodeInfo[] GetFiles(ISharePointCommandContext context, FolderNodeInfo folderNodeInfo)
        {
            List <FileNodeInfo> nodeInfos = new List <FileNodeInfo>();

            try
            {
                SPList   styleLibrary = context.Web.GetList(Utilities.CombineUrl(context.Web.ServerRelativeUrl, "Style%20Library"));
                SPFolder folder       = styleLibrary.RootFolder;
                if (folderNodeInfo != null)
                {
                    folder = context.Web.GetFolder(folderNodeInfo.Url);
                }

                SPFileCollection files = folder.Files;
                if (files != null)
                {
                    nodeInfos = files.ToFileNodeInfo();
                }
            }
            catch (Exception ex)
            {
                context.Logger.WriteLine(String.Format(Resources.FileSharePointCommands_RetrieveFilesException,
                                                       ex.Message,
                                                       Environment.NewLine,
                                                       ex.StackTrace), LogCategory.Error);
            }

            return(nodeInfos.ToArray());
        }
    public static SPListItem CreateLinkToDocumentFile(SPDocumentLibrary list, SPContentTypeId contentTypeId, string name, SPFieldUrlValue urlVal, string overrideIcon = null)
    {
        SPContentType contentType = list.ContentTypes[contentTypeId];
        string        extension   = "";

        if (urlVal != null && urlVal.Url != null)
        {
            extension = Path.GetExtension((urlVal.Url).Trim()).TrimStart(".".ToCharArray());
        }
        SPFolder         currentFolder = list.RootFolder;
        SPFileCollection files         = currentFolder.Files;
        string           fileUrl       = string.Concat(currentFolder.Url, "/", name, ".aspx");
        string           fileTemplate  = "<%@ Assembly Name='{0}' %>\r\n <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='System.IO' %>\r\n <%@ Import Namespace='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>\r\n <html>\r\n <head> <meta name='progid' content='SharePoint.Link' /> </head>\r\n <body>\r\n <form id='Form1' runat='server'>\r\n <SharePoint:UrlRedirector id='Redirector1' runat='server' />\r\n </form>\r\n </body>\r\n </html>";
        StringBuilder    fileContent   = new StringBuilder(fileTemplate.Length + 400);

        fileContent.AppendFormat(fileTemplate, typeof(SPDocumentLibrary).Assembly.FullName);
        Hashtable       properties = new Hashtable();
        SPContentTypeId ctId       = contentType.Id;

        properties["ContentTypeId"] = ctId.ToString();
        SPFile     file = files.Add(fileUrl, new MemoryStream((new UTF8Encoding()).GetBytes(fileContent.ToString())), properties, false, false);
        SPListItem item = file.Item;

        item[FLD_URL] = urlVal;
        if (list.Fields.Contains(g_guidIconOverride))
        {
            item[g_guidIconOverride] = string.Concat("|", overrideIcon ?? extension, "|");
        }
        item.IconOverlay = "linkoverlay.gif";
        item.UpdateOverwriteVersion();
        return(item);
    }
        public void CleansingFiles(string OutputFolder, string DocLib)
        {
            try
            {
                int    CleansingDays = new CleansingHelper().GetCleansingDays();
                SPSite Site          = new SPSite(ConfigurationManager.AppSettings["SharePointOnPremURL"].ToString());
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = Site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPFolder libFolder     = web.Folders[DocLib];
                        SPFileCollection file  = libFolder.Files;

                        foreach (SPFile f in file)
                        {
                            SPListItem item = f.Item;
                            int diff_days   = (DateTime.Now - f.TimeCreated).Days;
                            if (diff_days > CleansingDays)
                            {
                                item.Delete();
                            }
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                });
            }
            catch (Exception ex)
            {
                new GenerateTxt().GenerateTxtLogError(OutputFolder, ex.Message, "CleansingFiles SharePoint - " + DocLib);
            }
        }
Пример #4
0
        private void BindAttach()
        {
            var list = SPContext.Current.List;
            var item = SPContext.Current.ListItem;
            SPFileCollection files      = null;
            SPFolder         itemFolder = null;

            try
            {
                //Get tha Attachment Folder
                string strAttchmentFolderURL = item.Attachments.UrlPrefix;
                if (list.RootFolder.SubFolders.Count > 0)
                {
                    if (list.RootFolder.SubFolders["Attachments"] != null)
                    {
                        itemFolder = list.RootFolder.SubFolders["Attachments"];
                    }
                }

                //Get all the files in Attachment Folder that matches the GUID
                #region getFiles
                if (itemFolder.SubFolders[strAttchmentFolderURL] != null)
                {
                    files = itemFolder.SubFolders[strAttchmentFolderURL].Files;
                }
                #endregion

                rptAttach.DataSource = files;
                rptAttach.DataBind();
            }
            catch {}
        }
Пример #5
0
        public static string grantPermit(string siteUrl, string folderUrl, string userEmail)
        {
            try
            {
                //SPSite s = new SPSite(siteUrl);
                //SPWeb w = s.OpenWeb();
                int fileCount = 0;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            //get folder
                            SPFolder folder = web.GetFolder(@"RSAs Library/" + folderUrl);

                            //get list of items in folder to grant permission to
                            SPFileCollection folderFiles = folder.Files;
                            //SPFolderCollection subFolders = folder.SubFolders;

                            //select User
                            SPPrincipal user = web.SiteUsers.GetByEmail(userEmail);

                            //define read role
                            SPRoleDefinition readRole = web.RoleDefinitions.GetById(1073741826);

                            web.AllowUnsafeUpdates = true;
                            //remove permissions on files
                            folder.Item.BreakRoleInheritance(true);

                            //create Role Assignment Ref
                            SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)user);

                            //grant user permission to the folder
                            roleAssignment.RoleDefinitionBindings.Add(readRole);

                            folder.Item.RoleAssignments.Add(roleAssignment);

                            //grant user permission to all files in folder

                            foreach (SPFile file in folderFiles)
                            {
                                file.Item.BreakRoleInheritance(true);
                                file.Item.RoleAssignments.Add(roleAssignment);
                                fileCount++;
                            }
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
                return(String.Format("User {1} has been granted access to View {2} files in {0} Folder", fileCount, userEmail, folderUrl));
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        public SPFileCollectionInstance(ObjectInstance prototype, SPFileCollection fileCollection)
            : this(prototype)
        {
            if (fileCollection == null)
            {
                throw new ArgumentNullException("fileCollection");
            }

            m_fileCollection = fileCollection;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="web"></param>
        /// <param name="fileNameWithOutExtension"></param>
        /// <param name="fileName"></param>
        /// <param name="DocLib"></param>
        public void CreateWebPartPage(string fileNameWithOutExtension, string fileName, string DocLib)
        {
            SPWeb            web           = SPContext.Current.Web;
            SPFolder         libraryFolder = web.GetFolder(DocLib);
            SPFileCollection files         = libraryFolder.Files;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //string templateFilename = "spstd2.aspx";
                //string cityName = txtCityPageName.Text.Trim();
                string cityName         = fileNameWithOutExtension;
                string templateFilename = "NewCityPageLayout.aspx";
                //string hive = SPUtility.GetGenericSetupPath("15\\TEMPLATE\\" + SPContext.Current.Web.Language + "\\STS\\DOCTEMP\\SMARTPGS\\");
                string hive = "C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\\TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\";

                using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                {
                    // SPFolder libraryFolder = web.GetFolder(DocLib);
                    //SPFileCollection files = libraryFolder.Files;
                    if (!isFileExists(files, fileName))
                    {
                        SPFile newFile = files.Add(fileName, stream);

                        SPLimitedWebPartManager wpmngr = newFile.Web.GetLimitedWebPartManager(newFile.ServerRelativeUrl, PersonalizationScope.Shared);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDivisionHeader.dwp"), "Header", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CitiesLeftNavigation.webpart"), "LeftColumn", 0);
                        //  wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CityPageSummaryLinks.webpart"), "RightColumn", 0);
                        //wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityLOBs.dwp"), "MiddleColumn", 0);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Residential CEWP.dwp"), "Middle1Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Residential"), "Middle1Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Commercial CEWP.dwp"), "Middle1Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Commercial"), "Middle1Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Industrial CEWP.dwp"), "Middle2Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Industrial"), "Middle2Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Operational CEWP.dwp"), "Middle2Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Operational"), "Middle2Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDummyDescription.dwp"), "MiddleColumn", 2);

                        AddToCitiesList(fileNameWithOutExtension);

                        lblMsg.Text += string.Format("{0} Webpage successfully created...!<br>", fileName);
                    }
                    else
                    {
                        lblMsg.Text = "page already exists...!";
                    }
                }
            });

            // updatedatainCEWP(fileName, DocLib, txtbxDivision.Text.Trim(), txtbxStateCode.Text.Trim(), fileNameWithOutExtension);
        }
Пример #8
0
        private static SPFile CopyExternal(SPWeb web, SPFile copyFile, string destinationFolderUrl, string destination)
        {
            //copy the source file to the external location
            web.AllowUnsafeUpdates = true;
            SPFileCollection spFiles = web.GetFolder(destinationFolderUrl).Files;

            byte[] bFile = copyFile.OpenBinary();
            spFiles.Add(SPUrlUtility.CombineUrl(destination, copyFile.Name), bFile, false);
            web.AllowUnsafeUpdates = false;

            return(web.GetFile(web.Url + "/" + destinationFolderUrl + copyFile.Name));
        }
Пример #9
0
        internal static void PreProcessCustomXSL(XmlDocument xmlDocument)
        {
            try
            {
                SPWeb    root = SPContext.Current.Site.RootWeb;
                SPFolder xsl  = root.GetFolder(StyleXslFolderPath);
                if (xsl.Exists)
                {
                    XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDocument.NameTable);
                    mgr.AddNamespace("ddwrt", "http://schemas.microsoft.com/WebParts/v2/DataView/runtime");
                    mgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
                    mgr.AddNamespace("asp", "http://schemas.microsoft.com/ASPNET/20");
                    mgr.AddNamespace("msxsl", "urn:schemas-microsoft-com:xslt");
                    mgr.AddNamespace("SharePoint", "Microsoft.SharePoint.WebControls");
                    mgr.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/dsp");
                    mgr.AddNamespace("exclude-result-prefixes", "xsl msxsl ddwrt");
                    mgr.AddNamespace("designer", "http://schemas.microsoft.com/WebParts/v2/DataView/designer");
                    mgr.AddNamespace("ddwrt2", "urn:frontpage:internal");
                    mgr.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
                    mgr.AddNamespace("dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
                    mgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
                    mgr.AddNamespace("z", "#RowsetSchema");

                    SPFileCollection files      = xsl.Files;
                    XmlNode          refChild   = null;
                    XmlNode          parentNode = null;

                    XmlNodeList list = xmlDocument.SelectNodes("/xsl:stylesheet/xsl:import | /xsl:stylesheet/xsl:include", mgr);
                    if ((list != null) && (list.Count > 0))
                    {
                        refChild   = list[list.Count - 1];
                        parentNode = refChild.ParentNode;
                    }
                    else
                    {
                        parentNode = xmlDocument.SelectSingleNode("/xsl:stylesheet", mgr);
                    }
                    foreach (SPFile file in files)
                    {
                        XmlNode      newChild = xmlDocument.CreateNode(XmlNodeType.Element, "xsl", "include", "http://www.w3.org/1999/XSL/Transform");
                        XmlAttribute node     = xmlDocument.CreateAttribute("href");
                        node.Value = file.ServerRelativeUrl;
                        newChild.Attributes.SetNamedItem(node);
                        parentNode.InsertAfter(newChild, refChild);
                    }
                }
            }
            catch
            {
                //throw;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="files"></param>
        /// <param name="fName"></param>
        /// <returns></returns>
        private bool isFileExists(SPFileCollection files, string fName)
        {
            bool isFlag = false;

            foreach (SPFile file in files)
            {
                if (file.Name == fName)
                {
                    isFlag = true;
                    break;
                }
            }
            return(isFlag);
        }
Пример #11
0
        private static SPFile find(SPDocumentLibrary library, string fileName)
        {
            SPFileCollection files = library.RootFolder.Files;

            for (int fileIdx = 0; fileIdx < files.Count; fileIdx++)
            {
                if (files[fileIdx].Name == fileName)
                {
                    return(files[fileIdx]);
                }
            }

            return(null);
        }
Пример #12
0
        private List <String> GetFolderAndFile(String folderPath, String fileName)
        {
            List <String> listFile = new List <String>();

            if (String.IsNullOrEmpty(folderPath) || folderPath.Equals("/"))
            {
                return(listFile);
            }

            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        String   urlFolder = web.ServerRelativeUrl + folderPath;
                        SPFolder spFolder  = web.GetFolder(urlFolder);
                        if (spFolder.Exists == true)
                        {
                            SPFileCollection files = spFolder.Files;
                            if (files != null)
                            {
                                foreach (SPFile file in files)
                                {
                                    listFile.Add(file.ServerRelativeUrl);

                                    //HtmlGenericControl errorDiv = new HtmlGenericControl("div");
                                    //errorDiv.InnerHtml = "file: " + file.ServerRelativeUrl;
                                    //this.Controls.Add(errorDiv);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("La Folder: " + urlFolder + " non esiste");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("La Folder:  non esiste");
            }

            return(listFile);
        }
Пример #13
0
        public static void UploadFile(string spsURL, string srcFile, string dstFolder, string dstFile, string comments, string pubFlag)
        {
            using (SPSite site = new SPSite(spsURL)) {
                using (SPWeb web = site.OpenWeb()) {
                    if (File.Exists(srcFile))
                    {
                        // Check dst file exist and checkOut status
                        SPFile oDstFile = web.GetFile(dstFolder + "/" + dstFile);
                        Console.WriteLine("Get file: " + srcFile);
                        if (oDstFile.Exists)
                        {
                            if (oDstFile.CheckOutStatus.ToString() == "None")
                            {
                                oDstFile.CheckOut();
                            }
                        }
                        // Read data from file to variable
                        Stream fs       = File.Open(srcFile, FileMode.Open, FileAccess.Read);
                        byte[] var_data = new byte[fs.Length];
                        fs.Read(var_data, 0, var_data.Length);
//				oDstFile.CheckOut();
                        // Write data to MOSS 2007
                        SPFolder         folder = web.GetFolder(dstFolder);
                        SPFileCollection files  = folder.Files;
                        files.Add(dstFile, var_data, true);
                        if (pubFlag == "2")
                        {
                            oDstFile.CheckIn("");
                            oDstFile.Publish(comments);
                        }
                        else if (pubFlag == "1")
                        {
                            oDstFile.CheckIn(comments);
                        }
                        else if (pubFlag == "0")
                        {
                        }
                    }
                    else
                    {
                        Console.WriteLine("File not copy: " + srcFile);
                        // ERRRRRRRRRRRRROOOOOOOOOOOOOOOOOORRRRRRRRRRR
                    } // End if srcFile Exist
                }     // SPWeb close
            }         // SPSite close
        }             // Method UploadFile close
Пример #14
0
        /// <summary>
        ///     Function to publish all files inside folder
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="featureId"></param>
        private static void PublishFiles(SPFolder folder, string featureId)
        {
            try
            {
                if (folder == null)
                {
                    throw new ArgumentNullException("folder");
                }


                if (String.IsNullOrEmpty(featureId))
                {
                    throw new ArgumentNullException("featureId");
                }


                SPFileCollection files = folder.Files;
                var drafts             = from SPFile f
                                         in files
                                         where String.Equals(f.Properties["FeatureId"] as string, featureId, StringComparison.InvariantCultureIgnoreCase) &&
                                         f.Level == SPFileLevel.Draft
                                         select f;


                foreach (SPFile f in drafts)
                {
                    f.Publish("");
                    f.Update();
                }
            }
            catch (Exception err)
            {
                using (SPSite oSPSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb oSPWeb = oSPSite.OpenWeb())
                    {
                        LogErrorHelper logHelper = new LogErrorHelper(LIST_SETTING, oSPWeb);
                        logHelper.logSysErrorEmail(APP_NAME, err, "PublishFiles Error!");
                        logHelper = null;
                    }
                }
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }
        }
Пример #15
0
        // Creates document in given list (root folder).
        // Returns true if the file was created, false if it already exists
        // or throws exception for other failure
        protected bool CreateDocument(string sFilename, string sContentType, string sList)
        {
            try
            {
                SPSite site = SPContext.Current.Site;

                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[sList];
                    // this always uses root folder
                    SPFolder         folder = web.Folders[sList];
                    SPFileCollection fcol   = folder.Files;

                    // find the template url and open
                    string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
                    SPFile spf       = web.GetFile(sTemplate);
                    byte[] binFile   = spf.OpenBinary();
                    // Url for file to be created
                    string destFile = fcol.Folder.Url + "/" + sFilename;

                    // create the document and get SPFile/SPItem for
                    // new document
                    SPFile addedFile = fcol.Add(destFile, binFile, false);
                    SPItem newItem   = addedFile.Item;
                    newItem["ContentType"] = sContentType;
                    newItem.Update();
                    addedFile.Update();
                    return(true);
                }
            }
            catch (SPException spEx)
            {
                // file already exists?
                if (spEx.ErrorCode == -2130575257)
                {
                    return(false);
                }
                else
                {
                    throw spEx;
                }
            }
        }
Пример #16
0
        internal static SPFile AddDocument2Collection(SPFile _template, SPFileCollection _dstCollection, string _fileName)
        {
            SPFile _docFile = default(SPFile);

            using (Stream _tmpStrm = _template.OpenBinaryStream())
                using (MemoryStream _docStrm = new MemoryStream())
                {
                    byte[] _buff = new byte[_tmpStrm.Length + 200];
                    int    _leng = _tmpStrm.Read(_buff, 0, (int)_tmpStrm.Length);
                    _docStrm.Write(_buff, 0, _leng);
                    _docStrm.Position = 0;
                    WordprocessingDocument _doc = WordprocessingDocument.Open(_docStrm, true);
                    _doc.ChangeDocumentType(WordprocessingDocumentType.Document);
                    _doc.Close();
                    _docFile = _dstCollection.Add(_fileName, _docStrm, true);
                    _docStrm.Flush();
                    _docStrm.Close();
                }
            return(_docFile);
        }
Пример #17
0
        internal static List <FileNodeInfo> ToFileNodeInfo(this SPFileCollection files)
        {
            List <FileNodeInfo> nodeInfos = new List <FileNodeInfo>();

            foreach (SPFile file in files)
            {
                FileNodeInfo nodeInfo = new FileNodeInfo
                {
                    Id                = file.Item.ID,
                    Name              = file.Name,
                    UniqueId          = file.Item.UniqueId,
                    FileType          = file.Item[SPBuiltInFieldId.File_x0020_Type] as string,
                    ServerRelativeUrl = file.ServerRelativeUrl,
                    Title             = file.Item.Title,
                    IsCheckedOut      = file.Level == SPFileLevel.Checkout
                };
                nodeInfos.Add(nodeInfo);
            }

            return(nodeInfos);
        }
Пример #18
0
        static void Main(string[] args)
        {
            string lib            = ConfigurationManager.AppSettings["SharePointSite"];
            string relativeFolder = ConfigurationManager.AppSettings["RelativeFolder"];

            if (string.IsNullOrEmpty(lib))
            {
                Console.WriteLine("Failed: SharePointSite is not set in .config file.");
                return;
            }

            using (SPSite site = new SPSite(lib))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder folder = web.GetFolder(relativeFolder);

                    if (folder != null && folder.Exists)
                    {
                        SPFileCollection files = folder.Files;
                        foreach (SPFile file in files)
                        {
                            if (!Directory.Exists("origin-emails"))
                            {
                                Directory.CreateDirectory("origin-emails");
                            }
                            File.WriteAllBytes("origin-emails/" + file.Name, file.OpenBinary());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Sub Folder not exists.");
                    }
                }
            }
            Console.WriteLine("Download csv files Completed");
            ProcessFiles();
        }
Пример #19
0
    private static void PublishFiles(SPFolder folder, string featureId)
    {
        if (folder == null)
        {
            throw new ArgumentNullException("folder");
        }
        if (String.IsNullOrEmpty(featureId))
        {
            throw new ArgumentNullException("featureId");
        }
        SPFileCollection files = folder.Files;
        var drafts             = from SPFile f
                                 in files
                                 where String.Equals(f.Properties["FeatureId"] as string, featureId, StringComparison.InvariantCultureIgnoreCase) &&
                                 f.Level == SPFileLevel.Draft
                                 select f;

        foreach (SPFile f in drafts)
        {
            f.Publish("");
            f.Update();
        }
    }
Пример #20
0
 private bool FileExists(SPFileCollection files, string fileName)
 {
     foreach (SPFile file in files)
     {
         if (file.Name.Equals(fileName, StringComparison.CurrentCultureIgnoreCase))
             return true;
     }
     return false;
 }
Пример #21
0
        /// <summary>
        /// Copy subfolders and files of folder to a path
        /// </summary>
        /// <param name="myFolder">the folder that you want to get its subfolder and files</param>
        /// <param name="destinationPath">the path that you want to copy files of folder to</param>
        private void CreateSubDirectory(SPFolder myFolder, string destinationPath)
        {
            //get the document library of myFolder
            SPList             myList             = myFolder.DocumentLibrary;
            int                myListLength       = myList.Items.Count;
            SPListItem         myListItem         = myList.Items[0];
            string             tempPath           = destinationPath;
            SPFolderCollection myFolderCollection = myFolder.SubFolders;
            SPFileCollection   myFileCollection   = myFolder.Files;
            int                subFolderLength    = myFolderCollection.Count;
            int                subFileLength      = myFileCollection.Count;

            if (subFolderLength > 0 || subFileLength > 0)
            {
                if (subFolderLength > 0)
                {
                    for (int i = 0; i < subFolderLength; i++)
                    {
                        if (myFolderCollection[i].Name != "Forms")
                        {
                            tempPath += "\\" + myFolderCollection[i].Name;
                            if (!Directory.Exists(tempPath))
                            {
                                Directory.CreateDirectory(tempPath);
                            }
                            CreateSubDirectory(myFolderCollection[i], tempPath);
                            tempPath = destinationPath;
                        }
                    }
                }
                foreach (SPFile item in myFileCollection)
                {
                    DirectoryInfo myDirectoryInfo = new DirectoryInfo(destinationPath);
                    string        tempFilePath    = destinationPath;
                    tempFilePath += "\\" + item.Name;
                    if (File.Exists(tempFilePath))
                    {
                        File.Delete(tempFilePath);
                    }
                    using (FileStream myFileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
                    {
                        const int bufferSize = 4 * 1024 * 1024;
                        //byte[] fileContentBuffer = new byte[bufferSize];
                        byte[] fileContent = item.OpenBinary();
                        int    num         = fileContent.Length / bufferSize;
                        int    data        = fileContent.Length % bufferSize;
                        int    start       = 0;
                        while (start < num)
                        {
                            myFileStream.Write(fileContent, start * bufferSize, bufferSize);
                            start++;
                        }
                        myFileStream.Write(fileContent, start * bufferSize, data);
                    }
                    for (int a = 0; a < myListLength; a++)
                    {
                        if (myList.Items[a].Name == item.Name)
                        {
                            myListItem = myList.Items[a];
                            break;
                        }
                    }
                    myListItem["Source Path"] = tempFilePath;
                    myListItem.Update();
                    tempFilePath = destinationPath;
                }
            }
        }
Пример #22
0
        // Specific files according to user criteria in all sites
        public List <string> _getSpecificDocsInSiteCollection()
        {
            List <string>   FileRefs = new List <string>();
            SPSiteDataQuery DocFilesQuery;

            using (SPSite site = new SPSite(SiteUrl))
            {
                //using (SPWeb web = site.OpenWeb("/"))
                using (SPWeb web = site.OpenWeb())
                {
                    user = null;
                    if (UserLoginName != "")
                    {
                        user = web.EnsureUser(UserLoginName);// only when specific user
                    }
                    DocFilesQuery = new SPSiteDataQuery();

                    DocFilesQuery.Lists = "<Lists BaseType='1' /><Lists Hidden = \"TRUE\" />";// generic list // better!
                    //query.Lists = "<Lists ServerTemplate='101' /><Lists Hidden = \"TRUE\" />";// doc lib

                    DocFilesQuery.Query = CriteriaQuery();

                    // Select only needed columns: file reference
                    DocFilesQuery.ViewFields = "<FieldRef Name='FileRef' />";

                    // Search in all webs of the site collection
                    DocFilesQuery.Webs = "<Webs Scope='SiteCollection' />";

                    // constructring file url from GetSiteDataQuery
                    DataRowCollection filerows = web.GetSiteData(DocFilesQuery).Rows;
                    foreach (DataRow row in filerows)
                    {
                        // add relativeUrl into FileRef collection
                        FileRefs.Add(getRelativeFileRef(row["FileRef"].ToString()));
                    }


                    // specific attachments
                    SPListCollection listcoll = web.Lists;
                    foreach (SPList list in listcoll)
                    {
                        SPFolderCollection foldercoll = list.RootFolder.SubFolders;
                        foreach (SPFolder folder in foldercoll)
                        {
                            if (folder.Name == "Attachments")
                            {
                                SPFolderCollection attachmentFolders = folder.SubFolders;
                                foreach (SPFolder itemFolder in attachmentFolders)
                                {
                                    SPFileCollection files = itemFolder.Files;
                                    foreach (SPFile file in files)
                                    {
                                        if (CriteriaApply(file))
                                        {
                                            FileRefs.Add(file.ServerRelativeUrl);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }

            return(FileRefs);
        }
Пример #23
0
 /// <summary>
 /// Page on Load
 /// </summary>
 /// <param name="sender">Object sender</param>
 /// <param name="e">EventArgs e</param>
 protected void Page_Load(object sender, EventArgs e)
 {
     if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.New))
     {
         txtRichImageField.Visible = false;
         afAttach.Visible          = false;
     }
     if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Edit))
     {
         txtRichImageField.ControlMode = SPControlMode.Display;
     }
     if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Display))
     {
         ddlCat.Visible = false;
         lblCat.Visible = true;
         if (!IsPostBack)
         {
         }
     }
     else
     {
         ddlCat.Visible = true;
         lblCat.Visible = false;
     }
     if (!IsPostBack)
     {
         BindCat();
         BindAttach();
         if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Edit))
         {
             var item = SPContext.Current.Item;
             if (!string.IsNullOrEmpty(Convert.ToString(item[FieldsName.NewsRecord.English.CategoryName])))
             {
                 SPFieldLookupValueCollection returnVal = new SPFieldLookupValueCollection(Convert.ToString(item[FieldsName.NewsRecord.English.CategoryName]));
                 foreach (SPFieldLookupValue lookupValue in returnVal)
                 {
                     ListItem bitem = ddlCat.Items.FindByValue(lookupValue.LookupId.ToString());
                     if (bitem != null)
                     {
                         bitem.Selected = true;
                     }
                 }
             }
         }
     }
     else
     {
         if ("deleteattach".Equals(Convert.ToString(Request.Form["__EVENTTARGET"]), StringComparison.InvariantCultureIgnoreCase))
         {
             #region Delete
             var list = SPContext.Current.List;
             var item = SPContext.Current.ListItem;
             SPFileCollection files      = null;
             SPFolder         itemFolder = null;
             //Get tha Attachment Folder
             string strAttchmentFolderURL = item.Attachments.UrlPrefix;
             if (list.RootFolder.SubFolders.Count > 0)
             {
                 if (list.RootFolder.SubFolders["Attachments"] != null)
                 {
                     itemFolder = list.RootFolder.SubFolders["Attachments"];
                 }
             }
             string strTempID = Convert.ToString(Request.Form["__EVENTARGUMENT"]);
             //I know there is better way to remove characters
             strTempID = strTempID.Replace("{", "");
             strTempID = strTempID.Replace("}", "");
             //Get all the files in Attachment Folder that matches the GUID
             #region getFiles
             if (itemFolder.SubFolders[strAttchmentFolderURL] != null)
             {
                 files = itemFolder.SubFolders[strAttchmentFolderURL].Files;
             }
             #endregion
             foreach (SPFile file in files)
             {
                 if (strTempID.ToLower().Equals(file.UniqueId.ToString().ToLower()))
                 {
                     //Delete the file finally
                     file.Delete();
                     break;
                 }
             }
             #endregion
             Response.Redirect(Request.RawUrl);
         }
     }
 }
Пример #24
0
        private static void CopyFiles(SPFileCollection collFile)
        {
            //SPFileCollection collFile = oFolder.Files;

            foreach (SPFile oFile in collFile)
            {
                oFile.CopyTo("destlibUrl" + "/" + oFile.Name, true);
            }
        }
Пример #25
0
        private void SetupDisplayTemplateControls(List <MultipleImageUploadFieldValue> selectedValues)
        {
            string strLibraryName    = this.ParentField.LibraryName;
            string strUniqueFolderID = this.ParentField.UniqueFolderGuid;
            bool   editMode          = (this.ControlMode == SPControlMode.Edit);
            bool   newMode           = (this.ControlMode == SPControlMode.New);

            try
            {
                using (SPSite SiteCollection = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb site = SiteCollection.OpenWeb())
                    {
                        SPList   targetList = site.Lists.TryGetList(strLibraryName);
                        SPFolder RootFolder = targetList.RootFolder;
                        SPFolder subfolder  = null;
                        try
                        {
                            subfolder = RootFolder.SubFolders[strUniqueFolderID];
                            if (subfolder != null)
                            {
                                SPFileCollection files = subfolder.Files;
                                int      idIndex       = 1;
                                TableRow valueRow      = new TableRow();
                                TableImage.Rows.Add(valueRow);
                                int cellcount = 1;
                                foreach (SPFile file in files)
                                {
                                    var formattedValue = file.ServerRelativeUrl.ToLower().ToString();
                                    var selectedValue  = selectedValues.FirstOrDefault(val => val.URL.ToLower() == formattedValue) ?? new MultipleImageUploadFieldValue();

                                    if (!string.IsNullOrEmpty(selectedValue.URL))
                                    {
                                        if (cellcount == 4)
                                        {
                                            cellcount = 1;
                                            valueRow  = new TableRow();
                                            TableImage.Rows.Add(valueRow);
                                        }
                                        if (cellcount <= 3)
                                        {
                                            TableCell imageCell = new TableCell();
                                            imageCell.Width           = new Unit(15, UnitType.Percentage);
                                            imageCell.VerticalAlign   = VerticalAlign.Top;
                                            imageCell.HorizontalAlign = HorizontalAlign.Left;
                                            valueRow.Cells.Add(imageCell);

                                            // Creating the people editor and populating with the selected field
                                            Image image = new Image();
                                            image.ID       = "img" + file.UniqueId;
                                            image.ImageUrl = file.ServerRelativeUrl;
                                            image.Width    = new Unit(100, UnitType.Pixel);
                                            image.Height   = new Unit(100, UnitType.Pixel);
                                            imageCell.Controls.Add(image);

                                            HtmlGenericControl divImageName = new HtmlGenericControl();
                                            divImageName.InnerText = file.Name.ToString();
                                            imageCell.Controls.Add(divImageName);

                                            tableControlsList.Add(formattedValue, new ControlSet
                                            {
                                                Image = image,
                                                div   = divImageName
                                            });
                                            cellcount++;
                                        }
                                        idIndex++;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (tbxUserName.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxUserName, "User Name is required");
                tbxUserName.Focus();
            }
            else if (tbxPassword.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxPassword, "Password is required");
                tbxPassword.Focus();
            }
            else if (tbxDomain.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxDomain, "Domain is required");
                tbxDomain.Focus();
            }
            else if (tbxSharePointURL.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxSharePointURL, "SharePoint Site is required");
                tbxSharePointURL.Focus();
            }
            else if (drpdnlFormLibrary.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(drpdnlFormLibrary, "Formlibrary is required");
                drpdnlFormLibrary.Focus();
            }
            else
            {
                int highestFolderFileCount = 0;
                //int fileCount = 1;
                string        siteUrl         = String.Empty;
                byte[]        byteArr         = null;
                StreamReader  streamReader    = null;
                FileInfo[]    fileCollections = null;
                DirectoryInfo dirInfo         = null;
                StringBuilder fileName        = new StringBuilder();
                FileStream    fileStream      = null;

                try
                {
                    WindowsImpersonationContext wic = Utility.CreateIdentity(tbxUserName.Text.Trim(), tbxDomain.Text.Trim(), tbxPassword.Text.Trim()).Impersonate();

                    SPSite site = null;

                    //Check whether user enters full url of the site including "http"
                    if (tbxSharePointURL.Text.StartsWith("http"))
                    {
                        site = new SPSite(tbxSharePointURL.Text.Trim());
                    }
                    else
                    {
                        site = new SPSite("http://" + tbxSharePointURL.Text.Trim());
                    }
                    //MessageBox.Show(site.Url + "/" + drpdnlFormLibrary.Text.Trim());
                    SPWeb            web       = site.OpenWeb();
                    string           weburl    = web.Url;
                    SPFileCollection filesInSP = web.Files;

                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates  = true;

                    SPFile sharePointFile = null;
                    dirInfo         = new DirectoryInfo(tbxTargetFolder.Text.Trim());
                    fileCollections = dirInfo.GetFiles();

                    XmlDocument     xmlInputData = new XmlDocument();
                    XmlDataDocument xmlUserMap   = new XmlDataDocument();

                    LoadUserMapping(ref xmlUserMap);

                    //DataTable dtInputData = LoadInput2table(xmlInputData);
                    int      maxNumber     = 0;
                    SPFolder highestFolder = null;
                    string   tempSiteUrl   = String.Empty;
                    if (cbxFolderStructure.Checked)
                    {
                        highestFolder          = FileSplitUtility.GetHighestFolder(web, drpdnlFormLibrary.Text.Trim(), tbxArchiveFolderPrefix.Text, ref maxNumber);
                        highestFolderFileCount = highestFolder.Files.Count;
                        tempSiteUrl            = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString() + "/" + highestFolder.Name;
                    }
                    else
                    {
                        tempSiteUrl = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString();
                    }

                    FileUploadParam fileUploadParam = null;
                    string          currentUser     = tbxDomain.Text + "/" + tbxUserName.Text;

                    foreach (FileInfo file in fileCollections)
                    {
                        fileName.Append(file.FullName.Substring(file.DirectoryName.Length));

                        if (fileName.Length > 128)
                        {
                            fileName.Replace(fileName.ToString(), fileName.ToString().Substring(0, 124));
                            fileName.Append(file.Extension);
                        }
                        fileStream = file.Open(FileMode.Open, FileAccess.Read);
                        siteUrl    = tempSiteUrl + "/" + fileName.ToString().Substring(fileName.ToString().LastIndexOf(@"\") + 1);


                        streamReader = new StreamReader(fileStream);

                        byteArr = System.Text.Encoding.ASCII.GetBytes(streamReader.ReadToEnd());

                        string fileNameWithoutExtn = fileName.ToString().Substring(1, fileName.Length - 5);

                        try
                        {
                            //DateTime dtCreatedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["CreatedDate"]);
                            //DateTime dtModifiedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["LastModifiedDate"]);

                            //Check whether user needs folder structure to upload the files,
                            //If yes, assign values to file upload parameters
                            if (cbxFolderStructure.Checked)
                            {
                                //Assigning values to the parameters for uploading files.
                                fileUploadParam = new FileUploadParam();
                                //fileUploadParam.CreatedBy = strCreatedWinUser;
                                //fileUploadParam.ModifiedBy =strModifiedWinUser;
                                fileUploadParam.FileContent            = byteArr;
                                fileUploadParam.CurrentFileName        = fileName.ToString();
                                fileUploadParam.HighestFolderName      = highestFolder.Name;
                                fileUploadParam.HighestFolderFileCount = highestFolderFileCount;
                                fileUploadParam.FolderPrefix           = tbxArchiveFolderPrefix.Text.Trim();
                                fileUploadParam.SiteUrl    = siteUrl;
                                fileUploadParam.TargetList = web.Lists[drpdnlFormLibrary.Text.Trim()];
                                //fileUploadParam.CreatedDate =dtCreatedDate;
                                //fileUploadParam.ModifiedDate = dtModifiedDate;
                                fileUploadParam.AllowedFileLimit = int.Parse(tbxMaxFileLimit.Text);

                                sharePointFile = FileSplitUtility.UploadFilesInSharePoint(fileUploadParam);

                                if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                                {
                                    highestFolderFileCount = 0;
                                }
                                ++highestFolderFileCount;
                            }
                            else
                            {
                                try
                                {
                                    //SPUser creator = web.Users[strCreatedWinUser];
                                    //SPUser modifier = web.Users[strModifiedWinUser];

                                    //if (creator.LoginName != "" && modifier.LoginName != "")
                                    //{
                                    //    sharePointFile = filesInSP.Add(siteUrl, byteArr, creator, modifier, dtCreatedDate, dtModifiedDate);
                                    //}
                                    //else
                                    //{
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                    //}
                                }
                                catch (Exception exception)
                                {
                                    LogInfo("ERROR while convertin winuser to SPUser for file:" + fileName.ToString() + "  Error:" + exception.Message);
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                            {
                                highestFolderFileCount = 0;
                            }
                            ++highestFolderFileCount;
                        }
                        //ends here

                        fileStream.Flush();
                        fileName.Remove(0, fileName.Length);
                    }
                    wic.Undo();
                    MessageBox.Show("Uploaded Successfully", "Upload");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in  uploading the file " + fileName + Environment.NewLine +
                                    "Cannot proceed further." + Environment.NewLine +
                                    "See log file for more details in root folder", "Upload Error");
                    StreamWriter logWriter = new StreamWriter(dirInfo.Root + "/Log.txt", false);
                    logWriter.Write("Error Message: " + ex.Message + System.Environment.NewLine + "Source of Error: " + fileName);
                    logWriter.Flush();
                    return;
                }
                finally
                {
                    streamReader.Close();
                    fileStream.Close();
                }
            }
        }
Пример #27
0
        /// <summary>
        /// get the sub node of all directories and files from document library
        /// </summary>
        /// <param name="myNode">the xmlNode to save the attributes and innerText</param>
        /// <param name="myFolder">the SPFolder that you want to get its all sub directories and files</param>
        /// <param name="myXmlDoc">the XmlDocument to save your information</param>
        /// <returns></returns>
        private XmlNode GetSubNodeAllDirectory(XmlNode myNode, SPFolder myFolder, XmlDocument myXmlDoc)
        {
            SPFolderCollection myFolderCollection = myFolder.SubFolders;
            SPFileCollection   myFileCollection   = myFolder.Files;
            int myFolderLength = myFolderCollection.Count;
            int myFileLength   = myFileCollection.Count;
            int totalLength    = myFolderLength + myFileLength;

            if (myFolderLength > 0 || myFileLength > 0)
            {
                XmlNode[] myXmlNode = new XmlNode[totalLength];
                if (myFolderLength > 0)
                {
                    for (int i = 0; i < myFolderLength; i++)
                    {
                        if (myFolderCollection[i].Name != "Forms")
                        {
                            myXmlNode[i] = myXmlDoc.CreateElement(ChangeString(myFolderCollection[i].Name));
                            SPList myList = myFolder.DocumentLibrary;

                            SPListItem myListItem = null;
                            //myListItem = myFolder.Item;
                            for (int k = 0; k < myList.Folders.Count; k++)
                            {
                                if (myList.Folders[k].Name.ToString() == myFolderCollection[i].Name.ToString())
                                {
                                    myListItem = myList.Folders[k];
                                }
                            }
                            AddProperitys(myXmlNode[i], myXmlDoc, myListItem);
                            myFolder = myFolderCollection[i];
                            GetSubNodeAllDirectory(myXmlNode[i], myFolder, myXmlDoc);
                            myFolder = myFolder.ParentFolder;
                        }
                    }
                }
                for (int j = 0; j < myFileLength; j++)
                {
                    SPList     myList     = myFileCollection[j].DocumentLibrary;
                    SPListItem myListItem = null;
                    // myListItem = myFileCollection[j].Item;
                    for (int k = 0; k < myList.Items.Count; k++)
                    {
                        if (myList.Items[k].Name.ToString() == myFileCollection[j].Name.ToString())
                        {
                            myListItem = myList.Items[k];
                        }
                    }
                    myXmlNode[j + myFolderLength] = myXmlDoc.CreateElement(ChangeString(myFileCollection[j].Name));
                    AddProperitys(myXmlNode[j + myFolderLength], myXmlDoc, myListItem);
                }
                for (int i = 0; i < totalLength; i++)
                {
                    if (myXmlNode[i] != null)
                    {
                        myNode.AppendChild(myXmlNode[i]);
                    }
                }
            }
            return(myNode);
        }
Пример #28
0
        public static void EnsureWebpartPage(this SPWeb web, string url, string title, bool overwrite, bool useForm)
        {
            url = url.TrimStart("/".ToCharArray());

            SPFile file = null;

            if (IsAbsoluteUrl(url))
            {
                file = web.Site.RootWeb.GetFile(url);
            }
            else
            {
                file = web.GetFile(url);
            }

            if (file.Exists && !overwrite)
            {
                return;
            }

            //if (!file.Exists)
            {
                string   folderPath = Path.GetDirectoryName(url);
                SPFolder folder     = null;
                if (IsAbsoluteUrl(folderPath))
                {
                    folder = web.Site.RootWeb.GetFolder(folderPath);
                }
                else
                {
                    folder = web.GetFolder(folderPath);
                }
                if (folder == null)
                {
                    return;
                }

                var forms = folder.SubFolders.Cast <SPFolder>().FirstOrDefault(p => p.Name == "Forms");

                string templateFilename = "spstd11.aspx";
                if (useForm && forms != null && folder.Name != "Pages")
                {
                    folder = forms;
                }
                else
                {
                    templateFilename = "spstd4.aspx";
                }


                string newFilename = Path.GetFileName(url);
                string hive        = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");
                using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                {
                    SPFileCollection files   = folder.Files;
                    SPFile           newFile = files.Add(newFilename, stream, true);
                }
                //SPList list = web.Lists[folder.ParentListId];

                //if (list == null) return;


                //string postInformation =

                //  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +

                //  "<Method>" +

                //    "<SetList Scope=\"Request\">" + list.ID + "</SetList>" +

                //    "<SetVar Name=\"ID\">New</SetVar>" +

                //    "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +

                //    "<SetVar Name=\"Type\">WebPartPage</SetVar>" +

                //    "<SetVar Name=\"WebPartPageTemplate\">8</SetVar>" +

                //    string.Format("<SetVar Name=\"Title\">{0}</SetVar>" , title)+

                //    "<SetVar Name=\"Overwrite\">true</SetVar>" +

                //  "</Method>";

                //web.ProcessBatchData(postInformation);
            }
        }
Пример #29
0
        private Dictionary<string, SPFile> sortFiles(SPFileCollection files)
        {
            Dictionary<string, SPFile> sortedFiles = new Dictionary<string, SPFile>();

            foreach (SPFile file in files)
            {
                sortedFiles.Add(file.Name, file);
            }

            return sortedFiles;
        }
Пример #30
0
        private string Converter(SPItemEventProperties properties)
        {
            // find the template url and open
            SPList list = properties.Web.Lists[CustomerRecordsDocumentLibrary];
            // this always uses root folder
            SPFolder         folder = properties.Web.Folders[CustomerRecordsDocumentFolder];
            SPFileCollection fcol   = folder.Files;

            // find the template url and open

            //string sTemplate = "/" + CustomerRecordsDocumentFolder + "/Forms/template.dotx"; //cannot use the one in forms folder???
            string sTemplate = "/_cts/" + ContentType + "/template.dotx";
            SPFile spfDotx   = properties.Web.GetFile(sTemplate);

            byte[] binFileDotx = spfDotx.OpenBinary();
            // Url for file to be created

            string destFile = fcol.Folder.Url + "/" + properties.ListItem["Title"] + " " + properties.ListItem["FirstName"] + ".docx";

            MemoryStream documentStream;

            using (Stream tplStream = spfDotx.OpenBinaryStream())
            {
                documentStream = new MemoryStream((int)tplStream.Length);
                CopyStream(tplStream, documentStream);
                documentStream.Position = 0L;
            }

            using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true))
            {
                template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

                MainDocumentPart mainPart = template.MainDocumentPart;

                mainPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(@"c:\nonssense\xxx.dotx", UriKind.Absolute));

                mainPart.Document.Save();
            }

            SPFile addedFile = fcol.Add(destFile, documentStream, true);

            SPItem newItem = addedFile.Item;

            newItem["ContentType"]        = ContentType;
            addedFile.Item["ContentType"] = ContentType;

            //0x010100728E6ABBF6164BBC9A96D73680ED991B006E7E7B2E66671049AA392BFF57A7E72C still won't work
            //newItem["ContentTypeId"] = "0x010100728E6ABBF6164BBC9A96D73680ED991B";
            //addedFile.Item["ContentTypeId"] = "0x010100728E6ABBF6164BBC9A96D73680ED991B";

            //update content type
            newItem.Update();
            addedFile.Item.SystemUpdate();

            addedFile.Item["Accountant"] = properties.ListItem["Accountant"];
            addedFile.Item["Business"]   = properties.ListItem["Business"];
            addedFile.Item["Correspondance Preference"] = properties.ListItem["CorrespondancePreference"];
            addedFile.Item["Date Captured"]             = properties.ListItem["DateCaptured"];

            newItem["Accountant"] = properties.ListItem["Accountant"];
            newItem["Business"]   = properties.ListItem["Business"];
            newItem["Correspondance Preference"] = properties.ListItem["CorrespondancePreference"];
            newItem["Date Captured"]             = properties.ListItem["DateCaptured"];

            newItem["DOB"]          = properties.ListItem["DoB"];
            newItem["Email"]        = properties.ListItem["Email"];
            newItem["Gender"]       = properties.ListItem["Gender"];
            newItem["Home"]         = properties.ListItem["Home"];
            newItem["Mobile"]       = properties.ListItem["Mobile"];
            newItem["Marital"]      = properties.ListItem["Marital"];
            newItem["Qantas"]       = properties.ListItem["Qantas"];
            newItem["RACV"]         = properties.ListItem["RACV"];
            newItem["Referrer"]     = properties.ListItem["Referrer"];
            newItem["Residential"]  = properties.ListItem["Residential"];
            newItem["Solicitor"]    = properties.ListItem["Solicitor"];
            newItem["Will"]         = properties.ListItem["Will"];
            newItem["First Name"]   = properties.ListItem["FirstName"];
            newItem["Accountant P"] = properties.ListItem["AccountantP"];
            newItem["Business P"]   = properties.ListItem["BusinessP"];
            newItem["Correspondance Preference P"] = properties.ListItem["CorrespondancePreferenceP"];
            newItem["Date of Birth P"]             = properties.ListItem["DoBP"];
            newItem["Email P"]       = properties.ListItem["EmailP"];
            newItem["First Name P"]  = properties.ListItem["FirstNameP"];
            newItem["Gender P"]      = properties.ListItem["GenderP"];
            newItem["Home P"]        = properties.ListItem["HomeP"];
            newItem["Marital P"]     = properties.ListItem["MaritalP"];
            newItem["Mobile P"]      = properties.ListItem["MobileP"];
            newItem["Qantas P"]      = properties.ListItem["QantasP"];
            newItem["RACVP"]         = properties.ListItem["RACVP"];
            newItem["Smoker P"]      = properties.ListItem["SmokerP"];
            newItem["Smoker"]        = properties.ListItem["Smoker"];
            newItem["Solicitor P"]   = properties.ListItem["SolicitorP"];
            newItem["Sur Name P"]    = properties.ListItem["SurNameP"];
            newItem["Will P"]        = properties.ListItem["WillP"];
            newItem["Residential P"] = properties.ListItem["ResidentialP"];
            //newItem["Father"] = properties.ListItem["Father"];
            //newItem["Father DOB"] = properties.ListItem["FatherDOB"];
            //newItem["Father Health"] = properties.ListItem["FatherHealth"];
            //newItem["Mother"] = properties.ListItem["Mother"];
            //newItem["Mother DOB"] = properties.ListItem["MotherDOB"];
            //newItem["Mother Health"] = properties.ListItem["MotherHealth"];
            //newItem["Brother"] = properties.ListItem["Brother"];
            //newItem["Brother DOB"] = properties.ListItem["BrotherDOB"];
            //newItem["Brother Health"] = properties.ListItem["BrotherHealth"];
            //newItem["Brother 2"] = properties.ListItem["Brother2"];
            //newItem["Brother 2 DOB"] = properties.ListItem["Brother2DOB"];
            //newItem["Brother Health 2"] = properties.ListItem["BrotherHealth2"];
            //newItem["Sister"] = properties.ListItem["Sister"];
            //newItem["Sister DOB"] = properties.ListItem["SisterDOB"];
            //newItem["Sister Health"] = properties.ListItem["SisterHealth"];
            //newItem["Sister 2"] = properties.ListItem["Sister2"];
            //newItem["Sister DOB 2"] = properties.ListItem["SisterDOB2"];
            //newItem["Sister Health 2"] = properties.ListItem["SisterHealth2"];
            //newItem["Father P"] = properties.ListItem["FatherP"];
            //newItem["Father PDOB"] = properties.ListItem["FatherPDOB"];
            //newItem["Father Health 1"] = properties.ListItem["FatherHealth1"];
            //newItem["Mother P"] = properties.ListItem["MotherP"];
            //newItem["Mother PDOB"] = properties.ListItem["MotherPDOB"];
            //newItem["Mother Health P"] = properties.ListItem["MotherHealthP"];
            //newItem["Brother P"] = properties.ListItem["BrotherP"];
            //newItem["Brother PDOB"] = properties.ListItem["BrotherPDOB"];
            //newItem["Brother Health P"] = properties.ListItem["BrotherHealthP"];
            //newItem["Brother 2 P"] = properties.ListItem["Brother2P"];
            //newItem["Brother 2 PDOB"] = properties.ListItem["Brother2PDOB"];
            //newItem["Brother Health 2 P"] = properties.ListItem["BrotherHealth2P"];
            //newItem["Sister P"] = properties.ListItem["SisterP"];
            //newItem["Sister PDOB"] = properties.ListItem["SisterPDOB"];
            //newItem["Sister P Health"] = properties.ListItem["SisterHealthP"];
            //newItem["Sister 2 P"] = properties.ListItem["Sister2P"];
            //newItem["Sister 2 PDOB"] = properties.ListItem["Sister2PDOB"];
            //newItem["Sister Health 2 P"] = properties.ListItem["SisterHealth2P"];
            //newItem["Dependants First 1"] = properties.ListItem["DependantsFirst1"];
            //newItem["Dependants Education Occupation Level 1"] = properties.ListItem["DependantsEducationOccupationLevel1"];
            //newItem["Dependants School University 1"] = properties.ListItem["DependantsSchoolUniversity1"];
            //newItem["Dependants Surname 1"] = properties.ListItem["DependantsSurName1"];
            //newItem["Dependants"] = properties.ListItem["Dependants1"];
            //newItem["Relation 1"] = properties.ListItem["Relation1"];
            //newItem["Dependants Health 1"] = properties.ListItem["DependantsHealth1"];
            //newItem["Dependants First 2"] = properties.ListItem["DependantsFirst2"];
            //newItem["Dependants Surname 2"] = properties.ListItem["DependantsSurName2"];
            //newItem["Dependants 2"] = properties.ListItem["Dependants2"];
            //newItem["Relation 2"] = properties.ListItem["DependantsSurName1ddRelation2"]; //??
            //newItem["Dependants Education Occupation Level 2"] = properties.ListItem["DependantsEducationOccupationLevel2"];
            //newItem["Dependants School University 2"] = properties.ListItem["DependantsSchoolUniversity2"];
            //newItem["Dependants Health 2"] = properties.ListItem["DependantsHealth2"];
            //newItem["Dependants First 3"] = properties.ListItem["DependantsFirst3"];
            //newItem["Dependants Surname 3"] = properties.ListItem["DependantsSurName3"];
            //newItem["Dependants 3"] = properties.ListItem["Dependants3"];
            //newItem["Relation 3"] = properties.ListItem["Relation3"];
            //newItem["Dependants Education Occupation Level 3"] = properties.ListItem["DependantsEducationOccupationLevel3"];
            //newItem["Dependants School University 3"] = properties.ListItem["DependantsSchoolUniversity3"];
            //newItem["Dependants Health 3"] = properties.ListItem["DependantsHealth3"];
            //newItem["Dependants First 4"] = properties.ListItem["DependantsFirst4"];
            //newItem["Dependants Surname 4"] = properties.ListItem["DependantsSurName4"];
            //newItem["Dependants 4"] = properties.ListItem["Dependants4"];
            //newItem["Relation 4"] = properties.ListItem["Relation4"];
            //newItem["Dependants Education Occupation Level 4"] = properties.ListItem["DependantsEducationOccupationLevel4"];
            //newItem["Dependants School University 4"] = properties.ListItem["DependantsSchoolUniversity4"];
            //newItem["Dependants Health 4"] = properties.ListItem["DependantsHealth4"];
            //newItem["Dependants First 5"] = properties.ListItem["DependantsFirst5"];
            //newItem["Dependants Surname 5"] = properties.ListItem["DependantsSurName5"];
            //newItem["Dependants 5"] = properties.ListItem["Dependants5"];
            //newItem["Relation 5"] = properties.ListItem["Relation5"];
            //newItem["Dependants Education Occupation Level 5"] = properties.ListItem["DependantsEducationOccupationLevel5"];
            //newItem["Dependants School University 5"] = properties.ListItem["DependantsSchoolUniversity5"];
            //newItem["Dependants Health 5"] = properties.ListItem["DependantsHealth5"];
            //newItem["Job Title 1"] = properties.ListItem["JobTitle1"];
            //newItem["Employment Status"] = properties.ListItem["EmploymentStatus"];
            //newItem["Employer"] = properties.ListItem["Employer"];
            //newItem["Hours Per Week"] = properties.ListItem["HoursPerWeek"];
            //newItem["Qualifications"] = properties.ListItem["Qualifications"];
            //newItem["Remuneration"] = properties.ListItem["Remuneration"];
            //newItem["Duties"] = properties.ListItem["Duties"];
            //newItem["Job Title P"] = properties.ListItem["JobTitleP"];
            //newItem["Employment Status P"] = properties.ListItem["EmploymentStatusP"];
            //newItem["Employer P"] = properties.ListItem["EmployerP"];
            //newItem["Hours Per Week P"] = properties.ListItem["HoursPerWeekP"];
            //newItem["Qualifications P"] = properties.ListItem["QualificationsP"];
            //newItem["Remuneration P"] = properties.ListItem["RemunerationP"];
            //newItem["Duties P"] = properties.ListItem["DutiesP"];
            //newItem["Health Condition"] = properties.ListItem["HealthCondition"];
            //newItem["Health Condition P"] = properties.ListItem["HealthConditionP"];
            //newItem["House"] = properties.ListItem["House"];
            //newItem["Contents"] = properties.ListItem["Contents"];
            //newItem["Super"] = properties.ListItem["Supe"];
            //newItem["Cash"] = properties.ListItem["Cash"];
            //newItem["Shares"] = properties.ListItem["Shares"];
            //newItem["Investment Properties"] = properties.ListItem["InvestmentProperties"];
            //newItem["Business Value"] = properties.ListItem["BusinessValue"];
            //newItem["Potential Inheritance"] = properties.ListItem["PotentialInheritance"];
            //newItem["Mortgage"] = properties.ListItem["Mortgage"];
            //newItem["Personal Loans"] = properties.ListItem["PersonalLoans"];
            //newItem["Credit Card Debt"] = properties.ListItem["CreditCardDebt"];
            //newItem["Investment Loans"] = properties.ListItem["InvestmentLoans"];
            //newItem["Leases"] = properties.ListItem["Leases"];
            //newItem["Business Debt"] = properties.ListItem["BusinessDebt"];
            //newItem["Liabilities"] = properties.ListItem["Liabilites"];
            //newItem["House P"] = properties.ListItem["HouseP"];
            //newItem["Contents P"] = properties.ListItem["ContentsP"];
            //newItem["Super P"] = properties.ListItem["SuperP"];
            //newItem["Cash P"] = properties.ListItem["CashP"];
            //newItem["Shares P"] = properties.ListItem["SharesP"];
            //newItem["Investment Properties P"] = properties.ListItem["InvestmentPropertiesP"];
            //newItem["Business Value P"] = properties.ListItem["BusinessValueP"];
            //newItem["Potential Inheritance P"] = properties.ListItem["PotentialInheritanceP"];
            //newItem["Mortgage P"] = properties.ListItem["MortgageP"];
            //newItem["Personal Loans P"] = properties.ListItem["PersonalLoansP"];
            //newItem["Credit Card Debt P"] = properties.ListItem["CreditCardDebtP"];
            //newItem["Investment Loans P"] = properties.ListItem["InvestmentLoansP"];
            //newItem["Leases P"] = properties.ListItem["LeasesP"];
            //newItem["Business Debt P"] = properties.ListItem["BusinessDebtP"];
            //newItem["Liabilities P"] = properties.ListItem["LiabilitesP"];
            //newItem["House J"] = properties.ListItem["HouseJ"];
            //newItem["Contents J"] = properties.ListItem["ContentsJ"];
            //newItem["Super J"] = properties.ListItem["SuperJ"];
            //newItem["Cash J"] = properties.ListItem["CashJ"];
            //newItem["Shares J"] = properties.ListItem["SharesJ"];
            //newItem["Investment Properties J"] = properties.ListItem["InvestmentPropertiesJ"];
            //newItem["Business Value J"] = properties.ListItem["BusinessValueJ"];
            //newItem["Potential Inheritance J"] = properties.ListItem["PotentialInheritanceJ"];
            //newItem["Mortgage J"] = properties.ListItem["MortgageJ"];
            //newItem["Personal Loans J"] = properties.ListItem["PersonalLoansJ"];
            //newItem["Credit Card Debt J"] = properties.ListItem["CreditCardDebtJ"];
            //newItem["Investment Loans J"] = properties.ListItem["InvestmentLoansJ"];
            //newItem["Leases J"] = properties.ListItem["LeasesJ"];
            //newItem["Business Debt J"] = properties.ListItem["BusinessDebtJ"];
            //newItem["Liabilities J"] = properties.ListItem["LiabilitesJ"];
            //newItem["Income"] = properties.ListItem["Income"];
            //newItem["Client Income"] = properties.ListItem["ClientIncome"];
            //newItem["Partner Income"] = properties.ListItem["PartnerIncome"];
            //newItem["Income Protection"] = properties.ListItem["IncomeProtection"];
            //newItem["Income Protection C"] = properties.ListItem["IncomeProtectionC"];
            //newItem["Income Protection P"] = properties.ListItem["IncomeProtectionP"];
            //newItem["Life Cover"] = properties.ListItem["LifeCover"];
            //newItem["Disable"] = properties.ListItem["Disable"];
            //newItem["Trauma"] = properties.ListItem["Trauma"];
            //newItem["Other Insured"] = properties.ListItem["OtherInsured"];
            //newItem["Life Cover P"] = properties.ListItem["LifeCoverP"];
            //newItem["Disable P"] = properties.ListItem["DisableP"];
            //newItem["Trauma P"] = properties.ListItem["TraumaP"];
            //newItem["Other Insured P"] = properties.ListItem["OtherInsuredP"];
            //newItem["Life Cover C"] = properties.ListItem["LifeCoverC"];
            //newItem["Disable C"] = properties.ListItem["DisableC"];
            //newItem["Trauma C"] = properties.ListItem["TraumaC"];
            //newItem["Other Insured C"] = properties.ListItem["OtherInsuredC"];

            newItem.Update();
            addedFile.Item.Update();
            addedFile.Update();

            return((string)addedFile.Item[SPBuiltInFieldId.EncodedAbsUrl]);
        }