コード例 #1
0
        private void ManageFields()
        {
            _site     = SPContext.Current.Site;
            _web      = SPContext.Current.Web;
            appHelper = new AppSettingsHelper();
            _webUrl   = _web.Url;
            int.TryParse(GetParameter("ID"), out _iId);
            int.TryParse(GetParameter("appid"), out _appId);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                _eSite        = new SPSite(_site.Url);
                _eWeb         = _eSite.OpenWeb(_web.ServerRelativeUrl);
                _eCurrentNode = (_iId != 0) ? _eWeb.Navigation.GetNodeById(_iId) : null;
            });

            _currentNode = (_iId != 0) ? _web.Navigation.GetNodeById(_iId) : null;
            _nodeType    = GetParameter("nodetype");

            if ((_currentNode.ParentId == _web.Navigation.TopNavigationBar.Parent.Id) ||
                (_currentNode.ParentId == _web.Navigation.QuickLaunch.Parent.Id))
            {
                _isEditingHeading = true;
            }
            else
            {
                _isEditingHeading = false;
            }

            _origUserId = SPContext.Current.Web.CurrentUser.ID;
        }
コード例 #2
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //Get The Quick Launch and add a new root node if it doesn't already exist
            SPNavigationNodeCollection quickLinkNodes = ((SPWeb)(properties.Feature.Parent)).Navigation.QuickLaunch;
            SPNavigationNode           rootNode       = quickLinkNodes[0];

            if (rootNode.Title != rootNodeTitle)
            {
                rootNode = new SPNavigationNode(rootNodeTitle, ((SPWeb)(properties.Feature.Parent)).Url, false);
                quickLinkNodes.AddAsFirst(rootNode);
            }

            //Delete Items if they already exist
            foreach (SPNavigationNode quickLinkNode in rootNode.Children)
            {
                quickLinkNode.Delete();
            }

            //Add the Custom Links based on the Dictionary
            foreach (KeyValuePair <string, string> kvp in GetNav())
            {
                // add security trimmed nodes, set all to external=false
                var newNode = new SPNavigationNode(kvp.Key, kvp.Value, false);
                rootNode.Children.AddAsLast(newNode);
            }
            quickLinkNodes.Parent.Update();
        }
コード例 #3
0
        protected void OnDelete(object sender, EventArgs e)
        {
            if (_currentNode != null)
            {
                _eWeb.AllowUnsafeUpdates = true;
                _eWeb.Update();
                SPNavigationNode eNode = _eWeb.Navigation.GetNodeById(_currentNode.Id);

                // delete the ids from the
                // respective app items first
                switch (_nodeType)
                {
                case "topnav":
                    appHelper.DeleteAppTopNav(_appId, eNode.Id);
                    break;

                case "quiklnch":
                    appHelper.DeleteAppQuickLaunch(_appId, eNode.Id);
                    break;

                default:
                    break;
                }

                eNode.Delete();
                ClearCache();
            }

            Redirect();
        }
コード例 #4
0
        //private static void CreateRootFolder(SPWeb curweb, string folderName, string folderDescription)
        //{
        //    curweb.Lists.Add(folderName, folderDescription, SPListTemplateType.DocumentLibrary);
        //    curweb.RootFolder
        //}

        // Uncomment the method below to handle the event raised before a feature is deactivated.
        private static void CreateSiteNavigation(SPFeatureReceiverProperties prop)
        {
            SPSite site    = prop.Feature.Parent as SPSite;
            SPWeb  rootWeb = site.RootWeb;
            SPNavigationNodeCollection topNavNodes = rootWeb.Navigation.TopNavigationBar;



            SPNavigationNode node = new SPNavigationNode("DashboardNav", "", true);

            topNavNodes.AddAsLast(node);

            SPNavigationNode oNewNode = new SPNavigationNode("Org Browser", "");

            rootWeb.Navigation.TopNavigationBar.AddAsLast(oNewNode);
            oNewNode.Properties.Add("NodeType", "Heading");
            oNewNode.Update();

            SPNavigationNode oChild1 = new SPNavigationNode("Official", "");

            oNewNode.Children.AddAsFirst(oChild1);
            oChild1.Properties.Add("NodeType", "Heading");
            oChild1.Update();



            // rootWeb.Navigation.UseShared = false;
            rootWeb.Update();

            //SPNavigationNode oNewNode = new SPNavigationNode("Org Browser", "");
            //rootWeb.Navigation.TopNavigationBar.AddAsLast(oNewNode);
            //oNewNode.Properties.Add("NodeType", "Heading");
            //oNewNode.Update();
        }
コード例 #5
0
        // Private Methods (3) 

        private string CalculateUrl(SPNavigationNode node, bool isRootWeb)
        {
            var url = node.Url;

            if (node.Title.Equals("My Work"))
            {
                url = RelativeUrl + "/_layouts/15/epmlive/MyWork.aspx";
            }
            else if (node.Title.ToLower().Contains("timesheet"))
            {
                url = RelativeUrl + "/_layouts/15/epmlive/MyTimesheet.aspx";
            }

            if (isRootWeb)
            {
                return(url);
            }

            if (url.ToLower().Contains("_layouts"))
            {
                string[] parts = url.Split(new[] { "_layouts" }, StringSplitOptions.None);
                url = RelativeUrl + "/_layouts" + string.Join(string.Empty, parts.Skip(1));
            }
            else
            {
                url = string.Format(@"javascript:SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.showModalDialog', {{ url: '{0}', showMaximized: true }});", url);
            }

            return(url);
        }
コード例 #6
0
        internal static void UpdateNodeLink(string url, int appId, SPNavigationNode node, SPWeb spWeb,
                                            out string message,
                                            out MessageKind messageKind)
        {
            spWeb.AllowUnsafeUpdates = true;

            messageKind = MessageKind.SUCCESS;

            SPList spList = spWeb.Lists.TryGetList("Installed Applications");

            if (spList != null)
            {
                message = string.Format(@"Node: {0}, New URL: {1}, Old URL: {2}", node.Title, url, node.Url);

                var newNode = new SPNavigationNode(node.Title, url, node.IsExternal);

                SPNavigationNode prevNode = null;

                foreach (SPNavigationNode siblingNode in spWeb.Navigation.QuickLaunch.Cast <SPNavigationNode>()
                         .TakeWhile(siblingNode => siblingNode.Id != node.Id))
                {
                    prevNode = siblingNode;
                }

                if (prevNode == null)
                {
                    spWeb.Navigation.QuickLaunch.AddAsLast(newNode);
                }
                else
                {
                    spWeb.Navigation.QuickLaunch.Add(newNode, prevNode);
                }

                node.Delete();

                SPListItem spListItem = spList.GetItemById(appId);

                string nodes = (spListItem["QuickLaunch"] ?? string.Empty).ToString()
                               .Replace(node.Id.ToString(CultureInfo.InvariantCulture),
                                        newNode.Id.ToString(CultureInfo.InvariantCulture));

                if (!nodes.Contains("," + newNode.Id))
                {
                    nodes += "," + newNode.Id;
                }

                spListItem["QuickLaunch"] = nodes;
                spListItem.SystemUpdate();

                API.Applications.CreateQuickLaunchXML(spListItem.ID, spWeb);

                spWeb.AllowUnsafeUpdates = false;
                spWeb.Update();
            }
            else
            {
                throw new Exception("Cannot find the Installed Applications list.");
            }
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb site = properties.Feature.Parent as SPWeb;
            SPNavigationNodeCollection topNav  = site.Navigation.TopNavigationBar;
            SPNavigationNode           navNode = new SPNavigationNode("Wingtip Silverlight Product Browser", "_layouts/MSDN.WingtipProductBrowser/ProductBrowser.aspx");

            topNav.AddAsLast(navNode);
        }
コード例 #8
0
        public static void AddNavigationForPage(SPWeb web, SPFile page, string linkName)
        {
            SPNavigationNodeCollection navItems = web.Navigation.QuickLaunch;
            SPNavigationNode           newNode  = new SPNavigationNode(linkName, page.Url, false);

            navItems.AddAsFirst(newNode);
            web.Update();
        }
コード例 #9
0
        public SPNavigationNodeInstance(ObjectInstance prototype, SPNavigationNode navigationNode)
            : this(prototype)
        {
            if (navigationNode == null)
            {
                throw new ArgumentNullException("navigationNode");
            }

            m_navigationNode = navigationNode;
        }
コード例 #10
0
 protected virtual void ProcessLocalization(SPNavigationNode obj, NavigationNodeDefinitionBase definition)
 {
     if (definition.TitleResource.Any())
     {
         foreach (var locValue in definition.TitleResource)
         {
             LocalizationService.ProcessUserResource(obj, obj.TitleResource, locValue);
         }
     }
 }
コード例 #11
0
        public static SPNavigationNode AddNavigationLink(SPNavigationNode parentNode, string title, string url, string group)
        {
            var subNode = new SPNavigationNode(title, url);
            parentNode.Children.Add(subNode, parentNode);
            subNode.Properties.Add("Audience", ";;;;" + group);
            subNode.Update();
            parentNode.Update();

            return subNode;
        }
コード例 #12
0
        public SPNavigationNode AddNavigationLink(SPNavigationNode parentNode, string title, string url, string group)
        {
            var subNode = new SPNavigationNode(title, url);

            parentNode.Children.Add(subNode, parentNode);
            subNode.Properties.Add("Audience", ";;;;" + group);
            subNode.Update();
            parentNode.Update();

            return(subNode);
        }
コード例 #13
0
        /*
         * public SPNavigationNode AddHeading(string title, string url, string group)
         * {
         *  if (!url.Equals("javascript:void(0)"))
         *  {
         *      Uri uri = new Uri(url);
         *      return AddHeading(title, uri, group);
         *  }
         *  else
         *  {
         *      if (nodes != null)
         *      {
         *          SPNavigationNode nodeItem = SPNavigationSiteMapNode.CreateSPNavigationNode(title, url, Microsoft.SharePoint.Publishing.NodeTypes.Heading, nodes);
         *          nodeItem.Properties.Add("Audience", ";;;;" + group);
         *          nodeItem.Update();
         *
         *          return nodeItem;
         *      }
         *
         *      return null;
         *  }
         * }
         *
         * public SPNavigationNode AddHeading(string title, Uri url, string group)
         * {
         *  if (nodes != null)
         *  {
         *      SPNavigationNode nodeItem = SPNavigationSiteMapNode.CreateSPNavigationNode(title, url.ToString(), Microsoft.SharePoint.Publishing.NodeTypes.Heading, nodes);
         *      nodeItem.Properties.Add("Audience", ";;;;" + group);
         *      nodeItem.Update();
         *
         *      return nodeItem;
         *  }
         *
         *  return null;
         * }
         */
        #endregion

        public SPNavigationNode AddHeading(string title, string url, string group)
        {
            if (nodes != null)
            {
                SPNavigationNode nodeItem = SPNavigationSiteMapNode.CreateSPNavigationNode(title, url, Microsoft.SharePoint.Publishing.NodeTypes.Heading, nodes);
                nodeItem.Properties.Add("Audience", ";;;;" + group);
                nodeItem.Update();

                return(nodeItem);
            }
            return(null);
        }
コード例 #14
0
        private SPNavigationNode EnsureRootNavigationNode(WebModelHost webModelHost, NavigationNodeDefinitionBase rootNode)
        {
            var web = webModelHost.HostWeb;

            var quickLaunch  = GetNavigationNodeCollection(web);
            var existingNode = LookupNavigationNode(quickLaunch, rootNode);

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

            if (existingNode == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new navigation node");

                existingNode = new SPNavigationNode(rootNode.Title, ResolveTokenizedUrl(webModelHost, rootNode), rootNode.IsExternal);
                quickLaunch.AddAsLast(existingNode);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing navigation node");
            }

            existingNode.Title     = rootNode.Title;
            existingNode.Url       = ResolveTokenizedUrl(webModelHost, rootNode);
            existingNode.IsVisible = rootNode.IsVisible;

            ProcessProperties(existingNode, rootNode);
            ProcessLocalization(existingNode, rootNode);

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

            existingNode.Update();

            return(existingNode);
        }
コード例 #15
0
        private void ConfigTopNavigationBar(SPWeb web)
        {
            SPNavigationNodeCollection topnav = web.Navigation.TopNavigationBar;

            if (topnav.Count == 1 && topnav[0].Title == "Home" && topnav[0].Url == web.ServerRelativeUrl)
            {
                topnav.Delete(topnav[0]);

                string           linkTitle = web.Title;
                SPNavigationNode node      = new SPNavigationNode(linkTitle, web.ServerRelativeUrl);
                node = topnav.AddAsFirst(node);
            }
        }
コード例 #16
0
        private static void AddParentNode(SPWeb web, SPNavigationNodeCollection topnav)
        {
            SPWeb            parentWeb = web.ParentWeb;
            string           linkTitle = parentWeb.Title;
            SPNavigationNode node      = new SPNavigationNode(linkTitle, parentWeb.ServerRelativeUrl);

            node = topnav.AddAsFirst(node);

            if (!parentWeb.IsRootWeb)
            {
                AddParentNode(parentWeb, topnav);
            }
        }
コード例 #17
0
 private void AddNodes(XElement currentFrom, SPNavigationNode currentTo, string rootPath)
 {
     foreach (XElement r in currentFrom.Elements())
     {
         SPNavigationNode n = new SPNavigationNode(
             r.Attribute("title").Value,
             rootPath + r.Attribute("url").Value);
         SPNavigationNode newnode = currentTo.Children.AddAsLast(n);
         if (r.HasElements)
         {
             AddNodes(r, newnode, rootPath);
         }
     }
 }
コード例 #18
0
        /// <summary>
        /// reads a set of integers
        /// that represents a recorded node movement and
        /// perform the node re-ordering
        /// </summary>
        /// <param name="movementInfo"></param>
        private void MoveNode(string[] movementInfo)
        {
            int parentNodeID = Convert.ToInt32(movementInfo[0]);
            int oldIndex     = Convert.ToInt32(movementInfo[1]);
            //if (_appId != -1)
            //{
            //    // translate displayed index into real index in Web.Navigation
            //    oldIndex = AppSettingsHelper.GetRealIndex(parentNodeID, oldIndex, _appId, _nodeType);
            //}
            int newIndex = Convert.ToInt32(movementInfo[2]);
            //if (_appId != -1)
            //{
            //    // translate displayed index into real index in Web.Navigation
            //    newIndex = AppSettingsHelper.GetRealIndex(parentNodeID, newIndex, _appId, "topnav");
            //}

            SPNavigationNode           parentNode            = _web.Navigation.GetNodeById(parentNodeID);
            SPNavigationNodeCollection contextNodeCollection = parentNode.Children;
            SPNavigationNode           node = contextNodeCollection[oldIndex];

            int currentlastIndex = contextNodeCollection.Count - 1;

            if (newIndex != oldIndex)
            {
                if (newIndex == 0)
                {
                    node.MoveToFirst(contextNodeCollection);
                }
                else if (newIndex == currentlastIndex)
                {
                    node.MoveToLast(contextNodeCollection);
                }
                else
                {
                    if (newIndex < oldIndex)
                    {
                        node.Move(contextNodeCollection, contextNodeCollection[newIndex - 1]);
                    }
                    else
                    {
                        node.Move(contextNodeCollection, contextNodeCollection[newIndex]);
                    }
                }
            }

            // note:
            // when performing SPNavigationNode.(Move/MoveToFirst/MoveToLast)
            // SPNavigationNode.Update() is not necessary according to MSDN documents
        }
コード例 #19
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            SPWeb  site           = siteCollection.RootWeb;

            // create dropdown menu for custom site pages
            SPNavigationNodeCollection topNav = site.Navigation.TopNavigationBar;

            SPNavigationNode DropDownMenu1 =
                topNav.AddAsLast(new SPNavigationNode("Web Parts 101", ""));

            DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Web Part 1", "WebPartPages/WebPart1.aspx"));
            DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Web Part 2", "WebPartPages/WebPart2.aspx"));
            DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Web Part 3", "WebPartPages/WebPart3.aspx"));
            DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Web Part 4", "WebPartPages/WebPart4.aspx"));
            DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Web Part 5", "WebPartPages/WebPart5.aspx"));

            SPNavigationNode DropDownMenu2 =
                topNav.AddAsLast(new SPNavigationNode("Web Part Samples", ""));

            DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Custom Properties", "WebPartPages/CustomProperties.aspx"));
            DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Part Verbs", "WebPartPages/WebPartVerbs.aspx"));
            DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Part Connections", "WebPartPages/WebPartConnections.aspx"));
            DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Parts Preconnected", "WebPartPages/WebPartsPreconnected.aspx"));
            DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Async Web Part Demo", "WebPartPages/AsyncDemoWebPart.aspx"));


            SPFile page = site.GetFile("WebPartPages/WebPartsPreconnected.aspx");
            SPLimitedWebPartManager mgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared);

            FontConnectionProvider.FontConnectionProvider ProviderWebPart = new FontConnectionProvider.FontConnectionProvider();
            ProviderWebPart.Title         = "Left Brain";
            ProviderWebPart.UserGreeting  = "I look pretty";
            ProviderWebPart.TextFontSize  = 18;
            ProviderWebPart.TextFontColor = "Green";
            mgr.AddWebPart(ProviderWebPart, "Left", 0);

            FontConnectionConsumer.FontConnectionConsumer ConsumerWebPart = new FontConnectionConsumer.FontConnectionConsumer();
            ConsumerWebPart.Title        = "Right Brain";
            ConsumerWebPart.UserGreeting = "And so do I";
            mgr.AddWebPart(ConsumerWebPart, "Right", 0);

            mgr.SPConnectWebParts(
                ProviderWebPart,
                mgr.GetProviderConnectionPoints(ProviderWebPart).Default,
                ConsumerWebPart,
                mgr.GetConsumerConnectionPoints(ConsumerWebPart).Default
                );
        }
コード例 #20
0
        public SPNavigationNodeInstance Construct(string title, string url, object isExternal)
        {
            SPNavigationNode node;

            if (isExternal == Undefined.Value)
            {
                node = new SPNavigationNode(title, url);
            }
            else
            {
                node = new SPNavigationNode(title, url, TypeConverter.ToBoolean(isExternal));
            }

            return(new SPNavigationNodeInstance(this.InstancePrototype, node));
        }
コード例 #21
0
        private bool CanShowChildNode(SiteMapNode n, List <int> globalNavIds)
        {
            bool isVisible = false;

            SPNavigationNode sn = null;

            if (TryGetMatchingNavNode(n, out sn))
            {
                if (globalNavIds.Contains(sn.Id))
                {
                    isVisible = true;
                }
            }

            return(isVisible);
        }
コード例 #22
0
        private SPNavigationNode EnsureRootQuickLaunchNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchNode)
        {
            var web = webModelHost.HostWeb;

            var quickLaunch = web.Navigation.QuickLaunch;

            var existingNode = quickLaunch.OfType <SPNavigationNode>()
                               .FirstOrDefault(n => n.Url == quickLaunchNode.Url);

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

            if (existingNode == null)
            {
                existingNode = new SPNavigationNode(quickLaunchNode.Title, quickLaunchNode.Url, quickLaunchNode.IsExternal);
                quickLaunch.AddAsLast(existingNode);
            }

            existingNode.Title     = quickLaunchNode.Title;
            existingNode.Url       = quickLaunchNode.Url;
            existingNode.IsVisible = quickLaunchNode.IsVisible;

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

            existingNode.Update();

            return(existingNode);
        }
コード例 #23
0
        private static void UpdateQuickLaunch(SPWeb web)
        {
            SPNavigationNode groupNode = null;

            foreach (SPNavigationNode navigationNode in web.Navigation.QuickLaunch)
            {
                if (navigationNode.Title == "Dashboards")
                {
                    groupNode = navigationNode;
                }
            }

            if (groupNode == null)
            {
                groupNode = new SPNavigationNode("Dashboards", String.Empty);
                web.Navigation.QuickLaunch.AddAsFirst(groupNode);
                web.Update();
            }

            SPNavigationNode dashboardNode = null;
            SPNavigationNode trainingNode  = null;

            foreach (SPNavigationNode navigationNode in groupNode.Children)
            {
                if (navigationNode.Title == "Manager Dashboard")
                {
                    dashboardNode = navigationNode;
                }
                else if (navigationNode.Title == "My Training")
                {
                    trainingNode = navigationNode;
                }
            }

            if (trainingNode == null)
            {
                trainingNode = new SPNavigationNode("My Training", "trainingdashboard.aspx");
                groupNode.Children.AddAsFirst(trainingNode);
            }

            if (dashboardNode == null)
            {
                dashboardNode = new SPNavigationNode("Manager Dashboard", "managerdashboard.aspx");
                groupNode.Children.AddAsFirst(dashboardNode);
                web.Update();
            }
        }
コード例 #24
0
ファイル: ListHelper.cs プロジェクト: ssrisunt/dynamite
        /// <summary>
        /// Add the list to the quick launch bar
        /// </summary>
        /// <param name="list">The list</param>
        public void AddtoQuickLaunch(SPList list)
        {
            var web = list.ParentWeb;

            // Check for an existing link to the list.
            var listNode = web.Navigation.GetNodeByUrl(list.DefaultViewUrl);

            // No link, so create one.
            if (listNode == null)
            {
                // Create the node.
                listNode = new SPNavigationNode(list.Title, list.DefaultViewUrl);

                // Add it to Quick Launch.
                web.Navigation.AddToQuickLaunch(listNode, SPQuickLaunchHeading.Lists);
            }
        }
コード例 #25
0
        public virtual List<SPNavigationNode> FindMatches(
            SPNavigationNode[] allNodes,
            DeleteNavigationNodesDefinitionBase typedDefinition,
            Func<string, string> resolveTokenizedUrlAction)
        {
            var nodesToDelete = new List<SPNavigationNode>();

            foreach (var nodeMatch in typedDefinition.NavigationNodes)
            {
                var foundByTitle = false;

                // search by Title, first
                if (!string.IsNullOrEmpty(nodeMatch.Title))
                {
                    var nodeByTitle = allNodes.FirstOrDefault(f =>
                        string.Equals(f.Title, nodeMatch.Title, StringComparison.OrdinalIgnoreCase));

                    if (nodeByTitle != null)
                    {
                        foundByTitle = true;

                        if (!nodesToDelete.Contains(nodeByTitle))
                        {
                            nodesToDelete.Add(nodeByTitle);
                        }
                    }
                }

                // give a try by Url, then
                if (!foundByTitle && !string.IsNullOrEmpty(nodeMatch.Url))
                {
                    var matchUrl = resolveTokenizedUrlAction(nodeMatch.Url);

                    var nodeByUrl = allNodes.FirstOrDefault(f =>
                        !string.IsNullOrEmpty(f.Url)
                        && f.Url.EndsWith(matchUrl, StringComparison.OrdinalIgnoreCase));

                    if (nodeByUrl != null)
                    {
                        if (!nodesToDelete.Contains(nodeByUrl))
                            nodesToDelete.Add(nodeByUrl);
                    }
                }
            }
            return nodesToDelete;
        }
コード例 #26
0
        private static SPWeb CreateSite(SPSite Col, uint locale, string template, string SiteName)
        {
            SPWeb root = Col.RootWeb;
            SPWeb web  = root.Webs.Add(SiteName, SiteName, "Demo Description", locale, template, true, false);

            // add navigation
            SPNavigation navRoot             = root.Navigation;
            SPNavigationNodeCollection navQL = navRoot.QuickLaunch;
            var newNav = new SPNavigationNode(web.Title, web.ServerRelativeUrl);

            navQL.Add(newNav, newNav);

            // alternative
            // web.QuickLaunchEnabled = true;

            return(web);
        }
コード例 #27
0
        /// <summary>
        /// Adds the on quick launch bar.
        /// </summary>
        /// <param name="web">The web.</param>
        public void AddOnQuickLaunchBar(SPWeb web)
        {
            using (SPWeb rootWeb = web.Site.OpenWeb())
            {
                SPNavigationNodeCollection nodes   = rootWeb.Navigation.QuickLaunch;
                SPNavigationNode           navNode = new SPNavigationNode(web.Title, web.ServerRelativeUrl, false);

                foreach (SPNavigationNode node in nodes)
                {
                    if (node.Id == 1026)
                    {
                        node.Children.AddAsLast(navNode);
                        break;
                    }
                }
            }
        }
コード例 #28
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties.Feature.Parent is SPSite)
            {
                // cannot activate this feature on site level
                return;
            }
            SPWeb web = (SPWeb)properties.Feature.Parent;
            SPNavigationNodeCollection topNavi = web.Navigation.TopNavigationBar;

            // Check existing top element. If present remove first
            CheckAndRemove(topNavi);
            // Read navigation instruction
            XNamespace siteNM = "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0";

            using (Stream st = GetType().Assembly.GetManifestResourceStream("ApplicationPage.web.sitemap"))
            {
                using (XmlReader tr = new XmlTextReader(st))
                {
                    try
                    {
                        XElement siteMap = XElement.Load(tr);
                        // add nodes
                        var root = from r in siteMap.Descendants()
                                   where r.Attribute("title").Value.Equals("HR Department")
                                   select r;
                        // Found
                        if (root.Count() == 1)
                        {
                            XElement rootElement = root.First();
                            string   rootPath    = web.Url + PATH;
                            // create and add rootnode
                            SPNavigationNode rootNode = new SPNavigationNode(
                                rootElement.Attribute("title").Value,
                                rootPath + rootElement.Attribute("url").Value,
                                true);
                            SPNavigationNode topNode = topNavi.AddAsLast(rootNode);
                            AddNodes(rootElement, topNode, rootPath);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
コード例 #29
0
 protected virtual void ProcessProperties(SPNavigationNode existingNode, NavigationNodeDefinitionBase quickLaunchNode)
 {
     if (quickLaunchNode.Properties != null && quickLaunchNode.Properties.Any())
     {
         foreach (var prop in quickLaunchNode.Properties)
         {
             if (existingNode.Properties.ContainsKey(prop.Key))
             {
                 existingNode.Properties[prop.Key] = prop.Value;
             }
             else
             {
                 existingNode.Properties.Add(prop.Key, prop.Value);
             }
         }
     }
 }
コード例 #30
0
        private SPNavigationNode EnsureQuickLaunchNavigationNode(
            SPNavigationNode navigationNode,
            QuickLaunchNavigationNodeDefinition quickLaunchNode)
        {
            var quickLaunch = navigationNode.Children;

            var existingNode = quickLaunch.OfType<SPNavigationNode>()
                .FirstOrDefault(n => n.Url == quickLaunchNode.Url);

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

            if (existingNode == null)
            {
                existingNode = new SPNavigationNode(quickLaunchNode.Title, quickLaunchNode.Url, quickLaunchNode.IsExternal);
                quickLaunch.AddAsLast(existingNode);
            }

            existingNode.Title = quickLaunchNode.Title;
            existingNode.Url = quickLaunchNode.Url;
            existingNode.IsVisible = quickLaunchNode.IsVisible;

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

            existingNode.Update();

            return existingNode;
        }
コード例 #31
0
        private SPNavigationNode EnsurehNavigationNode(SPNavigationNode navigationNode, NavigationNodeDefinitionBase quickLaunchNode)
        {
            var topNavigationNode = navigationNode.Children;
            var existingNode      = LookupNavigationNode(topNavigationNode, quickLaunchNode);

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

            if (existingNode == null)
            {
                existingNode = new SPNavigationNode(quickLaunchNode.Title, ResolveTokenizedUrl(CurrentWebModelHost, quickLaunchNode), quickLaunchNode.IsExternal);
                topNavigationNode.AddAsLast(existingNode);
            }

            existingNode.Title     = quickLaunchNode.Title;
            existingNode.Url       = ResolveTokenizedUrl(CurrentWebModelHost, quickLaunchNode);
            existingNode.IsVisible = quickLaunchNode.IsVisible;

            ProcessProperties(existingNode, quickLaunchNode);
            ProcessLocalization(existingNode, quickLaunchNode);

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

            existingNode.Update();

            return(existingNode);
        }
コード例 #32
0
ファイル: SiteNavigation.cs プロジェクト: porter1130/C-A
 private void CreateLevelOne(SPNavigationNode node, System.Web.UI.HtmlTextWriter writer,string divId)
 {
     writer.WriteLine("<table width='100%' border='0' align='center' cellpadding='0' cellspacing='0'>");
     writer.WriteLine("<tr class='nav-group-tr'><td>");
     writer.WriteLine("<table width='100%' border='0' align='center' cellpadding='0' cellspacing='0'>");
     if (divId != "")
         writer.WriteLine("<tr onclick=\"showChildren('" + divId + "');\" style='cursor:hand;'><td width='10%' class='nav-group-left'>&nbsp;</td>");
     else
         writer.WriteLine("<tr><td width='10%' class='nav-group-left'>&nbsp;</td>");
     writer.WriteLine("<td align='left' NOWRAP >&nbsp;<a class='nav-group-center' href=\"" + node.Url + "\"><strong>" + node.Title + "</strong></a>&nbsp;</td>");
     if (divId != "")
         writer.WriteLine("<td width='10%' class='nav-group-right'>&nbsp;</td></tr>");
     else
         writer.WriteLine("<td width='10%'>&nbsp;</td></tr>");
     writer.WriteLine("<tr><td colspan='3' class='nav-sep'></td></tr>");
     writer.WriteLine("</table>");
     writer.WriteLine("</td></tr>");
     writer.WriteLine("</table>");
 }
コード例 #33
0
    /// <summary>
    /// Creates a SharePoint Web site (SPWeb).  The Web site is not created if it already exists.
    /// </summary>
    ///
    /// <param name="parentWebSiteUrl">The URL of the parent of the Web site to create.</param>
    ///
    /// <param name="relativeUrl">The relative URL of the SPWeb, e.g. "SlkSampleWeb123".</param>
    ///
    /// <param name="title">The title of the new Web site, e.g. "SLK Sample Web Site".  Not used
    ///     if the site collection exists already.</param>
    ///
    static void CreateWebSite(string parentWebSiteUrl, string relativeUrl, string title)
    {
        Console.WriteLine("Finding or creating Web site \"{0}\" under \"{1}\"", relativeUrl,
                          parentWebSiteUrl);
        using (SPSite spSite = new SPSite(parentWebSiteUrl))
        {
            using (SPWeb parentWeb = spSite.OpenWeb())
            {
                // if the Web site with name <relativeUrl> already exists, do nothing
                SPWeb spWeb;
                try
                {
                    using (spWeb = parentWeb.Webs[relativeUrl])
                    {
                        if (!spWeb.Exists)
                        {
                            throw new System.IO.FileNotFoundException();
                        }
                        Console.WriteLine("...exists already");
                        return;
                    }
                }
                catch (System.IO.FileNotFoundException)
                {
                    // Web site doesn't exist -- create it below
                }

                // create the Web site
                using (spWeb = parentWeb.Webs.Add(relativeUrl, title, String.Empty,
                                                  (uint)parentWeb.Locale.LCID, "STS", true, false))
                {
                    // add the new Web site to the "quick launch" navigation area of the parent
                    // Web site
                    SPNavigationNode node = new SPNavigationNode(spWeb.Title, relativeUrl);
                    if (parentWeb.Navigation.QuickLaunch != null)
                    {
                        parentWeb.Navigation.QuickLaunch.AddAsLast(node);
                    }
                }
                Console.WriteLine("...created");
            }
        }
    }
コード例 #34
0
 public static void CreateQuickLaunchMenuHeading(SPWeb spWeb, string title, string url, bool isExternal, QuickLaunchPosition position)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate
                                              {
                                                  using (var site = new SPSite(spWeb.Url))
                                                  {
                                                      SPWeb web = site.AllWebs[spWeb.ID];
                                                      web.AllowUnsafeUpdates = true;
                                                      var node1 = new SPNavigationNode(title, url,
                                                                                                    isExternal);
                                                      if (position == QuickLaunchPosition.AddAtLast)
                                                          web.Navigation.QuickLaunch.AddAsLast(node1);
                                                      else
                                                          web.Navigation.QuickLaunch.AddAsFirst(node1);
                                                      web.Update();
                                                      web.AllowUnsafeUpdates = false;
                                                      web.Update();
                                                  }
                                              });
 }
コード例 #35
0
        /// <summary>
        /// reads a set of integers
        /// that represents a recorded node movement and
        /// perform the node re-ordering
        /// </summary>
        /// <param name="movementInfo"></param>
        private void MoveNode(string[] movementInfo)
        {
            int parentNodeID = Convert.ToInt32(movementInfo[0]);
            int oldIndex     = Convert.ToInt32(movementInfo[1]);
            int newIndex     = Convert.ToInt32(movementInfo[2]);

            _eWeb.AllowUnsafeUpdates = true;

            SPNavigationNode           eParentNode            = _eWeb.Navigation.GetNodeById(parentNodeID);
            SPNavigationNodeCollection eContextNodeCollection = eParentNode.Children;
            SPNavigationNode           eNode = eContextNodeCollection[oldIndex];

            int currentlastIndex = eContextNodeCollection.Count - 1;

            if (newIndex != oldIndex)
            {
                if (newIndex == 0)
                {
                    eNode.MoveToFirst(eContextNodeCollection);
                }
                else if (newIndex == currentlastIndex)
                {
                    eNode.MoveToLast(eContextNodeCollection);
                }
                else
                {
                    if (newIndex < oldIndex)
                    {
                        eNode.Move(eContextNodeCollection, eContextNodeCollection[newIndex - 1]);
                    }
                    else
                    {
                        eNode.Move(eContextNodeCollection, eContextNodeCollection[newIndex]);
                    }
                }
            }

            // note:
            // when performing SPNavigationNode.(Move/MoveToFirst/MoveToLast)
            // SPNavigationNode.Update() is not necessary according to MSDN documents
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: vijaymca/SharePoint
        static void Main(string[] args)
        {
            SPSite site = new SPSite(@"http://hydpcnew00123:44393");
            /*
            foreach (SPWeb web in site.AllWebs)
            {
                Console.WriteLine("{0} is created on {1}",web.Title,web.Created);
            }
            */

            SPWeb myweb = site.OpenWeb();

            SPNavigationNodeCollection topnavbar = myweb.Navigation.TopNavigationBar;
            SPNavigationNode searchEnginesMenu = new SPNavigationNode("Search Engines","");

            topnavbar[0].Children.AddAsLast(searchEnginesMenu);

              //  SPNavigationNode msdnNode = new SPNavigationNode("Yahoo", "http://www.yahoo.com", true);

            searchEnginesMenu.Children.AddAsLast(new SPNavigationNode("Yahoo", "http://www.google.com", true));

            Console.WriteLine("Success..");
            Console.Read();
        }
コード例 #37
0
ファイル: SPDGServerWeb.cs プロジェクト: Acceleratio/SPDG
 public override void AddNavigationNode(string title, string url, NavigationNodeLocation location)
 {
     SPNavigationNodeCollection topnav = null;
     SPNavigationNode node = new SPNavigationNode(title, url);
     if (_spWeb.Navigation.GetNodeByUrl(node.Url) != null)
     {
         return;
     }
     switch (location)
     {
         case NavigationNodeLocation.TopNavigationBar:
             topnav = _spWeb.Navigation.TopNavigationBar;
             topnav.AddAsLast(node);
             break;
         case NavigationNodeLocation.QuickLaunchLists:
             _spWeb.Navigation.AddToQuickLaunch(node, SPQuickLaunchHeading.Lists);
             break;
         default:
             throw new ArgumentOutOfRangeException(nameof(location), location, null);
     }
 }
コード例 #38
0
        private void AddNavigation(SPWeb web)
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                if (!web.Navigation.UseShared)
                {
                    SPNavigationNodeCollection topNavigationNodes = web.Navigation.TopNavigationBar;

                    //You can also edit the Quick Launch the same way
                    //SPNavigationNodeCollection topNavigationNodes = web.Navigation.QuickLaunch;

                    SPNavigationNode objItem = new SPNavigationNode("Beach Camp Reservation", web.ServerRelativeUrl.TrimEnd('/') + Constants.BEACH_CAMP_CALENDAR_LIST_URL.TrimEnd('/') + "/Calendar.aspx", false);
                    topNavigationNodes.AddAsLast(objItem);
                    //SPNavigationNode objItemChild = new SPNavigationNode("Management Reservation", web.ServerRelativeUrl.TrimEnd('/') + "/Lists/BCCalendar/AllItems.aspx", false);
                    //objItem.Children.AddAsFirst(objItemChild);
                }
                web.Update();
                web.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, BeachCampFeatures.BeachCamp);
            }
        }
コード例 #39
0
ファイル: ListHelper.cs プロジェクト: ASAGARG/Dynamite
        /// <summary>
        /// Add the list to the quick launch bar
        /// </summary>
        /// <param name="list">The list</param>
        public void AddtoQuickLaunch(SPList list)
        {
            var web = list.ParentWeb;

            // Check for an existing link to the list.
            var listNode = web.Navigation.GetNodeByUrl(list.DefaultViewUrl);

            // No link, so create one.
            if (listNode == null)
            {
                // Create the node.
                listNode = new SPNavigationNode(list.Title, list.DefaultViewUrl);

                // Add it to Quick Launch.
                web.Navigation.AddToQuickLaunch(listNode, SPQuickLaunchHeading.Lists);
            }
        }
コード例 #40
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties) {

            try {
                Global.Debug = "start";
                SPWeb web = properties.Feature.Parent as SPWeb;
                if (web == null) {
                }

                Global.URL = "Tillsyn FeatureActivated: " + web.Url;

                SPList listKundkort = web.Lists.TryGetList("Kundkort");
                Global.Debug = "Kundkort";
                SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter");
                Global.Debug = "Aktiviteter";
                SPList listAdresser = web.Lists.TryGetList("Adresser");
                Global.Debug = "Adresser";
                SPList listAgare = web.Lists.TryGetList("Ägare");
                Global.Debug = "Ägare";
                SPList listKontakter = web.Lists.TryGetList("Kontakter");
                Global.Debug = "Kontakter";

               

                if (!web.Properties.ContainsKey("activatedOnce")) {
                    web.Properties.Add("activatedOnce", "true");
                    web.Properties.Update();
                    Global.Debug = "set activatedOnce flag";

                    #region sätt default-kommun-värden
                    if (municipals.Count > 0) {
                        Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000);
                    }
                    else {
                        municipals.Add("uppsala", new Municipal { AreaCode = "018", Name = "Uppsala", RegionLetter = "C" });
                        municipals.Add("borlänge", new Municipal { AreaCode = "0243", Name = "Borlänge", RegionLetter = "W" });
                    }
                    Global.Debug = "added municipals";
                    #endregion

                    #region hämta listor
                    //SPList listAgare = web.Lists.TryGetList("Ägare");
                    //Global.Debug = "Ägare";
                    //SPList listKontakter = web.Lists.TryGetList("Kontakter");
                    //Global.Debug = "Kontakter";
                    //SPList listAdresser = web.Lists.TryGetList("Adresser");
                    //Global.Debug = "Adresser";
                    SPList listSidor = web.Lists.TryGetList("Webbplatssidor");
                    Global.Debug = "Webbplatssidor";
                    SPList listNyheter = web.Lists.TryGetList("Senaste nytt");
                    Global.Debug = "Senaste nytt";
                    //SPList listBlanketter = web.Lists.TryGetList("Blanketter");
                    SPList listGenvagar = web.Lists.TryGetList("Genvägar");
                    Global.Debug = "Genvägar";
                    SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar");
                    Global.Debug = "Gruppkopplingar";
                    SPList listGenvagarTillsynsverktyg = web.Lists.TryGetList("Genvägar för tillsynsverktyg");
                    Global.Debug = "Genvägar för tillsynsverktyg";
                    SPList listUppgifter = web.Lists.TryGetList("Uppgifter");
                    Global.Debug = "Uppgifter";
                    SPList listDokument = web.Lists.TryGetList("Dokument");
                    Global.Debug = "Dokument";



                    SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar, listGenvagarTillsynsverktyg, listUppgifter, listDokument };
                    int i = 0;
                    foreach (SPList list in lists) {
                        i++;
                        if (list == null) {
                            Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000);
                        }
                    }
                    #endregion

                    var roleRead = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                    var roleEdit = web.RoleDefinitions.GetByType(SPRoleType.Editor);
                    SPRoleAssignment assignmentVisitorRead = new SPRoleAssignment(web.AssociatedVisitorGroup);
                    SPRoleAssignment assignmentMemberEdit = new SPRoleAssignment(web.AssociatedMemberGroup);
                    assignmentVisitorRead.RoleDefinitionBindings.Add(roleRead);
                    assignmentMemberEdit.RoleDefinitionBindings.Add(roleEdit);

                    if (listSidor != null) {
                        #region startsida
                        string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatBasicWikiLayout();
                        Global.Debug = "Skapa startsida";
                        SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage);

                        // Header
                        string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl;
                        _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hj&auml;rta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>");

                        #region Nyheter
                        ListViewWebPart wpAnnouncements = new ListViewWebPart();
                        wpAnnouncements.Width = "600px";
                        wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper();
                        wpAnnouncements.ViewGuid = string.Empty;
                        Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements);
                        AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]");
                        #endregion

                        #region Genvägar
                        ListViewWebPart wpLinks = new ListViewWebPart();
                        wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper();
                        wpLinks.ViewGuid = string.Empty;
                        Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks);
                        AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]");
                        #endregion

                        startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        startsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Startsida skapad";
                        #endregion

                        #region lägg till försäljningsställe
                        string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug = "Skapa nybutiksida";
                        SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage);

                        // Header
                        _wikiFullContent = _wikiFullContent.Replace("[[COL1]]",
@"<h1>Steg-för-steg - Lägg till nytt försäljningsställe</h1>
För att underlätta inläggningen av nya försäljningställen för steg-för-steg guiden nedan. 
I de första stegen lägger du in information kring försäljningsstället, i det näst sista stegen kopplar du ihop 
angivna uppgifter och i det sista steg sätter du behörighet på försäljningsställets innehåll i portalen.<br />
<br />
Du skapar ett nytt objekt via länken <b>Nytt objekt</b>. Ange önskad information och tryck <b>Spara</b>. 
Fält markerade med * är obligatoriska.<br />
<h2>STEG 1 - Lägg till ägare</h2>
Registrera ägaren, dvs organisationsnumret för försäljningsstället. <br />
Ange <b>juridiskt namn</b>, <b>adressuppgifter</b> och <b>organisationsnummer</b>.<br />
[[WP1]]
<h2>STEG 2 - Lägg till adressuppgifter</h2>
Adressuppgifterna till försäljningsstället. <br />
Här anger du <b>försäljningsställets namn</b>, <b>besöksadress</b> och <b>telefon</b>/<b>e-post</b>.<br />
[[WP2]]
<h2>STEG 3 - Lägg till kontaktperson</h2>
Lägg till de kontaktpersoner som finns för försäljningsstället.<br />
Ange <b>efternamn</b>, <b>förnamn</b>, <b>befattning</b>, <b>företag</b>, <b>telefon</b>, <b>mobil</b> och <b>e-postadress</b>.<br />
[[WP3]]
<h2>STEG&#160;4 - Lägg till försäljningsstället</h2>
För att slutföra inläggningen av försäljningstället måste du koppla ihop uppgifterna ovan. <br />
Välj Nytt objekt, ange försäljningsstället i fältet <b>Adress</b>, Ägande organisation i <b>Ägare</b> och lägg till önskade <b>kontaktpersoner</b>.<br />
[[WP4]]
<h2>STEG 5 - Ge rättigheter</h2>
För att ge rätt behörigheter för innehållet kring försäljningsstället måste rättigheter anges. <br />
<br />
Klicka på det nyligen tillagda försäljningsstället i listan <b>Lägg till försäljningsställe</b> (ovan) och välj <b>Ge rättigheter</b>.");

                        Global.Debug = "wpAgare";
                        XsltListViewWebPart wpAgare = new XsltListViewWebPart();
                        wpAgare.ChromeType = PartChromeType.None;
                        wpAgare.ListName = listAgare.ID.ToString("B").ToUpper();
                        wpAgare.ViewGuid = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAgare.Toolbar = "Standard";
                        Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare);
                        AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]");

                        Global.Debug = "wpAdresser";
                        XsltListViewWebPart wpAdresser = new XsltListViewWebPart();
                        wpAdresser.ChromeType = PartChromeType.None;
                        wpAdresser.ListName = listAdresser.ID.ToString("B").ToUpper();
                        wpAdresser.ViewGuid = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAdresser.Toolbar = "Standard";
                        Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser);
                        AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]");

                        Global.Debug = "wpKontakter";
                        XsltListViewWebPart wpKontakter = new XsltListViewWebPart();
                        wpKontakter.ChromeType = PartChromeType.None;
                        wpKontakter.ListName = listKontakter.ID.ToString("B").ToUpper();
                        wpKontakter.ViewGuid = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKontakter.Toolbar = "Standard";
                        Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter);
                        AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]");

                        Global.Debug = "wpKundkort";
                        XsltListViewWebPart wpKundkort = new XsltListViewWebPart();
                        wpKundkort.ChromeType = PartChromeType.None;
                        wpKundkort.ListName = listKundkort.ID.ToString("B").ToUpper();
                        wpKundkort.ViewGuid = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKundkort.Toolbar = "Standard";
                        Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort);
                        AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]");

                        nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        nybutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";

                        #endregion

                        #region mitt försäljningsställe
                        string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug = "Skapa minbutiksida";
                        SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpMinButik";
                        MinButikWP wpMinButik = new MinButikWP();
                        wpMinButik.ChromeType = PartChromeType.None;
                        wpMinButik.Adresser = "Adresser";
                        wpMinButik.Agare = "Ägare";
                        wpMinButik.Kontakter = "Kontakter";
                        wpMinButik.Kundkort = "Kundkort";
                        Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik);
                        AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]");

                        minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        minbutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";
                        #endregion

                        #region skapa tillsynsrapport
                        //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout
                        //_wikiFullContent = FormatSimpleWikiLayout();
                        //Global.Debug = "Skapa tillsynsrapport";
                        //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage);

                        //Global.Debug = "wpTillsyn";
                        //TillsynWP wpTillsyn = new TillsynWP();
                        //wpTillsyn.ChromeType = PartChromeType.None;
                        //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn);
                        //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]");

                        //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        //skapatillsynsida.Item.UpdateOverwriteVersion();
                        //Global.Debug = "Skapatillsynsida skapad";
                        #endregion

                        #region tillsynsverktyg
                        string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Tillsynsverktyg.aspx");//* Define page payout
                        _wikiFullContent = FormatBasicWikiLayout().Replace("[[HEADER]]", "").Replace("[[COL1]]", "[[WP1]][[WP2]]");
                        Global.Debug = "Tillsynsverktyg";
                        SPFile tillsynsverktygsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage);

                        #region Att göra
                        ListViewWebPart wpTodo = new ListViewWebPart();
                        wpTodo.ListName = listUppgifter.ID.ToString("B").ToUpper();
                        wpTodo.ViewGuid = listUppgifter.DefaultView.ID.ToString("B").ToUpper();
                        Guid wpTodoGuid = AddWebPartControlToPage(tillsynsverktygsida, wpTodo);
                        AddWebPartMarkUpToPage(wpTodoGuid, "[[WP1]]");
                        #endregion

                        #region Senaste aktiviteterna
                        ListViewWebPart wpLatest = new ListViewWebPart();
                        wpLatest.ListName = listAktiviteter.ID.ToString("B").ToUpper();
                        wpLatest.ViewGuid = string.Empty;
                        Guid wpLatestGuid = AddWebPartControlToPage(tillsynsverktygsida, wpLatest);
                        AddWebPartMarkUpToPage(wpLatestGuid, "[[WP2]]");
                        #endregion

                        #region Genvägar
                        ListViewWebPart wpLinks2 = new ListViewWebPart();
                        wpLinks2.ListName = listGenvagarTillsynsverktyg.ID.ToString("B").ToUpper();
                        wpLinks2.ViewGuid = listGenvagarTillsynsverktyg.DefaultView.ID.ToString("B").ToUpper();
                        Guid wpLinks2Guid = AddWebPartControlToPage(tillsynsverktygsida, wpLinks2);
                        AddWebPartMarkUpToPage(wpLinks2Guid, "[[COL2]]");
                        #endregion

                        tillsynsverktygsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        tillsynsverktygsida.Item.BreakRoleInheritance(false);
                        tillsynsverktygsida.Item.RoleAssignments.Add(assignmentMemberEdit);
                        tillsynsverktygsida.Item.UpdateOverwriteVersion();

                        Global.Debug = "tillsynsverktygsida skapad";
                        #endregion

                        #region inställningar
                        string compoundUrl6 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug = "Inställningar";
                        SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl6, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpSettings";
                        SettingsWP wpSettings = new SettingsWP();
                        wpSettings.ChromeType = PartChromeType.None;
                        Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings);
                        AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]");

                        installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        installningarsida.Item.BreakRoleInheritance(false);
                        installningarsida.Item.RoleAssignments.Add(assignmentMemberEdit);
                        installningarsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Installningarsida skapad";
                        #endregion
                    }

                    SPListItem item = null;

                    #region debugdata

                    //Global.Debug = "ägare";
                    //SPListItem item = listAgare.AddItem();
                    //item["Title"] = "TESTÄGARE AB";
                    //item[new Guid("0850AE15-19DD-431f-9C2F-3AFF3AE292CE")] = "123456-7890";
                    //item.Update();

                    //try {
                    //    Global.Debug = "kontakt";
                    //    item = listKontakter.AddItem();
                    //    item["Title"] = "Testsson";
                    //    item["FirstName"] = "Test";
                    //    item["Email"] = "*****@*****.**";
                    //    item["JobTitle"] = "testare";
                    //    item["CellPhone"] = "070 123 4567";
                    //    item.Update();

                    //    item = listKontakter.AddItem();
                    //    item["Title"] = "Jansson";
                    //    item["FirstName"] = "Peter";
                    //    item["Email"] = "*****@*****.**";
                    //    item.Update();
                    //}
                    //catch (Exception ex) {
                    //    Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
                    //}

                    //Global.Debug = "adress";
                    //item = listAdresser.AddItem();
                    //item["Title"] = "Testbutiken";
                    //item["Besöksadress"] = "Testgatan 13b";
                    //item["Postnummer"] = "790 00";
                    //item["Ort"] = "Borlänge";
                    //item["Telefon"] = "0243-123456";
                    //item.Update();

                    //Global.Debug = "kundkort";
                    //item = listKundkort.AddItem();
                    //item["Title"] = "Testbutiken (W0243-1000)";
                    //item["butikAdress"] = 1;
                    //item["butikAgare"] = 1;
                    //item["butikKontakt1"] = 1;
                    //item["butikKundnummer"] = "W0243-1000";
                    //item["butikLopnummer"] = "1000";
                    //item.Update();

                    #endregion

                    #region nyhet
                    Global.Debug = "nyhet";
                    item = listNyheter.AddItem();
                    item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här";
                    item["Body"] = @"Hej!

Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial.

" + web.Title + " kommun";
                    item.Update();
                    #endregion

                    #region länkar
                    Global.Debug = "länkar";
                    item = listGenvagar.AddItem();
                    Global.Debug = "Blanketter";
                    item["Title"] = "Blanketter";
                    item["URL"] = web.ServerRelativeUrl + "/Blanketter, Blanketter";
                    item.Update();
                    item = listGenvagar.AddItem();
                    Global.Debug = "Utbildningsmaterial";
                    item["Title"] = "Utbildningsmaterial";
                    item["URL"] = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial";
                    item.Update();

                    item = listGenvagarTillsynsverktyg.AddItem();
                    Global.Debug = "Lägg till försäljningsställe";
                    item["Title"] = "Lägg till försäljningsställe";
                    item["URL"] = web.ServerRelativeUrl + "/SitePages/Lägg%20till%20försäljningsställe.aspx, Lägg till försäljningsställe";
                    item.Update();
                    item = listGenvagarTillsynsverktyg.AddItem();
                    Global.Debug = "Nytt tillsynsprotokoll";
                    item["Title"] = "Nytt tillsynsprotokoll";
                    item["URL"] = web.ServerRelativeUrl + "/_layouts/15/listform.aspx?PageType=8&ListId=" + System.Web.HttpUtility.UrlEncode(listAktiviteter.ID.ToString("B")).ToUpper().Replace("-", "%2D") + "&RootFolder=, Nytt tillsynsprotokoll";
                    item.Update();

                    
                    #endregion

                    #region sätt kundnummeregenskaper
                    Global.Debug = "löpnummer";
                    web.Properties.Add("lopnummer", "1000");
                    Global.Debug = "prefixformel";
                    web.Properties.Add("prefixFormula", "%B%R-%N");
                    Global.Debug = "listAdresserGUID";
                    web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString());
                    Global.Debug = "listAgareGUID";
                    web.Properties.Add("listAgareGUID", listAgare.ID.ToString());
                    Global.Debug = "gruppkopplingar";
                    web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString());
                    try {
                        Municipal m = municipals[web.Title.ToLower()];
                        web.Properties.Add("municipalAreaCode", m.AreaCode);
                        web.Properties.Add("municipalRegionLetter", m.RegionLetter);
                    }
                    catch { }
                    Global.Debug = "properties";
                    web.Properties.Update();
                    #endregion

                    #region lägg till navigeringslänkar

                    try {
                        SPNavigationNode blanketter = new SPNavigationNode("Blanketter", "Blanketter", false);
                        SPNavigationNode utbildningsmaterial = new SPNavigationNode("Utbildningsmaterial", "Utbildningsmaterial", false);
                        SPNavigationNode minbutik = new SPNavigationNode("Mitt försäljningsställe", "SitePages/Mitt%20försäljningsställe.aspx", false);
                        SPNavigationNode tillsynsverktyg = new SPNavigationNode("Tillsynsverktyg", "SitePages/Tillsynsverktyg.aspx", false);
                        SPNavigationNode dokument = new SPNavigationNode("Dokument", "Documents", false);
                        //dokument.Properties["Audience"] = ";;;;" + web.AssociatedMemberGroup.Name;
                        SPNavigationNode installningar = new SPNavigationNode("Inställningar", "SitePages/Inställningar.aspx", false);

                        web.Navigation.QuickLaunch.AddAsLast(blanketter);
                        web.Navigation.QuickLaunch.AddAsLast(utbildningsmaterial);
                        web.Navigation.QuickLaunch.AddAsLast(minbutik);
                        web.Navigation.QuickLaunch.AddAsLast(tillsynsverktyg);

                        SPNavigationNode senaste = SPNavigationSiteMapNode.CreateSPNavigationNode("Hantera Senaste Nytt", "Lists/Nyheter/AllItems.aspx", NodeTypes.Default, web.Navigation.QuickLaunch);
                        senaste.Properties.Add("Audience", ";;;;" + web.AssociatedMemberGroup.Name);

                        web.Navigation.QuickLaunch.AddAsLast(dokument);
                        web.Navigation.QuickLaunch.AddAsLast(installningar);

                        SPNavigationNode uppgifter = new SPNavigationNode("Att göra", "Lists/Uppgifter", false);
                        SPNavigationNode aktiviteter = new SPNavigationNode("Aktiviteter", "Lists/Aktiviteter", false);
                        SPNavigationNode kundkort = new SPNavigationNode("Försäljningsställen", "Lists/Kundkort", false);
                        //SPNavigationNode forsaljningsstallen = new SPNavigationNode("Försäljningsställen", "Lists/Adresser", false);
                        SPNavigationNode kontakter = new SPNavigationNode("Kontakter", "Lists/Kundkort/Kontaktlista.aspx", false);
                        SPNavigationNode agare = new SPNavigationNode("Ägare", "Lists/Agare", false);
                        //SPNavigationNode forsaljningstillstand = new SPNavigationNode("Försäljningstillstånd", "Lists/Forsaljningstillstand");
                        SPNavigationNode laggtill = new SPNavigationNode("Lägg till försäljningsställe", "SitePages/Lägg%20till%20försäljningsställe.aspx", false);
                        SPNavigationNode editkontakter = new SPNavigationNode("Redigera kontakter", "Lists/Kontakter/Redigeringsvy.aspx", false);
                        SPNavigationNode editagare = new SPNavigationNode("Redigera ägare", "Lists/Agare/Redigeringsvy.aspx", false);
                        SPNavigationNode editadresser = new SPNavigationNode("Redigera adresser", "Lists/Adresser/Redigeringsvy.aspx", false);

                        tillsynsverktyg.Children.AddAsFirst(uppgifter);
                        tillsynsverktyg.Children.AddAsLast(aktiviteter);
                        tillsynsverktyg.Children.AddAsLast(kundkort);
                        //                    tillsynsverktyg.Children.AddAsLast(forsaljningsstallen);
                        tillsynsverktyg.Children.AddAsLast(kontakter);
                        tillsynsverktyg.Children.AddAsLast(agare);
                        tillsynsverktyg.Children.AddAsLast(laggtill);
                        tillsynsverktyg.Children.AddAsLast(editkontakter);
                        tillsynsverktyg.Children.AddAsLast(editagare);
                        tillsynsverktyg.Children.AddAsLast(editadresser);
                    }
                    catch (Exception ex) {
                        Global.WriteLog("lägg till navigeringslänkar\r\n\r\nMessage:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
                    }

                    #endregion

                    #region sätt rättigheter
                    try {
                        Global.Debug = "1";
                        listGenvagarTillsynsverktyg.BreakRoleInheritance(false);
                        listGenvagarTillsynsverktyg.RoleAssignments.Add(assignmentMemberEdit);
                        listGenvagarTillsynsverktyg.Update();

                        Global.Debug = "5";
                        listDokument.BreakRoleInheritance(false);
                        listDokument.RoleAssignments.Add(assignmentMemberEdit);
                        listDokument.Update();

                        //listKundkort.BreakRoleInheritance(true);
                        //listKundkort.RoleAssignments.Remove(web.AssociatedVisitorGroup);
                        //listKundkort.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead);
                        //listKundkort.Update();

                        //listAgare.BreakRoleInheritance(true);
                        //listAgare.RoleAssignments.Remove(web.AssociatedVisitorGroup);
                        //listAgare.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead);
                        //listAgare.Update();

                        //listAdresser.BreakRoleInheritance(true);
                        //listAdresser.RoleAssignments.Remove(web.AssociatedVisitorGroup);
                        //listAdresser.RoleAssignments.AddToCurrentScopeOnly(assignmentVisitorRead);
                        //listAdresser.Update();
                    }
                    catch (Exception ex) {
                        Global.WriteLog("sätt rättigheter\r\n\r\nMessage:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace + "\r\n\r\nDebug:\r\n" + Global.Debug, EventLogEntryType.Error, 2001);
                    }

                    #endregion
                }
                else {
                    Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000);
                }

                #region modify template global
                Global.Debug = "ensure empty working directory";
                DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun");
                string webid = web.Url.Replace("http://", "").Replace('/', '_');
                string dirname_insp = @"workdir_inspection_" + webid;
                string dirname_perm = @"workdir_permit_" + webid;
                DirectoryInfo diWorkDirInspection = diFeature.CreateSubdirectory(dirname_insp);
                DirectoryInfo diWorkDirPermit = diFeature.CreateSubdirectory(dirname_perm);

                if (!diWorkDirInspection.Exists)
                    diWorkDirInspection.Create();
                if (!diWorkDirPermit.Exists)
                    diWorkDirPermit.Create();

                XNamespace xsf = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition";
                XNamespace xsf2 = "http://schemas.microsoft.com/office/infopath/2006/solutionDefinition/extensions";
                XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions";
                XNamespace xd = "http://schemas.microsoft.com/office/infopath/2003";
                XNamespace rs = "urn:schemas-microsoft-com:rowset";
                XNamespace z = "#RowsetSchema";

                #endregion

                #region modify template tillsyn
                {
                    Global.Debug = "deleting files";
                    foreach (FileInfo fi in diWorkDirInspection.GetFiles()) {
                        fi.Delete();
                    }

                    #region extract
                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn";
                    //string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn";
                    //string filename = diFeature.FullName + @"\inspection.xsn";
                    string filename = diFeature.FullName + @"\inspection4.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDirInspection.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0) {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }
                    #endregion

                    Global.Debug = "get content type _tillsynName";
                    SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName];

                    #region modify manifest
                    Global.Debug = "modify manifest tillsyn";
                    XDocument doc = XDocument.Load(diWorkDirInspection.FullName + @"\manifest.xsf");
                    var xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                             where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                             select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/" + _tillsynName + "/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             //where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    foreach (var n in q2) {
                        SPList list = null;
                        switch(n.Attribute("name").Value) {
                            case "Kundkort":
                            case "Kundkort1":
                                list = listKundkort;
                                break;
                            case "Adresser":
                                list = listAdresser;
                                break;
                            case "Ägare":
                                list = listAgare;
                                break;
                            case "Kontakter":
                                list = listKontakter;
                                break;
                        }

                        if (list != null) {
                            var node2 = n.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                            node2.Attribute("sharePointListID").Value = "{" + list.ID.ToString() + "}";
                        }
                    }
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value = ctTillsyn.Id.ToString();
                    var q3 = q1.First().Element(xsf2 + "solutionDefinition").Element(xsf2 + "dataConnections").Elements(xsf2 + "sharepointListAdapterRWExtension");
                    foreach (var n in q3) {
                        var oldkey = n.Attribute("queryKey").Value;
                        oldkey = oldkey.Substring(oldkey.IndexOf('<'));
                        oldkey = web.Url + "/" + oldkey;
                        Regex r = new Regex("{.*?}");
                        Guid newguid = Guid.Empty;
                        switch (n.Attribute("ref").Value) {
                            case "Kundkort1":
                                newguid = listKundkort.ID;
                                break;
                            case "Adresser":
                                newguid = listAdresser.ID;
                                break;
                            case "Ägare":
                                newguid = listAgare.ID;
                                break;
                            case "Kontakter":
                                newguid = listKontakter.ID;
                                break;
                        }
                        n.Attribute("queryKey").Value = r.Replace(oldkey, "{" + newguid.ToString() + "}");
                    }
                    doc.Save(diWorkDirInspection.FullName + @"\manifest.xsf");

                    Global.Debug = "modify view1";
                    XDocument doc2 = XDocument.Load(diWorkDirInspection.FullName + @"\view1.xsl");
                    foreach (var d in doc2.Descendants("object")) {
                        d.Attribute(xd + "server").Value = web.Url + "/";
                    }
                    doc2.Save(diWorkDirInspection.FullName + @"\view1.xsl");

                    Global.Debug = "modify offline files";
                    foreach (FileInfo fi in diWorkDirInspection.GetFiles("*_offline.xml")) {
                        XDocument doc3 = XDocument.Load(fi.FullName);
                        foreach (var n in doc3.Descendants(z + "row")) {
                            string oldFileRef = n.Attribute("ows_FileRef").Value;
                            n.Attribute("ows_FileRef").Value = oldFileRef.Replace("sites/blg27", web.ServerRelativeUrl.Substring(1));
                        }
                        doc3.Save(fi.FullName);
                    }
                    #endregion

                    #region repack
                    Global.Debug = "repack";
                    string directive = "directives_inspection_" + webid + ".txt";
                    string cabinet = "template_inspection_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                        fiDirectives.Delete();
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDirInspection.GetFiles()) {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0) {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }
                    #endregion

                    #region upload
                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists) {
                        // delete it if it already exists
                        SPFile f = web.GetFile("Lists/Aktiviteter/" + _tillsynName + "/template.xsn");
                        if (f.Exists)
                            f.Delete();

                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/" + _tillsynName + "/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"] = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"];
                        folder.Properties["_ipfs_solutionName"] = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }
                    #endregion
                }
                #endregion

                #region modify template permit
                {
                    Global.Debug = "delete";
                    foreach (FileInfo fi in diWorkDirPermit.GetFiles()) {
                        fi.Delete();
                    }

                    #region extract
                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    string filename = diFeature.FullName + @"\givepermit.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDirPermit.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0) {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }
                    #endregion

                    Global.Debug = "get content type permit";
                    SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName];

                    #region modify manifest
                    Global.Debug = "modify manifest permit";
                    XDocument doc = XDocument.Load(diWorkDirPermit.FullName + @"\manifest.xsf");
                    var xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var q1 = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                             where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                             select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/" + _permitName + "/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}";
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value = ctPermit.Id.ToString();
                    doc.Save(diWorkDirPermit.FullName + @"\manifest.xsf");

                    //Global.Debug = "modify view1";
                    //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl");
                    //foreach (var d in doc2.Descendants("object")) {
                    //    d.Attribute(xd + "server").Value = web.Url + "/";
                    //}
                    //doc2.Save(diWorkDir.FullName + @"\view1.xsl");
                    #endregion

                    #region repack
                    Global.Debug = "repack";
                    string directive = "directives_permit_" + webid + ".txt";
                    string cabinet = "template_permit_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                        fiDirectives.Delete();
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDirPermit.GetFiles()) {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0) {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }
                    #endregion

                    #region upload
                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists) {
                        // delete it if it already exists
                        SPFile f = web.GetFile("Lists/Aktiviteter/" + _permitName + "/template.xsn");
                        if (f.Exists)
                            f.Delete();

                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/" + _permitName + "/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"] = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"];
                        folder.Properties["_ipfs_solutionName"] = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }
                    #endregion
                }
                #endregion

                #region set default forms
                Global.Debug = "set default forms";
                foreach (SPContentType ct in listAktiviteter.ContentTypes) {
                    switch (ct.Name) {
                        case "Tillsyn":
                        case "Ge försäljningstillstånd":
                            ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx";
                            ct.EditFormUrl = "~list/" + ct.Name + "/editifs.aspx";
                            ct.NewFormUrl = "~list/" + ct.Name + "/newifs.aspx";
                            ct.Update();
                            break;
                        default:
                            ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty;
                            ct.Update();
                            break;
                    }

                }

                // create our own array since it will be modified (which would throw an exception)
                var forms = new SPForm[listAktiviteter.Forms.Count];
                int j = 0;
                foreach (SPForm form in listAktiviteter.Forms) {
                    forms[j] = form;
                    j++;
                }
                foreach (var form in forms) {
                    SPFile page = web.GetFile(form.Url);
                    SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) {
                        if (wp is BrowserFormWebPart) {
                            BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject;
                            string[] aLocation = form.Url.Split('/');
                            string contenttype = aLocation[aLocation.Length - 2];
                            bfwp.FormLocation = "~list/" + contenttype + "/template.xsn";
                            limitedWebPartManager.SaveChanges(bfwp);

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine();
                            sb.Append("BrowserFormWebPart FormLocation: ");
                            sb.AppendLine(bfwp.FormLocation);
                            sb.Append("BrowserFormWebPart Title: ");
                            sb.AppendLine(bfwp.Title);
                            sb.Append("BrowserFormWebPart ID: ");
                            sb.AppendLine(bfwp.ID);
                            sb.Append("Form URL: ");
                            sb.AppendLine(form.Url);
                            sb.Append("Form TemplateName: ");
                            sb.AppendLine(form.TemplateName);
                            sb.Append("Form ID: ");
                            sb.AppendLine(form.ID.ToString());
                            sb.Append("Form ServerRelativeUrl: ");
                            sb.AppendLine(form.ServerRelativeUrl);
                            sb.AppendLine("BrowserFormWebPart Schema: ");
                            sb.AppendLine();
                            sb.AppendLine(form.SchemaXml);

                            //Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000);
                        }
                    } // foreach webpart
                } // foreach form

                #endregion

                #region cleanup

                Global.Debug = "cleanup";
                //diWorkDirInspection.Delete(true);
                diWorkDirPermit.Delete(true);
                foreach (FileInfo fi in diFeature.GetFiles("template*.xsn"))
                    fi.Delete();
                foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn"))
                    fi.Delete();

                #endregion

                #region stäng av required på rubrik
                Global.Debug = "stäng av required på rubrik - kundkort";
                SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                if (title != null) {
                    title.Required = false;
                    title.ShowInNewForm = false;
                    title.ShowInEditForm = false;
                    title.Update();
                }

                title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000);
                title.Required = false;
                title.ShowInNewForm = false;
                title.ShowInEditForm = false;
                title.Update();

                Global.Debug = "stäng av required på rubrik - aktiviteter";
                foreach (SPContentType ct in listAktiviteter.ContentTypes) {
                    SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                    if (flTitle != null) {
                        flTitle.Required = false;
                        flTitle.Hidden = true;
                        ct.Update();
                    }
                }
                #endregion

                Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001);
            }
            catch (Exception ex) {
                Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
            }
        } // feature activated
コード例 #41
0
        static void Main(string[] args)
        {
            string url = "http://epm2007demo/pwa03";
            using (var Site = new SPSite(url))
            {
                var navigationnode = new SPNavigationNode("Project Governance Report", "/" + Site.RootWeb.ServerRelativeUrl + "/_layouts/ITXProjectGovernanceReport/ITXPGReport.aspx", true);
                Site.RootWeb.Navigation.QuickLaunch.AddAsLast(navigationnode);
                Site.RootWeb.Update();

                return;
                Guid ListUID = Guid.Empty;
                try
                {
                    string listname = GroupListName;
                    if (GroupListName != string.Empty)
                    {
                        ListUID = Site.RootWeb.Lists.Add(listname, "List for configuring Project Governance Report Groups.",
                                                         SPListTemplateType.GenericList);
                        Site.RootWeb.Update();
                        Site.RootWeb.AllowUnsafeUpdates = true;
                        SPList ConfigurationList = Site.RootWeb.Lists[listname];
                        ConfigurationList.Fields.Add(GroupFieldName, SPFieldType.Choice, true);

                        // Creating a choice field here
                        var choice_field = (SPFieldChoice)ConfigurationList.Fields[GroupFieldName];
                        choice_field.Description = "Project Group name";
                        choice_field.EditFormat = SPChoiceFormatType.Dropdown;
                        choice_field.Required = true;
                        choice_field.FillInChoice = true;
                        choice_field.Choices.Add("Unknown");
                        choice_field.Update();
                        try
                        {
                            ConfigurationList.DefaultView.ViewFields.Add(choice_field);
                        }
                        catch (Exception)
                        {
                        }
                        for (int index = 0; index < ConfigurationList.Views.Count; index++)
                        {
                            try
                            {
                                ConfigurationList.Views[index].ViewFields.Add(choice_field);
                                ConfigurationList.Views[index].Update();
                            }
                            catch (Exception)
                            {
                            }
                        }

                        // Creating a ProjectUID field
                        ConfigurationList.Fields.Add(ProjectUIDFieldName, SPFieldType.Text, true);
                        var text_field = (SPFieldText)ConfigurationList.Fields[ProjectUIDFieldName];
                        try
                        {
                            ConfigurationList.DefaultView.ViewFields.Add(text_field);
                        }
                        catch (Exception)
                        {
                        }
                        for (int index = 0; index < ConfigurationList.Views.Count; index++)
                        {
                            try
                            {
                                ConfigurationList.Views[index].ViewFields.Add(text_field);
                                ConfigurationList.Views[index].Update();
                            }
                            catch (Exception)
                            {
                            }
                        }
                        ConfigurationList.Update();
                    }
                }
                catch (Exception ex)
                {
                }
            }
            Console.Read();
        }
コード例 #42
0
        /// <summary>
        /// SPEduQuickStart Information Architecture Navigation
        /// </summary>
        /// <param name="web"> </param>
        /// <returns></returns>
        public static void ProcessNavigation(SPWeb web)
        {
            // Let the subsite use the parent site's top link bar.
            web.Navigation.UseShared = true;

            // Get a collection of navigation nodes.
            SPNavigationNodeCollection nodes = web.ParentWeb.Navigation.UseShared ?
                web.ParentWeb.Navigation.QuickLaunch : web.ParentWeb.Navigation.TopNavigationBar;

            // Check for an existing link to the subsite.
            SPNavigationNode node = nodes
                .Cast<SPNavigationNode>()
                .FirstOrDefault(n => n.Url.Equals(web.ServerRelativeUrl));

            // No link, so add one.
            if (node != null) return;
            // Create the node.
            node = new SPNavigationNode(web.Title, web.ServerRelativeUrl);

            // Add it to the collection.
            nodes.AddAsLast(node);
        }
コード例 #43
0
        public static void AddPageToNavigation(SPWeb web, SPFile page, string navTitle)
        {
            web.RequireNotNull("web");
            page.RequireNotNull("page");
            navTitle.RequireNotNullOrEmpty("navTitle");

            // update the navigation
            SPNavigationNode node = new SPNavigationNode(navTitle, page.Url);
            // navigation is shared update the root
            if (web.ParentWeb.Navigation.UseShared)
            {
                using (SPSite site = new SPSite(web.Url))
                {
                    SPWeb rootWeb = site.RootWeb;
                    rootWeb.Navigation.TopNavigationBar.AddAsLast(node);
                }
            }

            else
            {
                web.Navigation.TopNavigationBar.AddAsLast(node);
            }
        }
コード例 #44
0
 private static SPNavigationNode CreateNode(string nodeTitle, string nodeUrl)
 {
     var node = new SPNavigationNode(nodeTitle, nodeUrl);
     return node;
 }
コード例 #45
0
 public static void CreateQuickLaunchMenuLink(SPWeb spWeb, string title, string url, bool isExternal, string parentHeading, QuickLaunchPosition position)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate
                                              {
                                                  using (var site = new SPSite(spWeb.Url))
                                                  {
                                                      SPWeb web = site.AllWebs[spWeb.ID];
                                                      foreach (SPNavigationNode node in web.Navigation.QuickLaunch)
                                                      {
                                                          if (node.Title == parentHeading)
                                                          {
                                                              web.AllowUnsafeUpdates = true;
                                                              var node1 = new SPNavigationNode(title, url, isExternal);
                                                              if (position == QuickLaunchPosition.AddAtLast)
                                                                  node.Children.AddAsLast(node1);
                                                              else
                                                                  node.Children.AddAsFirst(node1);
                                                              web.Update();
                                                              web.AllowUnsafeUpdates = false;
                                                              web.Update();
                                                              break;
                                                          }
                                                      }
                                                  }
                                              });
 }
コード例 #46
0
        /// <summary>
        /// Processes the top nav nodes.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="title">The title.</param>
        /// <param name="url">The URL.</param>
        /// <param name="parentUrl">The parent URL.</param>
        public static void ProcessTopNavNodes(SPWeb web, string title, string url, string parentUrl)
        {
            if (parentUrl == "/")
            {
                return;
            }
            web.Navigation.UseShared = true;
            SPNavigationNode parentNode = web.Navigation.GetNodeByUrl(parentUrl);
            SPNavigationNode node = new SPNavigationNode(title, url);

            parentNode.Children.AddAsLast(node);
            node.Update();
        }
コード例 #47
0
 public static void CreatTopLinkBarHeading(SPWeb spWeb, string title, string url, bool isExternal, TopLinkMenuPosition position, int positionIndex, bool overWrite)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate
     {
         using (var site = new SPSite(spWeb.Url))
         {
             SPWeb web = site.AllWebs[spWeb.ID];
             web.AllowUnsafeUpdates = true;
             SPNavigationNodeCollection navigation = web.Navigation.TopNavigationBar;
             if (navigation.Count > 0)
             {
                 if (overWrite)
                 {
                     DeleteLink(navigation, title);
                 }
             }
             if (navigation.Count > 0)
             {
                 if (position == TopLinkMenuPosition.None)
                 {
                     if (navigation[0].Children.Count > positionIndex)
                     {
                         var node = new SPNavigationNode(title, url, isExternal);
                         SPNavigationNode previousNode = navigation[0].Children[positionIndex];
                         navigation[0].Children.Add(node, previousNode);
                     }
                 }
                 else
                 {
                     var node = new SPNavigationNode(title, url, isExternal);
                     if (position == TopLinkMenuPosition.AddAtFist)
                     {
                         navigation[0].Children.AddAsFirst(node);
                     }
                     else
                     {
                         navigation[0].Children.AddAsLast(node);
                     }
                 }
                 web.Update();
                 web.AllowUnsafeUpdates = false;
                 web.Update();
             }
         }
     });
 }
コード例 #48
0
 public static void CreatTopLinkBarSubMenu(SPWeb spWeb, string headerTitle, string title, string url, bool isExternal, bool overWrite)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate
     {
         using (var site = new SPSite(spWeb.Url))
         {
             SPWeb web = site.AllWebs[spWeb.ID];
             web.AllowUnsafeUpdates = true;
             SPNavigationNodeCollection navigation = web.Navigation.TopNavigationBar;
             if (navigation.Count > 0)
             {
                 if (overWrite)
                 {
                     foreach (SPNavigationNode node in navigation)
                     {
                         if (node.Title.ToLower() == headerTitle.ToLower())
                         {
                             foreach (SPNavigationNode nodechild in node.Children)
                             {
                                 node.Children.Delete(nodechild);
                                 web.Update();
                                 break;
                             }
                         }
                     }
                 }
             }
             if (navigation.Count > 0)
             {
                 var node = new SPNavigationNode(title, url, isExternal);
                 foreach (SPNavigationNode tnode in navigation)
                 {
                     if (tnode.Title.ToLower() == headerTitle.ToLower())
                     {
                         tnode.Children.AddAsLast(node);
                         web.Update();
                         web.AllowUnsafeUpdates = false;
                         web.Update();
                         break;
                     }
                 }
             }
         }
     });
 }
        private void ConfigTopNavigationBar(SPWeb web)
        {
            SPNavigationNodeCollection topnav = web.Navigation.TopNavigationBar;

            if (topnav.Count == 1 && topnav[0].Title == "Home" && topnav[0].Url == web.ServerRelativeUrl)
            {
                topnav.Delete(topnav[0]);

                string linkTitle = web.Title;
                SPNavigationNode node = new SPNavigationNode(linkTitle, web.ServerRelativeUrl);
                node = topnav.AddAsFirst(node);
            }
        }