Пример #1
0
        /// <summary>
        /// Inserts a web part on a web part page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="webPart">Information about the web part to insert</param>
        /// <param name="page">Page to add the web part on</param>
        public static void AddWebPartToWebPartPage(this Web web, WebPartEntity webPart, string page)
        {
            //Note: getfilebyserverrelativeurl did not work...not sure why not
            Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl("");
            web.Context.Load(pagesLib.Files);
            web.Context.ExecuteQuery();

            Microsoft.SharePoint.Client.File webPartPage = null;

            foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
            {
                if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                {
                    webPartPage = aspxFile;
                    break;
                }
            }

            if (webPartPage == null)
            {
                return;
            }

            web.Context.Load(webPartPage);
            web.Context.ExecuteQuery();

            LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            WebPartDefinition     oWebPartDefinition    = limitedWebPartManager.ImportWebPart(webPart.WebPartXml);

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.WebPartZone, webPart.WebPartIndex);
            web.Context.ExecuteQuery();
        }
Пример #2
0
        internal static void DownloadFilesFromSharePoint(string siteUrl, string folderPath, string tempLocation)
        {
            string UserName = "******";
            string Password = "******";

            SecureString passWord = new SecureString();

            foreach (var c in "iluminadoAgosto27")
            {
                passWord.AppendChar(c);
            }


            ClientContext ctx = new ClientContext(siteUrl);

            ctx.Credentials = new SharePointOnlineCredentials(UserName, passWord);
            Web            site  = ctx.Web;
            FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;


            //Get the required RootFolder
            string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
            Folder barFolder = site.GetFolderByServerRelativeUrl(folderPath);

            ctx.ExecuteQuery();
            //Create new subFolder to load files into
            string newFolderName = "baseName";

            barFolder.Folders.Add(newFolderName);
            barFolder.Update();



            ctx.ExecuteQuery();
        }
Пример #3
0
        /// <summary>
        /// List the web parts on a page
        /// </summary>
        /// <param name="properties">Information about the site that this method operates on</param>
        public void GetWebParts(string folder)
        {
            UsingContext(ctx =>
            {
                Site site = ctx.Site;
                Web web   = site.RootWeb;

                Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
                ctx.Load(pagesLib.Files);
                ctx.ExecuteQuery();

                Microsoft.SharePoint.Client.File ofile = pagesLib.Files[0];
                ctx.Load(ofile);
                ctx.ExecuteQuery();

                LimitedWebPartManager limitedWebPartManager = ofile.GetLimitedWebPartManager(PersonalizationScope.Shared);
                ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title, wp => wp.Id));
                ctx.ExecuteQuery();

                if (limitedWebPartManager.WebParts.Count >= 0)
                {
                    for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++)
                    {
                        WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart;
                        Console.WriteLine(oWebPart.Title);
                        Console.WriteLine(limitedWebPartManager.WebParts[i].Id);
                    }
                }
            });
        }
Пример #4
0
        public void DeleteDemoPages(string folder)
        {
            UsingContext(ctx =>
            {
                Site site = ctx.Site;
                Web web   = site.RootWeb;

                //Note: getfilebyserverrelativeurl did not work...not sure why not
                Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
                ctx.Load(pagesLib.Files);
                ctx.ExecuteQuery();

                List <File> toDelete = new List <File>();

                foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
                {
                    if (aspxFile.Name.StartsWith("scenario1", StringComparison.InvariantCultureIgnoreCase) || aspxFile.Name.StartsWith("scenario2", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //aspxFile.DeleteObject();
                        toDelete.Add(aspxFile);
                    }
                }

                for (int i = 0; i < toDelete.Count; i++)
                {
                    toDelete[i].DeleteObject();
                }

                ctx.ExecuteQuery();
            });
        }
        public SP.FileCollection Attachments(SPListItem listItem, SPList list, object value)
        {
            if (value == null || !(bool)value)
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.Web web = clientContext.Web;
                clientContext.Load(web);
                SP.List splist = clientContext.ToList(list.Id);
                clientContext.Load(splist);
                SP.ListItem splistItem = splist.GetItemById(listItem.Id);
                clientContext.Load(splistItem);
                clientContext.ExecuteQuery();

                SP.Folder listFolder = splistItem.ParentList.RootFolder;
                clientContext.Load(listFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                SP.Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(listFolder.ServerRelativeUrl + "/attachments/" + splistItem.Id.ToString());
                clientContext.Load(attachmentsFolder);
                var attachments = attachmentsFolder.Files;
                clientContext.Load(attachments);
                clientContext.ExecuteQuery();

                return(attachments);
            }
        }
        public bool IsFolderValid(string url, Guid listId, string folderName, string currentDir)
        {
            folderName = folderName.Trim();
            if (String.IsNullOrEmpty(folderName))
            {
                return(false);
            }

            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);
                var subfolders = clientContext.LoadQuery(parentFolder.Folders.Where(folder => folder.Name == folderName));
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.FileNotFound(ex, "Coult not load subfolders for a directory '{0}'", currentDir);
                    return(false);
                }

                return(subfolders.Any());
            }
        }
 public bool IsFolderValid(SPList list, string folderName, string currentDir)
 {
     folderName = folderName.Trim();
     if (String.IsNullOrEmpty(folderName))
     {
         return(false);
     }
     using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
     {
         SP.List   splist       = clientContext.ToList(list.Id);
         SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
         clientContext.Load(parentFolder);
         var subfolders = clientContext.LoadQuery(parentFolder.Folders.Where(folder => folder.Name == folderName));
         try
         {
             clientContext.ExecuteQuery();
         }
         catch (Exception ex)
         {
             EventLogs.Warn(String.Format("An exception of type {0} occurred while loading subfolders for a directory '{1}'. The exception message is: {2}", ex.GetType().Name, currentDir, ex.Message), "SharePointClient", 778, CSContext.Current.SettingsID);
             return(false);
         }
         // subfolders.Count()>0 means, that the folder already exists
         return(!subfolders.Any());
     }
 }
Пример #8
0
        public static void LoadFolder(TreeNode parentNode, SPClient.Folder folder, MainBrowser form, bool isRootFolder = false)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(folder);
                ctx.ExecuteQuery();

                // Add folder node
                TreeNode node = parentNode.Nodes.Add(isRootFolder ? "Root Folder" : folder.Name);
                node.ImageKey         = Constants.IMAGE_FOLDER;
                node.SelectedImageKey = Constants.IMAGE_FOLDER;
                node.Tag = folder;
                node.ContextMenuStrip = form.mnContextItem;

                AddLoadingNode(node, LoadType.Folder);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (isRootFolder)
                {
                    TreeNode node = parentNode.Nodes.Add("Root Folder (Error)");
                    node.ImageKey         = Constants.IMAGE_FOLDER;
                    node.SelectedImageKey = Constants.IMAGE_FOLDER;
                }
                else
                {
                    AddLoadingNode(parentNode, LoadType.Folder);
                }
            }
        }
Пример #9
0
        public void AddHtmlToWikiPage(ClientContext ctx, Web web, string folder, string html, string page)
        {
            Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
            ctx.Load(pagesLib.Files);
            ctx.ExecuteQuery();

            Microsoft.SharePoint.Client.File wikiPage = null;

            foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
            {
                if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                {
                    wikiPage = aspxFile;
                    break;
                }
            }

            if (wikiPage == null)
            {
                return;
            }

            ctx.Load(wikiPage);
            ctx.Load(wikiPage.ListItemAllFields);
            ctx.ExecuteQuery();

            string wikiField = (string)wikiPage.ListItemAllFields["WikiField"];

            Microsoft.SharePoint.Client.ListItem listItem = wikiPage.ListItemAllFields;
            listItem["WikiField"] = html;
            listItem.Update();
            ctx.ExecuteQuery();
        }
        public SP.Folder NewFolder(string url, Guid listId, string folderName, string currentDir)
        {
            if (!IsFolderValid(url, listId, folderName, currentDir))
            {
                return(null);
            }

            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);

                // add a new folder
                SP.Folder newFolder = parentFolder.Folders.Add(folderName);
                parentFolder.Update();
                clientContext.Load(newFolder);
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.FileNotFound(ex, "Error occurred while creating a new folder with a name '{0}' for a directory '{1}'.", folderName, currentDir);
                    return(null);
                }

                CacheService.RemoveByTags(new[] { Documents.Tag(listId), Folders.Tag(listId) }, CacheScope.All);

                return(newFolder);
            }
        }
Пример #11
0
        /// <summary>
        /// Add html to a wiki style page
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="folder">System name of the wiki page library - typically sitepages</param>
        /// <param name="webPart">The html to insert</param>
        /// <param name="page">Page to add the html on</param>
        public static void AddHtmlToWikiPage(this Web web, string folder, string html, string page)
        {
            //Note: getfilebyserverrelativeurl did not work...not sure why not
            Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
            web.Context.Load(pagesLib.Files);
            web.Context.ExecuteQuery();

            Microsoft.SharePoint.Client.File wikiPage = null;

            foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
            {
                if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                {
                    wikiPage = aspxFile;
                    break;
                }
            }

            if (wikiPage == null)
            {
                return;
            }

            web.Context.Load(wikiPage);
            web.Context.Load(wikiPage.ListItemAllFields);
            web.Context.ExecuteQuery();

            string wikiField = (string)wikiPage.ListItemAllFields["WikiField"];

            ListItem listItem = wikiPage.ListItemAllFields;

            listItem["WikiField"] = html;
            listItem.Update();
            web.Context.ExecuteQuery();
        }
Пример #12
0
        /// <summary>
        /// Retrieves the server-relative URL of a folder from its absolute URL.
        /// </summary>
        /// <param name="webUrl">Web URL to establish context.</param>
        /// <param name="folderUrl">folder URL</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>The server-relative folder URL if found. Null otherwise.</returns>
        private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password)
        {
            string methodName = "SharePointManager2003.GetFolderUrlDirect";

            try
            {
                SP.ClientContext context = new SP.ClientContext(webUrl);
                context.Credentials = new NetworkCredential(username, password);

                // load the web data
                SP.Web web = context.Web;
                context.Load(web);

                // load the folder data
                Uri       uri    = new Uri(folderUrl);
                SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath);
                context.Load(folder);

                context.ExecuteQuery();

                // check if the URL belongs to a folder
                if (folder != null)
                {
                    return(folder.ServerRelativeUrl);
                }

                return(null);
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e);
                return(null);
            }
        }
Пример #13
0
        private static File UploadFile(Microsoft.SharePoint.Client.Folder folder, Stream stream, string fileName, bool overwrite)
        {
            if (folder == null)
            {
                throw new ArgumentNullException(nameof(folder));
            }
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            File targetFile = null;

            try
            {
                targetFile = folder.UploadFile(fileName, stream, overwrite);
            }
            catch (ServerException ex)
            {
                if (ex.ServerErrorCode != -2130575306) //Error code: -2130575306 = The file is already checked out.
                {
                    //The file name might contain encoded characters that prevent upload. Decode it and try again.
                    fileName = WebUtility.UrlDecode(fileName);
                    try
                    {
                        targetFile = folder.UploadFile(fileName, stream, overwrite);
                    }
                    catch (Exception)
                    {
                        //unable to Upload file, just ignore
                    }
                }
            }
            return(targetFile);
        }
        public SP.Folder NewFolder(SPList list, string folderName, string currentDir)
        {
            if (!IsFolderValid(list, folderName, currentDir))
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.List   splist       = clientContext.ToList(list.Id);
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);

                // add a new folder
                SP.Folder newFolder = parentFolder.Folders.Add(folderName);
                parentFolder.Update();
                clientContext.Load(newFolder);
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    EventLogs.Warn(String.Format("An exception of type {0} occurred while creating a new folder with a name '{1}' for a directory '{2}'. The exception message is: {3}", ex.GetType().Name, folderName, currentDir, ex.Message), "SharePointClient", 778, CSContext.Current.SettingsID);
                    return(null);
                }

                cacheService.RemoveByTags(new[] { GetTag(list.Id) }, CacheScope.Context | CacheScope.Process);
                return(newFolder);
            }
        }
 public SPOFolderPipeBind(Microsoft.SharePoint.Client.Folder folder)
 {
     if (!folder.IsPropertyAvailable("ServerRelativeUrl"))
     {
         folder.Context.Load(folder, f => f.ServerRelativeUrl);
         folder.Context.ExecuteQuery();
     }
     _serverRelativeUrl = folder.ServerRelativeUrl;
 }
Пример #16
0
        /// <summary>
        /// 加载个人笔记
        /// </summary>
        public void AddInPersonalNote()
        {
            try
            {
                this.LoadingVisibility = System.Windows.Visibility.Visible;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    //获取会议根目录
                    var mettingList = NoteCodeEnterEntity.clientContextManage.GetFolders(NoteCodeEnterEntity.PesonalFolderName);

                    //获取相关会议的所有文档
                    var mettingF = mettingList.Where(Item => Item.Name.Equals(NoteCodeEnterEntity.LoginUserName)).ToList <SP.Folder>();
                    if (mettingF.Count > 0)
                    {
                        //获取文件夹
                        SP.Folder folder = mettingF[0];
                        //个人笔记文件完全限定名
                        string PersonalFile = NoteCodeEnterEntity.SelfName + this.personalNoteName + this.personNoteFileExtention;

                        //加载当前所有文件
                        NoteCodeEnterEntity.clientContextManage.LoadMethod(folder.Files);
                        //获取当前所有文件
                        List <SP.File> fileList = folder.Files.ToList <SP.File>();
                        //获取个人笔记
                        var intPersonFileListCount = fileList.Count(Item => Item.Name.Equals(PersonalFile));

                        //个人笔记不存在
                        if (intPersonFileListCount < 1)
                        {
                            //创建个人笔记
                            string returnStr = NoteCodeEnterEntity.clientContextManage.CreateFile(folder, NoteCodeEnterEntity.FileRoot + "\\" + NoteCodeEnterEntity.LocalPersonalNoteFile, PersonalFile);
                        }

                        //获取文件路径
                        string fileUri = NoteCodeEnterEntity.SPSiteAddressFront + folder.ServerRelativeUrl + "/" + PersonalFile + this.owaWebExtentionName;

                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            //生成凭据通过智存空间验证
                            this.WebCManage = new WebCredentialManage(this.webBrowser, NoteCodeEnterEntity.WebLoginUserName, NoteCodeEnterEntity.WebLoginPassword);
                            //导航到个人空间
                            this.WebCManage.Navicate(fileUri);
                            this.LoadingVisibility    = System.Windows.Visibility.Collapsed;
                            this.PersonNoteVisibility = System.Windows.Visibility.Visible;
                        }));
                    }
                });
            }
            catch (Exception ex)
            {
                LogManage.WriteLog(this.GetType(), ex);
            }
            finally
            {
            }
        }
Пример #17
0
        public Core.Folder ToFolder(Folder folder)
        {
            if (folder == null)
            {
                return(null);
            }

            var errorFolder = folder as SharePointFolderErrorEntry;

            if (errorFolder != null)
            {
                return new Core.Folder
                       {
                           ID                = MakeId(errorFolder.ID),
                           ParentFolderID    = null,
                           CreateBy          = Owner,
                           CreateOn          = DateTime.UtcNow,
                           FolderType        = FolderType.DEFAULT,
                           ModifiedBy        = Owner,
                           ModifiedOn        = DateTime.UtcNow,
                           ProviderId        = ID,
                           ProviderKey       = ProviderKey,
                           RootFolderCreator = Owner,
                           RootFolderId      = MakeId(SpRootFolderId),
                           RootFolderType    = RootFolderType,
                           Shareable         = false,
                           Title             = MakeTitle(GetTitleById(errorFolder.ID)),
                           TotalFiles        = 0,
                           TotalSubFolders   = 0,
                           Error             = errorFolder.Error
                       }
            }
            ;

            var isRoot = folder.ServerRelativeUrl == SpRootFolderId;

            return(new Core.Folder
            {
                ID = MakeId(isRoot ? "" : folder.ServerRelativeUrl),
                ParentFolderID = isRoot ? null : MakeId(GetParentFolderId(folder.ServerRelativeUrl)),
                CreateBy = Owner,
                CreateOn = CreateOn,
                FolderType = FolderType.DEFAULT,
                ModifiedBy = Owner,
                ModifiedOn = CreateOn,
                ProviderId = ID,
                ProviderKey = ProviderKey,
                RootFolderCreator = Owner,
                RootFolderId = MakeId(RootFolder.ServerRelativeUrl),
                RootFolderType = RootFolderType,
                Shareable = false,
                Title = isRoot ? CustomerTitle : MakeTitle(folder.Name),
                TotalFiles = 0,
                TotalSubFolders = 0,
            });
        }
Пример #18
0
        /// <summary>
        /// Add web part to a wiki style page
        /// </summary>
        /// <param name="html">html to be inserted</param>
        /// <param name="page">Page to add the web part on</param>
        /// <param name="row">Row of the wiki table that should hold the inserted web part</param>
        /// <param name="col">Column of the wiki table that should hold the inserted web part</param>
        public void AddHtmlToWikiPage(string folder, string html, string page, int row, int col)
        {
            UsingContext(ctx =>
            {
                Site site = ctx.Site;
                Web web   = site.RootWeb;

                //Note: getfilebyserverrelativeurl did not work...not sure why not
                Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
                ctx.Load(pagesLib.Files);
                ctx.ExecuteQuery();

                Microsoft.SharePoint.Client.File webPartPage = null;

                foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
                {
                    if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                    {
                        webPartPage = aspxFile;
                        break;
                    }
                }

                if (webPartPage == null)
                {
                    return;
                }

                ctx.Load(webPartPage);
                ctx.Load(webPartPage.ListItemAllFields);
                ctx.ExecuteQuery();

                string wikiField = (string)webPartPage.ListItemAllFields["WikiField"];

                XmlDocument xd        = new XmlDocument();
                xd.PreserveWhitespace = true;
                xd.LoadXml(wikiField);

                // Sometimes the wikifield content seems to be surrounded by an additional div?
                XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement;
                if (layoutsTable == null)
                {
                    layoutsTable = xd.SelectSingleNode("div/table") as XmlElement;
                }

                // Add the html content
                XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement;
                XmlText text = xd.CreateTextNode("!!123456789!!");
                layoutsZoneInner.AppendChild(text);

                ListItem listItem     = webPartPage.ListItemAllFields;
                listItem["WikiField"] = xd.OuterXml.Replace("!!123456789!!", html);
                listItem.Update();
                ctx.ExecuteQuery();
            });
        }
Пример #19
0
        public static void LoadSubFolders(TreeNode parentNode, SPClient.Folder folder, MainBrowser form)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(folder.Folders);
                ctx.Load(folder.Files);
                ctx.ExecuteQuery();

                int total   = folder.Folders.Count + folder.Files.Count;
                int current = 0;

                // Add folder properties
                AddLoadingNode(parentNode, "Properties", Constants.IMAGE_PROPERTY, LoadType.FolderProperties);

                // Add folders
                foreach (SPClient.Folder subFolder in folder.Folders)
                {
                    LoadFolder(parentNode, subFolder, form);

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }

                // Add files
                foreach (SPClient.File file in folder.Files)
                {
                    // Add file node
                    TreeNode node = parentNode.Nodes.Add(file.Name);
                    node.ImageKey         = Constants.IMAGE_FILE;
                    node.SelectedImageKey = Constants.IMAGE_FILE;
                    node.Tag = file;
                    node.ContextMenuStrip = form.mnContextItem;

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, LoadType.Folder);
            }
        }
Пример #20
0
        //folder a tyetki verebilmek için url ile folder nesnesi sharepoişnt içinde getirirlir.
        private Folder GetFolderFromUrl(string url)
        {
            var list = web.Lists.GetByTitle(StaticHelper.Listname);

            cContext.Load(list);
            cContext.Load(list.RootFolder);
            cContext.ExecuteQuery();

            Microsoft.SharePoint.Client.Folder folder = web.GetFolderByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + url);

            return(folder);
        }
Пример #21
0
        public static string GetFolderUrl(this SPClient.Folder folder)
        {
            Uri ctxUrl = new Uri(folder.Context.Url.ToLower());

            if (!folder.IsPropertyAvailable("ServerRelativeUrl"))
            {
                folder.Context.Load(folder, f => f.ServerRelativeUrl);
                folder.Context.ExecuteQuery();
            }

            return(string.Format("{0}{1}", ctxUrl.GetServerUrl(), folder.ServerRelativeUrl));
        }
Пример #22
0
        public Folder <string> ToFolder(Folder folder)
        {
            if (folder == null)
            {
                return(null);
            }

            var result = ServiceProvider.GetService <Folder <string> >();

            if (folder is SharePointFolderErrorEntry errorFolder)
            {
                result.ID                = MakeId(errorFolder.ID);
                result.ParentFolderID    = null;
                result.CreateBy          = Owner;
                result.CreateOn          = DateTime.UtcNow;
                result.FolderType        = FolderType.DEFAULT;
                result.ModifiedBy        = Owner;
                result.ModifiedOn        = DateTime.UtcNow;
                result.ProviderId        = ID;
                result.ProviderKey       = ProviderKey;
                result.RootFolderCreator = Owner;
                result.RootFolderId      = MakeId(SpRootFolderId);
                result.RootFolderType    = RootFolderType;
                result.Shareable         = false;
                result.Title             = MakeTitle(GetTitleById(errorFolder.ID));
                result.TotalFiles        = 0;
                result.TotalSubFolders   = 0;
                result.Error             = errorFolder.Error;

                return(result);
            }

            var isRoot = folder.ServerRelativeUrl == SpRootFolderId;

            result.ID                = MakeId(isRoot ? "" : folder.ServerRelativeUrl);
            result.ParentFolderID    = isRoot ? null : MakeId(GetParentFolderId(folder.ServerRelativeUrl));
            result.CreateBy          = Owner;
            result.CreateOn          = CreateOn;
            result.FolderType        = FolderType.DEFAULT;
            result.ModifiedBy        = Owner;
            result.ModifiedOn        = CreateOn;
            result.ProviderId        = ID;
            result.ProviderKey       = ProviderKey;
            result.RootFolderCreator = Owner;
            result.RootFolderId      = MakeId(RootFolder.ServerRelativeUrl);
            result.RootFolderType    = RootFolderType;
            result.Shareable         = false;
            result.Title             = isRoot ? CustomerTitle : MakeTitle(folder.Name);
            result.TotalFiles        = 0;
            result.TotalSubFolders   = 0;

            return(result);
        }
Пример #23
0
 private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
 {
     try
     {
         #region ConnectToSharePoint
         var securePassword = new SecureString();
         foreach (char c in Password)
         {
             securePassword.AppendChar(c);
         }
         var onlineCredentials = new SharePointOnlineCredentials(Login, securePassword);
         #endregion
         #region Insert the data
         using (ClientContext CContext = new ClientContext(SiteUrl))
         {
             CContext.Credentials = onlineCredentials;
             Web web = CContext.Web;
             FileCreationInformation newFile = new FileCreationInformation();
             byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
             newFile.ContentStream = new MemoryStream(FileContent);
             newFile.Url           = Path.GetFileName(FileName);
             List   DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
             Folder Clientfolder    = null;
             if (ClientSubFolder == "")
             {
                 Clientfolder = DocumentLibrary.RootFolder;
             }
             else
             {
                 Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
                 Clientfolder.Update();
             }
             Microsoft.SharePoint.Client.File uploadFile = Clientfolder.Files.Add(newFile);
             CContext.Load(DocumentLibrary);
             CContext.Load(uploadFile);
             CContext.ExecuteQuery();
             Console.ForegroundColor = ConsoleColor.Green;
             Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
         }
         #endregion
     }
     catch (Exception exp)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
     }
     finally
     {
         Console.ReadLine();
     }
 }
Пример #24
0
        /// <summary>
        /// Deletes a web part from a page
        /// </summary>
        /// <param name="properties">Site to insert the web part on</param>
        /// <param name="title">Title of the web part that needs to be deleted</param>
        /// <param name="page">Page to add the web part on</param>
        public void DeleteWebPart(string folder, string title, string page)
        {
            UsingContext(ctx =>
            {
                Site site = ctx.Site;
                Web web   = site.RootWeb;

                //Note: getfilebyserverrelativeurl did not work...not sure why not
                Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
                ctx.Load(pagesLib.Files);
                ctx.ExecuteQuery();

                Microsoft.SharePoint.Client.File webPartPage = null;

                foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
                {
                    if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                    {
                        webPartPage = aspxFile;
                        break;
                    }
                }

                if (webPartPage == null)
                {
                    return;
                }

                ctx.Load(webPartPage);
                ctx.ExecuteQuery();

                LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
                ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
                ctx.ExecuteQuery();

                if (limitedWebPartManager.WebParts.Count >= 0)
                {
                    for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++)
                    {
                        WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart;
                        if (oWebPart.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase))
                        {
                            limitedWebPartManager.WebParts[i].DeleteWebPart();
                            ctx.ExecuteQuery();
                            break;
                        }
                    }
                }
            });
        }
Пример #25
0
        /// <summary>
        /// 数据刷新
        /// </summary>
        /// <param name="folder"></param>
        public void RefleshSpaceData(BreadLine bread_Line)
        {
            try
            {
                //面包线是否为null
                if (bread_Line == null)
                {
                    return;
                }
                if (bread_Line.Folder != null)
                {
                    //等待提示
                    this.ShowTip();

                    TimerJob.StartRun(new Action(() =>
                    {
                        //清除书架
                        this.Items_Clear();
                        //获取文件夹
                        SP.Folder folder = bread_Line.Folder;

                        ThreadPool.QueueUserWorkItem((o) =>
                        {
                            try
                            {
                                //加载当前会议文件夹
                                SpaceCodeEnterEntity.ClientContextManage.LoadMethod(folder.Folders);
                                //获取当会议文件夹
                                List <SP.Folder> folderList = folder.Folders.ToList <SP.Folder>();

                                //加载当前所有文件
                                SpaceCodeEnterEntity.ClientContextManage.LoadMethod(folder.Files);
                                //获取当前所有文件
                                List <SP.File> fileList = folder.Files.ToList <SP.File>();

                                DataLoad_All(folderList, fileList);
                            }
                            catch (Exception ex)
                            {
                                LogManage.WriteLog(this.GetType(), ex);
                            }
                        });
                    }));
                }
            }
            catch (Exception ex)
            {
                LogManage.WriteLog(this.GetType(), ex);
            }
        }
        private PnP.Framework.Provisioning.Model.Folder GetFolder(Microsoft.SharePoint.Client.Folder listFolder)
        {
            ListItem folderItem = listFolder.ListItemAllFields;

            ClientContext.Load(folderItem, fI => fI.HasUniqueRoleAssignments);
            ClientContext.Load(listFolder, l => l.Name, l => l.Folders);
            ClientContext.ExecuteQueryRetry();

            PnP.Framework.Provisioning.Model.Folder retFolder = new PnP.Framework.Provisioning.Model.Folder
            {
                Name = listFolder.Name
            };

            if (Recursive)
            {
                foreach (var folder in listFolder.Folders)
                {
                    var childFolder = GetFolder(folder);
                    retFolder.Folders.Add(childFolder);
                }
            }
            if (IncludeSecurity && folderItem.HasUniqueRoleAssignments)
            {
                var RoleAssignments = folderItem.RoleAssignments;
                ClientContext.Load(RoleAssignments);
                ClientContext.ExecuteQueryRetry();

                retFolder.Security.ClearSubscopes      = true;
                retFolder.Security.CopyRoleAssignments = false;

                ClientContext.Load(RoleAssignments, r => r.Include(a => a.Member.LoginName, a => a.Member, a => a.RoleDefinitionBindings));
                ClientContext.ExecuteQueryRetry();

                foreach (var roleAssignment in RoleAssignments)
                {
                    var principalName = roleAssignment.Member.LoginName;
                    var roleBindings  = roleAssignment.RoleDefinitionBindings;
                    foreach (var roleBinding in roleBindings)
                    {
                        retFolder.Security.RoleAssignments.Add(new PnP.Framework.Provisioning.Model.RoleAssignment()
                        {
                            Principal = principalName, RoleDefinition = roleBinding.Name
                        });
                    }
                }
            }

            return(retFolder);
        }
Пример #27
0
        public Folder GetParent(string url, Guid libraryId, string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(folderPath.Trim('/')))
            {
                return(null);
            }

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    SP.List splist = clientContext.Web.Lists.GetById(libraryId);

                    SP.Folder rootFolder = splist.RootFolder;
                    clientContext.Load(rootFolder, f => f.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    if (rootFolder.ServerRelativeUrl.Trim('/').Equals(folderPath.Trim('/'), StringComparison.InvariantCultureIgnoreCase))
                    {
                        // This is a root folder, so it has no parents
                        return(null);
                    }

                    var spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(spfolder, f => f.ServerRelativeUrl);
                    clientContext.Load(spfolder.ParentFolder, p => p.Name, p => p.ServerRelativeUrl, p => p.ItemCount);
                    clientContext.ExecuteQuery();

                    bool pathIsNotEmpty  = spfolder != null && !String.IsNullOrEmpty(spfolder.ServerRelativeUrl.Trim('/'));
                    bool isARootFolder   = spfolder == null || rootFolder.ServerRelativeUrl.Trim('/').Equals(spfolder.ServerRelativeUrl.Trim('/'));
                    bool hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    if (!hasParentFolder)
                    {
                        return(null);
                    }

                    if (spfolder.ParentFolder != null)
                    {
                        return(new Folder(spfolder.ParentFolder.Name, spfolder.ParentFolder.ServerRelativeUrl, spfolder.ParentFolder.ItemCount, libraryId));
                    }
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw new SPInternalException(ex.Message, ex);
            }
        }
Пример #28
0
        public void SaveFileToSharePoint(ClientContext clientContext)
        {
            Microsoft.SharePoint.Client.Folder folderSHPO = clientContext.Web.GetFolderByServerRelativeUrl(library);

            FileCreationInformation newFileAtributes = new FileCreationInformation();

            newFileAtributes.ContentStream = opdDisclaimer.OpenFile();;
            newFileAtributes.Url           = fileName;
            newFileAtributes.Overwrite     = true;

            Microsoft.SharePoint.Client.File newfile = folderSHPO.Files.Add(newFileAtributes);
            clientContext.Load(newfile);
            //Update the metadata for a field having name "DocType"

            clientContext.ExecuteQuery();
        }
Пример #29
0
        /// <summary>
        /// Gets and sets default content type of the list.
        /// </summary>
        /// <param name="requestObject">RequestObject object</param>
        /// <param name="clientContext">ClientContext object</param>
        /// <param name="url">SourceURL of the OneDrive document</param>
        /// <param name="contentTypeId">Content Type Id</param>
        /// <param name="operationType">Operation type specifies either get or set Content type operation</param>
        /// <param name="documentLibraryName">Name of the document library</param>
        /// <returns>Returns Content Type Id</returns>
        internal static string GetContentTypeList(RequestObject requestObject, ClientContext clientContext, string url, string contentTypeId, int operationType, string documentLibraryName)
        {
            try
            {
                using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(url.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken))
                {
                    List docLib = clientContext.Web.Lists.GetByTitle(documentLibraryName);
                    clientContext.Load(docLib);
                    clientContext.ExecuteQuery();
                    Microsoft.SharePoint.Client.Folder folder = docLib.RootFolder;
                    IList <ContentTypeId> list = new List <ContentTypeId>();
                    clientContext.Load(folder, item => item.ContentTypeOrder, item => item.UniqueContentTypeOrder);
                    clientContext.ExecuteQuery();
                    list = folder.ContentTypeOrder;
                    ServiceConstantStrings.OperationTypes type = (ServiceConstantStrings.OperationTypes)operationType;
                    switch (type)
                    {
                    case ServiceConstantStrings.OperationTypes.Update:
                        contentTypeId = list[0].StringValue;
                        break;

                    case ServiceConstantStrings.OperationTypes.Checkout:
                        int iterator = 0, index = 0;
                        for (iterator = 0; iterator < list.Count; iterator++)
                        {
                            if (list[iterator].StringValue == contentTypeId)
                            {
                                index = iterator;
                                break;
                            }
                        }
                        ContentTypeId currentContentTypeID = list[index];
                        list.RemoveAt(index);
                        list.Insert(0, currentContentTypeID);
                        folder.UniqueContentTypeOrder = list;
                        folder.Update();
                        clientContext.ExecuteQuery();
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(contentTypeId);
        }
Пример #30
0
        public Folder Delete(string url, Guid libraryId, string folderPath)
        {
            Folder folder;

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    SP.List splist = clientContext.Web.Lists.GetById(libraryId);

                    SP.Folder rootFolder = splist.RootFolder;
                    clientContext.Load(rootFolder, f => f.ServerRelativeUrl);

                    SP.Folder spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(spfolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);

                    clientContext.ExecuteQuery();

                    bool pathIsNotEmpty  = !String.IsNullOrEmpty(spfolder.ServerRelativeUrl.Trim('/'));
                    bool isARootFolder   = rootFolder.ServerRelativeUrl.Trim('/').Equals(spfolder.ServerRelativeUrl.Trim('/'));
                    bool hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    if (hasParentFolder && !IsHiddenFolder(spfolder.ServerRelativeUrl, rootFolder.ServerRelativeUrl))
                    {
                        folder = new Folder(spfolder.Name, spfolder.ServerRelativeUrl, spfolder.ItemCount, libraryId);

                        spfolder.DeleteObject();
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        throw new SPInternalException("Folder can not be removed.");
                    }
                }
            }
            catch (SPInternalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Delete() method LibraryId: {1} ServerRelativeUrl: '{2}' in SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), libraryId, folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(folder);
        }
Пример #31
0
        private void doCreateFolder(bool useNewContext)
        {
            SP.ClientContext ctx = getSpClientContext(useNewContext);
            try
            {
                int pathLengthToWeb = new Utility.Uri(m_spWebUrl).Path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Length;

                string[] folderNames = m_serverRelPath.Substring(0, m_serverRelPath.Length - 1).Split('/');
                folderNames = Array.ConvertAll(folderNames, fold => System.Net.WebUtility.UrlDecode(fold));
                var spfolders = new SP.Folder[folderNames.Length];
                string folderRelPath = "";
                int fi = 0;
                for (; fi < folderNames.Length; fi++)
                {
                    folderRelPath += System.Web.HttpUtility.UrlPathEncode(folderNames[fi]) + "/";
                    if (fi < pathLengthToWeb) continue;
                    var folder = ctx.Web.GetFolderByServerRelativeUrl(folderRelPath);
                    spfolders[fi] = folder;
                    ctx.Load(folder, f => f.Exists);
                    try { wrappedExecuteQueryOnConext(ctx, folderRelPath, true); }
                    catch (FolderMissingException)
                    { break; }
                    if (!folder.Exists) break;
                }

                for (; fi < folderNames.Length; fi++)
                    spfolders[fi] = spfolders[fi - 1].Folders.Add(folderNames[fi]);
                ctx.Load(spfolders[folderNames.Length - 1], f => f.Exists);

                wrappedExecuteQueryOnConext(ctx, m_serverRelPath, true);

                if (!spfolders[folderNames.Length - 1].Exists)
                    throw new Interface.FolderMissingException(Strings.SharePoint.MissingElementError(m_serverRelPath, m_spWebUrl));
            }
            catch (ServerException) { throw; /* rethrow if Server answered */ }
            catch (Interface.FileMissingException) { throw; }
            catch (Interface.FolderMissingException) { throw; }
            catch { if (!useNewContext) /* retry */ doCreateFolder(true); else throw; }
            finally { }
        }
        private Folder MoveFld(Folder folder, string newUrl, bool delete = true)
        {
            var newFolder = CreateFolder(newUrl);

            if (delete)
            {
                folder.Folders.ToList().ForEach(r => MoveFolder(r.ServerRelativeUrl, newUrl));
                folder.Files.ToList().ForEach(r => MoveFile(r.ServerRelativeUrl, newUrl));

                folder.DeleteObject();
                clientContext.ExecuteQuery();
            }
            else
            {
                folder.Folders.ToList().ForEach(r => CopyFolder(r.ServerRelativeUrl, newUrl));
                folder.Files.ToList().ForEach(r => CopyFile(r.ServerRelativeUrl, newUrl));
            }

            return newFolder;
        }
        public Core.Folder ToFolder(Folder folder)
        {
            if (folder == null) return null;

            var errorFolder = folder as SharePointFolderErrorEntry;
            if (errorFolder != null)
                return new Core.Folder
                {
                    ID = MakeId(errorFolder.ID),
                    ParentFolderID = null,
                    CreateBy = Owner,
                    CreateOn = DateTime.UtcNow,
                    FolderType = FolderType.DEFAULT,
                    ModifiedBy = Owner,
                    ModifiedOn = DateTime.UtcNow,
                    ProviderId = ID,
                    ProviderKey = ProviderKey,
                    RootFolderCreator = Owner,
                    RootFolderId = MakeId(SpRootFolderId),
                    RootFolderType = RootFolderType,
                    Shareable = false,
                    Title = MakeTitle(GetTitleById(errorFolder.ID)),
                    TotalFiles = 0,
                    TotalSubFolders = 0,
                    Error = errorFolder.Error
                };

            var isRoot = folder.ServerRelativeUrl == SpRootFolderId;
            return new Core.Folder
                {
                    ID = MakeId(isRoot ? "" : folder.ServerRelativeUrl),
                    ParentFolderID = isRoot ? null : MakeId(GetParentFolderId(folder.ServerRelativeUrl)),
                    CreateBy = Owner,
                    CreateOn = CreateOn,
                    FolderType = FolderType.DEFAULT,
                    ModifiedBy = Owner,
                    ModifiedOn = CreateOn,
                    ProviderId = ID,
                    ProviderKey = ProviderKey,
                    RootFolderCreator = Owner,
                    RootFolderId = MakeId(RootFolder.ServerRelativeUrl),
                    RootFolderType = RootFolderType,
                    Shareable = false,
                    Title = isRoot ? CustomerTitle : MakeTitle(folder.Name),
                    TotalFiles = 0,
                    TotalSubFolders = 0,
                };
        }