/// <summary>
    /// Adds a SharePoint Web site to the SLK user web list of a given user.  A user web list is
    /// the list of Web sites shown in E-Learning Actions pages that are displayed within a given
    /// site collection.
    /// </summary>
    ///
    /// <param name="loginName">The login name, e.g. "MyDomain\SlkLearner123".  If the login name
    ///     starts with ".\", it's assumed to be a local machine account.</param>
    ///
    /// <param name="siteCollectionUrl">The URL of the site collection containing the user web
    ///     list to update.</param>
    ///
    /// <param name="webSiteUrl">The URL of the Web site to add to the user web list.</param>
    ///
    static void AddToUserWebList(string loginName, string siteCollectionUrl, string webSiteUrl)
    {
        Console.WriteLine("Adding \"{0}\" to the user web list of \"{1}\" in \"{2}\"", webSiteUrl,
                          loginName, siteCollectionUrl);

        // "log in" to SharePoint as the user running this program
        using (SPSite currentUserSite = new SPSite(siteCollectionUrl))
        {
            if (loginName.StartsWith(@".\"))
            {
                loginName = String.Format(@"{0}\{1}", currentUserSite.HostName, loginName.Substring(2));
            }

            SPWeb rootWeb = currentUserSite.RootWeb;
            // set <spUser> to the user corresponding to <loginName>
            SPUser spUser = rootWeb.AllUsers[loginName];

            // "log in" to SharePoint as the user <spUser>, and set <slkStore> to refer to that
            // user and the site collection specified by <siteCollectionUrl>
            using (SPSite destinationSite = new SPSite(webSiteUrl, spUser.UserToken))
            {
                using (SPWeb destinationWeb = destinationSite.OpenWeb())
                {
                    SlkStore slkStore = SlkStore.GetStore(destinationWeb);
                    slkStore.AddToUserWebList(destinationWeb);
                }
            }
        }
    }
        protected void addButton_Click(object sender, EventArgs e)
        {
            // user clicked "Add" button (after clicking "Add a site to this list")

            bool showAddSite = true;

            bool previousValue = SPSecurity.CatchAccessDeniedException;

            SPSecurity.CatchAccessDeniedException = false;
            try
            {
                string destinationUrl = txtNewSite.Text.Trim();
                Uri    destinationUri = new Uri(destinationUrl);
                using (SPSite site = new SPSite(destinationUri.AbsoluteUri))
                {
                    using (SPWeb destinationWeb = site.OpenWeb())
                    {
                        // check if the site is a valid Slk site
                        SlkStore destinationSlkStore;
                        try
                        {
                            destinationSlkStore = SlkStore.GetStore(destinationWeb);
                        }
                        catch (SlkNotConfiguredException)
                        {
                            errorBanner.AddHtmlErrorText(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsNotEnabled, Server.HtmlEncode(destinationUrl)));
                            DisplayAddSite();
                            return;
                        }

                        // check if the user is an instructor on that site
                        if (!destinationSlkStore.IsInstructor(destinationWeb))
                        {
                            errorBanner.AddHtmlErrorText(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsNotInstructor, Server.HtmlEncode(destinationUrl)));
                            DisplayAddSite();
                            return;
                        }

                        // check if the site is already in the list
                        ReadOnlyCollection <SlkUserWebListItem> userWebList = SlkStore.FetchUserWebList();
                        foreach (SlkUserWebListItem webListItem in userWebList)
                        {
                            if (destinationWeb.ID.Equals(webListItem.SPWebGuid))
                            {
                                errorBanner.AddHtmlErrorText(ErrorType.Info, PageCulture.Format(PageCulture.Resources.ActionsAlreadyInList, Server.HtmlEncode(destinationWeb.Title)));
                                break;
                            }
                        }

                        // add the web to the list
                        SlkStore.AddToUserWebList(destinationWeb); //local slkstore
                        ShowAllSites    = false;
                        txtNewSite.Text = string.Empty;
                        newSite         = destinationWeb.ID;
                        showAddSite     = false;
                    }
                }
            }
            catch (UriFormatException)
            {
                // the url is an invalid format
                errorBanner.AddHtmlErrorText(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsInvalidSite, Server.HtmlEncode(txtNewSite.Text)));
            }
            catch (UnauthorizedAccessException)
            {
                // the user doesn't have permission to access this site, so show an error message
                errorBanner.AddHtmlErrorText(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsInvalidSite, Server.HtmlEncode(txtNewSite.Text)));
            }
            catch (FileNotFoundException)
            {
                errorBanner.AddHtmlErrorText(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsInvalidSite, Server.HtmlEncode(txtNewSite.Text)));
            }
            finally
            {
                SPSecurity.CatchAccessDeniedException = previousValue;
            }
            if (showAddSite)
            {
                DisplayAddSite();
            }
        }
Example #3
0
    static void Main(string[] args)
    {
        // load the XML spreadsheet into memory
        XPathNavigator rootNode;
        string         path;

        if (args.Length == 1)
        {
            path = args[0];
        }
        else
        {
            path = Path.Combine(Path.GetDirectoryName(
                                    Assembly.GetExecutingAssembly().Location), "UserWebList.xls");
        }
        using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read,
                                                  FileShare.ReadWrite))
        {
            rootNode = new XPathDocument(stream).CreateNavigator();
        }

        // create a namespace manager for accessing the XML spreadsheet
        string ssNamespace      = "urn:schemas-microsoft-com:office:spreadsheet";
        XmlNamespaceManager nsm = new XmlNamespaceManager(rootNode.NameTable);

        nsm.AddNamespace("ss", ssNamespace);

        // set <worksheetNode> to the "User Web Lists" worksheet
        XPathNavigator worksheetNode = rootNode.SelectSingleNode(
            "ss:Workbook/ss:Worksheet[@ss:Name = 'User Web Lists']", nsm);

        // loop once for each row in the worksheet
        const int     ExpectedCellCount = 2;
        List <string> cells             = new List <string>(ExpectedCellCount);

        foreach (XPathNavigator rowNode in worksheetNode.Select("ss:Table/ss:Row", nsm))
        {
            // set <cells> to the cells of this row
            cells.Clear();
            foreach (XPathNavigator cellNode in rowNode.Select("ss:Cell", nsm))
            {
                if (cellNode.MoveToAttribute("Index", ssNamespace))
                {
                    while (cells.Count < cellNode.ValueAsInt - 1)
                    {
                        cells.Add(String.Empty);
                    }
                    cellNode.MoveToParent();
                }
                XPathNavigator dataNode = cellNode.SelectSingleNode("ss:Data", nsm);
                cells.Add(dataNode.Value.Trim());
            }

            // ensure there are at least <ExpectedCellCount> cells
            while (cells.Count < ExpectedCellCount)
            {
                cells.Add(String.Empty);
            }

            // get the login name (i.e. "<domain>\<login-name>", or ".\<login-name>" for
            // local machine accounts), and the URL of the SharePoint Web site, listed in
            // this row of the worksheet; skip this row if either is blank
            string loginName = cells[0];
            string webUrl    = cells[1];
            if ((loginName.Length == 0) || (webUrl.Length == 0))
            {
                continue;
            }

            // "log in" to SharePoint as the user running this program, and set <spUser> to the
            // SPUser of the user specified by this worksheet row
            SPUser spUser;
            using (SPSite anonymousSite = new SPSite(webUrl))
            {
                if (loginName.StartsWith(@".\"))
                {
                    loginName = anonymousSite.HostName + loginName.Substring(1);
                }
                using (SPWeb rootWeb = anonymousSite.RootWeb)
                {
                    spUser = rootWeb.AllUsers[loginName];
                }
            }

            // "log in" to SharePoint as the user <spUser>, then add <webUrl> to the SLK user Web
            // list of that user
            using (SPSite spSite = new SPSite(webUrl, spUser.UserToken))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    Console.WriteLine("Adding {0} to the user Web list of {1}",
                                      spWeb.Url, spUser.Name);
                    SlkStore slkStore = SlkStore.GetStore(spWeb);
                    slkStore.AddToUserWebList(spWeb);
                }
            }
        }
    }