How to use explicit impersonation in SharePoint 2007

Tuesday, 28 July 2009 15:38 by myro

There are different ways for using impersonation in SharePoint 2007. Probably the most common way is calling the RunWithElevatedPrivileges method defined into the SPSecurity class. If you don't know how to impersonate using this method, you should visit the msdn reference.

But sometimes this approach doesn't work, infact this method is useless if you are trying to impersonate when writing event handlers. An another possible solution, is using the Explicit Impersonation in SharePoint 2007. This method will impersonate through user's SPUserToken class.

Here's the code snippet for impersonating a different user:

SPUser user = SPContext.Current.Web.AllUsers[@"DOMAIN\LOGINNAME"];
SPUserToken token = user.UserToken;
using (SPSite site = new SPSite(SPContext.Current.Site.Url,token))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["YourList"];
        list.Items[0]["Title"] = "Your new title";
        list.Items[0].Update();
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   SharePoint 2007
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed

SharePoint 2007 hidden fields in SPList and SPDocumentLibrary

Monday, 27 July 2009 16:42 by myro

Developing against the SharePoint's 2007 lists (SPList) or document libraries (SPDocumentLibrary), allow you see item's proprieties hidden into fields that are unaccessible from the user interface (your browser). This post will simply list all the fields that are accessible from code (hidden or not). and can be a useful reference when you need to obtain some more information from your items. If you want to easly see all the fields that are hidden by yourself, you need to lunch this simple console application in debug mode and set a breakpoint just after the SPListItem istance:

private static void ReadSpListItemsProperties(string listUrl)
{
    using (SPSite site = new SPSite(listUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.GetListFromUrl(listUrl);
            if (list.Items.Count == 0)
            {
                return;
            }
            SPListItem item = list.Items[0];

        } // set your breakpoint here!
    }
}

Now using the quickwatch tool in Visual Studio you can see all the hidden fields:

A basic document library has at least 66 fields in MOSS and a SharePoint's list has 48. It's more than you have expected right? 
Ok, here's the list:

All Fieds into Moss Document Library:

  • ["ContentType"]
  • ["xd_Signature"]
  • ["_UIVersion"]
  • ["RepairDocument"]
  • ["GUID"]
  • ["ScopeId"]
  • ["SelectFilename"]
  • ["Modified"]
  • ["PermMask"]
  • ["InstanceID"]
  • ["_EditMenuTableEnd"]
  • ["LinkCheckedOutTitle"]
  • ["CheckedOutUserId"]
  • ["Created_x0020_By"]
  • ["FSObjType"]
  • ["owshiddenversion"]
  • ["WorkflowVersion"]
  • ["CheckoutUser"]
  • ["_UIVersionString"]
  • ["ProgId"]
  • ["HTML_x0020_File_x0020_Type"]
  • ["Title"]
  • ["IsCheckedoutToLocal"]
  • ["ParentLeafName"]
  • ["File_x0020_Type"]
  • ["ID"]
  • ["TemplateUrl"]
  • ["ParentVersionString"]
  • ["File_x0020_Size"]
  • ["FileSizeDisplay"]
  • ["_SharedFileIndex"]
  • ["VirusStatus"]
  • ["_ModerationComments"]
  • ["_IsCurrentVersion"]
  • ["FileDirRef"]
  • ["Combine"]
  • ["_ModerationStatus"]  
  • ["ServerUrl"]
  • ["_EditMenuTableStart"]
  • ["LinkFilenameNoMenu"]
  • ["_Level"]
  • ["Created_x0020_Date"]
  • ["LinkFilename"]
  • ["FileLeafRef"]
  • ["_CheckinComment"]
  • ["Order"]
  • ["Last_x0020_Modified"]
  • ["MetaInfo"]
  • ["xd_ProgID"]
  • ["Editor"]
  • ["_HasCopyDestinations"]
  • ["UniqueId"]
  • ["EncodedAbsUrl"]
  • ["CheckedOutTitle"]
  • ["WorkflowInstanceID"]
  • ["DocIcon"]
  • ["FileRef"]
  • ["_SourceUrl"]
  • ["_CopySource"]
  • ["Created"]
  • ["SelectTitle"]
  • ["Modified_x0020_By"]
  • ["Edit"]
  • ["BaseName"]
  • ["ContentTypeId"]
  • ["Author"]
  • All Fieds into Moss List:

  • ["ContentType"]
  • ["ID"]
  • ["Attachments"]
  • ["_UIVersion"]
  • ["GUID"]
  • ["ScopeId"]
  • ["Modified"]
  • ["PermMask"]
  • ["InstanceID"]
  • ["owshiddenversion"]
  • ["ProgId"]
  • ["WorkflowVersion"]
  • ["FSObjType"]
  • ["LinkFilename"]
  • ["_Level"]
  • ["_UIVersionString"]
  • ["EncodedAbsUrl"]
  • ["HTML_x0020_File_x0020_Type"]
  • ["Title"]
  • ["LinkTitleNoMenu"]
  • ["File_x0020_Type"]
  • ["ServerUrl"]
  • ["_ModerationComments"]
  • ["_IsCurrentVersion"]
  •  
  • ["_ModerationStatus"]
  • ["FileDirRef"]
  • ["Last_x0020_Modified"]
  • ["_EditMenuTableStart"]
  • ["LinkFilenameNoMenu"]
  • ["Editor"]
  • ["Created_x0020_Date"]
  • ["Order"]
  • ["FileLeafRef"]
  • ["DocIcon"]
  • ["MetaInfo"]
  • ["_HasCopyDestinations"]
  • ["UniqueId"]
  • ["WorkflowInstanceID"]
  • ["FileRef"]
  • ["_CopySource"]
  • ["Created"]
  • ["LinkTitle"]
  • ["SelectTitle"]
  • ["Edit"]
  • ["BaseName"]
  • ["_EditMenuTableEnd"]
  • ["ContentTypeId"]
  • ["Author"]
  • Immagine that you need to overwrite an item's sensitive informations such as who modified it or create it.
    A simple implementation could be:

    item["Author"] = yourAuthor;
    item["Created"] = yourDate;
    item["Editor"] = yourEditor;
    item["Modified"] = yourDate2;
    item.UpdateOverwriteVersion();

    Now that you learned how to perform a dirty update in Moss, you can try to mess around a little more with your SharePoint 2007.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Tags:   ,
    Categories:   SharePoint 2007
    Actions:   Bookmark and Share | Permalink | Comments (3) | Comment RSSRSS comment feed

    How to delete Content Type in SharePoint 2007 when you receive "The Content type is in use" error

    Thursday, 16 July 2009 17:19 by myro

    A common problem in SharePoint 2007 is when you need to delete a Content Type from a List or from a Document Library: you receive the error 'The Content type is in use'. Ok, you understand that there is still a List or a Document Library that is using it and even if you remove all the associations from all your lists if you try to delete it you could receive again the same error.... 'The Content type is in use'
    What's going on?
    If you look at the msdn you will read that:

    A content type cannot be deleted from a list if that list contains items of that content type.

    So the problem is that you still have items in your List that are associated to that Content Type. A fast workaround is to select all the items, send them to the site's recycle bin, remove the Content Type and finally restore all those items from the bin back to the List.

    msdn reference: http://msdn.microsoft.com/en-us/library/bb802962.aspx

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Tags:  
    Categories:   SharePoint 2007
    Actions:   Bookmark and Share | Permalink | Comments (2) | Comment RSSRSS comment feed

    How to use SPFieldLookup to get the selected SPListItem reference in SharePoint 2007

    Wednesday, 15 July 2009 17:13 by myro

    A common task during SharePoint's developing is to read from a SharePoint List a item's (SPListItem) value defined in column. It's not a big deal if you information is stored into a text field:


    SPList list = SPContext.Current.Web.Lists["List with lookup column"];

    foreach (SPListItem item in list.Items)
    {
        string information =  (string)item["YourColum"]
    }

    This is an easy and fast approch that works well if your column (SPField) is defined as text (SPFieldText), but what happens if you try to read from a different column type, such as from a LookUp Field? What you will get is a rappresentation of that value with this syntax:  ID;#TITLE .

    Whould it be much better to obtain directly the referenced SPListItem, so you can do whatever you need? Learn how efficently read values from SPFields from this code snippet which is focused to read from lookup fields, but this kind of implementation can be applied on every SPField type:


    SPList list = SPContext.Current.Web.Lists["List with lookup column"];

    foreach (SPListItem item in list.Items)
    {
      

        if (item.Fields["YourLookUpField"] is SPFieldLookup)
        {
            SPFieldLookup field = (SPFieldLookup)item.Fields[YourLookUpField];
            Guid webId = field.LookupWebId;
            Guid listId = new Guid(field.LookupList);
            int itemId = Int32.Parse(item[YourLookUpField].ToString().Split(';')[0]);
            SPListItem lookupItem = null;
            // here is you reference...
            lookupItem = SPContext.Current.Site.OpenWeb(webId).Lists[listId].GetItemById(itemId);
            // do something...for this sample i will get the item's  title
            string title = lookupItem.Title;
        }
    }

    So remember that when you need to read values from SpListItems, first check your SPField's type,  the cast it and then obtain the value you need.

    Currently rated 3.0 by 1 people

    • Currently 3/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Tags:   ,
    Categories:   SharePoint 2007
    Actions:   Bookmark and Share | Permalink | Comments (2) | Comment RSSRSS comment feed

    Using PickerTreeDialog in SharePoint 2007 pages with postback support

    Tuesday, 14 July 2009 11:07 by myro

    In this post you will learn how to implement a Picker Tree Dialog into your custom SharePoint 2007's pages and handle the postbacks generated when and user press the OK or the Cancel button. Searching on the web i've found differents implementations, but none of them cares about postbacks that are generated once you submit the form.
    If you didn't recognize what is a SharePoint's Picker Tree Dialog, look at this image:

    This control comes only if yopu are using SharePoint's Moss (standard and enterprise) versions and is not avaible in Windows SharePoint Services (WSS). It allows you to browse the entire SiteCollection and to select Sites, Lists and Document Libraries. Now you will learn how to retreive the selected items on server side using postbacks.

    I will show how to use this control into a SharePoint's custom Page that is located under the /_layouts/ directory, but it won't be complicated to implement this tecnique into a SharePoint's WebPart. Let's start....

    First you need to import a directive for SharePoint's dll into the ASPX markup page:

    <%@ Import namespace="Microsoft.SharePoint" %>

    and then add a reference to the PickerTreeDialog.js:

    <script type="text/javascript" language="javascript"
          
     src='<%= String.Format("/_layouts/{0}/PickerTreeDialog.js", SPContext.Current.Web.Locale.LCID.ToString()) %>'>
    </
    script>

    As you see you can see, I use a localized PickerTreeDialog, so it doesn't matter if your web site is in english or in a different culture.
    Next you need to add 2 javascript funcions that will care on showing up the Picker Tree Dialog and handling the Postbacks caused from pressing the OK button.
    Add this 2 JavaScript functions:

    <script type="text/javascript">

        function performPostBack(param) {
            if (param.toString().indexOf("DELETE") == 0) {
                if (confirm('Are you sure you want to delete this configuration?')) {
                    __doPostBack("<%= this.UniqueID %>", param);
                }
            }
            else {
                __doPostBack("<%= this.UniqueID %>", param);
            }
        }
       
      
        function launchPicker()
        {
           var url = "<%= SPContext.Current.Web.Url %>";
           var callback = function(arr)
           {
                if (arr == null || arr == undefined) {
                return;
                }
               var strparam = "PICKER,";
               for (indx in arr) {
                   strparam = strparam + arr[indx] + "§";
               }
                performPostBack(strparam);
            }

            LaunchPickerTreeDialog('CbqPickerSelectListTitle',
            'CbqPickerSelectListTitle', '', "",
             url, null, "", "", "/_layouts/images/generic.png", 0, callback);
        }

    </script>  

    The performPostBack() funcion will perform the Page's postback and launchPicker() function will pop up the control.
    To invoke the launchPicker() function, let's use a classic Asp.Net Button control:

    <asp:Button runat="server" CausesValidation="false" Text="..." OnClientClick="javascript:launchPicker();" />


    Now we need to implement the IPostBackEventHandler interface into the page's code Behind, to be able to capture postback's paramters from server side.

    Use the interface:

     public partial class YourPageName : System.Web.UI.Page, IPostBackEventHandler

    and implement the required method:

     public void RaisePostBackEvent(string eventArgument)
    {
        string[] events = eventArgument.Split(',');

        switch (events[0].Trim())
        {
         
           case "PICKER":
           PickerParameterParser(events[1]);
           break;
        }

    }

    private void PickerParameterParser(string pickerParams)
    {
       string[] param = pickerParams.Split(new char[] { '§' }, StringSplitOptions.RemoveEmptyEntries);        
    }

    Now, everytime the Ok button is pressed your PickerParameterParser() method will be invoked and the param[]  array will contain all the PickerTreeDialog parameters that are passed using the callback.

    Lets's see what happens everytime you select a different item from the Picker Tree Dialog:

    The Root site has been selected:

    param[0] = Area:?Type:Guid:
    param[1] = SiteRelativeUrl

    example:

    param[0] = Area:?SPWeb:33cc66fc-c251-47a1-984a-3bb7e751a6cb:
    param[1] = /

    A sub site has been selected:

    param[0] = Type:Guid:
    param[1] = SiteRelativeUrl

    example:

    param[0] = SPWeb:fd00f025-b7df-4eae-83c0-7aec11c9929c:
    param[1] = /YourSubSiteName

    A List has been selected:

    param[0] = Type:Guid:ParentType:ParentGuid
    param[1] = SiteRelativeUrl
    param[2] = ListName

    example:

    param[0] = SPList:a525db03-551b-44c4-9450-e7add15e510c?SPWeb:33cc66fc-c251-47a1-984a-3bb7e751a6cb:
    param[1] = /
    param[2] = YourListName

    It's not hard to understand that a possibile PickerParameterParser implementation could be something like:

    private void PickerParameterParser (string pickerParams)
    {
        string[] param = pickerParams.Split(new char[] { '§' }, StringSplitOptions.RemoveEmptyEntries);
        if (param[0].StartsWith("Area"))
        {
            // add your code to handle when a rootsite is selected
        }
        else if (param[0].StartsWith("SPWeb"))
        {
            // add your code to handle when a SharePoint site is selected
        }
        else if (param[0].StartsWith("SPList"))
        {
            // add your code to handle when a SHarePoint List or Document library
            // is selected
            // Here's an example: let's write into a TextBox, the selected list's url:
            //texBoxListUrl.Text = String.Concat(SPContext.Current.Site.Url,
            //                SPContext.Current.Site.OpenWeb(param[1]).Lists[param[2]].DefaultViewUrl); 
        }
       
    }

    Have fun...

    Currently rated 5.0 by 1 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Tags:   ,
    Categories:   SharePoint 2007
    Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed