Monday, 23 May 2011

Sending the listitem to recycle bin using object model


SpListItem.delete() delets the item permanently while if you want to send the item to recycle bin and want the option for user to recover the item 

use the follwing code :

SPSite spsite = new SPSite("http://MyWebApplication");

SPWeb spweb = spsite.OpenWeb();

SPList splist=spweb.Lists["MyList"];

SPListItem spListItem = splist.Items.GetItemById(2);

//this method will send the item to recycle bin and user can restore the item later

spListItem.Recycle();

Friday, 20 May 2011

Enabling Usage Analysis in SharePoint 2007


To view Windows SharePoint Services usage logging in SharePoint 2007, you must first turn on Usage Analysis Processing on farm level and then SSP level.

To turn on the reporting on farm level performs the following steps:
·          On the Central Administration page, click Operations.
·          On the Operations page, under Logging and Reporting, click Usage Analysis Processing.
·          In the Logging Settings section, click to select the Enable logging check box.
·          In the Log file location box, type the location where you want to store the log file.

The default location for the log file is \Program Files\Common Files\Microsoft Shared\Web Server Extension\12\Logs.
·          In the Number of log files to create box, type a number between 1 and 30. 

In general, use a number that is one to three times the number of database servers in your server farm, with a maximum number of 30 log files.
·          In the Processing Settings section, click to select the Enable usage analysis processing check box.
·          Under Run processing between these times daily, specify the range of times to start the usage analysis log processing.

In the
 Start box, select the earliest time of day to start running log processing. In theEnd box, select the latest time to start running log processing.
·          Click OK.
Enable Advanced Usage Analysis Reporting at SSP level
  • On the Central Administration page, click Shared Services Administration, and then click the default Shared Services Provider.
  • On the Shared Services Provider home page, under Office SharePoint Usage Reporting, click Usage reporting.
  • On the Configure Advanced Usage Analysis Processing page, under Processing Settings, click the Enable advanced usage analysis processing check box.
  • In the Search Query Logging section, click the Enable search query logging check box.
  • Click OK.


    Thursday, 19 May 2011

    User Id from User Information List (Hidden Web Site List in SharPoint)

    Every user that we add to our web site have its own ID,

    This ID is numeric value. The source of this IDis the hidden list (User Information List) of every web site in SharePoint..

    This list can be accessed by the link " /_catalogs/users/simple.aspx" from the every SharePoint web site.

    This display the list of web site user that are added to the site.

    Simple.aspx page contains a data view webpart that display the list of website users.

    To get the data from this list use the following code :


    SPList spList = SPContext.Current.Web.SiteUserInfoList;


    Using this the basic information about the user can be accessed.

    Example:  To get the user's profile image, use the following code:


    SPSite spsite = new SPSite("http://MyWebApplication");
    SPWeb spweb = spsite.OpenWeb();
    SPList splist=spweb.SiteUserInfoList;
    SPListItem userInfo = splist.Items.GetItemById(SPContext.Current.Web.CurrentUser.ID);
    string pictureURL = Convert.ToString(userItem["Picture"]);





    Tuesday, 17 May 2011

    Creating User profile in SharePoint 2007 using object in form authentication


    string accountName = string.Empty;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    // Create the user profile object
    Microsoft.Office.Server.UserProfiles.UserProfile currentUserProfile = null;
    // Creating spsite object
    SPSite sc = new SPSite("http://webserverurl");
    // Get the server context
    Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(sc);
    // Get the user profile manager object               
    Microsoft.Office.Server.UserProfiles.UserProfileManager profileManager1 = new Microsoft.Office.Server.UserProfiles.UserProfileManager(context);
    // Check if the user exists
    if (!profileManager1.UserExists(accountName))
    {
    // Create user profile
    currentUserProfile = profileManager1.CreateUserProfile(accountName);
    }
    });

    Adding user to splist item as contributor using object model



    We have the cusotm permission in our list, so when an item is created in the list we have to add the specific user to the list item based on the business logic that was stored in the other list.

    Following code we have used to add the user to an item as a contribute role:

    // open the spsite object
    SPSite spSite = new SPSite("http://webapplicationurl");

    // open the spweb object
    SPWeb spWeb = spSite.OpenWeb();

    // Get the splist item object
    SPListItem spItem = spWeb.Lists["MyList"].GetItemById(5);

    // Create roll assignment object
    roleAssignment = new SPRoleAssignment(spUser);

    // Assign the roll defination
    roleDefinition = spWeb.RoleDefinitions["Contribute"];

    // Add the defination to rollassignment
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

    // add the user roll to list item
    spItem.RoleAssignments.Add(roleAssignment);

    //update the list item
    spItem.Update();

    Creating Custom Property in share point 2007 using object model

    To create the custom property in share point 2007 using object model use the following code .

    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(siteId))
                        {
                                elevatedSite.AllowUnsafeUpdates = true;

                                elevatedSite.RootWeb.AllowUnsafeUpdates = true;

    Microsoft.Office.Server.ServerContext serverContext = Microsoft.Office.Server.ServerContext.GetContext(elevatedSite);
                                Microsoft.Office.Server.UserProfiles.UserProfileManager profileManager = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serverContext);
                                Microsoft.Office.Server.UserProfiles.UserProfileConfigManager profileConfigManager = new Microsoft.Office.Server.UserProfiles.UserProfileConfigManager(serverContext);
                                Microsoft.Office.Server.UserProfiles.PropertyCollection propertyCollection = profileConfigManager.GetProperties();


    Microsoft.Office.Server.UserProfiles.Property customProperty = propertyCollection.Create(false);
    // Set the property seetings
                    customProperty.Name = propertyName;
                    customProperty.DisplayName = displayName;
                    customProperty.Type = "string";
                    customProperty.PrivacyPolicy = Microsoft.Office.Server.UserProfiles.PrivacyPolicy.OptIn;
                    customProperty.DefaultPrivacy = Microsoft.Office.Server.UserProfiles.Privacy.Private;
                    customProperty.Description = propertyName;
                    customProperty.IsSearchable = false;
                    customProperty.IsVisibleOnEditor = false;
                    customProperty.IsAlias = false;
                    customProperty.Length = 200;
                    customProperty.IsUserEditable = true;
                    propertyCollection.Add(customProperty);
    }
    }
                    });

    Deploying an sharepoint event handler

    We Can deploy a Event handler two method :

    Using object model :
    To deploy the event reciever using object model put the below code in console application and execute the console applicaton :


    SPSite spSite = new SPSite("http://webapplicationurl");
                        SPWeb spWeb = spSite.OpenWeb();
                        objSPList = spWeb.Lists["ListName"];
                        objSPList.EventReceivers.Add(SPEventReceiverType.ItemAdded, "AsseblyFullyQualifiedName", "ClassName");
                        objSPList.Update();



    Using Features :

    To deploy our event receiver as a feature, Create a Feature Folder ("My Custom Receiver")in the Feature folder in  (Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURE

    Put the below feature.xml and Elements.xml in "My Custom Receiver" folder. Deploy the written event Receiver in GAC.

    Feature.xml :


      <Feature Scope="Web" Title="Event Handler Deployment"
       Description = "My Custom Event handler"
       Id="2366B8CB-1C6A-469c-9119-717A6vu68358"
       xmlns="http://schemas.microsoft.com/sharepoint/">
      <ElementManifests>
        <ElementManifest Location="Elements.xml"/>
      </ElementManifests>
    </Feature>


    Elements.xml :


    </Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        <Receivers ListTemplateId="101">
          <Receiver>
            <Name>ItemAddedEvent</Name>
            <Type>ItemAdded</Type>
            <SequenceNumber>10000</SequenceNumber>
            <Assembly>EventAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=23d656782aea270a</Assembly>
            <Class>EventAssemblyName.ClassName</Class>
            <Data></Data>
            <Filter></Filter>
    </Receiver>
        </Receivers>
    </Elements>

    Receivers node parameters details :
    • Name – unique name for the receiver – you can set it upon your wish
    • Type – Type of event like adding/added/deleting/updating etc.
    • SequenceNumber – integer which determines in which order the event will be executed
    • Assembly – Name of the assembly deployed in the gac
    • Class – class which has the event handler implementation

    Install and deploy the feature using below command from command prompt:

    stsadm -o installfeature -filename "My Custom Receiver\Feature.xml"
    stsadm -o activatefeature -filename "My Custom Receiver\Feature.xml" -url http://webapplicationurl
    iisreset

    Friday, 13 May 2011

    copy splist item attachment to another splistitem

    In my recent project there was requirement where i have to attach an attachement from one item to another item.
    I have written the follwoing code snipet to do the same :


    //Initialize the source and target item
    SPListItem sListItem = null, tListItem = null;

    //get the folder with the attachments for the source list item
    SPFolder sListItemAttachmentsFolder = sListItem.Web.Folders["Lists"].SubFolders[sListItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sListItem.ID.ToString()];

    //Loop over the attachments, and add them to the target list item
    foreach (SPFile file in sListItemAttachmentsFolder.Files)
    {
    byte[] sFile = file.OpenBinary();
    tListItem.Attachments.AddNow(file.Name, sFile);
    }



    //Update the target listitem to save the changes
    tListItem.Update();

    Adding / Appending spuser in people picker using object model

    We were having the requirement to add a user to existing set of user in people type of fields using the object model. 

    Following code we have used to add/append a user with existing user in people type fields.

    bool bUserExists = false;
    SPWeb web = SPContext.Current.Web;
    SPFieldUserValueCollection spFieldUserValue = null;
    web.AllowUnsafeUpdates = true;
    //Get the list item
    SPListItem objListItem = web.Lists["Mylist"].GetItemById(1);

    // Check if there is any value in MyExitingUser of the splist item field
    if (objListItem["MyExitingUser"] != null)
    {
    spFieldUserValue= new SPFieldUserValueCollection(web, Convert.ToString(objListItem["MyExitingUser"]));
    }
    else
    {
    spFieldUserValue = new SPFieldUserValueCollection();
    }

    // Check if the user we are going to add already exist or not
    foreach (SPFieldUserValue fieldVale in spFieldUserValue)
    {
    if (fieldVale.LookupValue == sUserName)
    bUserExists = true;
    }
    // If user does't exist then add the existing user group.
    if (!bUserExists)
    {
          //Get the spuser object for the current user
          SPUser objUserContributor = web.AllUsers[sUserName];

          // Add create the SPFieldUserValue object for the current user
          SPFieldUserValue objContributor = new SPFieldUserValue(web, objUserContributor.ID, objUserContributor.LoginName);

    // Add to the people collection of existing user
          spFieldUserValue.Add(objContributor);

          // Set the splist item with the updated values
          objListItem["MyExitingUser"] = spFieldUserValue.ToString();

          // Update the list item
          objListItem.Update();

          web.AllowUnsafeUpdates = false;
    }t