Tuesday, 4 December 2012

[ERROR FIX:] The selected control cannot store data because it is bound to a field or group that will not be included by default when a new form is created.


I. PROBLEM

For my today’s task, I was asked to investigate an error found in an infopath form wherein the sharepoint user could not create a new list item. When I opened the form in infopath designer, I could see the control but I could see an error “Control bound to missing field or group”. Not having a single idea on what it meant, I right-clicked the control and clicked on “More Info”.

"The selected control cannot store data because it is bound to a field or group that will not be included by default when a new form is created. To fix this problem, move the control into an optional section which is bound to the group that contains the controls field or group."




II. SOLUTION

After consuming some time trying to figure out what had caused this error, I realized that this is a configuration error that has something to do with the schema on both the queryfields and datafields. The queryfields are what infopath is looking when the form attempts to ‘query’ a data. On the other hand, datafields are needed by infopath when the form is trying to ‘save’ a data. The error has something to do with the datafields that is why the user is not able to save a new item on the list. So as a solution, simply go to the data tab and click on Default Values. Make sure that all the fields are checked in datafields. Follow the screenshot below.



HOW TO MAKE AN ATTACHMENT A REQUIRED FIELD IN INFOPATH FORM


I. INTRODUCTION

For today, I was asked by my project manager to modify an existing infopath form. The requirement is to make the attachment a required field in the infopath form. I thought that this is an easy thing to do as I have already experienced making a textfield required in an infopath form. For a normal textfield, this can be done by ticking the ‘Cannot be blank’ checkbox in the Validation tab.
In an attachment field, this will have a different approach and this is what I will discuss on this post.

II. SCOPE

This post assumes that the reader already knows how to create a custom list in sharepoint 2010. It is also required that the reader knows how to customize the layout of the sharepoint list form by using Infopath. A good post about doing this is located on this site. ( http://msdn.microsoft.com/en-us/library/office/gg180738(v=office.14).aspx )

III. REQUIREMENTS
- Sharepoint 2010
- Infopath Form

IV. IMPLEMENTATION

1. Navigate to
http://<your site collection>/ in your browser.
2. Navigate to your list and open the list form in the Infopath Designer 2010.

To open the list form in the Infopath 2010 Designer
1. On the List tab of the ribbon, Click Customize form as shown in Figure 1.

Figure 1. Customizing the list form


2. We will focus our attention in the attachment control. Drag the attachment field into the canvas and add a label ‘Attachment’ beside it.

Figure 2. Attachment field


3. To make the attachment field required, we will add a dummy textbox control that will contain the required rule. To do this, add a textbox control and place it before the attachment field.

Figure 3. Textbox in attachment field


4. Right click on the textbox control, hover on ‘Rules’ and click on Manage Rules.

Figure 4. Manage Rules on textbox


5. Create a rule for the textbox. Click on the ‘New’ rule button and click on Validation. Add a name to your rule. On the Condition window, Select the ‘Attachments’ field and on the condition, select ‘Is Blank’.

Figure 5. Condition window

  
6. Create another rule to hide the textbox. Click on the ‘New’ rule button and click on Formatting. Tick on the checkbox ‘Hide this control’.

Figure 6. Hide the control


7. That’s it! We are done. Try to add an item to the list and try to not add an attachment. The save operation should fail. The infopath should raise an error indicating that a required attachment field is empty.

Wednesday, 10 October 2012

HOW TO CREATE A LOOKUP FORM USING SHAREPOINT MODAL

I. INTRODUCTION

For today, I was tasked to create a lookup form using the very useful sharepoint modal in SP2010. The design is to have a textbox and a small button beside it that will trigger the modal. The modal contains a gridview with all the available values that the user will select. The user selects a valid value by clicking the row on the grid and its click event will close the modal and the selected value will be displayed on the textbox. 



II. SCOPE

This solution should have an existing custom webpart that will be the container of our controls. This tutorial will not detail out how to create a custom webpart in visual studio.

III. REQUIREMENTS

- Sharepoint 2010
- Visual Studio 2010

IV. IMPLEMENTATION
1. On the parent user control (ascx page), create a javascript function that will trigger the Sharepoint modal dialog.

function openLookup() {
        var options = SP.UI.$create_DialogOptions();
        options.title = "Lookup";
        options.width = 200;
        options.allowMaximize = false;
        options.autoSize = true;
        options.showClose = true;        SP.UI.ModalDialog.commonModalDialogOpen("/_layouts/Lookup.aspx", options, closecallback, null);    }


You can ignore the parameters being passed to the commonModalDialogOpen method, I will explain this later on the following steps.

Refer to the following link http://msdn.microsoft.com/en-us/library/ff410058.aspx for more information about the options being set in the modal dialog.

2. This javascript function would mean that the modal will load an aspx page located in "/_layouts/Lookup.aspx" .  For the next step, we will create this application page for the modal to show.
a. In your Sharepoint solution, right-click on the layouts folder. Select on Add->New Item. Select Application Page and on the name, Type in Lookup.aspx.



b. On the Lookup.aspx, the application page template has four contentplaceholders (PageHead, Main, PageTitle, PageTitleInTitleArea). We are more interested in the Main contentplaceholder because it will be in there where we will place our gridview. Place the code below on the “Main” contentplaceholder.

<asp:GridView ID="gvLookup" runat="server" AutoGenerateColumns="false" BorderWidth="5px" CssClass="tbl" AlternatingRowStyle-BackColor="#E9EFDA">
<Columns>  
<asp:TemplateField HeaderText="Select valid values" ItemStyle-CssClass="itemStyle" HeaderStyle-BorderWidth="0" HeaderStyle-CssClass="center">
<ItemTemplate>
 <span id="lookup" onclick="ModalClose_click('<%# Eval("Navio")%>');" style="cursor:pointer;" >
<%# Eval("Navio")%>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


c. Now create a javascript function on the application page. Name this function ModalClose_click and it has a parameter that will soon be passed on to the parent user control. So for the code on Step B, we will be passing the row value of the datagrid to the parent control. Place the function below on the script tag of the lookup.aspx.

function ModalClose_click(gridValue) {  
SP.UI.ModalDialog.commonModalDialogClose("OK", gridValue);
}


d. On the code-behind of the lookup application page, place the following code to populate our gridview.

protected void Page_Load(object sender, EventArgs e)
        {
       DisplayList();
        }

 private void DisplayList()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Navio", typeof(string));

            dt.Rows.Add("Navio1");
            dt.Rows.Add("Navio2");
            dt.Rows.Add("Navio3");
            dt.Rows.Add("Navio4");

            gvLookup.DataSource = dt;
            gvLookup.DataBind();
        }


 3. On the parent user control, create a textbox that will hold the selected value from the modal lookup. Also, create an input button that will be used to trigger the modal dialog. When you click on the button, it will trigger the javascript function that we created earlier.

 Navio : <asp:TextBox ID="txtShip" runat="server" Width="200px" />
             <input type="button" value="..." onclick="openLookup();" />


 4. The last javascript function that we will create is the closecallback that will be triggered when the SP.UI.ModalDialog.commonModalDialogClose method is called on the application page. Remember on Step 2.b where we set the parameters to pass on the value ‘OK’ and the row value of our datagrid. The closecallback function will look something like the one below.

function closecallback(result, value) {
        if (result === "OK") {
            document.getElementById('<%= txtShip.ClientID %>').value = value;
        }


Basically we are saying that when the result is equal to the value ‘OK’, we will assign the selected row value to the txtShip textbox in our user control.

Thursday, 20 September 2012

[ERROR FIX:] The term ‘Add-SPSolution ’ is not recognized as the name of a cmdlet, function, script file, or operable program.


I. PROBLEM

For my today’s task, my onshore counterpart has given me a backup file (.bak) to restore on a new site collection. So I have decided to do a restore script in Powershell to accomplish this job.  I was about to run my script in Powershell, when I came across this error. .

“The term ‘Add-SPSolution ’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”



I thought that Powershell can automatically interpret Microsoft. Sharepoint.Powershell commands, but I was wrong.

II. SOLUTION

On top of your powershell script, add a code to reference Microsoft.Sharepoint.Powershell so it will be made available to Powershell ISE.
Add the line below at the start of your powershell script.

Add-PSSnapin Microsoft.Sharepoint.Powershell –EA 0

But for a long-term solution, so you do not have to constantly adding the above line every time you write a script, you may refer to the site below.

http://blogs.msdn.com/b/kaevans/archive/2011/11/14/add-microsoft-sharepoint-powershell-snap-in-to-all-powershell-windows.aspx



Tuesday, 18 September 2012

HOW TO PRINT A DATATABLE TO PDF FORM USING MIGRADOC AND PDFSHARP


HOW TO PRINT A DATATABLE TO PDF FORM USING MIGRADOC AND PDFSHARP

I. INTRODUCTION
This post will detail out how to print a datatable in a PDF form using Migradoc and PDFSharp (http://www.pdfsharp.com/PDFsharp/).  This functionality can be accomplished using a regular web application but since I was asked to do it in Sharepoint, the step by step implementation will be via a Sharepoint site collection. Special thanks to Mr. John Arrieta who is the original creator of this POC.

II. SCOPE
This post assumes that there is already an existing site collection created in Sharepoint 2010. The content of the datatable doesn’t come from an external data source and was just hard-coded for the purpose of presentation.

III. REQUIREMENTS
- Sharepoint 2010
- Visual Studio 2010
- Migradoc and PDF Assemblies (required DLLs)

IV. IMPLEMENTATION

1.  Open Visual Studio and create an Empty Sharepoint Application. Input your Site Collection URL and click Finish. On my VM, the site collection URL is (http://valedevserver:3706)



2. Since we will be using third-party assemblies for the PDF printing, you have to download the required DLLs in (http://www.pdfsharp.com/PDFsharp/). In the Solution Explorer Toolbar, right-click on references and click on ‘Add Reference’.  On the dialog box, add the assemblies needed.




3. We will create a class that will contain the methods to print our datatable. On the Solution Explorer Toolbar, right-click on ‘Add’  and then ‘New Item’. Create a new class. In my solution, I have named my class to be PDFform.cs.



4. Add the reference in the using section on the newly created class file. This class file handles the creation and formatting of the PDF.

using System.Data;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.DocumentObjectModel.Shapes;

5. Replace the contents of your class with the codes below.

class PDFform
    {
        // The MigraDoc document that represents the invoice.
        Document document;
        DataTable dt;
        string path;
                
        // The text frame of the MigraDoc document that contains the address.
        TextFrame addressFrame;
/// The table of the MigraDoc document that contains the data
  Table table;

// Initializes a new instance of the class and opens the specified datasource
        public PDFform(DataTable dtIn, string pathIn)
        {
            dt = dtIn;
            path = pathIn;
        }
// Creates the document.
        public Document CreateDocument()
        {
            // Create a new MigraDoc document
            this.document = new Document();
            this.document.Info.Title = "";
            this.document.Info.Subject = "";
            this.document.Info.Author = "Aftab";
DefineStyles();
CreatePage();
FillContent();

return this.document;
        }
// Defines the styles used to format the MigraDoc document.
        void DefineStyles()
        {
            // Get the predefined style Normal.
            Style style = this.document.Styles["Normal"];
            // Because all styles are derived from Normal, the next line changes the 
            // font of the whole document. Or, more exactly, it changes the font of
            // all styles and paragraphs that do not redefine the font.
            style.Font.Name = "Verdana";
style = this.document.Styles[StyleNames.Header];
            style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = this.document.Styles[StyleNames.Footer];
            style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
            style = this.document.Styles.AddStyle("Table", "Normal");
            style.Font.Name = "Verdana";
            style.Font.Name = "Times New Roman";
            style.Font.Size = 9;
// Create a new style called Reference based on style Normal
            style = this.document.Styles.AddStyle("Reference", "Normal");
            style.ParagraphFormat.SpaceBefore = "5mm";
            style.ParagraphFormat.SpaceAfter = "5mm";
            style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
        }
// Creates the static parts of the invoice.
        void CreatePage()
        {
            // Sets the PDF Page Orientation
            this.document.DefaultPageSetup.Orientation = Orientation.Landscape;
// Each MigraDoc document needs at least one section.
            Section section = this.document.AddSection();

// Put a logo in the header
            Image image = section.AddImage(path);
image.Top = ShapePosition.Top;
            image.Left = ShapePosition.Left;
            image.WrapFormat.Style = WrapStyle.Through;
// Create footer
            Paragraph paragraph = section.Footers.Primary.AddParagraph();
            paragraph.AddText("This is the footer section");
            paragraph.Format.Font.Size = 9;
            paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
            this.addressFrame = section.AddTextFrame();
            this.addressFrame.Height = "3.0cm";
            this.addressFrame.Width = "7.0cm";
            this.addressFrame.Left = ShapePosition.Left;
            this.addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
            this.addressFrame.Top = "5.0cm";
            this.addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
            paragraph = this.addressFrame.AddParagraph("Karachi,Pakistan");
            paragraph.Format.Font.Name = "Times New Roman";
            paragraph.Format.Font.Size = 7;
            paragraph.Format.SpaceAfter = 3;
// Add the print date field
            paragraph = section.AddParagraph();
            paragraph.Format.SpaceBefore = "6cm";
            paragraph.Style = "Reference";
            paragraph.AddFormattedText("Patients Detail", TextFormat.Bold);
            paragraph.AddTab();
            paragraph.AddText("Date, ");
            paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
            this.table = section.AddTable();
            this.table.Style = "Table";
            this.table.Borders.Color = TableBorder;
            this.table.Borders.Width = 0.25;
            this.table.Borders.Left.Width = 0.5;
            this.table.Borders.Right.Width = 0.5;
            this.table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
            Column column;
            foreach (DataColumn col in dt.Columns)
            {
                column = this.table.AddColumn(Unit.FromCentimeter(3));
                column.Format.Alignment = ParagraphAlignment.Center;
            }
// Create the header of the table
            Row row = table.AddRow();
            row.HeadingFormat = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color = TableBlue;

for (int i = 0; i < dt.Columns.Count; i++)
            {
                row.Cells[i].AddParagraph(dt.Columns[i].ColumnName);
                row.Cells[i].Format.Font.Bold = false;
                row.Cells[i].Format.Alignment = ParagraphAlignment.Left;
                row.Cells[i].VerticalAlignment = VerticalAlignment.Bottom;
            }
this.table.SetEdge(0, 0, dt.Columns.Count, 1, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
        }
// Creates the dynamic parts of the PDF
        void FillContent()
        {
            // Fill address in address text frame
            Paragraph paragraph = this.addressFrame.AddParagraph();
            paragraph.AddText("Dr. Anwar Ali");
            paragraph.AddLineBreak();
            paragraph.AddText("Health And Social Services ");
            paragraph.AddLineBreak();
            paragraph.AddText("Karachi");
            Row newRow;
for (int i = 0; i < dt.Rows.Count; i++)
            {
                // Format Cells and Display Records
                newRow = this.table.AddRow();
                newRow.TopPadding = 1.5;
for (int j = 0; j < dt.Columns.Count; j++)
                {
                    newRow.Cells[j].Shading.Color = TableGray;
                    newRow.Cells[j].VerticalAlignment = VerticalAlignment.Center;
newRow.Cells[j].Format.Alignment = ParagraphAlignment.Left;
                    newRow.Cells[j].Format.FirstLineIndent = 1;
                    newRow.Cells[j].AddParagraph(dt.Rows[i][j].ToString());
         this.table.SetEdge(0, this.table.Rows.Count - 2, dt.Columns.Count, 1, Edge.Box, BorderStyle.Single, 0.75);
                }
            }
        }
// Some pre-defined colors
#if true
        // RGB colors
        readonly static Color TableBorder = new Color(81, 125, 192);
        readonly static Color TableBlue = new Color(235, 240, 249);
        readonly static Color TableGray = new Color(242, 242, 242);
#else
    // CMYK colors
    readonly static Color tableBorder = Color.FromCmyk(100, 50, 0, 30);
    readonly static Color tableBlue = Color.FromCmyk(0, 80, 50, 30);
    readonly static Color tableGray = Color.FromCmyk(30, 0, 0, 0, 100);
#endif
    }

5. For the next step, we will create a webpart that will serve as our User Interface for this function. Right-click on our Sharepoint solution and click on ‘New Item’ and then select ‘Visual Webpart’.

6. Create a Gridview on the User Control. This will contain our hard-coded datatable and a button that will trigger our PDF printing. Our user interface will look something like the one below.



6. On the source code of the created visual webpart, add javascript function that creates a new browser window to display the generated PDF. Set the OnClientClick event of the button to the javascript function.

<script type="text/javascript">
        function PostToNewWindow() {
            originalTarget = document.forms[0].target;
            document.forms[0].target = '_blank';
            window.setTimeout("document.forms[0].target=originalTarget;", 300);
            return true;
        } 
</script>

<asp:Button ID="btnSaveViewPDF" runat="server" onclick="btnSaveViewPDF_Click"
    Text="Save  and View PDF" OnClientClick="return PostToNewWindow();" />

7. On the code-behind of the created visual webpart, add the following code on the PageLoad event and ButtonClick events. A script fix has been added on the PageLoad to handle viewing of PDF in a new browser window.  ButtonClick event handles the creation of the PDF by calling the PDFform class created earlier and saves it in the 14th hive of Sharepoint, then renders the saved PDF document on a new browser window.

DataTable dt = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            // Script Fix for Viewing PDF in a new browser window
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), 
                "UpdatePanelFixup", "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", true);

// Sample Data
            dt.Columns.Add("Column 1", typeof(string));
            dt.Columns.Add("Column 2", typeof(string));
            dt.Columns.Add("Column 3", typeof(string));
            dt.Rows.Add("Data 1", "Data 2", "Data 3");
            dt.Rows.Add("Data 1", "Data 2", "Data 3");
            dt.Rows.Add("Data 1", "Data 2", "Data 3");

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
      protected void btnSaveViewPDF_Click(object sender, EventArgs e)
        {
                // Create instance of PDFform class
                PDFform pdfForm = new PDFform(dt, "ImageLogo");
                // Create a MigraDoc document
                MigraDoc.DocumentObjectModel.Document document = pdfForm.CreateDocument();
                document.UseCmykColor = true;
                // Create a renderer for PDF that uses Unicode font encoding
                PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
                // Set the MigraDoc document
                pdfRenderer.Document = document;
                // Create the PDF document
                pdfRenderer.RenderDocument();
                // Save the PDF document...
                string filename = "PDFReport1.pdf";
                //14 Hive Path
                string spSetupPath = SPUtility.GetGenericSetupPath(string.Empty);
                pdfRenderer.Save(spSetupPath + filename); ;
                // ...and start a viewer.
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                //Set the appropriate ContentType.         
                Response.ContentType = "Application/pdf";
                //Get the physical path to the file.         
                Response.WriteFile(spSetupPath + filename);
                Response.Flush();
                Response.End();
        }


8. On this step, the solution is now ready to be deployed in Sharepoint. Right-click on our Sharepoint solution and click on Deploy.

9. To consume our Visual webpart, Edit a page and insert a webpart.  On the Categories section, Click on the Customs group. Add the custom webpart (VisualWebPart1) on the Sharepoint page.



10. Clicking the button will open a new browser window containing the generated PDF. Created PDF is located at the 14 hive.





Friday, 14 September 2012

HOW TO READ AN EXCEL DATA USING SHAREPOINT WEB SERVICES


INTRODUCTION
This post aims to describe how to access Excel File data using the built-in Excel webservice exposed by Sharepoint. It will also detail out how to export extracted data from an Excel file to a datatable.

SCOPE
This post assumes that the Excel File has already been uploaded into one of the document libraries (Shared Documents) in a site collection. It will not detail out how to upload Excel files in a document library.

REQUIREMENTS
-Sharepoint 2010
-Visual Studio 2010

IMPLEMENTATION


1.  Open Visual Studio and create an Empty Sharepoint Application. Input your Site Collection URL and click Finish.




2. On the Solution Explorer Toolbar, right-click on references and click on ‘Add Service Reference’. Click on the ‘Advanced’ button. On the dialog box, Click on Add Web Reference button.




3. On the Add Web Reference dialog box, access the excelservice.asmx. On my Virtual Machine, the URL is: ‘http://win-a80foe01p0e:4039/_vti_bin/excelservice.asmx’. Type in the name of the Web reference and click on the ‘Add Reference’ button.





4. In this tutorial, I have named my Web Reference to be ‘XLService’. This should now be available in the web references section in the Solution Explorer.

5. On your code-behind file, add a reference to the Excel Service in the Using section.

using TestExcelServices.XLService;

6. Inside your method, create an instance of the ExcelService class and set its URL and Credentials Properties. When the application calls the web service, the default network credentials need to be passed to the web service to get authenticated to use the data repository.

ExcelService objXL = new ExcelService();

objXL.Url = @"http://win-a80foe01p0e:4039/_vti_bin/excelservice.asmx";
objXL.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

7. Next is to create the datatable that will be the container of the queried data from the Excel file. On this example, I will declare a datatable with 4 columns.

//Create Datatable Structure
DataTable dt = new DataTable();
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("ProductType", typeof(string));
dt.Columns.Add("Date", typeof(string));
dt.Columns.Add("TotalProductType", typeof(int));

8. Declare the Cell ranges of each of your fields on the datatable.

My Excel file looks something like the one below:



On this example, I will assign my cell ranges to be like this:
string ProductRange = "B2:B1000";
string ProductTypeRange = "C2:C1000";
string DateRange = "E2:E1000";
string TotalProductRange = "D2:D1000";

9. Get the SessionID by calling the OpenWorkbook method. Add on your code like the one below.

string sessionID = objXL.OpenWorkbook(@"http://win-a80foe01p0e:4039/Shared%20Documents/Test.xlsx", "en-US", "en-US", out wsStatus);

10. Call the GetRangeA1 method to query the excel data per range. So for my example, the following code should be implemented.

object[] ProductData = objXL.GetRangeA1(sessionID, sheetName, ProductRange, false, out wsStatus);
object[] ProductTypeData = objXL.GetRangeA1(sessionID, sheetName, ProductTypeRange, false, out wsStatus);
object[] DateData = objXL.GetRangeA1(sessionID, sheetName, DateRange, false, out wsStatus);
object[] TotalProductData = objXL.GetRangeA1(sessionID, sheetName, TotalProductRange, false, out wsStatus);

11. Formulate a For Loop that will browse through each of the generated objects and save it on the datatable that we have created earlier.

for (int i = 0; i < ProductData.Length; i++)
            {
                if (string.IsNullOrEmpty(Convert.ToString(((object[])(ProductData[i]))[0])))
                {
                    break;
                }
                newRow = dt.NewRow();
                newRow["Product"] = ((object[])(ProductData[i]))[0].ToString();
                newRow["ProductType"] = ((object[])(ProductTypeData[i]))[0].ToString();
                newRow["Date"] = ((object[])(DateData[i]))[0].ToString();
                newRow["TotalProductType"] = Convert.ToInt32(((object[])(TotalProductData[i]))[0]);

                dt.Rows.Add(newRow);
            }

12. Here is the complete code for this method.



13. After this call, we can now bind the resulting datatable in our gridview.

Thursday, 13 September 2012

HOW TO DEPLOY INFOPATH FORMS USING POWERSHELL

INTRODUCTION
This post aims to describe how to deploy infopath forms as form templates in a sharepoint site using Powershell.

SCOPE
This post will not detail out how to create a custom infopath form. It will assume that there is already an existing Infopath source files that are for deployment.
  
REQUIREMENTS
Sharepoint 2010
Microsoft Infopath Designer 2010

IMPLEMENTATION

1.Locate the manifest.xml, right-click and click on Design. The Infopath Designer should load.


2.Whenever modifications have been made to the form, it is a good practice to change the version of the infopath form. This is because when you create a version 1.0 and so on for a form, all of the previous versions will be saved in Sharepoint. To do this, Click on File on the Infopath Form Designer. On the Info Ribbon tab, Click on Advanced Form Options.
The Form Option dialog box should appear.


3.Change the version on the Version field.
4.[Not Required] If you would like to create another set of source files for the modified Infopath form, you can do so by re-exporting the source files into another location.
Click File and select the Publish Ribbon. Click on the Export Source Files.


5.Select the folder where you want to save the Source Files. On the Folder field, type in the folder name where you want to save the files.

6.To publish your form into an Infopath .xsn format, Click on File and Click on the Info Ribbon Tab. On the Info Ribbon Tab, Click on the Quick Publish button.


7.Please take note on the location of the .xsn to be published. The directory is displayed on the right hand part of the Quick Publish section.




8.This operation will result in the creation of a .xsn file. A .xsn file defines the data structure, appearance, and behavior of Finished forms. This particular file is what is to be deployed in sharepoint.




9.Deploy Infopath form using Powershell. Click on Start>All Programs>Microsoft Sharepoint 2010 Products. Click on Sharepoint 2010 Management Shell.




10.To Uninstall the existing xsn Form Template. Type in the Management shell

Uninstall-SPInfoPathFormTemplate -Identity Exampleform.xsn


11.Install the new solution based on the .xsn file path. For example, the .xsn is located in drive c:/

Install-SPInfoPathFormTemplate -Path C:\Form.xsn

12.To disable the feature on the site collection level, type in the management shell. For example, the site collection URL is http://SPSite.

Disable-SPInfoPathFormTemplate -Identity "Form.xsn" -Site http://SPSite 

13.To enable the feature on the site collection level, type in the management shell. For example, the site collection URL is http://SPSite.

Enable-SPInfoPathFormTemplate -Identity "Form.xsn" -Site "http://SPSite"

14.Verify that the form was indeed deployed on the Sharepoint site. Browse to your site, make sure that you have the necessary rights to view the Form Templates. Click on Site Actions > View All Site Contents and Click on Form Templates.




15.The Infopath form should be on the List of the Form Templates.






Oscar L. Barit Jr. "I am Oca, i am writing to share with you some sharepoint matters that i learned on my day job. Enjoy! Mwah Mwah Tsup Tsup! "