Thursday, June 2, 2011

Check if a folder exists in a SharePoint List


Below code is to check if the folder already exists in a SharePoint List.


 private void CreateFolderInList(string folderName, string listName, SPListCollection listCollection)
        {
            try
            {
                //Creating folder in "Sites" Lists
                SPList list = listCollection[listName];

                //Check if the Folder is already available in the list
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq><Eq><FieldRef Name=’FSObjType’/><Value Type=’Lookup’>1</Value></Eq></And></Where>";

  query.ViewAttributes = "Scope=\"RecursiveAll\""


                //Retrieve the items based on Query
                SPListItemCollection items = list.GetItems(query);

  //Item count is "0" if the folder does not exist
                if (items.Count == 0)
                {
                    folderItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);
                    folderItem["Title"] = folderName;
                    folderItem.Update();
                    //return folderItem.Url;
                }
            }
            catch (Exception ex)
            {
               

            }
}

Prevent duplicate item in a SharePoint List

The following Event Handler code will prevent users from creating duplicate value in  "Title" field.

ItemAdding Event Handler

 public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            if (properties.ListTitle.Equals("My List"))
            {
                try
                {
                    using(SPSite thisSite = new SPSite(properties.WebUrl))
                    {
                        SPWeb thisWeb = thisSite.OpenWeb();
                        SPList list = thisWeb.Lists[properties.ListId];
                        SPQuery query = new SPQuery();
                        query.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.AfterProperties["Title"] + "</Value></Eq></Where>";
                        SPListItemCollection listItem = list.GetItems(query);
                        if (listItem.Count > 0)
                        {
                            properties.Cancel = true;
                            properties.ErrorMessage = "Item with this Name already exists. Please create a unique Name.";
                        }
                    }
                }
                catch (Exception ex)
                {
                    PortalLog.LogString("Error occured in event ItemAdding(SPItemEventProperties properties)() @ AAA.BBB.PreventDuplicateItem class. Exception Message:" + ex.Message.ToString());
                    throw new SPException("An error occured while processing the My List Feature. Please contact your Portal Administrator");
                }
            }
        }


Feature.xml


<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="1c2100ca-bad5-41f5-9707-7bf4edc08383"
          Title="Prevents Duplicate Item"
          Description="Prevents duplicate Name in the "My List" List"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
  </ElementManifests>
</Feature>

Element.xml


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="100">
    <Receiver>
      <Name>AddingEventHandler</Name>
      <Type>ItemAdding</Type>
      <SequenceNumber>10000</SequenceNumber>
      <Assembly>AAA.BBB, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8003cf0cbff32406</Assembly>
      <Class>AAA.BBB.PreventDuplicateItem</Class>
      <Data></Data>
      <Filter></Filter>
    </Receiver>
  </Receivers>
</Elements>

The source code of this feature is available at Technet Gallery

Friday, May 27, 2011

Email the Approval Status to "Created By"/"Modified By" user from Visual Studio workflow

Below is the code snippet to send an email about the approval status to the user who submitted/created the list item in a SharePoint list. Assume that the Visual studio workflow is attached to the list and will trigger the workflow when the item is edited in the list.


  if (workflowProperties.Item.ModerationInformation.Status == SPModerationStatusType.Denied)
  {
        StringDictionary headers = new StringDictionary();
        headers.Add("from", "administrator@domain.com");
        headers.Add("subject", "Request - Denied");
        headers.Add("content-type", "text/html");
        System.Text.StringBuilder strMessage = new System.Text.StringBuilder();

       //link to list item display form (view item)
       strMessage.Append("The request submitted in ABC site has been rejected."+ workflowProperties.WebUrl+ "/" + workflowProperties.List.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + workflowProperties.ItemId);
        strMessage.Append("<br><br> Approver's comments: "+ workflowProperties.Item.ModerationInformation.Comment);

        SPListItem item = workflowProperties.Item;
        SPUser spUser = GetSPUser(item, "Created By");
        if (!String.IsNullOrEmpty(spUser.Email))
        {
                 headers.Add("to", spUser.Email);
                 SPUtility.SendEmail(web, headers, strMessage.ToString());
        }
  }

//Function to get the user instance who submitted the item
  private SPUser GetSPUser(SPListItem item, string fieldName)
        {
            SPFieldUser field = item.Fields[fieldName] as SPFieldUser;
            if (field != null && item[fieldName] != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
            }
            return null;
        }

Tuesday, May 24, 2011

Limited Access permission in SharePoint

Scenario: We have a list which doesn't inherit permissions from the site. Also, at the root of the list, there are folders, which are also set to NOT inherit permissions from the parent folder (which is the root of the list). We have added a Site group to the folder with 'Contribute' permission.

Issue: We see that the site group which we added to the folder is also added automatically at list level as well. The group have “Limited Access” permissions to the list.

Explanation: When you set permissions (for example: Full Control/Contribute) to the Folder after you break the permissions inherit. The users\group will have “Limited Access” permissions to the list, not the same permissions with the folder.

As discussed on "Anonymous Users, Forms Pages, and the Lockdown Feature  "  on Microsoft Enterprise Content Management (ECM) Team Blog  :   
   
In SharePoint, anonymous users’ rights are determined by the Limited Access permission level. Limited Access is a special permission level that cannot be assigned to a user or group directly. The reason it exists is because if you have a library or subsite that has broken permissions inheritance, and you give a user/group access to only that library/subsite, in order to view its contents, the user/group must have some access to the root web. Otherwise the user/group will be unable to browse the library/subsite, even though they have rights there, because there are things in the root web that are needed to render the site or library. Therefore, when you give a group permissions only to a subsite or library that is breaking permissions inheritance, SharePoint will automatically give Limited Access to that group or user on the root web.

Source:
More information about “Limited Access” permissions:
http://office.microsoft.com/en-us/windows-sharepoint-services-help/permission-levels-and-permissions-HA010100149.aspx
http://paulgalvinsoldblog.wordpress.com/2008/11/02/what-is-limited-access-anyway/

Monday, May 23, 2011

Send an email with html format using SPUtility.SendEmail

SPWeb oWeb = SPContext.Current.Web

StringDictionary headers = new StringDictionary();

headers.Add("from",  "system@domain.com");
headers.Add("to", spUser.Email);
headers.Add("subject", "Welcome to the SharePoint group: ABC site: ");
headers.Add("content-type", "text/html"); //This is the default type

System.Text.StringBuilder strMessage = new System.Text.StringBuilder();                  
strMessage.Append("<br><br><b>Login Instructions: </b><br>");
strMessage.Append("<font color='red'><UL><li>If you are a US employee ALWAYS login in using the following login format </font><br>");

SPUtility.SendEmail(web, headers,strMessage.ToString());

Tuesday, May 17, 2011

Programmatically set permissions to a folder in a SharePoint list

This method can be used to bind permission to a folder in a SharePoint list

 /// <summary>
/// Method to set the permission at folder level for the newly created site groups
/// </summary>
/// <param name="web">The current web instance</param>
/// <param name="groupName">Name of the Site group that is added to the folder</param>
/// <param name="listName">Name of the list</param>
/// <param name="folderName">Name of the folder in the list</param>
/// <param name="role">Role/permission level set to the group to access folder for the site group users</param>

 private void SetRoleDefinitionBinding(SPWeb web,string groupName, string listName, string folderName, string role)
        {
            try
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[groupName]);
                SPList list = web.Lists[listName];
                SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq></Where>";
                //Retrieve the items based on Query
                SPListItemCollection items = list.GetItems(query);
               
                //Get the name and Url for the folder
                foreach (SPListItem item in items)
                {
                    SPFolder folder = web.GetFolder(item.Url);
                    folder.Item.BreakRoleInheritance(true);
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[role]);
                    folder.Item.RoleAssignments.Add(roleAssignment);
                    web.Update();
                }
      
            }
            catch (Exception ex)
            {
              
                //Error handling
            }
        }