in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

tanujashares

  • MOSS Service Pack 1 Released

    Many of you, might have already gone through the MOSS / WSS SP1, but those who have not seen this yet, please go through it.

    Glad to see that SP is released one quarter before schedule ... 

    See if any issues bugging to you have been resolved or not Smile

    Here are some usefule links -

    http://office.microsoft.com/download/afile.aspx?AssetID=AM102512381033

    http://support.microsoft.com/kb/942390/

    Share with everyone what major issues been resolved.

     

    --tanuja

  • Customize the OOB list menus in SharePoint 2007 lists

    Customization in SharePoint List Menus-

    In SharePoint 2007, as all of us know, portal can be created within very less span of time using the OOB features... but what if the customer is skeptical about certain UI and functionality which cannot be addressed by MOSS OOB features?

    The only way is to go into SharePoint customizations and it takes a lot of effort to tweak few small things.

    In the subsequent blog posts I am going to write about the different customizations that we can do in SharePoint 2007 & InfoPath 2007.

    So start with menubar .... what do we get as OOB?

    Its a toolbar defined as a user control ascx. This control takes care of the permissions assigned to user and appropriately allows the menus which are accessible to user.

    Now, we want to add some other links, menus to the toolbar for our requirement, how should we customize it?

    OK - This can be done using FEATURES in SharePoint 2007.

    Step 1 - Create a list definition for the particular list.

    Step 2 - Create a feature in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES withe the name you want, say "CustomMenu"

    Step 3 - Then add Feature.xml file to this folder containing -

    <?xml version="1.0" encoding="utf-8" ?>
    <Feature Id="{255E99BB-534A-4b93-AE6A-1691C300DF7C}"
        Title="Custom Menu"
        Description="This example shows how you can implement custom menu."
        Version="1.0.0.0"
        Scope="Site"
        xmlns="http://schemas.microsoft.com/sharepoint/">
     <ElementManifests>
      <ElementManifest Location="Element.xml" />
     </ElementManifests>
    </Feature>

    Step 4- Now add Element.xml file in the same folder containing -

    <?xml version="1.0" encoding="utf-8" ?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">

    <CustomAction Id="CustomMenu"
       RegistrationType="List"
       RegistrationId="3001" 
       GroupId="NewMenu"
       Location="Microsoft.SharePoint.StandardMenu"
       Sequence="1000"
       ImageUrl="/_layouts/images/itann.gif"
       Title="Custom Menu for sample">
      <UrlAction Url=http://www.google.com/></UrlAction>
     </CustomAction>

    </Elements>

    In this config, you need to pass Registration Id as the list template ID you created in step 1 or the ID as 100, 101 for OOB custom list, document library etc.

    Step 5- Install & deploy this feature using stsadm commands.

    stsadm -o deactivatefeature -filename CustomMenu\Feature.xml -url http://localhost/
    stsadm -o uninstallfeature -force -filename CustomMenu\Feature.xml
    stsadm -o installfeature  -filename CustomMenu\Feature.xml
    stsadm -o activatefeature -filename CustomMenu\Feature.xml -url http://localhost/

    You need to put the URL of your site collection instead of putting http://localhost/

    And here you go with the new menu in your list.

    But what if you want to remove the existing menu as "New Item" as well? Is there any direct way similar to feature we used, to remove menu? The answer unfortnately is NO. And we need to try out some different technique now.

    The technique is to modify the toolbar user control in Lists.

    How to go for it?

    Step 1 - Create new NewToolbar.ascx file

    <%@ Control Language="C#"   AutoEventWireup="false" %>
    <mailto:%25@Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <mailto:%25@Register TagPrefix="SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.WebControls"%>
    <mailto:%25@Register TagPrefix="Mymenu" Assembly="NewSubMenu, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bb9e88afc6454ba1" namespace="Bechtel.eSub.NewSubMenu"%>
    <mailto:%25@Register TagPrefix="SPHttpUtility" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" namespace="Microsoft.SharePoint.Utilities"%>
    <%@ Register TagPrefix="wssuc" TagName="ToolBar" src="~/_controltemplates/ToolBar.ascx" mce_src="~/_controltemplates/ToolBar.ascx" %>
    <%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="~/_controltemplates/ToolBarButton.ascx" mce_src="~/_controltemplates/ToolBarButton.ascx" %>

    <SharePoint:RenderingTemplate ID="ViewToolBar1" runat="server">
     <Template>
      <wssuc:ToolBar CssClass="ms-menutoolbar" EnableViewState="false" id="toolBarTbl" ButtonSeparator="<img src='/_layouts/images/blank.gif' alt=''>" RightButtonSeparator="&nbsp;&nbsp;" runat="server">
       <Template_Buttons>
          
        <Mymenu:NewMenu ID="MyNewMenu" AccessKey="<%$Resources:wss,tb_NewMenu_AK%>" runat="server"/>
        <SharePoint:ActionsMenu  AccessKey="<%$Resources:wss,tb_ActionsMenu_AK%>" runat="server" />
        <SharePoint:SettingsMenu  AccessKey="<%$Resources:wss,tb_SettingsMenu_AK%>" runat="server" />
        </Template_Buttons>
       
       <Template_RightButtons>
          <SharePoint:PagingButton ID="PagingButton1" runat="server"/>
          <SharePoint:ListViewSelector ID="ListViewSelector1" runat="server"/>
       </Template_RightButtons>
      </wssuc:ToolBar>
     </Template>
    </SharePoint:RenderingTemplate>

    Step 2 - Save this file in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES

    Step 3- Create a receiving class to add menus to this toolbar. So create a new class library project in Visual Studio 2005. Name it as per specified in ascx (NewSubMenu).

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using System.Web.UI;

    namespace NewSubMenu
    {
        public class NewMenu : NewMenu
        {
            protected override void AddMenuItems()
            {
                AddMenuItem("1", "New Item", "", "Click here to copy an item to this list", "/_layouts/custompage.aspx", "");
                AddMenuItem("2", "New Itme 2", "", "Click here for next item ", "/_layouts/custompage.aspx", "");

            }

        }

    }

    Step 4- Compile this assembly and put it in GAC.

    Step 5- Change the list defnition of the list in which you want to customize your menus. Go to schema.xml file and modify the following line to incorporate new toolbar in list-

    <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,All_Tasks;" DefaultView="TRUE" MobileView="True" MobileDefaultView="False" ToolbarTemplate="ViewToolBar1" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/issues.png" Url="AllItems.aspx>

    Step 6- Redeploy the list definition using stsadm commands and iisreset and then here you go.

    How can you change these menus for different list inherited from same list definition? -

    Modify the class NewMenu we wrote to read the info from config list and populate menus depending upon the list name. So it will create the menus dynamically depending upon the list name.

    In this class , this.lsit provides the SPList object of current list and you can play with it the way you want, before adding actual sub menus.

    --tanuja

  • Impersonation in SharePoint 2007 ......

     

    SharePoint security model makes it easy to programmatically execute code within the current user context.

    Just write and deploy web part / event handler code and it runs in the security context of the logged in user. There are even built-in functions that take advantage of the user's security context - such as GetSubwebsForCurrentUser() - without requiring any extra coding on our part which is simple yet effective security mechanism.

    But there are situations when the code needs to be executed with permissions greater than that of the current user (like instantiating a site collection or enumerating list permissions or reading a lookup / configuration list on which user may not have access rights).

    In such situations, the code needs to be executed with elevated permission level or under the context of user with higher permissions i.e. Impersonation.

    So here are the two approaches for u ----

    Executing code as another named user

    Process

    When we create a SharePoint site programmatically using the Microsoft.SharePoint namespace, we can supply a user token which enables you to create objects in the context of a specific user. You can impersonate a user by supplying the user token for that user, obtained from the Microsoft.SharePoint.SPUser object. The user token, SPUserToken, is a binary object that contains the identification and domain group membership of a user.

    This allows you to use the Microsoft.SharePoint.SPSite constructor to instantiate a site collection object that runs as if that user was making changes.

    SPSite site = new SPSite("SiteCollection_Url");

    SPWeb web = site.OpenWeb();

    SPUser user = web.AllUsers["User_Name"];

    SPUserToken token = user.UserToken;

    SPSite impersonatedSiteCollection = new SPSite("SiteCollection_Url", token);

    Any objects (SPWeb, SPList, etc) that you create from this impersonated site collection will execute as the impersonated user.

    Where to Use -

    This Approach is useful to run any code which requires specific permissions to execute that code (like permission for reading a particular list), rather than having a full control access permission.

    In such a case, service account can be created by specific access rights just sufficient enough to execute the code.

    Caution-

    Although impersonation provides a powerful new technique for managing security, it should be used with care to make sure that unwanted activity is not performed by users who shouldn't have the ability to impersonate.

    Executing code with elevated privileges

    Process

    Method 1 -

    Elevation of privilege is a new feature of that enables you to programmatically perform actions in code using an increased level of privilege. The Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.

    For example:

    1. Define a public method that acts simply as a front end to the method that does the "real" work.

    public void ProcessMethod()

    {

    SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated( ProcessMethodAsElevated);

    SPSecurity.RunWithElevatedPrivileges(elevatedMethod);

    }

    The code uses a method from SPSecurity to indicate the name of the method that will run with Full Control(Basically using Application Pool Account).

    In the first line, simply pass in the name of the method as the parameter. In the second line, you execute that method with elevated privileges.

    2. Now create the method that does the real work. It is called by the first method (delegate), but executes with Full Control(under Application Pool Account):

    private void ProcessMethodAsElevated()

    {

    //code goes here to do our work

    }

    Method 2 -

    We can also implement this method by creating dummy delegate method within a code.

    SPSecurity.RunWithElevatedPrivileges(

                            delegate()

                            {

                                        //code goes here to do our work

                               

                            });

     

    Where to Use -

    This approach can be used in scenarios to read or update Site Collection, Site related objects using Full control in event handlers, features or web parts (i.e. code being executed under SharePoint Context.

    Caution-

    In this approach, we can't use any SharePoint objects that were created outside the method or else the impersonation won't work.

    We also can't use anything like SPControl.GetContextWeb(Context) because that also blows the impersonation out of the water.

    Instead, we can tweak it like SPSite site = new SPSite(SPControl.GetContextSite(Context).ID). In this case, we are instantiating a new SPSite object and only using the GUID of the current site. i.e. recreation of the SPSite object with new permissions.

    Also, we should dispose of the SPSite object created within the RunWithElevatedPrivileges() before exiting the scope, because that SPSite will still have the SHAREPOINT\system identity even outside of the RunWithElevatedPrivileges() scope.

    RunWithElevatedPrivileges() has no effect when running in a standalone exe.

     

    ----Tanuja


Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts