SharePoint 2007 (MOSS/WSS) how to change the template link within a InfoPath Form under a Form Library to point it to a New Form Template

Requirement: You have designed an InfoPath Form Template and published it as a Content Type. You have a Form Library where you have made this Content Type as the Default Content Type. You have added few Forms which are associated with this Form Template or Content Type. Now you want to add few more fields into the Template and want to publish the new version and make it as Default Content Type. Also you want to change the old Form Instances available in the Library to point to this new Template so that newly added fields will remain blank in the old Forms. Here is a code for a Web Part to do that. You have to enter the name of the Form Library (not the full path) in the textbox available and hit the submit button.

 

using System;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

namespace ChangeTemplateWP

{

    [Guid("790c62d1-cb13-4cb3-bc55-78b8fc2093cf")]

    public class ChangeTemplateWP : System.Web.UI.WebControls.WebParts.WebPart

    {

        System.Web.UI.WebControls.Button submitButton;

        System.Web.UI.WebControls.TextBox textFormLib;

        protected override void Render(HtmlTextWriter writer)

        {

            EnsureChildControls();

            textFormLib.RenderControl(writer);

            submitButton.RenderControl(writer);

        }

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            submitButton = new System.Web.UI.WebControls.Button();

            textFormLib = new System.Web.UI.WebControls.TextBox();

            submitButton.Text = "Change Template";

            submitButton.Click += new EventHandler(submitButton_Click);

            Controls.Add(textFormLib);

            Controls.Add(submitButton);

        }

        void submitButton_Click(object sender, EventArgs e)

        {

            SPSite _site = SPContext.Current.Site;

            SPWeb _web = SPContext.Current.Web;

            SPList _list = _web.Lists[textFormLib.Text];

            for (int i = 0; i < _list.ContentTypes.Count; i++)

            {

                string _oldURL = _list.ContentTypes[i].DocumentTemplateUrl;

                string _newURL = _list.ContentTypes[0].DocumentTemplateUrl;

                foreach (SPListItem _item in _list.Items)

                {

                    _item.ReplaceLink(_oldURL, _newURL);

                }

            }

           

        }

    }

}