Friday, June 20, 2008

Get a SharePoint list (SPList) Root Folder Name and Display Name (Title)

Summary

1. Introduction
2. Samples
1.1. Getting List names programmatically in c#
1.2. Retrieving a list by its names programmatically in C#
1 - Document Library
2 - Standard Lists
3. Warnings
1. Special characters
2. File Not Found exception

1.Introduction

Reading MSDN for SPList Class , it seems it's not very obvious to:
get the name of a SharePoint list.
look for a list in a SharePoint web site using its name.
Here is the only excerpt of the SPList Class Library Reference in MSDN speaking of the list name:
 
[...]
Use an indexer to return a single list from the collection. For example, if the collection is assigned to a variable named collLists, use collLists[index] in C#, or collLists(index) in Visual Basic 2005, where index is the index number of the list in the collection, the display name of the list, or the GUID of the list.
[...]

For instance SPList class has no Name property or GetName method.
Furthermore, a SharePoint list will have TWO names if you had renamed it!
The Root Folder Name (like the Internal Name for a SPList Field ) is the one you have set when you have created the list.
This name will be always present in your browser Address Bar when you display the list
The display name (the one you have used if you have renamed the list).
This name will appear as your list Title, when you display the list and the as a link to the list in your QuickLaunch menu if you have added to. (If you have not renamed your List, the root folder name and the display name are the same).

2.Samples

1.1 Getting List names programmatically in c#

So, how to get a SharePoint list Root Folder Name and Display Name (Title) in C# programming.
The following code sample will display these two names for all lists of a SharePoint web site:

                            SPWeb myWeb = SPContext.Current.Web;

                            Debug.WriteLine("MyWeb lists : ");

                            foreach (SPList aList in myWeb.Lists)

                            {

                                Debug.WriteLine("************************************");

                                Debug.WriteLine("list Title (Display Name): " + aList);

                                Debug.WriteLine("list Title (Display Name): " + aList.Title);

                                Debug.WriteLine("list Root Folder Name: " + aList.RootFolder.Name);

                                Debug.WriteLine("************************************");

                            }


2.2 Retrieving a list by its names programmatically in C#

And now, how to retrieve a SharePoint list using Root Folder Name or Display Name:
Notice that:
Document Libraries URL finishes by "/Website/DocLibRootFolderName"
Other Lists URL finishes by "/Website/Lists/OtherListsRootFolderName"

1 - Document Library

Assume we need to instantiate a SPList object corresponding to a Document Library with,
Root Folder Name: mycustomdoclib1
Display Name: Invoices
the following code sample will illustrate that:

  • Root Folder Name:

                            SPWeb myWeb = SPContext.Current.Web;

                            //SPList myList = myWeb.GetList("sites/my-collaboration-portal/docs/mycustomdoclib1");

                            SPList myList = myWeb.GetList(SPUrlUtility.CombineUrl(myWeb.ServerRelativeUrl, "mycustomdoclib1"));

  • Display Name:

                            SPList myList = myWeb.Lists["Invoices"];

2 - Standard Lists

Assume  we need to instantiate a SPList object corresponding to a list that is not a document library with,
Root Folder Name: mycustomlist1
Display Name: Clients
the following code sample will illustrate that:

  • Root Folder Name:

                            SPWeb myWeb = SPContext.Current.Web;

                            //SPList myList = myWeb.GetList("sites/my-collaboration-portal/docs/Lists/ mycustomlist1 ");

                            SPList myList = myWeb.GetList(SPUrlUtility.CombineUrl(myWeb.ServerRelativeUrl, "/Lists/ mycustomlist1 ")); 
 

  • Display Name:

                            SPList myList = myWeb.Lists["Clients"];

3. Warnings:

3.1 Special characters

When you set your list display name, you will generally do it using the Web Site user language. If this language is not English, you will sometimes have to use special characters like:
É, è , ù, ê, Ø, ñ, ô, …

SharePoint generally use Unicode escape sequence for these characters. Assume your list display name in French is:
"ma première doclib",

you will have to use that string to retrieve it:

                            SPList myList = myWeb.Lists["ma premi\u00e8re doclib"];


If you are looking for any Unicode escape sequence, you can download a mapping table here.

If you have too many fields with special characters to manipulate, think to use Visual Studio Advanced Save Options and save your .aspx Page file in "UTF-8 with signature" or "Unicode" format, doing that will allow you to write your fields name using your language special characters. You can also modify your Web Application web.config to obtain the same result.

About this topic you can read this post:

Unicode in Visual Studio .Net

Tricks:

To avoid using special characters in your requests:
Use an English name for the list when you create it, and rename your list using Web Site user language.
Use the list Internal Name with SPWeb.GetList method to retrieve a list using server code (VB .net, C#...).

3.2 File Not Found exception

There is a lack in SharePoint when you are trying to find objects, because the methods you are using for that will throw an exception if the object does not exist instead of returning null. That forces you to manage certain parts of your code by handling exception that is not a good coding practice.

                            SPList listVariable;

                            try

                            {

                                listVariable = myWeb.Lists["ListIWant"];

                            }

                            catch (Exception e) { }

There is at least two ways of avoiding exception handling when trying to retrieve a list:

1 - Loop-through-the-lists

                            SPList listVariable;

                            foreach (SPList tempList in myWeb.Lists)

                            {

                                if (tempList.Title == "ListIWant")

                                {

                                    listVariable = tempList;

                                    break;

                                }

                            }

It is not so fool as it seems to be since someone found that loop was always faster than the previously described methods.

Fast access items in an SPListCollection

2 - Use-LINQ

There is a LINQ request posted by Adam Buenz that allows you to look for a list without throwing an exception if it does not exists.
By the way the Linq request actually is doing a loop.

        public static bool InspectForList(string listName)

        {

            var results = SPContext.Current.Web.Lists.Cast<SPList>().Where(item => Equals(string.Compare(item.Title, listName, true), 0));

            return results.Count() > 0;

        }

What Are The Biggest SharePoint API Mistakes?

For ending, a last advice,
You should always use the root folder name of a list to look for it, since this name will never change.

 

 

 

Thursday, June 12, 2008

Improve readibility of CAML in SPQuery using C# and Visual Studio

Introduction
If you want to break down line in C# while writing CAML to define an SPQuery query, you maybe try to look for C# continuation line character, the equivalent of _ in VB .net. Referring to C# Language Specification, C# doesn't need one. A line continues until a ; is reached.
However, If you try to break line in a string in Visual Studio you will have a "new line in constant " exception.
The solution is to use @ character before your string. Code sample
 SPSite mySite = new SPSite("http://frev1149:8080/");
 SPQuery myQuery = new SPQuery();
 myQuery.Query= @"
   <Where>
      <Eq>
        <FieldRef Name='StateMonthReport'/>
        <Value Type='Text'>Refusee</Value>
      </Eq>
   </Where>
   ";
 SPList myList = mySite.OpenWeb().Lists["Transmises"];
 SPListItemCollection myItems = myList.GetItems(myQuery);

Sunday, June 8, 2008

Create multiple Ajax-enabled Web Sites in Windows Sharepoint Services and MOSS 2007

Introduction
The goal of this post is to point out the key that will allow you to use Ajax for multiple sites in Windows SharePoint Services or MOSS 2007. Our team met the problem. We had several SharePoint Web Sites that had to exchange informations with an Ajax Web Service, and we couldn't use the SPContext object in the web service code because it was always instantiated the site collection top level site SPContext object.
We used a temporary solution passing the SharePoint Web Site GUID as a parameter to the Web Method.
Thanks to Daniel Larson that answered to a comment I posted on his blog, we found the solution. You may find it in a more complete version in the chapter 5 of his book written with Ted Pattison:

Inside Microsoft Windows SharePoint Services 3.0

Tutorial

To make a clear demonstration I will customize the WsAjaxEnabledWSSApplication I created in a previous post:

Integrate ASP.NET Web Service based AJAX with MOSS 2007 or Windows SharePoint Services 3.0

1 - Adding a new aspx page that will display the Title of the web site.

I add to the solution a new aspx page that will display the Title of the web site that is invoking the Ajax Web Service. This Title must be returned by the Ajax Web Service.



2 - Adding a new Web Method that will return the Title of the web site.

I add to the web service a new Web Method in order to get the Title of the Web Site that is invoking Web Service:
        [WebMethod]
        public string GetSPWebTitle()
        {
            return (SPContext.Current.Web.Title);
        }


3 - The AjaxRetrieveSPWebTitle.aspx page inline code

And now, the most interesting, the .aspx page inline code :
<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Globalization" %>

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <script runat="server">
    
        private const string WebInitScriptKey = @"WSAjaxEnebledWSSApplication.AjaxRetrieveSPWebGUID.aspx";
        private const string WebInitScriptFormat = @"window.spWebUrl = '{0}';";

        public void Page_Load(object sender, EventArgs e)
        {
            string webInitScript = string.Format(CultureInfo.InvariantCulture, WebInitScriptFormat, SPContext.Current.Web.Url);
            this.Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), WebInitScriptKey, webInitScript, true);
        }
    </script>

    <script type="text/javascript">
        function getMyWebTitle(){
            WsAjaxEnabledWSSApplication.HelloWorldService.set_path(window.spWebUrl + "/_vti_bin/AjaxWebService/HelloWorldService.asmx");
            WsAjaxEnabledWSSApplication.HelloWorldService.GetSPWebTitle(OnComplete, OnTimeOut, OnError);
        }
        
        function OnComplete(args){
            document.getElementById("divWebServiceReturn").innerText=args;
        }
        
        function OnTimeOut(args){
            alert("Time Out");
        }
        
        function OnError(args){
            alert("Error");
        }
    </script>

    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <services>
                <asp:ServiceReference InlineScript="true" Path="~/_vti_bin/AjaxWebService/HelloWorldService.asmx" />
         </services>
    </asp:ScriptManager>
    <br />
    <br />
    <input type="button" value="Get myWeb Title" onclick="JavaScript:getMyWebTitle();" />
    <br />
    <br />
    <span>Ajax Web Service returned that web site Title: </span>
    <div style="display: inline; color: Black" id="divWebServiceReturn">
    </div>
</asp:Content>

4 - Summary.

So the Key point is :
to set the path correctly before calling the service
   WsAjaxEnabledWSSApplication.HelloWorldService.set_path(window.spWebUrl + "/_vti_bin/AjaxWebService/HelloWorldService.asmx");

And to set the path, I used the JavaScript property as used by Daniel Larson and Ted Pattison in SharePoint AJAX Toolkit:
   window.spWebUrl 


5 - Testing

I am now creating a new subsite, mySubsite1.
As my .aspx page is an application page, for any site in my Site Collection that will be using that page, I will get its Title :





Sunday, May 25, 2008

Enumerate Role Assignments to retrieve Groups and Users Permissions in a Windows Sharepoint Services 3.0 or MOSS Site

Introduction:

The following .aspx page with C# in line code, enumerates all the roles assignments of a Windows SharePoint Services 3.0 or MOSS site collection and displays in DebugView Window for each web site:
  • The role member and reports if it is a Group or an User.
  • If it is a group, displays the number of users in the Group and the users list.
  • In any case, displays the Permissions list.
Why to use it?

When you want to check the users and the groups present in a Site Collection web sites and their role, it can take time doing it by browsing "People and Group" administration pages for each web site. It would be nice to display all the information in a single report. The following code sample will give you this kind of report, and it will be easier for you to reorder Users and Groups using it.

How to use it?

Copy the following code in an .aspx file.
Paste the file in the LAYOUTS diectory.
Start DebugView.
Browse the page with site administrator permissions from any site using the usual Application Page url (...myWebSite/_layouts/thisPage.aspx).
Check Report in DebugView window.

Code Sample:
<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" %>
 
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Diagnostics" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderMain" runat="server"> 
<asp:Label ID="lblMessage" runat="server" />
    <script runat="server">       
        protected string WriteIsRootWeb(SPWeb aWeb){
            if (aWeb.IsRootWeb)
            {
                return " (This is the Site Collection Root Web)";
            }
            else
            {
                return "";
            }
        }
 
        public void Page_load(object sender, EventArgs e)
        {
            bool isAgroup = true;
            SPGroup aGroup=null;
 
            foreach (SPWeb aWeb in SPContext.Current.Site.AllWebs)
            {
 
                Debug.WriteLine("\n******************************************");
                Debug.WriteLine("Roles Assignments Report on web site " + aWeb.Title + WriteIsRootWeb(aWeb));
                Debug.WriteLine("******************************************\n");
 
 
                Debug.WriteLine("List of " + aWeb.Title + " Groups");
 
                foreach (SPGroup Group in aWeb.Groups)
                {
                    Debug.WriteLine(Group.Name + " ID: " + Group.ID);
                }
 
                Debug.WriteLine("");
 
                foreach (SPRoleAssignment aRole in aWeb.RoleAssignments)
                {
                    isAgroup = true;
                    Debug.WriteLine("*************\n");
                    try
                    {
                        aGroup = aWeb.Groups.GetByID(aRole.Member.ID);
                    }
                    catch
                    {
                        isAgroup = false;
                    }
 
                    if (isAgroup)
                    {
                        Debug.WriteLine("Group Id : " + aRole.Member.ID.ToString() + " | " + " Principal Name : " + aRole.Member.Name);
 
                        Debug.WriteLine("Number of users:" + aWeb.Groups.GetByID(aRole.Member.ID).Users.Count);
                        aGroup = aWeb.Groups.GetByID(aRole.Member.ID);
                        Debug.WriteLine("");
                        Debug.WriteLine("List of " + aGroup.Name + " users");
 
                        foreach (SPUser aUser in aGroup.Users)
                        {
                            Debug.WriteLine("\t - " + aUser.Name);
                        }
                        Debug.WriteLine("");
                    }
                    else
                    {
                        Debug.WriteLine("User Id : " + aRole.Member.ID.ToString() + " | " + " Principal Name : " + aRole.Member.Name);
                    }
 
                    Debug.WriteLine("\nList of permissions for " + aRole.Member.Name + ":");
 
                    for (int i = 0; i < aRole.RoleDefinitionBindings.Count; i++)
                    {
                        Debug.WriteLine(aRole.RoleDefinitionBindings[i].BasePermissions.ToString());
                    }
 
                    Debug.WriteLine("");
                }
            }
            lblMessage.Text="Your report has been generated in DebugView";
        }
    </script>
</asp:Content >

if you want a much more complete report for SharePoint users and groups Permissions, Role Assignments within a SharePoint Site Collection, in HTML fomat generated inside an Application Page, see...

Enumerate Role Assignments to retrieve Groups and Users Permissions - Generating a complete report

if you want to know more about DebugView, see...

Use DebugView in Windows SharePoint Services 3.0 programming.



Use DebugView in Windows SharePoint Services 3.0 and MOSS programming

While programming Windows SharePoint Services or MOSS Sites, tools, debugView allows you to display trace messages at runtime.
How to use it ?
Download dbgview.exe. Simply execute the DebugView program file (dbgview.exe) and DebugView will immediately start capturing debug output.

Warning:
You have to set to true the "debug" attribute in "configuration" section of the concerned Web Application.



You must select "Capture Win32" and "Capture Events" in Capture Menu



To expose your code traces to DebugView, use this kind of instruction :

System.Diagnostics.Debug.WriteLine("myVar1Value : " + Var1.Value);


Why to use it ?
  • After having deployed. You can check traces on a server where there is no Visual Studio set up.
  • You can debug your in line code while using NotePad.
  • You can debug without using Visual Studio console, or spoiling your pages with "Response.Write" instructions.
  • It is very comfortable to have your traces written in an other window than Visual Studio. You have more space to write traces and check them.
  • After having developed your application, you don't need to clear the debug instructions from your code. You compile in Realease mode, and all instructions are ignored, excepted if you check that checkbox in Visual Studio (right click your project in Solution Explorer Window, and select "Properties"):

    Define DEBUG Constant

Go to the TechNet reference page.
You will find the link to download DebugView at the bottom of the page.

Saturday, May 24, 2008

Integrate ASP.NET Web Service based AJAX with MOSS 2007 or Windows SharePoint Services 3.0

Introduction:

As Windows SharePoint Services version 3 is built on ASP.NET 2.0, you can use most of ASP .Net Ajax functionalities in Sharepoint. There is two ways to use Asp .Net Ajax in a Solution:
  • by using an Update Pannel
  • by using an ASP .Net Ajax enabled Web Service
I have found nothing on the Web Service based method explaining how to exactly deploy it in a MOSS or Windows SharePoint Services application. So we did it by ourselves, and most of the following was done thanks to the work of François Michael Dain.

Tutorial:

Asp .Net Web Service Ajax enabled application, in Windows SharePoint Services 3.0

We are now going to build a simple Asp .Net Ajax Enabled Windows SharePoint Services Application based on Web Service method. We will build something simple, as an "Hello World" tutorial.

1 - Configuring the web Application web.config file.

First of all you have to configure your Web Application web.config file in order your SharePoint Application to be compliant with Asp .Net Ajax. There is excellent posts on doing that :

2 - Adding a Web Service to your Web Application.

After having configured your web.config properly, add a web service inside your SharePoint Web Application doing this :
Start Visual Studio and create a Class Library Project.
This is the solution in Visual Studio at the beginning, (We use WSPBuilder Project Template).



Under 12 hive, add "ISAPI" directory, then your Ajax Web Service Directory.



After having added your Web Service, your Solution should look like this :


Here is the code of HelloWorldService.asmx

<%@ WebService Language="C#" CodeBehind="HelloWorldService.asmx.cs" Class="WsAjaxEnabledWSSApplication.HelloWorldService" %>


Here is the code of HelloWorldService.asmx.cs

#region using

using System;

using System.ComponentModel;

using System.Web;

using System.Web.Script.Services;

using System.Web.Services;

 

 

#endregion

 

namespace WsAjaxEnabledWSSApplication

{

    ///

    /// Summary description for HelloWorldService

    ///

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.Web.Script.Services.ScriptService()]

    [ToolboxItem(false)]

    public class HelloWorldService : System.Web.Services.WebService

    {

        [WebMethod]

        public string HelloWorld(string userName)

        {

            return "Hello, " + userName;

        }

    }

}


3 - Building your Solution and adding your Web Service dll to the GAC.

Build your Solution, go to debug directory, copy WsAjaxEnabledWSSApplication.dll and paste it in the GAC (C:\windows\assembly).
If an "Access Denied" Pop Up message occurs, just paste it a second time and you will be succeed in pasting it.
Now you should do a IISReset, but it won't be necessary since we are going to modify the Web Application web.config file and this action will recycle the Web Application Pool.

4 - Adding your Solution dll referrence to the SafeControls section of the Web Application web.config file.

In the Gac (C:\windows\assembly), find your dll reference and right click it to display porperties. you can the copy name, culture, version and Public Key Token on a note pad and then build that line (change to suit your assembly and namespace etc...) :

<SafeControl Assembly="WsAjaxEnabledWSSApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9073b0a00e9670f8" 
Namespace="WsAjaxEnabledWSSApplication" TypeName="*" Safe="True" />

Make a back-up copy of your Web Application web.config file.
Open your Web Application web.config file and add the previous line in the SafeControls section
Don't forget to save the web.config file.

5 - Modyfying HelloWorldService.asmx file and deploying the Web Service.

Add this line at the top of your HelloWorldService.asmx file:

<%@ Assembly Name="WsAjaxEnabledWSSApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9073b0a00e9670f8" %>

Then, copy your AjaxWebService directory to ISAPI folder under the 12 hive. Here is a picture of the directory after copying.



6 - Testing your Web Service.

Open IIS mmc, locate your Web Service and right click it to browse it.



You should obtain that results:



If you enter the url of your Web Service followed by /js
(http://localhost:8080/_vti_bin/AjaxWebService/HelloWorldService.asmx/js)
You will be asked to save a js file.



Rename the file in AjaxWebService.js. Save the .js file on your server Desktop.



Edit AjaxWebService.js file and check that most of the lines are beginning by your namespace and WebService Name:
WsAjaxEnabledWSSApplication.HelloWorldService
The last line should show the complete call to your Web Service method :
WsAjaxEnabledWSSApplication.HelloWorldService.HelloWorld



7 - Creating a Windows SharePoint Services Applicative Page for consuming your web service

If it's not already done, create a site collection, for example : AjaxEnabledSite.
In your Visual Studio project, creat a new directory under 12 hive:
TEMPLATE\LAYOUTS
Add an .aspx page, asume we call it : AjaxHelloWorld.aspx
Your project should now look like this :



Here is the code of AjaxHelloWorld.aspx page :

<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>

<%@ Page Language="C#"  MasterPageFile="~/_layouts/application.master"%>

 

<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderMain" runat="server" >

test

</asp:Content >


Deploy your AjaxHelloWorld.aspx page with WSP Builder or just copy it in LAYOUTS directory.
Test your page by browsing it:



8 - Adding Ajax Code to your Applicative Page

In Visual Studio, add this code inside the asp:Content tag of AjaxHelloWorld.aspx :

   <script type="text/javascript">

        function sayHello(){

            WsAjaxEnabledWSSApplication.HelloWorldService.HelloWorld(document.getElementById("txt1").value, OnComplete, OnTimeOut, OnError);

        }

 

        function OnComplete(args){

            document.getElementById("txt2").innerText=args;

        }      

        function OnTimeOut(args){

            alert("Time Out");

        }      

        function OnError(args){

            alert("Error");

        }

 

    </script>

 

    <asp:ScriptManager ID="ScriptManager1" runat="server">

        <services>

                <asp:ServiceReference InlineScript="true" Path="../_vti_bin/AjaxWebService/HelloWorldService.asmx" />

         </services>

    </asp:ScriptManager>

 

    <input type="text" id="txt1"/>

    <br />

    <input type="button" value="Say Hello" onclick="JavaScript:sayHello();" />

    <br />

    <input type="text" id="txt2"/>



Deploy your page with WSP Builder or just copy it in LAYOUTS directory.

9 - Consuming your Ajax Web Service

You can now test your Ajax Web Service Based Applicative Page :



You have noticed that we didn't need any single line of server side code in our AjaxHelloWorld.aspx page.
Warnings :

This was a first step to roughly understand how to build and deploy an Web Service based AJAX web site in WSS or MOSS. The drawback of the present example is that you will be embarassed if you have several web sites that have to call the web service, since it will know as Context only one site : the site collection top level site. If you want to create and deploy several AJAX enabled web sites in WSS or MOSS see:
Create multiple Ajax enabled web sites in Windows SharePoint Services or MOSS 2007

Check User Permissions in Windows SharePoint Services or MOSS 2007

Introduction:
Windows SharePoint Services 3.0 implements new types in its object model to support the new security model. Old model is obsolete but keep beeing usable. In Windows SharePoint Services 3.0 or MOSS 2007 sites, you have sometimes to check user, Permissions, Rights, Roles, when loading a page, doing an action, and decide what to do depending on these Permissions. all these Classes are obosolete :
  • SPPermission
  • SPRole
  • SPRights
There is however several Methods working around these tasks, for example :
  • SPSite.CheckPermissions
  • SPSite.DoesUserHavePermissions
  • SPWeb.CheckPermissions
  • SPWeb.DoesUserHavePermissions
  • SPList.CheckPermissions
  • SPList.DoesUserHavePermissions
  • SPListItem.CheckPermissions
  • SPListItem.DoesUserHavePermissions
  • ...
Here is a sample of C# code to check user specific Permission to a web site (SPWeb). For instance, we check if user can edit list items.
Code Sample :

        SPWeb myWeb = SPContext.Current.Site.OpenWeb();

 

        if (myWeb.DoesUserHavePermissions("DomainName\\user1", SPBasePermissions.EditListItems))

        {

            System.Diagnostics.Debug.WriteLine("user1 can edit lisItems");

        }

        else

        {

            System.Diagnostics.Debug.WriteLine("user1 cannot edit lisItems");

        }

if you are puzzled by "System.Diagnostics.Debug.." and want to know more about DebugView, see...
Use DebugView in Windows SharePoint Services 3.0 programming.