Thursday, November 7, 2013

Deploy infopath form as content type when new form item

Download Infopath Form and Project at HERE

Open Infopath 2010 designer >> New >> Blank Form >> Design Form
Design form like this
File >> Form Options
At Security and Trust “left panel” do like this
File >> Publish >> Network Location
Save infopath file to folder microsofttechnology.net
Continue publish your infopath form to your folder
Save it in same folder microsofttechnology.net
Here is path of infopath file is published >> Next
Delete all text at textbox >> Next
Click OK
Click Publish
Click Close
Publish infopath form to Central admin: Go to your central admin >> General Application Settings >> at InfoPath Form Services category click to “”Manage form templates
Click to Upload form template link
Browse to your infopath publish file
Upload successful
Activate your infopath form

Open your visual studio >> Add new project >> Empty Sharepoint Project >> Named is microsofttechnology
Right click to project >> add new item >> content type >> Named is microsofttechnologyCT
Choose inherit from Form content type
Here is default content
Replace code in file by
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Form (0x010101) -->
  <ContentType ID="0x01010100b3c8d04f923b4193b1b58f387884038a"
               Name="microsofttechnologyCT"
               Group="microsofttechnology"
               Inherits="TRUE"
               RequireClientRenderingOnNew="FALSE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
    <DocumentTemplate TargetName="/FormServerTemplates/microsofttechnologyPublish.xsn" />
  </ContentType>
</Elements>
Right click to project >> add new item >> Module >> Named is microsofttechnologyModule
Right click to project >> add new item >> Module >> Named is microsofttechnologyModule

Delete the Sample.txt

Right click to microsofttechnologyModule >> Add new existing item
Browse to your infopath publish form
Clear the path properties of infopath form
Result like this
Add URL and Type into Elements.xml of module like this
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="microsofttechnologyModule" Url="FormServerTemplates">
  <File Path="microsofttechnologyPublish.xsn" Url="microsofttechnologyPublish.xsn" Type="GhostableInLibrary"/>
</Module>
</Elements>
Explain for URL=”FormServerTemplates”: we publish form into FormServerTemplates form library
Rename Feature1 to microsofttechnologyFeature (option)
Add event receiver for feature
Default content like this
Add references to Microsoft.Office.InfoPath.Server.Dll (path: C>:\Program Files\Microsoft Office Servers\14.0\Bin)
Using namespace:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Security;
using Microsoft.Office.InfoPath.Server.Administration;

using Microsoft.SharePoint.Workflow;
Add code like this
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Security;
using Microsoft.Office.InfoPath.Server.Administration;

using Microsoft.SharePoint.Workflow;

namespace microsofttechnology.Features.microsofttechnologyFeature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("503fca19-7ed2-40c4-b0a8-dd2883af7e9c")]
    public class microsofttechnologyFeatureEventReceiver : SPFeatureReceiver
    {
        private const string MINIMALACTIVEXTOOPEN = "SharePoint.OpenXmlDocuments.2";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPWeb web = site.RootWeb;
            // Update the custom content type to allow rendering in web browser.
            SPContentType ct = web.ContentTypes[new SPContentTypeId("0x01010100b3c8d04f923b4193b1b58f387884038a")];
            if (ct.NewDocumentControl != MINIMALACTIVEXTOOPEN || ct.RequireClientRenderingOnNew)
            {
                ct.NewDocumentControl = MINIMALACTIVEXTOOPEN;
                // Ensure the RequireClientRenderingOnNew property is correctly set for web browsing.
                ct.RequireClientRenderingOnNew = false;
                // Don't forget to update the content type with the changes.
                ct.Update(true, false);
            }
            web.AllowUnsafeUpdates = true;
            web.Lists.Add("MicrosoftTechnologyForm", "This is Form library for MicrosoftTechnology", SPListTemplateType.XMLForm);
            web.Update();
            SPList myFormLibrary = web.Lists["MicrosoftTechnologyForm"];
            myFormLibrary.OnQuickLaunch = true;
            myFormLibrary.ContentTypesEnabled = true;
            SPContentType spContentType = web.AvailableContentTypes["microsofttechnologyCT"];
            myFormLibrary.ContentTypes.Add(spContentType);
            myFormLibrary.Update();
            SetDefaultContentTypeOnSite(web, myFormLibrary);           

        }
        public void SetDefaultContentTypeOnSite(SPWeb web, SPList splist)
        {
            if (splist.ContentTypesEnabled)
            {
                SPFolder rootFolder = splist.RootFolder;
                IList<SPContentType> ctList = rootFolder.ContentTypeOrder;
                if (ctList.Count > 1)
                {
                    foreach (SPContentType ct in ctList)
                    {
                        if (ct.Name.Equals("Form"))
                        {
                            splist.ContentTypes["Form"].Delete();
                            splist.Update();
                            continue;
                        }
                    }
                    rootFolder.Update();
                }
            }
        }
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            base.FeatureInstalled(properties);

            FormsService formsService = GetFormsService();
            if (formsService == null)
            {
                //throw new ArgumentNullException("formsService",
                //                string.Format("Unable to retrieve FormsService during installation of \"{0}\". Argument formsService was null."),
                //                                properties.Feature.Definition.Name);
            }

            // Get list of form templates that are being deployed as part of this feature.
            List<String> formTemplates = GetInfoPathFormTemplates(properties.Definition.Properties, properties.Definition.RootDirectory);
            foreach (string formTemplate in formTemplates)
            {
                if (formsService.FormTemplates.ItemFromFile(formTemplate) == null)
                {
                    FormTemplateCollection.RegisterFormTemplate(formTemplate, properties.Definition, false);
                }
            }
        }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            base.FeatureUninstalling(properties);

            FormsService formsService = GetFormsService();
            if (formsService == null)
            {
                //throw new ArgumentNullException("formsService",
                //                    string.Format("Unable to retrieve FormsService during uninstallation of \"{0}\". Argument formsService was null."),
                //                    properties.Feature.Definition.Name);
            }

            // Get list of form templates that were deployed as part of this feature.
            List<String> formTemplates = GetInfoPathFormTemplates(properties.Definition.Properties, properties.Definition.RootDirectory);
            foreach (string formTemplate in formTemplates)
            {
                if (formsService.FormTemplates.ItemFromFile(formTemplate) != null)
                {
                    formsService.FormTemplates.UnregisterFormTemplate(formTemplate, properties.Definition);
                }
            }
        }
        private List<String> GetInfoPathFormTemplates(SPFeaturePropertyCollection properties, string featureRootPath)
        {
            FileInfo[] filesInfo = new DirectoryInfo(featureRootPath).GetFiles("*.xsn");
            List<String> infoPathFormFileSpecs = new List<String>();
            foreach (FileInfo fileInfo in filesInfo)
            {
                infoPathFormFileSpecs.Add(Path.Combine(fileInfo.DirectoryName, fileInfo.Name));
            }

            return infoPathFormFileSpecs;
        }
        private FormsService GetFormsService()
        {
            FormsService formsService = null;
            if (SPFarm.Local != null)
            {
                formsService = SPFarm.Local.Services.GetValue<FormsService>(string.Empty);
            }
            else
            {
                formsService = SPContext.Current.Site.WebApplication.Farm.Services.GetValue<FormsService>(string.Empty);
            }
            return formsService;
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        //public override void FeatureActivated(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
Build project
Double click to the feature and set scope is Site >> Deploy project
The result as:
Form library is created
Infopath form is uploaded
Content type is created
Demo: clickto MicrosoftTechnologyForm >> Add document
Appear infopath form >> input information then save it
The result as


Thanks.

2 comments:

  1. A special thanks for this informative post. ! I'm so glad to find your page and it's helpful information.

    ReplyDelete