Example #1
0
    static void InitializeClientContext() {

      // create new client context
      string targetSharePointSite = ConfigurationManager.AppSettings["targetSharePointSite"];
      clientContext = new ClientContext(targetSharePointSite);
      
      // get user name and secure password
      string userName = ConfigurationManager.AppSettings["accessAccountName"];
      string pwd = ConfigurationManager.AppSettings["accessAccountPassword"];
      SecureString spwd = new SecureString();
      foreach (char c in pwd.ToCharArray()) {
        spwd.AppendChar(c);
      }
    
        // create credentials for SharePoint Online using Office 365 user account
      clientContext.Credentials = new SharePointOnlineCredentials(userName, spwd);

      // initlaize static variables for client context, web and site
      siteCollection = clientContext.Site;
      clientContext.Load(siteCollection);
      site = clientContext.Web;
      clientContext.Load(site);
      siteRootFolder = site.RootFolder;
      clientContext.Load(siteRootFolder);
      clientContext.Load(site.Lists);

      TopNavNodes = site.Navigation.TopNavigationBar;
      clientContext.Load(TopNavNodes);
      clientContext.ExecuteQuery();

    }
        internal static void CreateSearchNavigationNodes(ClientContext clientContext, Web web, Dictionary <string, string> searchNavigationNodes)
        {
            if (searchNavigationNodes == null || searchNavigationNodes.Count == 0)
            {
                return;
            }

            var searchNavigation = web.Navigation.GetNodeById(1040);
            NavigationNodeCollection nodeCollection = searchNavigation.Children;

            clientContext.Load(searchNavigation);
            clientContext.Load(nodeCollection);
            clientContext.ExecuteQuery();

            for (int i = nodeCollection.Count - 1; i >= 0; i--)
            {
                nodeCollection[i].DeleteObject();
            }


            foreach (KeyValuePair <string, string> newNode in searchNavigationNodes.Reverse <KeyValuePair <string, string> >())
            {
                nodeCollection.Add(new NavigationNodeCreationInformation
                {
                    Title = newNode.Key,
                    Url   = newNode.Value
                });
            }

            clientContext.ExecuteQuery();
        }
Example #3
0
        private void GetDataAndUpdateCommonViewIfNecessary(bool needGetColor)
        {
            NavigationNodeCollection navigationNodeCollection = null;

            NavigationNodeFolder[] array = null;
            if (Utilities.IsWebPartDelegateAccessRequest(OwaContext.Current) || (!needGetColor && this.FolderId.Equals(this.UserContext.CalendarFolderOwaId)) || !this.TryGetNodeFoldersFromNavigationTree(out array, out navigationNodeCollection))
            {
                base.CalendarTitle = ((this.folder != null) ? this.folder.DisplayName : string.Empty);
                this.CalendarColor = -2;
                return;
            }
            this.CalendarColor = CalendarColorManager.GetCalendarFolderColor(this.UserContext, navigationNodeCollection, array);
            OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromNavigationNodeFolder(this.UserContext, array[0]);

            if (owaStoreObjectId.IsArchive)
            {
                base.CalendarTitle = string.Format(LocalizedStrings.GetNonEncoded(-83764036), array[0].Subject, Utilities.GetMailboxOwnerDisplayName((MailboxSession)owaStoreObjectId.GetSession(this.UserContext)));
            }
            else
            {
                base.CalendarTitle = array[0].Subject;
            }
            foreach (NavigationNodeFolder navigationNodeFolder in array)
            {
                if (!navigationNodeFolder.IsGSCalendar && navigationNodeFolder.IsPrimarySharedCalendar)
                {
                    navigationNodeFolder.UpgradeToGSCalendar();
                }
                if (this.olderExchangeCalendarTypeInNode == NavigationNodeFolder.OlderExchangeCalendarType.Unknown)
                {
                    this.olderExchangeCalendarTypeInNode = navigationNodeFolder.OlderExchangeSharedCalendarType;
                }
            }
        }
        protected virtual NavigationNode LookupNavigationNode(NavigationNodeCollection nodes,
                                                              NavigationNodeDefinitionBase definition)
        {
            var context = nodes.Context;

            context.Load(nodes);
            context.ExecuteQueryWithTrace();

            var currentNode = nodes
                              .OfType <NavigationNode>()
                              .FirstOrDefault(n => !string.IsNullOrEmpty(n.Title) && (n.Title.ToUpper() == definition.Title.ToUpper()));

            if (currentNode == null)
            {
                var url = ResolveTokenizedUrl(CurrentModelHost, definition);

                url = HttpUtility.UrlKeyValueDecode(url);

                currentNode = nodes
                              .OfType <NavigationNode>()
                              .FirstOrDefault(n => !string.IsNullOrEmpty(n.Url) && (n.Url.ToUpper().EndsWith(url.ToUpper())));
            }

            return(currentNode);
        }
        private void RemoveQuickLaunchNode(ClientContext clientContext)
        {
            //load web again... could be improved
            Web web = clientContext.Web;

            clientContext.Load(web);
            clientContext.ExecuteQuery();

            // Remove the entry from the 'Recents' node
            NavigationNodeCollection nodes = web.Navigation.QuickLaunch;

            clientContext.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children));
            clientContext.ExecuteQuery();
            var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault();

            if (recent != null)
            {
                var appLink = recent.Children.Where(x => x.Title == "Core.SiteInformation").FirstOrDefault();
                if (appLink != null)
                {
                    appLink.DeleteObject();
                }
                clientContext.ExecuteQuery();
            }
        }
Example #6
0
        // Token: 0x06002EB5 RID: 11957 RVA: 0x0010BEBC File Offset: 0x0010A0BC
        private void OpenOtherUserCalendar(RecipientInfoAC recipientInfo)
        {
            ExchangePrincipal exchangePrincipal = null;

            if (base.UserContext.DelegateSessionManager.TryGetExchangePrincipal(recipientInfo.RoutingAddress, out exchangePrincipal))
            {
                if (string.Equals(base.UserContext.MailboxSession.MailboxOwnerLegacyDN, exchangePrincipal.LegacyDn, StringComparison.OrdinalIgnoreCase))
                {
                    throw new OwaEventHandlerException("Cannot open own folder", LocalizedStrings.GetNonEncoded(-1770024075), true);
                }
                try
                {
                    NavigationNodeCollection.AddGSCalendarToSharedFoldersGroup(base.UserContext, exchangePrincipal);
                    OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromGSCalendarLegacyDN(exchangePrincipal.LegacyDn);
                    NavigationHost.RenderFavoritesAndNavigationTrees(this.Writer, base.UserContext, owaStoreObjectId, new NavigationNodeGroupSection[]
                    {
                        NavigationNodeGroupSection.Calendar
                    });
                    this.RenderOpenOtherUserFolderReponse("IPF.Appointment", owaStoreObjectId);
                    return;
                }
                catch (OwaSharedFromOlderVersionException)
                {
                    throw new OwaEventHandlerException(LocalizedStrings.GetNonEncoded(995407892), LocalizedStrings.GetNonEncoded(1354015881), true);
                }
            }
            throw new OwaEventHandlerException("Cannot get the exchange principal of the target user when open other user's calendar", LocalizedStrings.GetNonEncoded(1988379659), true);
        }
Example #7
0
        public void DeleteSearchNavigationNodeTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var web = clientContext.Web;

                // First clear all search nav nodes
                var nodeCollection = web.LoadSearchNavigation();
                foreach (var node in nodeCollection.ToList())
                {
                    node.DeleteObject();
                }
                clientContext.ExecuteQueryRetry();

                web.AddNavigationNode("Test Node", new Uri("https://www.microsoft.com"), string.Empty, NavigationType.SearchNav);

                web.DeleteNavigationNode("Test Node", string.Empty, NavigationType.SearchNav);

                NavigationNodeCollection searchNavigation = web.LoadSearchNavigation();

                if (searchNavigation.Any())
                {
                    var navNode = searchNavigation.FirstOrDefault(n => n.Title == "Test Node");
                    Assert.IsNull(navNode);
                }
            }
        }
Example #8
0
        public void AddNewGroup()
        {
            base.ThrowIfCannotActAsOwner();
            string text = ((string)base.GetParameter("SB")).Trim();

            if (text.Length == 0)
            {
                throw new OwaEventHandlerException("User did not provide name for new group", LocalizedStrings.GetNonEncoded(-1749891264), true);
            }
            NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
            NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            NavigationNodeGroup        navigationNodeGroup        = NavigationNodeCollection.CreateCustomizedGroup(navigationNodeGroupSection, text);
            Guid navigationNodeGroupClassId = navigationNodeGroup.NavigationNodeGroupClassId;

            navigationNodeCollection.Add(navigationNodeGroup);
            navigationNodeCollection.Save(base.UserContext.MailboxSession);
            navigationNodeCollection = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            navigationNodeGroup      = navigationNodeCollection[navigationNodeCollection.FindGroupById(navigationNodeGroupClassId)];
            NavigationGroupHeaderTreeNode navigationGroupHeaderTreeNode  = new NavigationGroupHeaderTreeNode(base.UserContext, navigationNodeGroup);
            NavigationGroupHeaderTreeNode navigationGroupHeaderTreeNode2 = navigationGroupHeaderTreeNode;

            navigationGroupHeaderTreeNode2.CustomAttributes += " _NF=1";
            this.Writer.Write("<div id=ntn>");
            navigationGroupHeaderTreeNode.RenderUndecoratedNode(this.Writer);
            this.Writer.Write("</div>");
        }
Example #9
0
        public override void AddNavigationNode(string title, string url, NavigationNodeLocation location)
        {
            NavigationNodeCreationInformation newNavNode = new NavigationNodeCreationInformation();

            newNavNode.Title = title;
            newNavNode.Url   = url;

            NavigationNodeCollection navNodeColl = null;

            switch (location)
            {
            case NavigationNodeLocation.TopNavigationBar:
                navNodeColl = _web.Navigation.TopNavigationBar;
                break;

            case NavigationNodeLocation.QuickLaunchLists:
                navNodeColl = _web.Navigation.QuickLaunch;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(location), location, null);
            }


            try
            {
                navNodeColl.Add(newNavNode);
                _context.ExecuteQuery();
            }
            catch (Exception)
            {
                //ignore, already exists
            }
        }
Example #10
0
        public static NavigationTree CreateNavigationTree(UserContext userContext, NavigationNodeGroupSection groupSection)
        {
            List <FolderList> folderLists = new List <FolderList>();

            folderLists.Add(new FolderList(userContext, userContext.MailboxSession, new string[]
            {
                NavigationNode.GetFolderClass(groupSection)
            }, 10000, false, null, FolderList.FolderTreeQueryProperties));
            if (userContext.ArchiveAccessed)
            {
                userContext.TryLoopArchiveMailboxes(delegate(MailboxSession archiveSession)
                {
                    folderLists.Add(new FolderList(userContext, archiveSession, new string[]
                    {
                        NavigationNode.GetFolderClass(groupSection)
                    }, 10000, false, null, FolderList.FolderTreeQueryProperties));
                });
            }
            NavigationNodeCollection navigationNodeCollection = NavigationNodeCollection.TryCreateNavigationNodeCollection(userContext, userContext.MailboxSession, groupSection);

            return(NavigationTree.CreateNavigationTreeByFolderLists(userContext, folderLists.ToArray(), new NavigationNodeCollection[]
            {
                navigationNodeCollection
            })[0]);
        }
Example #11
0
        static void InitializeClientContext(string targetsite)
        {
            // create new client context
            clientContext = new ClientContext(targetsite);

            // get user name and secure password
            string       userName = ConfigurationManager.AppSettings["accessAccountName"];
            string       pwd      = ConfigurationManager.AppSettings["accessAccountPassword"];
            SecureString spwd     = new SecureString();

            foreach (char c in pwd.ToCharArray())
            {
                spwd.AppendChar(c);
            }

            // create credentials for SharePoint Online using Office 365 user account
            clientContext.Credentials = new SharePointOnlineCredentials(userName, spwd);

            // initlaize static variables for client context, web and site
            siteCollection = clientContext.Site;
            clientContext.Load(siteCollection);
            site = clientContext.Web;
            clientContext.Load(site);
            siteRootFolder = site.RootFolder;
            clientContext.Load(siteRootFolder);
            clientContext.Load(site.Lists);

            TopNavNodes = site.Navigation.TopNavigationBar;
            clientContext.Load(TopNavNodes);
            clientContext.ExecuteQuery();
        }
        protected override void ExecuteCmdlet()
        {
            if (Url == null)
            {
                ClientContext.Load(SelectedWeb, w => w.Url);
                ClientContext.ExecuteQueryRetry();
                Url = SelectedWeb.Url;
            }
            if (Parent.HasValue)
            {
                var parentNode = SelectedWeb.Navigation.GetNodeById(Parent.Value);
                ClientContext.Load(parentNode);
                ClientContext.ExecuteQueryRetry();
                var addedNode = parentNode.Children.Add(new NavigationNodeCreationInformation()
                {
                    Title      = Title,
                    Url        = Url,
                    IsExternal = External.IsPresent,
                    AsLastNode = !First.IsPresent
                });
                ClientContext.Load(addedNode);
                ClientContext.ExecuteQueryRetry();
                WriteObject(addedNode);
            }
            else
            {
                NavigationNodeCollection nodeCollection = null;
                if (Location == NavigationType.SearchNav)
                {
                    nodeCollection = SelectedWeb.LoadSearchNavigation();
                }
                else if (Location == NavigationType.Footer)
                {
                    nodeCollection = SelectedWeb.LoadFooterNavigation();
                }
                else
                {
                    nodeCollection = Location == NavigationType.QuickLaunch ? SelectedWeb.Navigation.QuickLaunch : SelectedWeb.Navigation.TopNavigationBar;
                    ClientContext.Load(nodeCollection);
                }
                if (nodeCollection != null)
                {
                    var addedNode = nodeCollection.Add(new NavigationNodeCreationInformation()
                    {
                        Title      = Title,
                        Url        = Url,
                        IsExternal = External.IsPresent,
                        AsLastNode = !First.IsPresent
                    });
                    ClientContext.Load(addedNode);
                    ClientContext.ExecuteQueryRetry();
                    WriteObject(addedNode);
                }
                else
                {
                    throw new Exception("Navigation Node Collection is null");
                }
#pragma warning restore CS0618 // Type or member is obsolete
            }
        }
Example #13
0
        public void Move()
        {
            base.ThrowIfCannotActAsOwner();
            StoreObjectId nodeId  = (StoreObjectId)base.GetParameter("srcNId");
            StoreObjectId nodeId2 = (StoreObjectId)base.GetParameter("tgtid");
            int           num     = base.IsParameterSet("mt") ? ((int)base.GetParameter("mt")) : 0;
            NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
            NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            NavigationNode             navigationNode             = navigationNodeCollection.RemoveFolderOrGroupByNodeId(nodeId);

            if (navigationNode == null)
            {
                base.RenderPartialFailure(-289549140, OwaEventHandlerErrorCode.NotSet);
            }
            else
            {
                int num2;
                int num3;
                if (navigationNodeCollection.TryFindGroupAndNodeIndexByNodeId(nodeId2, out num2, out num3))
                {
                    if (navigationNode is NavigationNodeGroup)
                    {
                        if (num3 >= 0)
                        {
                            throw new OwaInvalidRequestException("The target node must be a navigation node group");
                        }
                        if (num != 1 && num != 2)
                        {
                            throw new OwaInvalidRequestException("Can only move a group before or after another group");
                        }
                        navigationNodeCollection.Insert((num == 2) ? (num2 + 1) : num2, navigationNode as NavigationNodeGroup);
                    }
                    else if (navigationNode is NavigationNodeFolder)
                    {
                        if (num3 >= 0)
                        {
                            if (num != 1 && num != 2)
                            {
                                throw new OwaInvalidRequestException("Can only move a folder before or after another folder");
                            }
                            navigationNodeCollection[num2].Children.Insert((num == 2) ? (num3 + 1) : num3, navigationNode as NavigationNodeFolder);
                        }
                        else
                        {
                            navigationNodeCollection[num2].Children.Add(navigationNode as NavigationNodeFolder);
                        }
                    }
                }
                else
                {
                    base.RenderPartialFailure((navigationNodeGroupSection == NavigationNodeGroupSection.First) ? 817935633 : 444965652, OwaEventHandlerErrorCode.NotSet);
                }
                navigationNodeCollection.Save(base.UserContext.MailboxSession);
            }
            NavigationHost.RenderFavoritesAndNavigationTrees(this.Writer, base.UserContext, null, new NavigationNodeGroupSection[]
            {
                navigationNodeGroupSection
            });
        }
        protected override void ExecuteCmdlet()
        {
            if (Url == null)
            {
                ClientContext.Load(SelectedWeb, w => w.Url);
                ClientContext.ExecuteQueryRetry();
                Url = SelectedWeb.Url;
            }
            if (Parent.HasValue)
            {
                var parentNode = SelectedWeb.Navigation.GetNodeById(Parent.Value);
                ClientContext.Load(parentNode);
                ClientContext.ExecuteQueryRetry();
                var addedNode = parentNode.Children.Add(new NavigationNodeCreationInformation()
                {
                    Title      = Title,
                    Url        = Url,
                    IsExternal = External.IsPresent,
                    AsLastNode = !First.IsPresent
                });
                ClientContext.Load(addedNode);
                ClientContext.ExecuteQueryRetry();
                WriteObject(addedNode);
            }
            else
            {
#pragma warning disable CS0618 // Type or member is obsolete
                if (!string.IsNullOrEmpty(Header))
                {
                    var newNavNode = SelectedWeb.AddNavigationNode(Title, new Uri(Url, UriKind.RelativeOrAbsolute), Header, Location, External.IsPresent, !First.IsPresent);
                    WriteObject(newNavNode);
                }
                else
                {
                    NavigationNodeCollection nodeCollection = null;
                    if (Location == NavigationType.SearchNav)
                    {
                        nodeCollection = SelectedWeb.LoadSearchNavigation();
                    }
                    else
                    {
                        nodeCollection = Location == NavigationType.QuickLaunch ? SelectedWeb.Navigation.QuickLaunch : SelectedWeb.Navigation.TopNavigationBar;
                        ClientContext.Load(nodeCollection);
                    }
                    var addedNode = nodeCollection.Add(new NavigationNodeCreationInformation()
                    {
                        Title      = Title,
                        Url        = Url,
                        IsExternal = External.IsPresent,
                        AsLastNode = !First.IsPresent
                    });
                    ClientContext.Load(addedNode);
                    ClientContext.ExecuteQueryRetry();
                    WriteObject(addedNode);
                }
#pragma warning restore CS0618 // Type or member is obsolete
            }
        }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            NavigationNodeDefinitionBase quickLaunchModel)
        {
            NavigationNodeCollection quickLaunch = null;
            var result = GetRootNavigationNode(webModelHost, quickLaunchModel, out quickLaunch);

            return(result);
        }
        private NavigationNode EnsureRootQuickLaunchNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel)
        {
            NavigationNodeCollection quickLaunch = null;

            var context = webModelHost.HostWeb.Context;

            var existingNode = GetRootNavigationNode(webModelHost, quickLaunchModel, out quickLaunch);
            var previousNode = quickLaunch.Count > 0 ? quickLaunch.Last() : null;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = existingNode,
                ObjectType       = typeof(NavigationNode),
                ObjectDefinition = quickLaunchModel,
                ModelHost        = webModelHost
            });

            if (existingNode == null)
            {
                existingNode = quickLaunch.Add(new NavigationNodeCreationInformation
                {
                    Title        = quickLaunchModel.Title,
                    IsExternal   = quickLaunchModel.IsExternal,
                    Url          = quickLaunchModel.Url,
                    PreviousNode = previousNode
                });

                context.ExecuteQuery();
            }

            existingNode.Title     = quickLaunchModel.Title;
            existingNode.Url       = quickLaunchModel.Url;
            existingNode.IsVisible = quickLaunchModel.IsVisible;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = existingNode,
                ObjectType       = typeof(NavigationNode),
                ObjectDefinition = quickLaunchModel,
                ModelHost        = webModelHost
            });

            existingNode.Update();

            context.ExecuteQuery();

            return(existingNode);
        }
 public SitePageManager(ClientContext clientContext)
 {
     this.clientContext = clientContext;
       this.hostWeb = clientContext.Web;
       this.sitePages = hostWeb.Lists.GetByTitle("Site Pages");
       clientContext.Load(hostWeb, web => web.Id);
       clientContext.Load(sitePages);
       topNavNodes = hostWeb.Navigation.TopNavigationBar;
       clientContext.Load(topNavNodes);
       clientContext.ExecuteQuery();
       hostWebID = hostWeb.Id.ToString();
 }
Example #18
0
 public SitePageManager(ClientContext clientContext)
 {
     this.clientContext = clientContext;
     this.hostWeb       = clientContext.Web;
     this.sitePages     = hostWeb.Lists.GetByTitle("Site Pages");
     clientContext.Load(hostWeb, web => web.Id);
     clientContext.Load(sitePages);
     topNavNodes = hostWeb.Navigation.TopNavigationBar;
     clientContext.Load(topNavNodes);
     clientContext.ExecuteQuery();
     hostWebID = hostWeb.Id.ToString();
 }
 private void GetNavNodes(ClientContext cc, NavigationNodeCollection navigationNodes)
 {
     foreach (var navNode in navigationNodes)
     {
         //Console.Write(navNode.Title, navNode.Url, navNode.Id, cc.Web.Url)
         cc.Load(navNode.Children);
         cc.ExecuteQuery();
         if (navNode.Children.Count > 0)
         {
             GetNavNodes(cc, navNode.Children);
         }
     }
 }
Example #20
0
        private void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx)
        {
            Web web = ctx.Web;

            ctx.Load(web, w => w.UserCustomActions);
            ctx.ExecuteQuery();

            ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId);
            ctx.ExecuteQuery();

            UserCustomAction userCustomAction = web.UserCustomActions.Add();

            userCustomAction.Location = "Microsoft.SharePoint.StandardMenu";
            userCustomAction.Group    = "SiteActions";
            BasePermissions perms = new BasePermissions();

            perms.Set(PermissionKind.ManageWeb);
            userCustomAction.Rights   = perms;
            userCustomAction.Sequence = 100;
            userCustomAction.Title    = "Modify Site";

            string realm    = TokenHelper.GetRealmFromTargetUrl(new Uri(ctx.Url));
            string issuerId = WebConfigurationManager.AppSettings.Get("ClientId");

            var    modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", Request.Url.Authority);
            string url           = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});";

            url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl);

            userCustomAction.Url = url;
            userCustomAction.Update();
            ctx.ExecuteQuery();

            // Remove the entry from the 'Recents' node
            NavigationNodeCollection nodes = web.Navigation.QuickLaunch;

            ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children));
            ctx.ExecuteQuery();
            var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault();

            if (recent != null)
            {
                var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault();
                if (appLink != null)
                {
                    appLink.DeleteObject();
                }
                ctx.ExecuteQuery();
            }
        }
Example #21
0
        /// <summary>
        /// Deletes a navigation node from the quickLaunch or top navigation bar
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="nodeTitle">the title of node to delete</param>
        /// <param name="parentNodeTitle">if string.Empty, then will delete this node as top level node</param>
        /// <param name="navigationType">the type of navigation, quick launch, top navigation or search navigation</param>
        public static void DeleteNavigationNode(this Web web, string nodeTitle, string parentNodeTitle, NavigationType navigationType)
        {
            web.Context.Load(web, w => w.Navigation.QuickLaunch, w => w.Navigation.TopNavigationBar);
            web.Context.ExecuteQueryRetry();
            NavigationNode deleteNode = null;

            try
            {
                if (navigationType == NavigationType.QuickLaunch)
                {
                    var quickLaunch = web.Navigation.QuickLaunch;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        deleteNode = quickLaunch.SingleOrDefault(n => n.Title == nodeTitle);
                    }
                    else
                    {
                        foreach (var nodeInfo in quickLaunch)
                        {
                            if (nodeInfo.Title != parentNodeTitle)
                            {
                                continue;
                            }

                            web.Context.Load(nodeInfo.Children);
                            web.Context.ExecuteQueryRetry();
                            deleteNode = nodeInfo.Children.SingleOrDefault(n => n.Title == nodeTitle);
                        }
                    }
                }
                else if (navigationType == NavigationType.TopNavigationBar)
                {
                    var topLink = web.Navigation.TopNavigationBar;
                    deleteNode = topLink.SingleOrDefault(n => n.Title == nodeTitle);
                }
                else if (navigationType == NavigationType.SearchNav)
                {
                    NavigationNodeCollection nodeCollection = web.LoadSearchNavigation();
                    deleteNode = nodeCollection.SingleOrDefault(n => n.Title == nodeTitle);
                }
            }
            finally
            {
                if (deleteNode != null)
                {
                    deleteNode.DeleteObject();
                }
                web.Context.ExecuteQueryRetry();
            }
        }
Example #22
0
        private void AddNode(NavigationNodeCreator node, NavigationNodeCollection navigationNodes)
        {
            var found = false;

            foreach (var existingNode in navigationNodes)
            {
                if (node.Title == existingNode.Title)
                {
                    found = true;
                    if (node.Children != null && node.Children.Count > 0)
                    {
                        _ctx.Load(existingNode, n => n.Children.Include(c => c.Title));
                        _ctx.ExecuteQueryRetry();
                        foreach (var childNode in node.Children)
                        {
                            AddNode(childNode, existingNode.Children);
                        }
                    }
                    break;
                }
            }
            if (!found)
            {
                var creator = new NavigationNodeCreationInformation
                {
                    Title      = node.Title,
                    IsExternal = node.IsExternal,
                    Url        =
                        node.IsExternal
                            ? node.Url.Replace("{@WebUrl}", _web.Url).Replace("{@WebServerRelativeUrl}", _web.ServerRelativeUrl)
                            : GetUrl(node.Url)
                };
                if (node.AsLastNode)
                {
                    creator.AsLastNode = true;
                }
                var newNode = navigationNodes.Add(creator);

                if (node.Children != null && node.Children.Count > 0)
                {
                    _ctx.Load(newNode, n => n.Children.Include(c => c.Title));
                    _ctx.ExecuteQueryRetry();
                    foreach (var childNode in node.Children)
                    {
                        AddNode(childNode, newNode.Children);
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        /// Deletes the quick launch nodes on a web
        /// </summary>
        /// <param name="ctx">SharePoint clientcontext</param>
        public static void DeleteQuickLaunchNodes(ClientContext ctx)
        {
            NavigationNodeCollection qlNodes = ctx.Web.Navigation.QuickLaunch;

            ctx.Load(qlNodes);
            ctx.ExecuteQuery();

            var nodes = qlNodes.ToList();

            for (var i = nodes.Count - 1; i > -1; i--)
            {
                nodes[i].DeleteObject();
            }
            ctx.ExecuteQuery();
        }
Example #24
0
 public void PersistExpandStatus()
 {
     base.ThrowIfCannotActAsOwner();
     if (!base.UserContext.IsWebPartRequest)
     {
         NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
         NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
         int num = navigationNodeCollection.FindChildByNodeId((StoreObjectId)base.GetParameter("srcNId"));
         if (num >= 0)
         {
             navigationNodeCollection[num].IsExpanded = (bool)base.GetParameter("exp");
             navigationNodeCollection.Save(base.UserContext.MailboxSession);
         }
     }
 }
Example #25
0
        public static void AddQuickLaunch(NavigationNodeCollection quickLaunch, string Title, string Url, bool isChildNode = false)
        {
            NavigationNodeCreationInformation navci = new NavigationNodeCreationInformation();

            navci.AsLastNode = true;
            navci.Title      = Title;
            navci.Url        = Url;
            if (!isChildNode)
            {
                quickLaunch.Add(navci);
            }
            else
            {
                quickLaunch[quickLaunch.Count - 1].Children.Add(navci);
            }
        }
Example #26
0
        public static void AddGoogleToNav(ClientContext ctx)
        {
            Web web = ctx.Web;
            NavigationNodeCollection QuickLanchcoll = web.Navigation.QuickLaunch;
            //ctx.Load(QuickLanchcoll);
            //ctx.ExecuteQuery();

            NavigationNodeCreationInformation NewNode = new NavigationNodeCreationInformation();

            NewNode.Title = "Google";
            NewNode.Url   = "https://google.com";

            QuickLanchcoll.Add(NewNode);
            //ctx.Load(QuickLanchcoll);
            ctx.ExecuteQuery();
        }
Example #27
0
        public void SetCalendarColor()
        {
            base.ThrowIfCannotActAsOwner();
            int serverColorIndex = CalendarColorManager.GetServerColorIndex((int)base.GetParameter("Idx"));
            NavigationNodeCollection navigationNodeCollection = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, NavigationNodeGroupSection.Calendar);

            NavigationNodeFolder[] array            = null;
            OwaStoreObjectId       owaStoreObjectId = (OwaStoreObjectId)base.GetParameter("fId");

            if (owaStoreObjectId.IsGSCalendar)
            {
                array = navigationNodeCollection.FindGSCalendarsByLegacyDN(owaStoreObjectId.MailboxOwnerLegacyDN);
            }
            else
            {
                array = navigationNodeCollection.FindFoldersById(owaStoreObjectId.StoreObjectId);
            }
            if (array == null || (array.Length == 0 && !owaStoreObjectId.IsGSCalendar))
            {
                using (Folder calendarFolder = this.GetCalendarFolder(false))
                {
                    NavigationNodeGroupType groupType = NavigationNodeGroupType.MyFoldersGroup;
                    bool flag = base.UserContext.IsInOtherMailbox(calendarFolder);
                    if (flag || Utilities.IsOneOfTheFolderFlagsSet(calendarFolder, new ExtendedFolderFlags[]
                    {
                        ExtendedFolderFlags.SharedIn,
                        ExtendedFolderFlags.ExchangeCrossOrgShareFolder
                    }))
                    {
                        groupType = NavigationNodeGroupType.SharedFoldersGroup;
                    }
                    array = new NavigationNodeFolder[]
                    {
                        navigationNodeCollection.AddFolderToDefaultGroup(base.UserContext, groupType, calendarFolder, flag)
                    };
                }
            }
            if (array != null)
            {
                foreach (NavigationNodeFolder navigationNodeFolder in array)
                {
                    navigationNodeFolder.NavigationNodeCalendarColor = serverColorIndex;
                }
                navigationNodeCollection.Save(base.UserContext.MailboxSession);
            }
        }
Example #28
0
        public virtual void DeleteNodesByMatch(DeleteNavigationNodesDefinitionBase typedDefinition,
                                               NavigationNodeCollection nodesCollection,
                                               Func <string, string> resolveTokenizedUrlAction)
        {
            var allNodes      = nodesCollection.ToArray();
            var nodesToDelete = FindMatches(allNodes, typedDefinition, resolveTokenizedUrlAction);

            if (nodesToDelete.Any())
            {
                var context = nodesCollection.Context;

                foreach (var node in nodesToDelete.ToArray())
                {
                    node.DeleteObject();
                }

                context.ExecuteQueryWithTrace();
            }
        }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel, out NavigationNodeCollection quickLaunch)
        {
            var web     = webModelHost.HostWeb;
            var context = webModelHost.HostWeb.Context;

            quickLaunch = web.Navigation.QuickLaunch;

            context.Load(quickLaunch);
            context.ExecuteQuery();



            var existingNode = quickLaunch.OfType <NavigationNode>()
                               .FirstOrDefault(n => n.Url == quickLaunchModel.Url);

            return(existingNode);
        }
Example #30
0
        /// <summary>
        /// Creates a navigation node as a child of another (first or second level) navigation node.
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="parentNodes">Level one nodes under which the node should be created</param>
        /// <param name="nodeToCreate">Node information</param>
        /// <param name="parentNodeTitle">The title of the immediate parent node (level two if child should be level three, level one otherwise)</param>
        /// <param name="l1ParentNodeTitle">The level one parent title or null, if the node to be created should be a level two node</param>
        /// <returns></returns>
        private static NavigationNode CreateNodeAsChild(Web web, NavigationNodeCollection parentNodes, NavigationNodeCreationInformation nodeToCreate, string parentNodeTitle, string l1ParentNodeTitle)
        {
            if (l1ParentNodeTitle != null)
            {
                var l1ParentNode = parentNodes.FirstOrDefault(n => n.Title.Equals(l1ParentNodeTitle, StringComparison.InvariantCultureIgnoreCase));
                if (l1ParentNode == null)
                {
                    return(null);
                }
                web.Context.Load(l1ParentNode.Children);
                web.Context.ExecuteQueryRetry();
                parentNodes = l1ParentNode.Children;
            }

            var parentNode     = parentNodes.FirstOrDefault(n => n.Title.Equals(parentNodeTitle, StringComparison.InvariantCultureIgnoreCase));
            var navigationNode = parentNode?.Children.Add(nodeToCreate);

            return(navigationNode);
        }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            NavigationNodeDefinitionBase navigationNodeModel, out NavigationNodeCollection rootNavigationNodes)
        {
            var web     = webModelHost.HostWeb;
            var context = webModelHost.HostWeb.Context;

            rootNavigationNodes = GetNavigationNodeCollection(web);

            context.Load(rootNavigationNodes);
            context.ExecuteQueryWithTrace();

            // TODO, crazy URL matching to find 'resolved URL'

            var existingNode = rootNavigationNodes.OfType <NavigationNode>()
                               .FirstOrDefault(n => n.Url.ToUpper().EndsWith(navigationNodeModel.Url.ToUpper()));

            return(existingNode);
        }
        public virtual void DeleteNodesByMatch(DeleteNavigationNodesDefinitionBase typedDefinition,
            NavigationNodeCollection nodesCollection,
            Func<string, string> resolveTokenizedUrlAction)
        {
            var allNodes = nodesCollection.ToArray();
            var nodesToDelete = FindMatches(allNodes, typedDefinition, resolveTokenizedUrlAction);

            if (nodesToDelete.Any())
            {
                var context = nodesCollection.Context;

                foreach (var node in nodesToDelete.ToArray())
                {
                    node.DeleteObject();
                }

                context.ExecuteQueryWithTrace();
            }
        }
Example #33
0
        public void DeleteSearchNavigationNodeTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var web = clientContext.Web;

                web.AddNavigationNode("Test Node", new Uri("https://www.microsoft.com"), string.Empty, NavigationType.SearchNav);

                web.DeleteNavigationNode("Test Node", string.Empty, NavigationType.SearchNav);

                NavigationNodeCollection searchNavigation = web.LoadSearchNavigation();

                if (searchNavigation.Any())
                {
                    var navNode = searchNavigation.FirstOrDefault(n => n.Title == "Test Node");
                    Assert.IsNull(navNode);
                }
            }
        }
        public void Execute(ClientContext ctx, NavigationNodeCollection nodes, string title, Uri target)
        {
            Logger.Verbose($"Started executing {nameof(AddNavigationNode)} for title '{title}' with url '{target}'");

            var candidate = nodes.SingleOrDefault(n => n.Title == title);
            if (candidate != null)
            {
                Logger.Warning($"Title '{title}' already on navigation");
                return;
            }

            nodes.Add(new NavigationNodeCreationInformation
            {
                Title = title,
                Url = target.ToString(),
                AsLastNode = true
            });

            ctx.ExecuteQuery();
        }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel, out NavigationNodeCollection quickLaunch)
        {
            var web = webModelHost.HostWeb;
            var context = webModelHost.HostWeb.Context;

            quickLaunch = web.Navigation.QuickLaunch;

            context.Load(quickLaunch);
            context.ExecuteQuery();

            var existingNode = quickLaunch.OfType<NavigationNode>()
                .FirstOrDefault(n => n.Url == quickLaunchModel.Url);

            return existingNode;
        }