Impersonate another user c#

on Friday, December 4, 2009

public class Impersonator
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

public bool impersonate(String userName, String domain, String password)
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
return true;
if (token != IntPtr.Zero)
if (tokenDuplicate != IntPtr.Zero)
return false;

public void undoImpersonation()

//Sample Code

Impersonator imp = new Impersonator();
bool isTrue=imp.impersonate("testuser1", "buildmachine", "password");
if (isTrue)
items = testDocLib.GetItems(query);


SharePoint Hard Limits and Recommendation

on Thursday, December 3, 2009

Entity Max Permissible Size
Site Name 128 characters
Site URL 255 characters
Display name 128 characters
Connection string 384 characters
Email address 128 characters
Version numbers 064 characters
Virtual Server Friendly Name 064 characters
SQL Database Name 123 characters
SQL Database Column 128 characters
SQL Database Table Name 128 characters
SQL Role Name 128 characters
Server Name 128 characters
Windows User Name 300 characters
Windows Password 300 characters
Dependencies per object 032 objects
Zone enumeration value 004 zones
Default SQL command timeout 300 seconds
Number of simultaneous workflows that can be run 015

Site object

Guidelines for acceptable performance Notes Scope of impact when performance degrades
Site collection 50,000 per Web application Total farm throughput degrades as the number of site collections increases. Farm
Web site 250,000 per site collection You can create a very large total number of Web sites by nesting the subsites. For example, 100 sites, each with 1000 subsites, is 100,000 Web sites. The maximum recommended number of sites and subsites is 125 sites with 2,000 subsites each, for a total of 250,000 sites. Site collection
Subsite 2,000 per Web site The interface for enumerating subsites of a given Web site does not perform well as the number of subsites surpasses 2,000. Site view
Document 5 million per library You can create very large document libraries by nesting folders, using standard views and site hierarchy. This value may vary depending on how documents and folders are organized, and by the type and size of documents stored. Library
Item 2,000 per view Testing indicates a reduction in performance beyond two thousand items. Using indexing on a flat folder view can improve performance. List view
Document file size 50MB (2GB max*) File save performance is proportional to the size of the file. The default maximum is 50 MB. This maximum is enforced by the system, but you can change it to any value up to 2 GB. Library, file save performance
List 2,000 per Web site Testing indicates a reduction in list view performance beyond two thousand entries. List view
Field type 256 per list This is not a hard limit, but you might experience list view performance degradation as the number of field types in a list increases. List view
Column 2,000 per document library4,096 per list This is not a hard limit, but you might experience library and list view performance degradation as the number of columns in a document library or list increases. Library and list view
Web Part 50 per page This figure is an estimate based on simple Web Parts. The complexity of the Web Parts dictates how many Web Parts can be used on a page before performance is affected. Page

The following table lists the recommended guidelines for people objects.

People object

Guidelines for acceptable performance Notes
Users in groups 2 million per Web site You can add millions of people to your Web site by using Microsoft Windows security groups to manage security instead of using individual users.
User profile 5 million per farm This number represents the number of profiles which can be imported from a directory service, such as Active Directory, into the people profile store.
Security principal 2,000 per Web site The size of the access control list is limited to a few thousand security principals (users and groups in the Web site).

The following table lists the recommended guidelines for search objects.

Search object

Guidelines for acceptable performance Notes
Search indexes One per SSPMaximum of 20 per farm Office SharePoint Server 2007 supports one content index per SSP. Given that we recommend a maximum of 20 SSPs per farm, a maximum of 20 content indexes is supported. Note that an SSP can be associated with only one index server and one content index. However, an index server can be associated with multiple SSPs and have a content index for each SSP.
Indexed documents 50,000,000 per content index Office SharePoint Server 2007 supports 50 million documents per index server. This could be divided up into multiple content indexes based on the number of SSPs associated with an index server.
Content sources 500 per SSP* This is a hard limit enforced by the system.
Start Addresses 500 per content source* This is a hard limit enforced by the system.
Alerts 1,000,000 per SSP This is the tested limit.
Scopes 200 per site This is a recommended limit per site. We recommend a maximum of 100 scope rules per scope.
Display groups 25 per site These are used for a grouped display of scopes through the user interface.
Crawl rules 10,000 per SSP We recommend a maximum 10,000 crawl rules irrespective of type.
Keywords 15,000 per site We recommend a maximum of 10 Best Bets and five synonyms per keyword.
Crawled properties 500,000 per SSP These are properties that are discovered during a crawl.
Managed properties 100,000 per SSP These are properties used by the search system in queries. Crawled properties are mapped to managed properties. We recommend a maximum of 100 mappings per managed property.
Authoritative pages 200 per relevance level This is the maximum number of sites in each of the four relevance levels.
Results removal 100 This is the maximum recommended number of URLs that should be removed from the system in one operation.
Crawl logs 50,000,000 Number of individual log entries in the crawl log.

The following table lists the recommended guidelines for logical architecture objects.

Logical architecture object

Guidelines for acceptable performance Notes
Shared Services Provider (SSP) 3 per farm (20 per farm maximum)  
Zone 5* per farm The number of zones defined for a farm is hard coded to 5.
Web application 99 per SSP This limit includes the number of Web applications on child farms consuming resources on this SSP.
Internet Information Services (IIS) application pool 8 per Web server Maximum number is determined by hardware capabilities.
Site collection 50,000 per Web application  
Content database 100 per Web application  
Site collection 50,000 per database  

The following table lists the recommended guidelines for physical objects.

Physical object

Guidelines for acceptable performance Notes
Index servers 1 per SSP*  
Application servers running Excel Calculation Services No limit  
Query servers No limit Because 100 content databases are supported for each query server, the number of query servers required per farm is based on the number of content databases in the farm. For example, if there are 500 content databases in your farm, you will need at least 5 query servers.
Web server/database server ratio 8 Web servers per database server The scale out factor is dependent upon the mix of operations.
Web server/domain controller ratio 3 Web servers per domain controller Depending on how much authentication traffic is generated, your environment may support a greater number of Web servers per domain controller.

SPSiteDataQuery example

on Wednesday, December 2, 2009

I have been playing with the SPSiteDataQuery a fair bit recently and thought it would be interesting to post some of the results.

When using the SPSiteDataQuery to perform a search there are four main properties you are going to set which determine the results you will get. If you have seen my previous post (XML results using SPSiteDataQuery in SharePoint) you will have seen that they are Lists, Query, Webs and ViewFields.

If you read nothing else then remember this...If you make a mistake in the Webs or Lists properties, invalid XML or invalid attributes, the SPSiteDataQuery will fall back to it's default behavior and will not throw an error!! Knowing this can save a lot of time...ensure your properties are correctly formatted.

So, assuming the basic setup is

SPSiteDataQuery q = new SPSiteDataQuery();
q.Lists = "<Lists BaseType='1'/>";
q.Query = "<Where><Gt><FieldRef Name='ID' /><Value Type='Number'>0</Value></Gt></Where>";
q.Webs = "<Webs Scope='SiteCollection' />";
q.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='ID' />"';
q.RowLimit = 10;

Here are the changes you can make to achieve different result sets and tips as to why the query could be failing.


The Webs Property

There are basically three different values for this...

"<Webs Scope='SiteCollection' />" This will search the entire site collection no matter which web you use to execute the query.
"<Webs Scope='Recursive' />" This will search the web on which you execute the query and recurse through any child webs.

"" If you leave it blank then it will only search the web on which you execute the query. No child webs will be queried. This is important as I have read on several other sites that this is not possible with SPSiteDataQuery, but it is!!

I would also point out that that if you get anything wrong with this property SharePoint will not throw an error, it will just default to the blank behavior...It will only search the web on which you executed the query. This is an important point as "<Webs scope='Recursive' />"  or "<Webs Scope='recursive' />" (small 's' in Scope and small 'r' in recursive) look OK but are actually invalid and the query will default to only the current web.


The Lists Property

This defines what type of document libraries and lists WSS will search for your items. You can specify the exact type of list, the base type or even specific lists. Examples of the Lists property are...

"<Lists BaseType='1'/>" As above, this will search all lists which are based on a 'Document Library. This is useful if you only want to find documents. Other values for BaseType include...

0 - Generic list - This will search all lists and not document libraries.
1 - Document Library
3 - Discussion Forum
4 - Vote or Survey
5 - Issues list

(no, I don't know what happened to number 2!!)

I should also point out that the default is to search BaseType = '0' , and so if you do not set or make a mistake in the XML only lists will be searched.

"<Lists ServerTemplate='850'/>" This will limit the search to only a particular list template (850 is the Pages template in a publishing site). The number is fairly random and is defined in the list definition. I haven't needed to look at them as yet so I don't know a better way than looking in the definitions in the FEATURES folder for SharePoint. If you make a mistake with this property it will revert to the default.

Another options is Hidden, which determines if hidden lists or document libraries are searched. This an additional attribute and would be used like this...

"<Lists ServerTemplate='850' Hidden='TRUE'/>"

The MaxListLimit attribute specifies the total number of lists to search. You will receive an exception if the query exceeds the MaxListLimit. The default amount is 1000 and by setting this to 0 you can search everything. So the following would only search the first 50 lists...

"<Lists BaseType='1' MaxListsLimit='50'/>"

Another thing you can do with the Lists property is to query specific lists. This can be done by specifying the Guid of the list you want to search. An example would be...

"<Lists><List ID="129AB4CAE-12EF-9871-DE45-F34A180D3EAB5"/></Lists>"

You would obviously need to know the Guid of the lists you wish to query before creating this property.


The ViewFields property

The ViewFields property specifies the fields (columns), that will be returned in the query. This is very similar to SQL and you should ensure that you specify any fields that you may wish to use in you Where or OrderBy part of the query.

Things to point out here is that that you can specify the ID(Guid) of the property or the name of the property...this is the Internal Name, not the name you may see in the UI. For example the standard publishing field "Image Caption" would become "PublishingImageCaption" as that is it's internal name.

So, to add the "Image Caption" filed to the results we would need...

"<FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='PublishingImageCaption' />"

Another thing to remember is that not all lists or documents libraries contain the same fields. If you are not worried about a particular field and want the item returned whether the field (column) exists or not the you can set Nullable to true. So if we have some items which may not have an 'Image Caption' column then we could use...

"<FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='PublishingImageCaption' Nullable='TRUE'/>"

and this would still find those items without an 'Image Caption' column (field).


The Query Property

This property will allow you to bot limit and order you results. You can do both or just one, but it is similar to SQL in what you can do. There is a lot to this, but I will give a couple of samples...

Querying by date...

string sLastWeek = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today.AddDays(-1));
q.Query = "<Where><Gt><FieldRef Name='Created'><Value Type='DateTime'>" + sLastWeek + "</Value></Gt></Where>";

This will find items created within the last week. The <Gt> denotes 'Greater Than', you could also use <Gte>, <Lt> or <Eq>. These can be combined to create more complex queries.

q.Query = "<OrderBy><FieldRef Name='Title' Ascending='FALSE'></OrderBy>";

This will order the items descending by the title (Z-A).

q.Query = "<Where><Gt><FieldRef Name='Created'><Value Type='DateTime'>" + sLastWeek + "</Value></Gt></Where><OrderBy><FieldRef Name='Title' Ascending='FALSE'></OrderBy>";

This is a combination of the above...items created in the last week ordered Z-A.

Finally, make sure you set the RowLimit may not get any results otherwise!!

Custom PowerShell Commands

on Monday, November 23, 2009

To Create Custom Cmdlet, Your class can inherit from either PSCmdlet or Cmdlet class.

You could override below methods.
BeginProcessing-- Provides optional one-time, preprocessing functionality for the cmdlet.
ProcessRecord -- Provides record-by-record processing functionality for the cmdlet. It may be called any number of times or not at all, depending on the input of the cmdlet.

EndProcessing Provides optional one-time, post-processing functionality for the cmdlet.
StopProcessing Stops processing when the user stops the cmdlet asynchronously, such as by entering the key combination Ctrl+C.

To register this cmdlet you need to create a custom SnapIn by inheriting from PSSnapIn or CustomPSSnapin
You have to override below property.
Description: Supply short description of your Snap-in here.

Name: Supply name of your Snap-in here.
Vendor: Supply vendor information for your Snap-in here.
Cmdlets: This is where you provide collection of Cmdlets that need to be registered. I will discuss this in details.

Make sure you override the CmdLets property which should return all the Cmdlets that you want to register with PowerShell.
public override Collection Cmdlets

if (null == _cmdlets)
_cmdlets = new Collection();
_cmdlets.Add(new CmdletConfigurationEntry
("Get-Book", typeof(GetBookCommand), "AmazonPS.dll-Help.xml"));
return _cmdlets;

You need to mark the class with RunInstaller attribute

Then you have to install this snapin using installUtil 64 bit utility.
Then the snapin will be registered with the powershell.

Every time you open the powershell console. You have to run Add-PSSnapIn command.

Custom stsadm commnad in SharePoint 2007

The STSADM.EXE utility enables many administrative operations in Windows SharePoint Services that cannot be done with the Central Administration application. See the article Stsadm.exe command-line tool (Office SharePoint Server) in Microsoft TechNet for details. With Windows SharePoint Services 3.0 you can extend the functionality of the STSADM utility by adding your own operations and command line parameters with simple projects using any .NET language.

Creating such a project requires two major tasks.

  1. Create a class that implements the ISPStsadmCommand interface.

  2. Inform STSADM about your extension by registering the class and its assembly.

Create a class that implements ISPStsadmCommand

  1. Start a Class Library project in Visual Studio.

  2. Add using statements for Microsoft.SharePoint and Microsoft.SharePoint.StsAdmin.

  3. Use a namespace that follows the pattern CompanyName.TechnologyName.Feature.SubFeature. For example, AjaxInc.SharePoint.StsAdmin.CustomCommands. (See Names of Namespaces.)

  4. Use a class name that expresses the common denominator of the new STSADM operations that you will be creating; for example, "SortCommands".

  5. The class should inherit ISPStsadmCommand; with a declaration similar to the following.

    public class SortCommands : ISPStsAdminCommand

  6. Write the implementation of the GetHelpMessage method. See the example below.

  7. Write the implementation of the Run method. See the example below.

  8. Compile the project, using the namespace name as the name of the assembly.

  9. Deploy the assembly to the global assembly cache; for example C:\Windows\Assembly.

Register the new class and assembly

  1. Create a text file (UTF-8) named stsadmcommands.uniqueID.xml, where uniqueID is the name of your company or some other ID that ensures uniqueness on any server on which your extension of STSADM might be deployed. The XML declaration should read simply <?xml version="1.0" encoding="utf-8" ?>. The top-level element is <commands></commands>.

  2. For each custom STSADM operation you created—that is, each possible value of the command parameter of GetHelpMessage and Run—add a <command/> element (inside the <commands> element) to your stsadmcommands file with the following syntax. (See the following example.) Change the version and culture values as needed.

            class="fully_qualified_class_name, assembly_name, 
        <!-- other command elements, if any -->

  3. Replace command_name, fully_qualified_class_name, and assembly_name with the appropriate values. (Do not include the ".dll" extension on the assembly name.)

  4. Replace value with the public key token for your assembly which you obtain with these steps.

    1. Right-click your assembly in the global assembly cache and select Properties.

    2. On the General tab, copy the Public Key Token value.

    3. Paste it as the value for PublicKeyToken.

  5. Copy the stsadmcommands.uniqueID.xml file to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG.


The following example shows the *.cs file and, below that, the stsadmcommands.uniqueID.xml file for a custom STSADM operation, called enumfeatures, that will list the features at a site.

using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;

namespace MS.Samples.SharePoint
    public class SimpleCommandHandler : ISPStsadmCommand
        public string GetHelpMessage(string command)
            return "-url <full url to a site in SharePoint>";

        public int Run(string command, StringDictionary keyValues, out string output)
            command = command.ToLowerInvariant();

            switch (command)
                case "enumfeatures":
                    return this.EnumerateFeatures(keyValues, out output);

                    throw new InvalidOperationException();

        private int EnumerateFeatures(StringDictionary keyValues, out string output)
            if (!keyValues.ContainsKey("url"))
                throw new InvalidOperationException("The url parameter was not specified.");

            String url = keyValues["url"];

            SPFeatureCollection features = null;
            SPWeb web = null;

                SPSite site = new SPSite(url);

                web = site.OpenWeb();

                features = web.Features;
            catch (Exception e)
                throw new InvalidOperationException("Error retrieving url '" + url + "'.  Please check the format of your url, and ensure that the site exists.  Details: " + e.Message);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Features at '" + web.Url + "':\n");

            foreach (SPFeature feature in features)
                sb.AppendLine(feature.Definition.DisplayName + " (" + feature.DefinitionId + ")");
            output = sb.ToString();

            return 0;

Workaround for Double Hop issue

on Friday, November 13, 2009

public class UnImpersonator : IDisposable
        private static extern int RevertToSelf();

        private WindowsIdentity connectedUser = null;

        public UnImpersonator()
            connectedUser = WindowsIdentity.GetCurrent();

        void IDisposable.Dispose()

//Sample Usage 

protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                using (new UnImpersonator())
                    SqlConnection cn = new SqlConnection("Data Source=servername;Initial Catalog=Employee;Integrated Security=true;");
                    SqlCommand cm = new SqlCommand("select empid,empname from employee", cn);
                    ddlEmployee.DataSource = cm.ExecuteReader();
                    ddlEmployee.DataTextField = "empname";
                    ddlEmployee.DataValueField = "empid";


ListFieldIterator Control to render the sharepoint fields the way you want.

on Monday, November 9, 2009

This control renders each field in a list item with an appropriate control. A single line text field will be rendered as a text box while a lookup field will be rendered as combo box. This control resides in the Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll.

In its simplest way you can declare the control as follows:

<spuc:ListFieldIterator ID="TestListFieldIterator" runat="server"
                        ControlMode="Edit" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" />

This renders the first list item as follows:


You can also set the ControlMode attribut to Display which renders the list item as follows:


If the control mode is set to New, empty controls are shown.

The way a choice field is rendered depends on the definition of the column. If you opted for a dropdown list when you created the column, the field is rendered as a dropdown. If you opted for check boxes for multi selection, the field is rendered as a list of check boxes:


You can set different properties of the ListFieldIterator control:

  • ListId: This property must contain the id – which is a Guid - of the list you want to display.
  • ControlMode: Defines whether the controls are displayed in display mode, edit mode or new mode.
  • ExcludeFields: Specify the fields that don’t need to be rendered. Separate each field with ;#
  • Item: In code behind, you can retrieve the current list item by using this property.
  • ItemId: in code behind, you can retrieve the id of the current list item. But you can also decide which item to render by setting this attribute declaratively.
<spuc:ListFieldIterator ID="TestListFieldIterator" runat="server"
            ControlMode="Edit" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" ItemId="2" />

  • List: In code behind, you can retrieve the current list by using this property.
  • Template: you can set this property if you have deployed your own custom template to the 12\TEMPLATE\CONTROLTEMPLATES folder.

If you first add one or more controls to render fields from the list, and then add a ListFieldIterator control, it will automatically detect the fields already rendered and will not render them anymore. This can be useful if you want to change the order in which the controls must appear, or even more if you want to change the standard rendering of one or more fields (f.e. if you want to render one of the fields using Silverlight :) ).

<spuc:RichTextField ID="ContactTextField" runat="server"  
      ControlMode="Edit" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" FieldName="Description"/>

<spuc:ListFieldIterator ID="TestListFieldIterator" runat="server"
      ControlMode="Edit" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" />


This does not count for controls added AFTER the ListFieldIterator control.

Don’t forget to add a page directive in order to be able to use the control:

<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls"
             Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

You can use this control in web parts and application pages but in general it is used in custom list definitions. When creating a custom list definition, the columns of the list will be rendered in a standard DisplayForm, NewForm and EditForm. If this standard rendering behavior does not satisfy your needs you can develop your own custom control templates. They need to be deployed in the 12\TEMPLATE\CONTROLTEMPLATES directory and need to be referenced in Forms element of the schema.xml of the custom list definition:

    <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx"  WebPartZoneID="Main"/>
    <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" Template="CustomersForm" WebPartZoneID="Main"/>
    <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" Template="CustomersForm" WebPartZoneID="Main"/>

The Template attribute must contain the name of the template that is defined in an ascx control deployed in the 12\TEMPLATE\CONTROLTEMPLATES folder.

Some Important Links

on Friday, November 6, 2009

Add Custom Actions to UI

Default Custom Action Locations and IDs

Content Types

Hide Multiple Upload menu from a Document Library

on Tuesday, November 3, 2009

Use this javascript

<script language="JavaScript">
function HideNewIcons()
var doc = document.getElementsByTagName('ie:menuitem');
for(var i=0;i<doc.length;i++)

Add Custom Menus using CustomAction

Following are few examples of how to add a new menu to EditControlBlock,SiteSettings Gallary,SiteActions menu.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="">
    Title="MY ECB ITEM">
    <UrlAction Url="/_layouts/viewlsts.aspx"/>

   Title="MY ECB ITEM">
    <UrlAction Url="/_layouts/viewlsts.aspx"/>

   Title="MY ECB ITEM">
    <UrlAction Url="/_layouts/viewlsts.aspx"/>


Using ControlAssembly to Add New Menus to any GroupId

Check my other blogpost

Hiding Menus in SharePoint


  1. If you want to hide a menu on perticular page then use CEWP(Content Editor WebPart) and put javascript in Source Editor to hide the menu. The id of the menu can be found using ViewSource from the browser. For example to hide siteactions menu from a perticular page use below javascript. Note that to execute any javascript after onload you haveto use _spBodyOnLoadFunctionNames function.

    <script language="JavaScript">
    function HideNewIcons()
    var doc = document.getElementById('siteactiontd');"hidden";

  2. Modify default.master page and put it inside that file.

  3. Use a Feature.

    If you want to control the hiding of the menus by using a Feature so you can turn them on and off at will, and at the farm, application, site collection or site level the you have a little more work to do, but not too much.
    I will return here later and add a full step by step, but here's the code you will need:

    A SharePoint Delegate control:

    Add this to the bottom of your Master Page just before the </body> tag (The ControlId is up to you, but needs to match the Id used in the elements file):
    <SharePoint:DelegateControl runat="server" ControlId="MiscControls" AllowMultipleControls="true"/>

    A .Net User Control: HideMenus.ascx
    <%@ Control Language="C#" ClassName="HideMenus" %>

    <script language="JavaScript">
    var doc = document.getElementsByTagName('ie:menuitem');
    for (var i = 0; i < doc.length; i++){
    itm = doc(i)
    if ('MultipleUpload')!=null'OpenInExplorer')!=null)

    A feature file: Feature.xml
    Title="Hide Menus"
    Description="Sample feature to hide selected menus (MAX Technical Training demo)"
    xmlns=""> <ElementManifests>
    <ElementManifest Location="elements.xml" />

    An elements file: Elements.xml

    <Elements xmlns=""> <Control ControlSrc="~/_controltemplates/HideMenus.ascx" Sequence="100"

SharePoint CustomAction Identifiers

Id GroupId Location Sequence RegistrationType RegistrationId
ReportListActionsMenuCustomizer SiteActions Microsoft.SharePoint.StandardMenu      
Extend WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 10    
Unextend WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 20    
Delete WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 30    
ManagedPaths WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 60    
EmailSettings WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 70    
GeneralSettings WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 80    
ManageContentDatabases WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 90    
ManageWebAppFeatures WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 110    
ListWebApplications WebApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 120    
CreateSite SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 10    
DeleteSite SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 20    
SiteUse SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 40    
QuotaDefinition SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 50    
SiteQuota SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 60    
SiteOwners SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 70    
ListSiteCollections SiteManagement Microsoft.SharePoint.Administration.ApplicationManagement 80    
WebPartSecurity ApplicationSecurity Microsoft.SharePoint.Administration.ApplicationManagement 10    
SelfService ApplicationSecurity Microsoft.SharePoint.Administration.ApplicationManagement 20    
WebApplicationSecurity ApplicationSecurity Microsoft.SharePoint.Administration.ApplicationManagement 30    
ManagePolicy ApplicationSecurity Microsoft.SharePoint.Administration.ApplicationManagement 40    
ManageAuthenticationProviders ApplicationSecurity Microsoft.SharePoint.Administration.ApplicationManagement 50    
OfficialFile ExternalService Microsoft.SharePoint.Administration.ApplicationManagement 20    
HtmlViewer ExternalService Microsoft.SharePoint.Administration.ApplicationManagement 30    
DocConversion ExternalService Microsoft.SharePoint.Administration.ApplicationManagement 40    
WorkflowManagement WorkflowManagement Microsoft.SharePoint.Administration.ApplicationManagement 10    
FarmServers Topology Microsoft.SharePoint.Administration.Operations 10    
TopologyServices Topology Microsoft.SharePoint.Administration.Operations 20    
IncomingEmailServer Topology Microsoft.SharePoint.Administration.Operations 40    
ApproveDGs Topology Microsoft.SharePoint.Administration.Operations 50    
EmailConfiguration Topology Microsoft.SharePoint.Administration.Operations 40    
RunningJobs GlobalConfiguration Microsoft.SharePoint.Administration.Operations 10    
JobDefinitions GlobalConfiguration Microsoft.SharePoint.Administration.Operations 20    
AlternateAccessMappings GlobalConfiguration Microsoft.SharePoint.Administration.Operations 30    
ManageFarmFeatures GlobalConfiguration Microsoft.SharePoint.Administration.Operations 50    
Solutions GlobalConfiguration Microsoft.SharePoint.Administration.Operations 60    
ServiceAccount Security Microsoft.SharePoint.Administration.Operations 10    
Irm Security Microsoft.SharePoint.Administration.Operations 15    
Antivirus Security Microsoft.SharePoint.Administration.Operations 20    
BlockedFileTypes Security Microsoft.SharePoint.Administration.Operations 30    
AdministrationRoles Security Microsoft.SharePoint.Administration.Operations 40    
Backup BackupRestore Microsoft.SharePoint.Administration.Operations 10    
BackupHistory BackupRestore Microsoft.SharePoint.Administration.Operations 20    
Restore BackupRestore Microsoft.SharePoint.Administration.Operations 30    
BackupStatus BackupRestore Microsoft.SharePoint.Administration.Operations 40    
DiagnosticLogging LoggingAndReporting Microsoft.SharePoint.Administration.Operations 10    
UsageAnalysis LoggingAndReporting Microsoft.SharePoint.Administration.Operations 20    
DefaultDatabase DataConfiguration Microsoft.SharePoint.Administration.Operations 10    
DataRetrieval DataConfiguration Microsoft.SharePoint.Administration.Operations 20    
SiteUpgradeStatus Upgrade Microsoft.SharePoint.Administration.Operations 10    
FinalizeUpgrade Upgrade Microsoft.SharePoint.Administration.Operations 20    
CreateSite Links Microsoft.SharePoint.Administration.ApplicationCreated 10    
HomePage Links Microsoft.SharePoint.Administration.ApplicationCreated 20    
ManageAnalytics PortalAnalytics Office.Server.ServiceProvider.Administration 10    
PortalSiteUsage SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 30    
PortalWebUsage SiteAdministration Microsoft.SharePoint.SiteSettings 30    
AddBDCApp BDC Office.Server.ServiceProvider.Administration 101    
BDCApplications BDC Office.Server.ServiceProvider.Administration 102    
BDCEntities BDC Office.Server.ServiceProvider.Administration 103    
MNGPerms BDC Office.Server.ServiceProvider.Administration 104    
BDCProfPage BDC Office.Server.ServiceProvider.Administration 105    
6a9c4822-504f-42fa-b356-817f821f623b ActionsMenu Microsoft.SharePoint.StandardMenu   List 107
ExportEventToolbarButton   DisplayFormToolbar   List 106
ExportContactToolbarButton   DisplayFormToolbar   List 105
ChangeNameDescription General Microsoft.SharePoint.ContentTypeSettings 10    
ChangeOptionalSettings General Microsoft.SharePoint.ContentTypeSettings 20    
ChangeWorkflowSettings General Microsoft.SharePoint.ContentTypeSettings 30    
RemoveContentType General Microsoft.SharePoint.ContentTypeSettings 100    
AddField Fields Microsoft.SharePoint.ContentTypeSettings 10    
ReorderFields Fields Microsoft.SharePoint.ContentTypeSettings 20    
ChangeNameDescriptionGroup General Microsoft.SharePoint.ContentTypeTemplateSettings 10    
ChangeOptionalSettings General Microsoft.SharePoint.ContentTypeTemplateSettings 20    
ChangeWorkflowSettings General Microsoft.SharePoint.ContentTypeTemplateSettings 40    
RemoveContentType General Microsoft.SharePoint.ContentTypeTemplateSettings 100    
AddField Fields Microsoft.SharePoint.ContentTypeTemplateSettings 10    
  Fields Microsoft.SharePoint.ContentTypeTemplateSettings 15    
ReorderFields Fields Microsoft.SharePoint.ContentTypeTemplateSettings 20    
SiteActionsToolbar SiteActions Microsoft.SharePoint.StandardMenu 2001    
DeployManage ContentDeployment Microsoft.SharePoint.Administration.Operations 10    
DeploySettings ContentDeployment Microsoft.SharePoint.Administration.Operations 20    
DeployStatus ContentDeployment Microsoft.SharePoint.Administration.Operations 30    
ChangeDMSettings General Microsoft.SharePoint.ContentTypeSettings 100 ContentType 0x0101
ChangeDMSettings General Microsoft.SharePoint.ContentTypeTemplateSettings 100 ContentType 0x0101
ExcelServerSettings ExcelServer Office.Server.ServiceProvider.Administration 51    
ExcelServerFileTrustedLocations ExcelServer Office.Server.ServiceProvider.Administration 52    
ExcelServerTrustedDcls ExcelServer Office.Server.ServiceProvider.Administration 53    
ExcelServerSafeDataProviders ExcelServer Office.Server.ServiceProvider.Administration 54    
ExcelServerUserDefinedFunctions ExcelServer Office.Server.ServiceProvider.Administration 55    
ewrViewAsHtmlFromForm   DisplayFormToolbar 2500 FileType xlsx
ewrViewAsHtmlFromForm   DisplayFormToolbar 2500 FileType xlsb
ewrViewAsHtmlFromForm   EditFormToolbar 2500 FileType xlsx
ewrViewAsHtmlFromForm   EditFormToolbar 2500 FileType xlsb
ewrViewAsHtmlFromEcb   EditControlBlock 255 FileType xlsx
ewrViewAsHtmlFromEcb   EditControlBlock 255 FileType xlsb
ewrViewSnapshotInExcel   EditControlBlock 256 FileType xlsx
ewrViewSnapshotInExcel   EditControlBlock 256 FileType xlsb
FeaturePushdown Upgrade Microsoft.SharePoint.Administration.Operations 70    
HoldECBItem   EditControlBlock 100 ContentType 0x01
IPFSApplicationConfigurationManage IPFSApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 10    
IPFSApplicationConfigurationConfig IPFSApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 20    
IPFSApplicationConfigurationUpload IPFSApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 30    
IPFSApplicationConfigurationManageDataConnectionFiles IPFSApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 40    
IPFSApplicationConfigurationManageFormsServiceProxy IPFSApplicationConfiguration Microsoft.SharePoint.Administration.ApplicationManagement 50    
FormServerEcbItemOpenXsn   EditControlBlock 255 FileType xsn
FormServerEcbItemOpenInfoPathDocument   EditControlBlock 255 ProgId InfoPath.Document
FormServerEcbItemOpenInfoPathDocument2   EditControlBlock 255 ProgId InfoPath.Document.2
FormServerEcbItemOpenInfoPathDocument3   EditControlBlock 255 ProgId InfoPath.Document.3
FormServerEcbItemOpenInfoPathDocument4   EditControlBlock 255 ProgId InfoPath.Document.4
EnableAudienceTargeting GeneralSettings Microsoft.SharePoint.ListEdit 10    
SiteDirSettings SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 21    
MasterSiteDirectorySettings GlobalConfiguration Microsoft.SharePoint.Administration.Operations 21    
SiteDirectoryLinksCheckerJob GlobalConfiguration Microsoft.SharePoint.Administration.Operations 22    
Migration Upgrade Microsoft.SharePoint.Administration.Operations 50    
AreaNavigationSettings Customization Microsoft.SharePoint.SiteSettings 10    
SearchServiceManagement SearchGroup Microsoft.SharePoint.Administration.ApplicationManagement 10    
configureEnhacedSearch SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 1    
ManageScopes SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 2    
ManageSpecialTerms SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 3    
SearchSettings Search Office.Server.ServiceProvider.Administration 10    
SspSearchAnalytics Search Office.Server.ServiceProvider.Administration 30    
ManageSSP OfficeServerCoreServices Microsoft.SharePoint.Administration.ApplicationManagement 10    
ManageInterFarmServices OfficeServerCoreServices Microsoft.SharePoint.Administration.ApplicationManagement 20    
CheckFarmServices OfficeServerCoreServices Microsoft.SharePoint.Administration.ApplicationManagement 30    
SessionState OfficeServerCoreServices Microsoft.SharePoint.Administration.ApplicationManagement 40    
QuiesceFarm GlobalConfiguration Microsoft.SharePoint.Administration.Operations 50    
LicenseConversion Upgrade Microsoft.SharePoint.Administration.Operations 80    
ChangeCTConverterSettings General Microsoft.SharePoint.ContentTypeTemplateSettings 100    
SchedulingLink GeneralSettings Microsoft.SharePoint.ListEdit.DocumentLibrary 10    
AreaTemplateSettings Customization Microsoft.SharePoint.SiteSettings 10    
CmsMasterPageCatalog Galleries Microsoft.SharePoint.SiteSettings 100    
AreaWelcomePage Customization Microsoft.SharePoint.SiteSettings 10    
AreaCacheSettings SiteAdministration Microsoft.SharePoint.SiteSettings 200    
SiteCacheSettings SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 200    
SiteCacheProfiles SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 200    
ObjectCacheSettings SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 200    
CreatePublishingPage WebPages Microsoft.SharePoint.Create 100    
PublishingSiteActionsMenuCustomizer SiteActions Microsoft.SharePoint.StandardMenu      
AreaChromeSettings Customization Microsoft.SharePoint.SiteSettings 10    
SiteManagement SiteAdministration Microsoft.SharePoint.SiteSettings 210    
NoCrawlSettingsPage Customization Microsoft.SharePoint.SiteSettings 210    
SiteManagerLogs SiteAdministration Microsoft.SharePoint.SiteSettings 250    
VariationSettings SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 210    
VariationLabels SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 220    
VariationLogs SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 230    
TranslatableSettingsPage SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 230    
PolicyTemplate SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 90    
ListPolicySettings Permissions Microsoft.SharePoint.ListEdit 100    
ContentTypePolicySettings General Microsoft.SharePoint.ContentTypeSettings 100    
ContentTypeTemplatePolicySettings General Microsoft.SharePoint.ContentTypeTemplateSettings 100    
AuditSettings SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 70    
PolicyRptConfiguration LoggingAndReporting Microsoft.SharePoint.Administration.Operations 40    
PolicyFeaturesConfig Security Microsoft.SharePoint.Administration.Operations 50    
RelLinksSettings SiteAdministration Microsoft.SharePoint.SiteSettings 100    
AuditReporting SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 71    
WorkflowReporting LeftNavBarLinks Microsoft.SharePoint.Workflows 100    
PeopleAndGroups UsersAndPermissions Microsoft.SharePoint.SiteSettings 10    
SiteCollectionAdministrators UsersAndPermissions Microsoft.SharePoint.SiteSettings 20    
User UsersAndPermissions Microsoft.SharePoint.SiteSettings 40    
ProjectSettings Customization Microsoft.SharePoint.SiteSettings 10    
NavOptions Customization Microsoft.SharePoint.SiteSettings 20    
Theme Customization Microsoft.SharePoint.SiteSettings 30    
TopNav Customization Microsoft.SharePoint.SiteSettings 40    
QuickLaunch Customization Microsoft.SharePoint.SiteSettings 50    
SaveAsTemplate Customization Microsoft.SharePoint.SiteSettings 60    
ReGhost Customization Microsoft.SharePoint.SiteSettings 80    
MasterPageCatalog Galleries Microsoft.SharePoint.SiteSettings 10    
ManageCType Galleries Microsoft.SharePoint.SiteSettings 20    
ManageField Galleries Microsoft.SharePoint.SiteSettings 30    
SiteTemplates Galleries Microsoft.SharePoint.SiteSettings 40    
ListTemplates Galleries Microsoft.SharePoint.SiteSettings 50    
WebParts Galleries Microsoft.SharePoint.SiteSettings 60    
Workflows Galleries Microsoft.SharePoint.SiteSettings 70    
RegionalSettings SiteAdministration Microsoft.SharePoint.SiteSettings 10    
LibrariesAndLists SiteAdministration Microsoft.SharePoint.SiteSettings 20    
WebUsage SiteAdministration Microsoft.SharePoint.SiteSettings 30    
UserAlerts SiteAdministration Microsoft.SharePoint.SiteSettings 40    
RSS SiteAdministration Microsoft.SharePoint.SiteSettings 60    
SrchVis SiteAdministration Microsoft.SharePoint.SiteSettings 65    
ManageSubWebs SiteAdministration Microsoft.SharePoint.SiteSettings 70    
ManageSiteFeatures SiteAdministration Microsoft.SharePoint.SiteSettings 80    
DeleteWeb SiteAdministration Microsoft.SharePoint.SiteSettings 90    
DeletedItems SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 10    
SiteCollectionUsage SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 30    
Storage SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 40    
ManageSiteCollectionFeatures SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 45    
Hierarchy SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 50    
Portal SiteCollectionAdmin Microsoft.SharePoint.SiteSettings 60    
SkuUpgrade Upgrade Microsoft.SharePoint.Administration.Operations 60    
CmsCheckSpellingEditForm   EditFormToolbar 10 ContentType 0x01
CmsCheckSpellingNewForm   NewFormToolbar 10 ContentType 0x01
SingleSignon Security Microsoft.SharePoint.Administration.Operations 50    
ManageProf UAP Office.Server.ServiceProvider.Administration 11    
ManagePriv UAP Office.Server.ServiceProvider.Administration 13    
ManagePS UAP Office.Server.ServiceProvider.Administration 14    
TrustedPersLinks UAP Office.Server.ServiceProvider.Administration 15    
ManagePubLinks UAP Office.Server.ServiceProvider.Administration 16    
ManagePersLinks UAP Office.Server.ServiceProvider.Administration 17    
ManagePermissions UAP Office.Server.ServiceProvider.Administration 18    
ManageAud AUD Office.Server.ServiceProvider.Administration 21