How to: Create a Web Application in a SharePoint Web Site

This programming task describes how to create a custom Web application, or Web Site, in Visual Studio 2005 that operates within the context of Windows SharePoint Services. The example creates a tool that reports a list of all the SharePoint Web sites to which a specified user belongs, as well as a list of the groups to which the user belongs for each Web site.

Note Note:

The phrase "Web application" has varying meanings depending on the context. This topic concerns browser-based applications that run from an aspx page. It is not about Web applications in the sense of Internet Information Services (IIS) "Web sites" or "Application Pools". Hence, it is not about the things represented by the SPWebApplication class in the Windows SharePoint Services 3.0 object model.

Procedure

To create a tool for reporting a user's SharePoint Web sites and groups

  1. In Visual Studio 2005, create a new Web application and set a reference to Microsoft.SharePoint.dll. For information about how to perform these steps, or about how to create a Web application on a front-end Web server from a remote computer that is not running Windows SharePoint Services, see Getting Started with Programmatically Customizing a SharePoint Web Site in Visual Studio.

  2. In Design view, use the Toolbox to add a label, a text box, and a button to Default.aspx. To open the Toolbox, click Toolbox on the View menu.

    Note Note:

    To create a Web application that modifies data in the content database, you need to add a FormDigest control and a page directive to the .aspx file that contains the form. For information about how to add this control, see Security Validation and Making Posts to Update Data.

  3. To open the code-behind file named Default.aspx.cs, double-click the button you added in the previous step.

  4. At the beginning of the file, add using directives (Imports statements in Visual Basic) that reference the Microsoft.SharePoint and Microsoft.SharePoint.Utilities, as follows:

    Visual Basic
    Imports Microsoft.SharePoint
    Imports Microsoft.SharePoint.Utilities

    C#
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;

    You must reference the Microsoft.SharePoint namespace in order to return the specified user and the groups to which the user belongs. You must reference the Microsoft.SharePoint.Utilities namespace in order to encode strings that are displayed in the example.

  5. At the beginning of the class definition return the site collection object for the current request context as follows:

    Visual Basic
    Partial Class _Default
       Inherits System.Web.UI.Page
    
       Dim oSite As SPSite = SPContext.Current.Site
       ...

    C#
    public partial class _Default : System.Web.UI.Page
    {
       SPSite oSite = SPContext.Current.Site;
       ...
  6. Create a method that uses the AllWebs property of the SPSite class, the AllUsers property of the SPWeb class, and the Groups property of the SPUser class within nested foreach statements, in order to return a user object for the user name specified in the text box, as well as the list of groups to which that user belongs.

    Within the default class in Default.aspx.cs, add the following method to return the users and groups for each Web site in the current site collection:

    Visual Basic
    Protected Sub GetSitesAndGroups()
       Dim strUser As String = SPEncode.HtmlEncode(TextBox1.Text) _
          & " is a user in the following groups:<BR>"
    
       Dim collWebs As SPWebCollection = oSite.AllWebs
    
       For Each oWebsite As SPWeb In collWebs
          Dim strGroups As String = ""
    
          'Use AllUsers not Users to ensure you find the user
          Dim collUsers As SPUserCollection = oWebsite.AllUsers
    
          For Each oUser As SPUser In collUsers
             If oUser.LoginName.ToUpper() = TextBox1.Text.ToUpper() Then
                Dim collGroups As SPGroupCollection = oUser.Groups
    
                For Each oGroup As SPGroup In collGroups
                   strGroups += SPEncode.HtmlEncode(oGroup.Name) & "  "
                Next oGroup
    
                strUser = strUser _
                   & oWebsite.ServerRelativeUrl.ToString() _
                   & " -- " & strGroups & "<BR>"
             End If
          Next oUser
    
          oWebsite.Dispose()
       Next oWebsite
    
       Label1.Text = strUser
    End Sub

    C#
    protected void GetSitesAndGroups()
    {
       string strUser = SPEncode.HtmlEncode(TextBox1.Text) +
          " is a user in the following groups:<BR>";
    
       SPWebCollection collWebs = oSite.AllWebs;
    
       foreach (SPWeb oWebsite in collWebs)
       {
          string strGroups = "";
    
          /*Use AllUsers not Users to ensure you find the user*/
          SPUserCollection collUsers = oWebsite.AllUsers;
          foreach (SPUser oUser in collUsers)
          {
             if (oUser.LoginName.ToUpper() == TextBox1.Text.ToUpper())
             {
                SPGroupCollection collGroups = oUser.Groups;
    
                foreach (SPGroup oGroup in collGroups)
                {
                   strGroups += SPEncode.HtmlEncode(oGroup.Name) + 
                      "  ";
                }
    
                strUser += oWebsite.ServerRelativeUrl.ToString() +
                   " -- " + strGroups + "<BR>";
             }
          }
    
          oWebsite.Dispose();
       }
    
          Label1.Text = strUser;
    }

    The code example iterates through all the users of all the Web sites within the current site collection, and if the value of the LoginName property for a given user matches the user name that is entered in the text box, then the names of all the user's groups for the site are collected and displayed.

  7. To run the code added in the previous step and avoid receiving an access denied error message, the user implementing the GetSitesAndGroups method must have Full Control permission. Add the following code to the Button1_Click event handler, which uses the RunWithElevatedPrivileges method to allow the current user to iterate through the users and groups of each Web site within the current site collection.

    Visual Basic
    Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim elevatedGetSitesAndGroups As New SPSecurity.CodeToRunElevated(AddressOf GetSitesAndGroups)
       SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups)
    End Sub

    C#
    protected void Button1_Click(object sender, EventArgs e)
    {
       SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(GetSitesAndGroups);
       SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups);
    }
  8. On the Debug menu, click Start Debugging, or press F5. If a Debugging Not Enabled dialog box appears, make sure Add a new Web.config file with debugging enabled is selected, and click OK.

    The browser opens the page. When you type the logon name of a user on a site within the current site collection, the label displays the Web sites and groups to which the specified user belongs.

  9. To run the application after creating it in Visual Studio 2005, navigate to http://Server_Name/_layouts/Web_Application_Name/Default.aspx.

See Also

Tags :


Community Content

jcm.net
Code bug?

I get a bug when i try this code sample.

CodeToRunElevated(GetSitesAndGroups)

I had to use AddressOf:

CodeToRunElevated(AddressOf GetSitesAndGroups)

And then the next line gives me Object not set to reference... error?

SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups)

 

Anyone know how to get this to work?

thanks.

Tags : bug vb.net

Hector Mike
Couple of comments

I got it to run, but some things were tricky.  This is what it took for me:

1. Opened VS 2005.

2. Chose File - New Web Site - ASP.NET Web Site.

3. Created it in the file system using C# at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\MyWebProjectName.  Added said TextBox1, Label1, and Button1 per instructions above.  Added code shown above.

4. Right-clicked the project in Solution Explorer, chose Property Pages from the popup menu.

5. Clicked References, added a reference to Microsoft (r) SharePoint (r) Services.

6. Clicked Start Options, set Server to 'Use custom server', set base URL to 'http://LocalServer:PortNum/_layouts', set start actions to 'Don't open a page'.

7. Closed Property Pages window.

8. Opened the Web.config file, commented out the <authentication mode="Windows"/> tag, added the tag <customErrors mode="Off"/> immediately below it.

9. Clicked Build - Build Web Site.

10. Set some breakpoints, clicked Debug - Attach to Process, selected the instance of w3wp.exe that corresponds to my application pool.  (If no w3wp.exe exists in the list, you'll need to navigate to http://LocalServer:PortNum/ first.)  Clicked Attach.

11. Navigated to http://LocalServer:PortNum/_layouts/MyWebProjectName/Default.aspx, entered a name of MyDomain\SomeSharePointUser into TextBox1, clicked Button1.

12. Continued through breakpoints.  Observed output.

Tags : c# suggestion

Charlie Lim
Got a different bug.

I did every step from this sample used vb.net. But when I run this project, a exception happened at this line:

Dim mySite As SPSite = SPContext.Current.Site

The error message was: System.InvalidOperationException

Why???

Tags : bug vb.net

JiaJun
How to use master page in a custom web application

I tried to integrate application.master page in my custom web application, but failed.

How to use it?

Tags :

Jits
Master Pages

To use Master Pages... in each page that references a master page, you need to change (at the top of the aspx markup):

MasterPageFile="~/Default.master"

to:

MasterPageFile="Default.master"

This is because when the page runs it will be under the context of the SP site, so the url to the page will be something like:
http://<server_name>/<root_site>/<sub_site>/_layouts/<custom_app>/<page>.aspx

Tags :

StenGuy69
Continued frustration, and VB code fix

I was able to correct a build error by correcting the button click handler code to be: (required change in BOLD)

Dim elevatedGetSitesAndGroups As New SPSecurity.CodeToRunElevated(AddressOf GetSitesAndGroups)
SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups)

But even after a sucessfule build, I was not able to get SharePoint to serve up my page... What's the deal???

I am not having a good time getting this SharePoint application development stuff to work, and am just about ready to give up and build them separately and port into SharePoint using the Page Viewer Web Part... Anybody have any advice for me?

Sincerely,

Frustrated novice...

Tags : code vb

Needo
No error, but not allowing too see the page

I have have done everything, its fine, no error. But when i run the application, is pops up a dialof to ask username and password.

When i enter my username and password , it does not allow me too see the page, even though i have full rights at Sharepoint server.

I donot know what to do, there is no error.

Please help

needo

Tags : bug site

Neil Yan
I got System.InvalidOperationException

I got the exception as title at this line:

SPSite mySite = SPContext.Current.Site

Are there anyone get this exception? If you get the same exception, or you know how to fix it. please contact me. yan0lovesha@hotmail.com

thanks,

Neil


Tags :

Noelle Mallory - MSFT
I got error --> "Visual Web Developer does not support creating Web sites on a SharePoint

when i m trying to create new web site on sharepoint i got following error
"Visual Web Developer does not support creating Web sites on a SharePoint
Web server"

pls help me out

[Noelle Mallory - MSFT] Please post questions to the MSDN Forums at http://forums.microsoft.com/msdn. You will likely get a quicker response through the forum than through the Community Content.

Tags :

AnonymousToday
What's the difference?

Could somebody explain the difference between this tutorial and the one at the URL below.

http://msdn2.microsoft.com/en-us/library/ms868589.aspx

Thanks.

Tags :

KevorkV
The difference...
Mr. Alias, that link you've provided is not for WSS v3. Hope this answers your question.
Tags :

Stian Kirkeberg
Added a blog article about the subject

See

http://blogs.msdn.com/mcsnoiwb/archive/2008/10/02/how-to-creating-a-vs-web-application-below-a-sharepoint-iis-web-application.aspx


Page view tracker