Pages

Search This Blog

Monday, March 28, 2011

SPWeb.AssociatedGroups creating sharepoint groups using object model

I have created groups using object model in feature activation but was not able to view the groups at the time of adding the user to created groups. Then searching the web come to a web property AssociatedGroups, which add the group to site group.

SPGroup sNewGroup;
SPRoleAssignment roleAssignment;
SPRoleDefinition permLevel;
string[] sGrupToSearch = { sGroupName };
SPGroupCollection spCurrentGroup = objSPWeb.SiteGroups.GetCollection(sGrupToSearch);
if (spCurrentGroup.Count < 1)
objSPWeb.SiteGroups.Add(sGroupName, objSPWeb.Site.Owner, objSPWeb.Site.Owner, sGroupName);
sNewGroup = objSPWeb.SiteGroups[sGroupName];
roleAssignment = new SPRoleAssignment(sNewGroup);
permLevel = objSPWeb.RoleDefinitions[strPermissionLevel];
roleAssignment.RoleDefinitionBindings.Add(permLevel);
objSPWeb.RoleAssignments.Add(roleAssignment);
objSPWeb.AssociatedGroups.Add(sNewGroup);
objSPWeb.Update();

Code to delete user form sharepoint, membership provider and web stie

While developing user registration in an sharepoint form authentication site we need to test the user registration process so i have create a small code to delete the user from sharepoint site, member ship provider and sharepoint site if already added.

Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(new SPSite("http://mysite:8888"));

Microsoft.Office.Server.UserProfiles.UserProfileManager profileManager = new Microsoft.Office.Server.UserProfiles.UserProfileManager(context);
try
{
objWeb.SiteUsers.Remove(sLoginName);
objWeb.Update();
}
catch { }
try
{

profileManager.RemoveUserProfile(sLoginName);

}
catch { }
try
{

Membership.DeleteUser(sLoginName);

}
catch { }
Add a connection string for your membership provider in app.config in case of windows application
Add the reference to microsoft.sharepoint.dll and Microsoft office server dll.

Adding content type related custom action to a list display form page

Feature to display a custom link in display page in an content type.

Feature.xml

Id="{57258975-0764-43b4-AE55-6415794168FA}"
Title="Display Page Custom Link"
ActivateOnDefault="TRUE"
Description="This feature is used to add a custom link on display page for content type"
Scope="Web"
Hidden="False" >

Element.xml


Id="respondlink"
Location="DisplayFormToolbar"
RegistrationType="ContentType"
RegistrationId="0x0100B7D4482D0BF60A409FEEB760AC7F386A"
Sequence="33445"
Title="Respond">

Error:- "Column 'Page Content' does not exist. It may have been deleted by another user."

In a scenario I have to write the content in the “page content area” with some formatting. Using UI we can do this very easily by just clicking on “Edit as HTML” link and writing the HTML code in the editor.
Programmatically we can do this using the following code snippet:
PublishingPage objPublishingPage;
PublishingWeb objPublishingWeb;
String PageUrl =http://...;
String PageName =”XYZ.aspx”;
objPublishingWeb = PublishingWeb.GetPublishingWeb(SPWebObject);
objPublishingPage = objPublishingWeb.GetPublishingPage(PageUrl + "/" + PageName);
if (objPublishingPage != null)
{
objPublishingPage.CheckOut();
objPublishingPage.ListItem["Page Content"]=PageContent;
objPublishingPage.ListItem.Update();
}
This works fine till you are not using the multilingual feature. But I have to also publish the content in its locale language in the multilingual page, in which the above code fails and give the error “Column 'Page Content' does not exist. It may have been deleted by another user. ”. In Multilingual page the column “Page Content” changes its language to its local so it’s hard to find the column instead of this we can use the following code snippet:
PublishingPage objPublishingPage;
PublishingWeb objPublishingWeb;
String PageUrl =http://...;
String PageName =”XYZ.aspx”;
objPublishingWeb = PublishingWeb.GetPublishingWeb(SPWebObject);
objPublishingPage = objPublishingWeb.GetPublishingPage(PageUrl + "/" + PageName);
if (objPublishingPage != null)
{
objPublishingPage.CheckOut();
objPublishingPage.ListItem["PublishingPageContent"]=PageContent;
objPublishingPage.ListItem.Update();
}

Deleting site columns with all references from a site collection : SharePoint 2010

Its a common scenario in many sharepoint projects wherein we need to delete a site column from a site collection which is no longer being used.

However, when we try to delete such site column programmatically,sharepoint gives us the error:

 "Site columns which are included in content types or on lists cannot be deleted. Please remove all instances of this site column prior to deleting it."

Therefore, we need to delete all references of this site column wherever they are being used in the site collection.

In order to achieve this, SharePoint 2010 provides a very useful method called 'ListsFieldUsedIn()' which can be called on a SPField object.This method provides us with a 'SPFieldTemplateUsage' collection in which we can find the 'WebID',as well as the 'listID' where this site column is being used.Once we have this collection, we can iterate through it and delete all the column references using the 'WebID' and 'ListID'.

Once all these references have been deleted , we can simply call the Delete() method on the 'SPField' object to delete the site column.

Here's the method which takes the field to be deleted and the root web of the site collection as input parameters and deletes the site column along with all the references:

private void DeleteColumn(SPField field, SPWeb web)
        {
            ICollection<SPFieldTemplateUsage> collection = field.ListsFieldUsedIn();
            foreach (SPFieldTemplateUsage usage in collection)
            {

                SPWeb webSite = web.Site.AllWebs[usage.WebID];
                SPList list = webSite.Lists[usage.ListID];

                if (list.ContentTypesEnabled)
                {
                    SPContentTypeCollection listContentTypes = list.ContentTypes;
                    foreach (SPContentType contentType in listContentTypes)
                    {
                        if (contentType.Fields.ContainsField(field.InternalName))
                        {
                            contentType.FieldLinks.Delete(field.InternalName);
                            contentType.Update();

                        }

                    }
                }

                if (list.Fields.ContainsField(field.InternalName))
                {
                    list.Fields.Delete(field.InternalName);
                }



                webSite.Dispose();
            }

            foreach (SPContentType contentType in web.ContentTypes)
            {

                if (contentType.Fields.ContainsField(field.InternalName))
                {
                    contentType.FieldLinks.Delete(field.InternalName);
                    contentType.Update(true);

                }

            }

          
            field.Delete();
          

        }





Enable Button on Ribbon only when user selects any Item in Sharepoint 2010

http://www.directsharepoint.com/2011/03/enable-button-on-ribbon-only-when-user.html

If you want to have your ribbon button enabled only when user selects some item in the default view of your List/Library, you can do this by getting the client object modal objects of SharePoint.

SP.ListOperation.Selection.getSelectedItems() will give you the IDs of the selected items. Another important object is EnabledScript which actually enables/disables the button on returning true/false values.
In order to achieve this, create a button on ribbon and then attach an CommandUIHandler to the button which will call the javascript method where you can write your own logic for processing your selected item IDs.

I have created a Feature and written the below XML on the Elements.xml file.



<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="Ribbon.Library.Actions.AddButtonInRibbon"
    Location="CommandUI.Ribbon"
    RegistrationType="ContentType"
    RegistrationId="Your Content Type ID"
    Title="Custom.CustomUIActions.RibbonManifest">
    <CommandUIExtension>
      <!--Declare a  CommandUIDefinition and specify the location in ribbon where you want to place tour button-->
      <!--For More information on locations refer to file - \Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\GLOBAL\XML\CMDUI.XML-->
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Documents.Share.Controls._children">
          <Button Id="Ribbon.Documents.Share.NewRibbonButton"
            Command="CustomUIActions.PageComponent.Command.DoAction"
             Image16by16="/_layouts/images/docidlookup.png"
            Image32by32="/_layouts/images/rtrsendtoicon.png"
            LabelText="Click Here To Get Selected IDs"
            TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
     
      <!-- Define a handler-->
      <!-- "Enabled Script" will return true if Item is selected by user in List view, else will return false which
      will disable the Button-->
      <!-- fsObjType = "0" for Item, "1" for Folder-->
      <CommandUIHandlers>
        <CommandUIHandler
          Command="CustomUIActions.PageComponent.Command.DoAction"
          CommandAction="javascript:PerformCustomAction()"
          EnabledScript="javascript:function ItemSelected()
          {
            var items = SP.ListOperation.Selection.getSelectedItems();
            if(items.length>0)
            {
            if(items[0].fsObjType == '0')
              {
                return true;
              }
            }
          }
          ItemSelected();
          " />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

  <!-- Create another custom action that will do processing for your selected items-->
  <!-- Register this script block in script link-->
  <!-- This will be an asynchronous operation, that’s why we are creating two delegates for  this - onSuccessMethod , onFailureMethod -->  <CustomAction Id="CustomUIActions.PageComponent.Command.DoAction"
    Location="ScriptLink"
    ScriptBlock="          
      function PerformCustomAction() {
        context = new SP.ClientContext.get_current(); 
        site = context.get_site();
        context.load(site, 'Url', 'ServerRelativeUrl');  
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod)); 
      }

      function onSuccessMethod(sender, args) { 
        var items = SP.ListOperation.Selection.getSelectedItems();
        var myItems = '';
        var k;
          for (k in items)
          {
            myItems += items[k].id + ';';
          }
        alert('Items selected by you:' + myItems);
      } 

      function onFailureMethod(sender, args) { 
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace()); 
      } 
    " />
 
</Elements>

Wednesday, March 23, 2011

Managed Path in Sharepoint 2010

In this article we will see how we can create managed path in Sharepoint 2010.
Sometimes we have to define which URL's SharePoint should maintain for a sitecolllection. To define this we have to create managed path for web application.
The managed paths are web application specific i.e. the managed path created for one web application will not appear in any other web application.
We can create two types of managed path:
1.   Wildcard Inclusion
2.   Explicit Inclusion
Explicit Inclusion managed path allows us to create a single site collection on that path and Wildcard Inclusion allows us to create multiple site collection on that managed path.
Let’s see how we can create managed path in Sharepoint 2010:
Go to Sharepoint 2010 Central Administration and click on Managed Path as shown in below image.
Now write the managed path which you want to create and click on Add Path button.

The managed path has been created for that particular web application.

Now click on create new site collection and select the same web application you will see the managed path created by you.

Tuesday, March 22, 2011

Send Mail through code in Sharepoint using SMTP Mail

Many a times, we need to build our own mail sending utility while working on SharePoint Projects. The requirement could be either to send a mail to document owner for any specific changes made to the document, sending error mails to administrator etc. We can use "SPUtility.SendEmailbut everyone is aware of its long length limitation of 2048 characters. So I tried using SmtpMail instead. In Below example I have instantiated an object of

SmtpMail which is derived from “System.Web.Mail” namespace. the main task while instanciating the SmtpMail object is to retrieve the “fromAddress” and “smtpServerAddress”. We can get these from the Web Application Context:

“WebApplication.OutboundMailSenderAddress”
“WebApplication.OutboundMailServiceInstance.Server.Address”


public static String SendMail(String strMessage, String siteUrl)
        {
            String strMailIds = String.Empty;
            String fromAddress, smtpServer;
            String strErrorMsg = String.Empty;
            System.Web.Mail.MailMessage objMailMsg;
            try
            {

            SPSecurity.RunWithElevatedPrivileges(delegate()
              {
                using (SPSite objSite = new SPSite(siteUrl))
                {
                  using (SPWeb PrevelegedWeb = objSite.OpenWeb())
                  {
                    strMailIds = "test@abc.com;test2@abc.com";
fromAddress = PrevelegedWeb.Site.WebApplication.OutboundMailSenderAddress;
smtpServer = revelegedWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
                    if (!(String.IsNullOrEmpty(fromAddress)
&& String.IsNullOrEmpty(smtpServer)))
                    {
                        MailMessage objMailMsg = new System.Web.Mail.MailMessage();
                        objMailMsg.From = fromAddress;
                        objMailMsg.To = strMailIds;
                        objMailMsg.Subject = "This is a test Mail";
                        objMailMsg.BodyFormat = MailFormat.Html;
                        objMailMsg.Body = strMessage;
                        SmtpMail.SmtpServer = smtpServer;
                        SmtpMail.Send(objMailMsg);
                    }
                    else
                    {
strErrorMsg = "There is an error in sending email
 because of server configuration. ";
                    }
                  }
                }
              });
            }
            catch (Exception Ex)
            {
                throw new Exception("An error has occured while sending mail", Ex);
            }
            return strErrorMsg;
        }







Monday, March 21, 2011

Clearing taxonomy (managed metadata) field value programmatically : SharePoint 2010

Recently, in one of our projects we came across a requirement where in we needed to clear all fields for a list item on an item copy or a checkin.
In order to implement this , we used eventhandlers for ItemCheckedIn and implemented the code to clear all fields, setting all fields to null i.e.

private void ClearPropertiesOfItem(SPListItem itemCopiedOrCheckedIn, List<String> fieldsTobeCleared)
        {
            String validationFormula = "";

            try
            {
                if (fieldsTobeCleared.Count > 0)
                {
                   
                    foreach (String fieldToBeCleared in fieldsTobeCleared)
                    {
                        foreach (SPField field in itemCopiedOrCheckedIn.Fields)
                        {
                            if (field.Title.Equals(fieldToBeCleared))
                            {
                                if (!String.IsNullOrEmpty(field.ValidationFormula))
                                {
                                    validationFormula = field.ValidationFormula;
                                    field.ValidationFormula = string.Empty;
                                    field.Update();
                                }

                                                                                               
                                    itemCopiedOrCheckedIn[field.Id] = null;
                               
                                                             
                                if (!String.IsNullOrEmpty(validationFormula))
                                {
                                    field.ValidationFormula = validationFormula;
                                    field.Update();
                                }
                            }

                        }

                      
                    }
                 
                    itemCopiedOrCheckedIn.SystemUpdate();
                }
            }
            catch (Exception Ex)
            {
                throw new Exception(base.GetResourceString(COMMON.Constants.EXCEPTION_OCCURED_WHILE_CLEARING_PROPERTIES), Ex);
            }
        }


This worked well for all fields except the managed metadata or the taxonomy columns which give an exception while setting the value to null.
In order to clear these columns , we explicitly need to set the properties "WssId, TermGuid and Label" to null as is shown below:


private void ClearPropertiesOfItem(SPListItem itemCopiedOrCheckedIn, List<String> fieldsTobeCleared)
        {
            String validationFormula = "";

            try
            {
                if (fieldsTobeCleared.Count > 0)
                {
                   
                    foreach (String fieldToBeCleared in fieldsTobeCleared)
                    {
                        foreach (SPField field in itemCopiedOrCheckedIn.Fields)
                        {
                            if (field.Title.Equals(fieldToBeCleared))
                            {
                                if (!String.IsNullOrEmpty(field.ValidationFormula))
                                {
                                    validationFormula = field.ValidationFormula;
                                    field.ValidationFormula = string.Empty;
                                    field.Update();
                                }

                                //special handling for managed metadata column (single value)


                                if (field.TypeAsString.Equals(“TaxonomyFieldType
“))
                                {
                                    if (itemCopiedOrCheckedIn[field.Id] != null)
                                    {
                                        TaxonomyFieldValue managedMetadataFieldValue = itemCopiedOrCheckedIn[field.Id] as TaxonomyFieldValue;
                                        managedMetadataFieldValue.WssId = 0;
                                        managedMetadataFieldValue.TermGuid = null;
                                        managedMetadataFieldValue.Label = null;

                                        TaxonomyField managedMetadataField = itemCopiedOrCheckedIn.Fields[field.Id] as TaxonomyField;
                                        managedMetadataField.SetFieldValue(itemCopiedOrCheckedIn, managedMetadataFieldValue);
                                    }
                                   
                                }
                                else if (field.TypeAsString.Equals("TaxonomyFieldTypeMulti"))//special handling for managed metadata column (multi value)

                                {
                                    if (itemCopiedOrCheckedIn[field.Id] != null)
                                    {

                                        TaxonomyFieldValueCollection managedMetadataFieldValueColl = new TaxonomyFieldValueCollection(string.Empty);

                                        managedMetadataFieldValueColl.PopulateFromLabelGuidPairs(itemCopiedOrCheckedIn[field.Id].ToString());

                                        int fieldValueCount = managedMetadataFieldValueColl.Count;
                                                                               
                                        managedMetadataFieldValueColl.RemoveRange(0, fieldValueCount);
                                                                            
                                        TaxonomyField managedMetadataField = itemCopiedOrCheckedIn.Fields[field.Id] as TaxonomyField;

                                        managedMetadataField.SetFieldValue(itemCopiedOrCheckedIn, managedMetadataFieldValueColl);
                                    }

                                }
                                else
                                {
                                    itemCopiedOrCheckedIn[field.Id] = null;
                                }
                                                             
                                if (!String.IsNullOrEmpty(validationFormula))
                                {
                                    field.ValidationFormula = validationFormula;
                                    field.Update();
                                }
                            }

                        }

                      
                    }
                 
                    itemCopiedOrCheckedIn.SystemUpdate();
                }
            }
            catch (Exception Ex)
            {
                throw new Exception(base.GetResourceString(COMMON.Constants.EXCEPTION_OCCURED_WHILE_CLEARING_PROPERTIES), Ex);
            }
        }