Tuesday, December 3, 2013

How to access added item values of List Item in ItemAdded event handlers into SharePoint

 
 Code:
 
 
public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            string strTitle = string.Empty;
           using (SPSite site = new SPSite(properties.WebUrl))
           {
           using (SPWeb web = site.OpenWeb())
           {
           SPList list = web.Lists[properties.ListTitle ];
           SPListItem item = list.GetItemByIdSelectedFields(properties.ListItemId, "Title");
           strTitle = (String)item.DisplayName ;
            }
            }
 

Working with BeforeProperties and AfterProperties on SPItemEventReceiver

Here are the results for a list:
List
BeforeProperties
AfterProperties
properties.ListItem
ItemAdding
No value
New value
Null
ItemAdded
No value
New value
New value
ItemUpdating
No value
Changed value
Original value
ItemUpdated
No value
Changed value
Changed value
ItemDeleting
No value
No value
Original value
ItemDeleted
No value
No value
Null
No value means that column value in the hash table was not available. 
New value means that the correct value for the column was available. 
Changed value means that the correct updated value was available.
Original value means that the correct original value was available.
Here is the same test against a document library:
Library
BeforeProperties
AfterProperties
properties.ListItem
ItemAdding
No value
No value
Null
ItemAdded
No value
No value
New value
ItemUpdating
Original value
Changed value
Original value
ItemUpdated
Original value
Changed value
Changed value
ItemDeleting
No value
No value
Original value
ItemDeleted
No value
No value
Null

Properties.ListItem refers the the current value for the list item at that point in the event.  Null means that the item is not available.  My analysis yields the following results:
  • Not surprisingly, we get null values for for ItemAdding (before item is added) and ItemDeleted (after item is deleted). 
  • As correctly documented in the SDK, item events for lists do not expose BeforeProperties.
  • ItemAdding and ItemAdded correctly report the value in the AfterProperties for an list item, but not a library item.  This is curious.

 

 

Code to create Terms and Term Set programmatically

General code:
 using (SPSite site = new SPSite("http://site"))
            {
                TaxonomySession _TaxonomySession = new TaxonomySession(site);

                //Get instance of the Term Store 
                TermStore _TermStore = _TaxonomySession.TermStores["My Term Store"];

                //Now create a new Term Group
                Group _Group = _TermStore.CreateGroup("My New Group");

                //Create a new Term Set in the new Group
                TermSet _TermSet = _Group.CreateTermSet("My New Termset");

                //Add terms to the term set
                Term _term1 = _TermSet.CreateTerm("First Term", 1033);
                Term _term2 = _TermSet.CreateTerm("Second Term", 1033);
                Term _term3 = _TermSet.CreateTerm("Third Term", 1033);
                Term _term4 = _TermSet.CreateTerm("Last Term", 1033);

                //commit changes
                _TermStore.CommitAll();

            }
 Scenario:
1) The "Term Store Management" is located in Central admin site (http:\\Spadmin\).
2) Pages library is located in the publishing site.
3) We have to write and event handler such that when ever a page is created in pages library in publishing site , the title field of the page should be added to the Central administration  "Term Store Management" Taxanomy group related Term Set.

Solution:

We will write an event handler for Pages library such that which will read the title and using Elevated privileges it will add the title to Central admin taxanomy term set.

Note(Trick): Make sure the Application pool running account(service account) of the central admin should be added as admin or Contributor to the Taxanomy :Term Store Administrators.


Event Handler code: 


public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            string strTitle = string.Empty;
           using (SPSite site = new SPSite(properties.WebUrl))
           {
           using (SPWeb web = site.OpenWeb())
           {
           SPList list = web.Lists[properties.ListTitle ];
           SPListItem item = list.GetItemByIdSelectedFields(properties.ListItemId, "Title");
           strTitle = (String)item.DisplayName ;
            }
            }

    //Code to add capture field (Title field value of Pages library) value to Taxanomy in Central administration
_____________________________________________________________________________________
**********Another Code to access central administration site URL***************

   Microsoft.SharePoint.Administration.SPAdministrationWebApplication centralWeb =SPAdministrationWebApplication.Local;

            string cntrlAdmnwebUrl = centralWeb.Sites[0].Url;

            SPSecurity.RunWithElevatedPrivileges(delegate()
              {
                  using (SPSite CntrlAdmsite = new SPSite(cntrlAdmnwebUrl))
                  {


                      TaxonomySession _TaxonomySession = new TaxonomySession(CntrlAdmsite);

                      //

________________________________________________________________________________


          SPSecurity.RunWithElevatedPrivileges(delegate()
              {
            using (SPSite CntrlAdmsite = new SPSite("http://hccspdev03:2013/"))
                  {

             TaxonomySession _TaxonomySession = new TaxonomySession(CntrlAdmsite);

                      //Get instance of the Term Store

             TermStore _TermStore = _TaxonomySession.TermStores["Managed Metadata Service"];

                      // Get instance of Term Group

                      Group _Group = _TermStore.Groups["HCCCOM"];

                      // Get instance of Term Set in the new Group

                      TermSet _TermSet = _Group.TermSets["BannerLocation"];

                      //Add terms to the term set

                      Term term = _TermSet.CreateTerm(strTitle, 1033);

                      //commit changes

                      _TermStore.CommitAll();
                  }
              });
        }




Monday, December 2, 2013

Sharepoint Webpart Tool editor panel code for parameters

For Normal webpart:
Step1: inherit IWebEditable

public partial class NMCWebPart : WebPart
{

Step 2: Declare variable that are supposed to appear in Tool part editor

 [Category("Custom Properties")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Title1")]
        [WebDescription("Main title the Web Part.")]
        public string TextMainTitle
        {
            get;
            set;
        }
        [Category("Custom Properties")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Title2")]
        [WebDescription("Sub title the Web Part.")]
        public string TextSubTitle
        {    get;
            set;
        }
Step 3 : use these variables in our coding:

 protected override void Render(HtmlTextWriter writer)
        {

            //base.Render(writer);
            writer.Write("<h4><b>" + Title1+ "</b></h4><br>");
            writer.Write("<h3>" + Title2+ "<br><br>");
            writer.Write("<table><tr><td>");
            lblName.RenderControl(writer);
            writer.Write("</td><td>");
*****************OR********************************

        public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
        {
            if (Title1!= null)
            {
                lblMainTitle.Text = Title1;
  
            }
                if (Title2!= null)
                {
                     lblSubTitle.Text = Title2;
                }

_______________________________________
For VS2013 webparts, It will have ascx control, so all the Rendering part will be covered by ascx design.

for this in desing I have taken two labels, label1 and label 2 and we don't want to write any Render method.

[Category("Custom Properties")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Main Title")]
        [WebDescription("Main title the Web Part.")]
        public string TextMainTitle
        {
            get
            {
                if (label1 != null)
                {
                    return label1 .Text;
                }
                else
                {
                    return string.Empty;
                }
            }

            set
            {
                if (label1 != null)
                {
                    label1 .Text = value;
                }
            }
        }
        [Category("Custom Properties")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Sub Title")]
        [WebDescription("Sub title the Web Part.")]
        public string TextSubTitle
        {
            get
            {
                if (label2!= null) ///Means initially if control not loaded
                {
                    return label2.Text;
                }
                else
                {
                    return string.Empty;
                }
            }

            set
            {
                if (label2!= null)
                {
                    label2.Text = value;
                }
            }
        }