Pages

Showing posts with label WebPart. Show all posts
Showing posts with label WebPart. Show all posts

Wednesday, November 16, 2011

How to add web part on SharePoint 2010 Wiki Pages / On Rich Content Programmatically


While working with SharePoint 2010 one of my fried came across a scenario where he needed to modify the home page of team site using a feature. Feature should delete the existing content in out of the box team site’s home page and add new web parts.

Though this sounds very simple in first shot but practically little tricky, that’s what I experienced.
SharePoint 2010 has come up with new features and one of them is modification in team sites. If you observe that when a new out of the box team site is created, there is no default.aspx instead default page is replaced by Home.aspx. Home.aspx is a wiki page and resides in the Site Pages library of team site.
As this is a wiki page so it’s good that this supports direct editing and you can add web parts directly in the rich text area using UI. But when it comes to adding web parts to this page programmatically then problem begins.

Waldek Mastykarz has given excellent workaround to this problem where he has shown how to add a web part in Publishing Page Content of publishing page.  We can use similar technique to add web parts to wiki page as well, only difference is of field name of wiki page.
In the example I have added two list view web parts in Home.aspx page , one reside at left and other one is at right of page. This can be done with simple HTML markup where <td> and <tr> are defined with certain widths.

In my case Ultimate output should be like this HTML
//<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\">
//  <table id=\"layouts table\" style=\"width:100%\">
//      <tr style=\"vertical-align: top;\">
//          <td style=\"width=66.6%\">
//              <div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div>
//          </td>
//          <td style=\"width=33.3%\">
//              <div class=\"ms-rtestate-read {1}\" id=\"div_{1}\"></div>
//          </td>
//      </tr>
//  </table>
//</div>

In example above {0} and {1} would be replaced by GUIDs of web parts.
I have tried this with console application for POC but one can add this in feature receiver.



using (SPSite site = newSPSite("http://yoursite/"))
{
using (SPWeb _web = site.OpenWeb("/yourteamsite"))
   {
SPList _list1 = _web.Lists.TryGetList("List1");
SPList _list2 = _web.Lists.TryGetList("List2");
SPList _sitePages = _web.Lists.TryGetList("Site Pages");

SPFile _file = _web.GetFile(_web.Url + "/SitePages/Home.aspx");

if (_list1 != null&& _list2 != null)
     {
XsltListViewWebPart _list1View = newXsltListViewWebPart();
       _list1View.ListId = _list1.ID;
       _list1View.ViewGuid = _list1.DefaultView.ID.ToString("B").ToUpper();
       _list1View.XmlDefinition = _list1.DefaultView.GetViewXml();

XsltListViewWebPart _list2View = newXsltListViewWebPart();
       _list2View.ListId = _list2.ID;
       _list2View.ViewGuid = _list2.DefaultView.ID.ToString("B").ToUpper();
       _list2View.XmlDefinition = _list2.DefaultView.GetViewXml();

if (_file != null)
       {
using (SPLimitedWebPartManager _mgr = _web.GetLimitedWebPartManager(_file.Url, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
         {
Guid storageKey1 = Guid.NewGuid();
string wpId = String.Format("g_{0}", storageKey1.ToString().Replace('-', '_'));
          _list1View.ID = wpId;

Guid storageKey2 = Guid.NewGuid();
string _liWPID = String.Format("g_{0}", storageKey2.ToString().Replace('-', '_'));
           _list2View.ID = _liWPID;
           _list2View.ID = _liWPID;

//Deleting Web Parts
for (int i = _mgr.WebParts.Count - 1; i > 0; i--)
          {
            _mgr.DeleteWebPart(_mgr.WebParts[i]);
          }

//Adding Web Part
          _mgr.AddWebPart(_list1View, "wpz", 0);
          _mgr.AddWebPart(_list2View, "wpz", 1);

//Deleting Wiki Content
           _file.Item[SPBuiltInFieldId.WikiField] = string.Empty;
 _file.Item.UpdateOverwriteVersion();

string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><table id=\"layouts table\" style=\"width:100%\"><tr style=\"vertical-align: top;\"><td style=\"width:66.6%\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div></td><td style=\"width:33.3%\"><div class=\"ms-rtestate-read {1}\" id=\"div_{1}\"></div></td></tr></table></div>", storageKey1.ToString("D"), _ storageKey2.ToString("D"));


_file.Item[SPBuiltInFieldId.WikiField] = marker;
            _file.Item.UpdateOverwriteVersion();

Console.WriteLine("done");
          }
}

        }

       }
      }

Console.ReadLine();
   }

Monday, August 22, 2011

Hide Web Part’s Default Tool Part or Hiding Appearance from Web Part Properties

If the user wants to hide the default properties of a web part or some sections in the default tool part of a web part. How to do this? Here are the approaches.
I created a simple web part inheriting from SharePoint Web Part class So according to me, there can be two ways to do this.
(Microsoft.SharePoint.WebPartPages.WebPart) which has only a text box as user interface.
1.    Hide entire default tool part of a web part – this is pretty simple
2.    Hide specific sections in the default tool part. Example: hide only the appearance section in the default tool part.
And here are my approaches –
1.    Hiding the entire default tool part is very easy thing to achieve. When you override the GetToolParts method of the web part then you don’t have to add the default tool part in the array of ToolPart.
So sample can be written like:
Note that WebPartToolPart object is commented and not added in the array.
With this approach, you can only show the custom tool part for a web part.
public override Microsoft.SharePoint.WebPartPages.ToolPart[] GetToolParts()
{
  ToolPart[] _toolparts = new ToolPart[1];
  try
  {
    //WebPartToolPart _wptp = new WebPartToolPart();
    CustomToolPart _custom = new CustomToolPart();
     //_toolparts[0] = _wptp;
     _toolparts[0] = _custom;

  }
  catch (Exception ex)
  {
               
  }
  return _toolparts;
}

2.    Hiding the Specific Section of default tool part
Suppose we don’t want to hide the default tool part entrirely but need to hide specific sections like appearance.
so this approach shows that how we can achieve this.
when you are in your custom TooPart class and inside then this.Parent represents the ToolPart of a web part. If you try to do this.Parent.Controls then you can see that you get collection of controls inside the ToolPart pane. so we can easily set the visibility of those controls like
Note that you can add this code in CreateChildControls of your tool part class

if (Parent != null && Parent.Controls != null && Parent.Controls[1] != null)
{
  if (Parent.Controls[1].Controls != null)
  {
     Parent.Controls[1].Controls[0].Visible = false;
   }
}

Please Note that I have not tried these methods when web part is derived from ASP.NET Web Part class i.e. System.Web.UI.WebControls.WebParts.WebPart , If I get to know some update on that then I will update this post.

Here is my entire sample code

public class HiddenPropertiesWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{

  public override Microsoft.SharePoint.WebPartPages.ToolPart[] GetToolParts()
  {
    ToolPart[] _toolparts = new ToolPart[2];
    try
    {
      WebPartToolPart _wptp = new WebPartToolPart();
      CustomToolPart _custom = new CustomToolPart();
      _toolparts[0] = _wptp;
      _toolparts[1] = _custom;

    }
    catch (Exception ex)
    {
               
    }
    return _toolparts;
 }

 protected override void CreateChildControls()
 {
   try
   {
     base.CreateChildControls();
     TextBox _txtBox = new TextBox();
     this.Controls.Add(_txtBox);
   }
   catch (Exception ex)
   {
     this.Controls.Add(new LiteralControl(string.Format("{0}-{1}", "Error", ex.Message)));
   }
  }
}

public class CustomToolPart : ToolPart
{
  protected override void CreateChildControls()
  {
    try
    {
      base.CreateChildControls();
      DropDownList _ddl = new DropDownList();
      _ddl.Items.Add("Item1");
      _ddl.Items.Add("Item2");
      this.Controls.Add(_ddl);

      //Hiding the Desired Section in the Default ToolPart

      // Parent.Controls[1] shows - default tool part
      // Parent.Controls[1].Controls[0] shows - default tool part's first control - that is Appearance
      if (Parent != null && Parent.Controls != null && Parent.Controls[1] != null)
      {
        if (Parent.Controls[1].Controls != null)
        {
          Parent.Controls[1].Controls[0].Visible = false;
        }
      }
     }
     catch (Exception ex)
     {
       this.Controls.Add(new LiteralControl(string.Format("{0}-{1}", "Error", ex.Message)));
     }
    }
}