SharePoint In Action

An attempt to share my day-to-day SharePoint experience

Code – Web Part – Create Customized Wiki Pages based on your own Wiki templates

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Drawing;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Web.UI;
using System.IO;
namespace CustomizedWikiPages.wp_CustomizedWikiPages
{
    [ToolboxItemAttribute(false)]
    public class wp_CustomizedWikiPages : WebPart
    {
        private Panel pnlMain = new Panel();
        private Table tblMain = new Table();
        private TextBox txtWikiPagename = new TextBox();
        private DropDownList ddlTemplates = new DropDownList();
        private Button btnCreateWiki = new Button();
        private string WikiListUrl;
        private string WikiPageUrl;
        private HiddenField hdnRedirectionUrl = new HiddenField();

        protected override void CreateChildControls()
        {
            tblMain.Width = Unit.Pixel(700);
            tblMain.Style.Add("color", "#000000");

            txtWikiPagename.Width = Unit.Pixel(285);
            ddlTemplates.Width = Unit.Pixel(290);

            TableRow tr0 = new TableRow();
            TableCell tc01 = new TableCell();
            Label lblDesc = new Label();
            tc01.HorizontalAlign = HorizontalAlign.Left;
            lblDesc.Text = "You can create customized wiki pages using templates. New templates can be created any time.";
            tc01.Controls.Add(lblDesc);
            tc01.ColumnSpan = 2;
            tc01.Height = 40;
            tr0.Controls.Add(tc01);
            tblMain.Controls.Add(tr0);

            TableRow tr1 = new TableRow();           
            TableCell tc11 = new TableCell();           
            TableCell tc12 = new TableCell();
            tc11.Width = Unit.Pixel(120);
            tc12.Width = Unit.Pixel(580);
            tc11.HorizontalAlign = HorizontalAlign.Right;
            tc12.HorizontalAlign = HorizontalAlign.Left;
            tc11.Text = "Wiki Page Name ";
           
            tc12.Controls.Add(txtWikiPagename);
            tr1.Controls.Add(tc11);
            tr1.Controls.Add(tc12);
            tblMain.Controls.Add(tr1);

            TableRow tr2 = new TableRow();
            TableCell tc21 = new TableCell();
            TableCell tc22 = new TableCell();
            tc21.HorizontalAlign = HorizontalAlign.Right;
            tc22.HorizontalAlign = HorizontalAlign.Left;           
            tc21.Text = "Page Template ";           
            tc22.Controls.Add(ddlTemplates);
            tr2.Controls.Add(tc21);
            tr2.Controls.Add(tc22);
            tblMain.Controls.Add(tr2);

            TableRow tr3 = new TableRow();
            tr3.Height = Unit.Pixel(50);
            tr3.VerticalAlign = VerticalAlign.Middle;
            TableCell tc31 = new TableCell();
            TableCell tc32 = new TableCell();
            tc31.Style.Add("text-align","center");
            tc31.Style.Add("height", "50px");
            tc31.Style.Add("padding-top", "20px");
            btnCreateWiki.Text = "Create Wiki Page";

            tc31.HorizontalAlign = HorizontalAlign.Center;
            btnCreateWiki.Click += new EventHandler(btnCreateWiki_Click);
            tc31.Controls.Add(btnCreateWiki);

            tr3.Controls.Add(tc31);
            tr3.Controls.Add(tc32);
            tblMain.Controls.Add(tr3);

            //************************************************************

            hdnRedirectionUrl.Value = "";
            Controls.Add(hdnRedirectionUrl);        

             //************************************************************
            pnlMain.Width = Unit.Pixel(700);
            pnlMain.Style.Add("Padding", "10px");
            pnlMain.BackColor = Color.FromName("#FCBC97");
            pnlMain.BorderWidth = Unit.Pixel(1);
            pnlMain.BorderStyle = BorderStyle.Solid;
            pnlMain.BorderColor = Color.Black;
            pnlMain.Controls.Add(tblMain);
            pnlMain.Controls.Add(hdnRedirectionUrl);
            this.Controls.Add(pnlMain);
            PopulateTemplatesDropDown();        
        }

        protected void PopulateTemplatesDropDown()
        {
            using (SPWeb wikiSite = SPContext.Current.Site.OpenWeb("/your wiki site name"))
            {
                SPList wikiTemplatesList = wikiSite.Lists["your wiki template library name"];
                List<string> templates = new List<string>();
                foreach (SPListItem wikiTemplate in wikiTemplatesList.Items)
                {
                    if (wikiTemplate.DisplayName.ToLower() != "home")
                        templates.Add(wikiTemplate.DisplayName);
                }
                ddlTemplates.DataSource = templates;
                ddlTemplates.DataBind();
            }
        }

        private static void EnsureSitePagesLibrary(SPWeb web, SPList sitePagesLibrary)
        {
            if (sitePagesLibrary == null)
            {
                sitePagesLibrary = web.Lists.EnsureSitePagesLibrary();
            }
            if (sitePagesLibrary == null)
            {
                throw new SPException(SPResource.GetString("ListGone", new object[0]));
            }
            if (sitePagesLibrary.BaseTemplate != SPListTemplateType.WebPageLibrary)
            {
                throw new SPException(SPResource.GetString("OnlyInWikiLibraries", new object[0]));
            }
            if (sitePagesLibrary.ParentWeb != web)
            {
                throw new SPException(SPResource.GetString("WikiNotInWebException", new object[0]));
            }
        }

        public string GetWikiTemplateContent()
        {
            StringBuilder sb = new StringBuilder("");
            using (SPWeb wikiSite = SPContext.Current.Site.OpenWeb("/your wiki site name"))
            {
                SPList wikiTemplatesList = wikiSite.Lists["your wiki template library name"];
                SPQuery query = new SPQuery();
                query.Query = string.Concat(
                               "<Where><Eq>",
                                  "<FieldRef Name='FileLeafRef'/>",
                                  "<Value Type='Text'>" + ddlTemplates.SelectedItem.Text + ".aspx" + "</Value>",
                               "</Eq></Where>"
                               );

                SPListItemCollection items = wikiTemplatesList.GetItems(query);
                if (items.Count == 0)
                {
                    txtWikiPagename.Text = "Template could not be found : " + ddlTemplates.SelectedItem.Text;
                    txtWikiPagename.ForeColor = Color.Red;
                }
                if (items.Count > 1)
                {
                    txtWikiPagename.Text = "Duplicate templates : " + ddlTemplates.SelectedItem.Text;
                    txtWikiPagename.ForeColor = Color.Red;
                }
                else
                {
                    txtWikiPagename.ForeColor = Color.Black;
                    string wikiTemplateFileName = wikiTemplatesList.RootFolder.ServerRelativeUrl + "/" + ddlTemplates.SelectedItem.Text.Trim() + ".aspx";
                    SPFile wikiPage = wikiSite.GetFile(wikiTemplateFileName);
                    sb.Append(wikiPage.Item["WikiField"].ToString());
                }
               
            }
            return sb.ToString();
        }

        public static void ChangeWikiContent(SPFile wikiFile, string content)
        {
            if (wikiFile == null)
            {
                throw new ArgumentNullException("wikiFile");
            }
            wikiFile.Item[SPBuiltInFieldId.WikiField] = content;
            wikiFile.Update();
            wikiFile.Item.UpdateOverwriteVersion();
        }

        private void CreateCustomizedWiki()
        {
            using (SPWeb wikiSite = SPContext.Current.Site.OpenWeb("/wiki"))
            {               
                SPList wikiPagesList = wikiSite.Lists["your wiki list name"];
                SPQuery query = new SPQuery();
                query.Query = string.Concat(
                               "<Where><Eq>",
                                  "<FieldRef Name='FileLeafRef'/>",
                                  "<Value Type='Text'>" + txtWikiPagename.Text.Trim() + ".aspx" + "</Value>",
                               "</Eq></Where>"
                               );

                SPListItemCollection items = wikiPagesList.GetItems(query);
                if (items.Count > 0)
                {
                    txtWikiPagename.Text = "Duplicate File Name : " + txtWikiPagename.Text;
                    txtWikiPagename.ForeColor = Color.Red;
                }
                else
                {
                    try
                    {
                        txtWikiPagename.ForeColor = Color.Black;
                        wikiSite.AllowUnsafeUpdates = true;
                        WikiListUrl = wikiPagesList.RootFolder.ServerRelativeUrl;
                        WikiPageUrl = WikiListUrl + "/" + txtWikiPagename.Text.Trim() + ".aspx";
                        SPFile wikiPage = wikiPagesList.RootFolder.Files.Add(WikiPageUrl, SPTemplateFileType.WikiPage);
                        ChangeWikiContent(wikiPage, GetWikiTemplateContent());
                        wikiSite.AllowUnsafeUpdates = false;
                    }
                    catch(Exception ex)
                    {
                        txtWikiPagename.Text = ex.Message;
                    }
                }               
            }
        }

        protected void btnCreateWiki_Click(object sender, EventArgs e)
        {
            CreateCustomizedWiki();           
        }

    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: