Monday 31 December 2012

Hiding the Site Actions button on Public Facing SharePoint Foundation (or Server) sites:

• Open up SharePoint Designer
• Open the Master Page being utilized for your sites
• Locate the following snippet of code:
   Collapse | Copy Code
  <span class="ms-siteactionsmenu" id="siteactiontd">
• Add:
  Collapse | Copy Code
<SharePoint:SPSecurityTrimmedControl runat="server" Permissions="ManageSubWebs">just before the line of code in 3.
• Right click on the tag in step 3 and click on Select Tag.
• Enter this after the span tag: </SharePoint:SPSecurityTrimmedControl>.
• Save the Master Page.
• Approve and publish if required (server version).

How to Add Data Connection and convert Data connection into UDC (Universal Data Connection ) file in InfoPath 2010 with SharePoint 2010.

Following Steps:- For Add New Data Connection:

1. Open InfoPath Designer 2010- Select "New" Tab- Select "Blank Form" then Click "Design".
2. Go to Data tab - Click "Data Connection" then Click Add.

3. One Pop window open then Select "Receive data" and then Next.
4. Then Select the source of your data like "SharePoint Library or List".
5.  Provide SharePoint Site Details http://Server-name/sites/site-name/.
6. Then Select list or libraray, then Next and Select Fields.
7. Then Next and finaly Ok.



Following Steps:- For Convert Data Connection into UDC File:

1. Open the Data Connection in Data Tab, then Select the Data connection file and click "Convert to connection File".
2. Provide Specify the URL of the New Data connection file in sharepoint(like Data Connection Library) (for example: http://server-name/sites/site-name/DataConnection/test.udcx)
3. And select the Relative to Site Collection in Collection link type.
4 Then Click Ok and Check in SharePoint Data Connection Library.

Sunday 30 December 2012

New for InfoPath 2013 Developers.

What's New for InfoPath 2013 Developers


InfoPath is designed to make it easy to build rich forms-based applications on the Microsoft SharePoint Server platform. Microsoft InfoPath 2013 in conjunction with Microsoft SharePoint Server 2013 and InfoPath Forms Services have many features for developers. InfoPath Forms Services, which is available in SharePoint Server 2013, enables you to deploy an InfoPath form template to a SharePoint Server so that users without the InfoPath rich client can open and fill out InfoPath forms in a Web browser.

Form templates created using InfoPath 2013 continue to support business logic written against the classes and members of the Microsoft.Office.InfoPath namespace, which works the same way for a form opened in the InfoPath filler and in a form opened in a Web browser. By using business logic written to this managed object model, and by working with design checking features in InfoPath Designer, you can create a single form template that you can deploy to an appropriately configured document library on SharePoint Server 2013, which will run in both the InfoPath filler and in a Web browser.

    New Features and Improvements

  • New Way to Write and Edit Code
  • SharePoint Sandboxed Solutions
  • Publish Forms with One Click
  • Enhance SharePoint List Forms
  • Host Forms on Portal Pages using the InfoPath Form Web Part
  • Richer Web Forms
  • Standards Compliant Browser Forms
  • Provide Enhanced Information Security and Integrity with Digital Signatures
  • New Controls

New Way to Write and Edit Code

The Microsoft Visual Studio Tools for Applications IDE that was integrated with InfoPath 2010 has been removed in InfoPath 2013. To write or edit form code in InfoPath 2013 now requires Visual Studio 2012 with the Microsoft Visual Studio Tools for Applications 2012 add-on installed. The programming experience itself has not fundamentally changed, but you can now use the full Visual Studio development experience when writing managed code for your InfoPath forms.

The following sections describe features that were first added in InfoPath 2010 and SharePoint Server 2010 and continue to add value for developers using InfoPath 2013 and SharePoint Server 2013.


SharePoint Sandboxed Solutions

With InfoPath, it is easier than ever to deploy forms with code to SharePoint Server 2013. In Office InfoPath 2007, all forms with code had to be approved and uploaded by a SharePoint farm administrator. With support for sandboxed solutions in SharePoint Server 2013, form designers that have site collection administration permissions can now publish most forms with code, directly to their SharePoint sites. A resource quota setting on the server limits excessive resource usage. The site collection administrator remains in control and makes trust decisions about the solution. The farm administrator can be hands-off. For more information about publishing InfoPath form templates as sandboxed solutions


Publish Forms with One Click

InfoPath is designed to make it easier than ever to publish updates to your forms.. After the first time that you publish a form template, instead of clicking through several dialog boxes, you can complete this task with one click of the new Quick Publish button, which is available on the Quick Access Toolbar, and in the new Microsoft Office Backstage, which is available by clicking the File tab.


Enhance SharePoint List Forms

Using InfoPath, you can now extend and enhance the forms used for creating, editing and viewing items in a SharePoint list. By opening a list, clicking the List tab under List Tools, and then clicking Customize Form, you can auto generate an InfoPath form which resembles the default, out-of-the-box SharePoint list form. You can then customize and enhance this form by modifying the layout, creating additional views, and adding rules and data validation in InfoPath. When you are finished modifying your improved list form, you can publish it to SharePoint using the new one-click publish feature in InfoPath.


Host Forms on Portal Pages using the InfoPath Form Web Part

In SharePoint Server 2013, it is easier than ever to host your forms on Web pages using the new InfoPath Form Web Part. In Microsoft Office SharePoint Server 2007, users who want host their InfoPath forms on Web pages have to write code in Visual Studio. Now, without writing a single line of code, you can add theInfoPath Form Web Part to a Web Parts page and point it to your published form.You can use theInfoPath Form Web Part to host any InfoPath browser form that is published to a SharePoint list or form library. You can also connect it to other Web Parts on the page to send or receive data.


Richer Web Forms

The feature gap between client and browser forms has been narrowed, creating a more consistent form filling experience for all users. Controls and functionality that are now supported in browser forms include the following:

  • Bulleted, numbered, and plain lists
  • Multiple selection list boxes
  • Combo boxes
  • Picture buttons
  • Hyperlink capabilities
  • Choice group and section
  • Date and time controls
  • Person/group pickers
  • Filtering functionality

  • Standards Compliant Browser Forms

    InfoPath browser forms are now compliant with Web Content Accessibility Guidelines 2.0 (WCAG 2.0) AA, which enables form designers to create forms that are available for users with disabilities.


    Provide Enhanced Information Security and Integrity with Digital Signatures

    InfoPath supports Cryptography Next Generation (CNG) digitally signed content. To help you ensure the integrity of the information that is contained in your forms, the InfoPath client and SharePoint Server 2013 provide the controls necessary to enable single, co-sign, and counter-sign scenarios for the full form or sections of the form. Forms can be signed in Internet Explorer using the ActiveX signature line control. Signed forms can be viewed in any browser supported by SharePoint Server 2013.


    New Controls

    InfoPath provides a richer set of controls that can be added to your forms. The following list briefly describes some of the new controls:

  • Picture Button — Instead of a gray rectangle; use any image as a button in your form.
  • Hyperlink — Enable users to enter their own hyperlinks when filling out forms.
  • Person/Group Picker — Enable users to check and query account names and groups when filling out forms.
  • Entity Picker — Enable users to select values from external lists on a server that is running SharePoint Server 2013 when forms.
  • Signature Line — Provide users with a signature line or stamp image, such as an inkan or hanko seal, when digitally signing forms.

  • Thursday 20 December 2012

    4 Ways to programmatically add a row to a repeating table in InfoPath

    Method 1 - Use a string to add a row to a repeating table in Infopath:-


    string my = NamespaceManager.LookupNamespace("my");
    StringBuilder sb = new StringBuilder();
    sb.Append("<my:group2 xmlns:my=\"");
    sb.Append(my);
    sb.Append("\">");
    sb.Append("<my:field1 xmlns:my=\"");
    sb.Append(my);
    sb.Append("\">");
    sb.Append("Cell 1");
    sb.Append("</my:field1>");
    sb.Append("<my:field2 xmlns:my=\"");
    sb.Append(my);
    sb.Append("\">");
    sb.Append("Cell 2");
    sb.Append("</my:field2>");
    sb.Append("<my:field3 xmlns:my=\"");
    sb.Append(my);
    sb.Append("\">");
    sb.Append("Cell 3");
    sb.Append("</my:field3>");
    sb.Append("</my:group2>");
    MainDataSource.CreateNavigator().SelectSingleNode(
    &nsbp; "/my:myFields/my:group1", NamespaceManager).AppendChild(sb.ToString());


    Method 2 - Use an XPathNavigator object to add a row to a repeating table in InfoPath:-

    XmlDocument doc = new XmlDocument();
    XmlNode group = doc.CreateElement("group2", NamespaceManager.LookupNamespace("my"));
    XmlNode field = doc.CreateElement("field1", NamespaceManager.LookupNamespace("my"));
    XmlNode node = group.AppendChild(field);
    node.InnerText = "Cell 1";
    field = doc.CreateElement("field2", NamespaceManager.LookupNamespace("my"));
    node = group.AppendChild(field);
    node.InnerText = "Cell 2";
    field = doc.CreateElement("field3", NamespaceManager.LookupNamespace("my"));
    node = group.AppendChild(field);
    node.InnerText = "Cell 3";
    doc.AppendChild(group);
    MainDataSource.CreateNavigator().SelectSingleNode(
      "/my:myFields/my:group1",
      NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());

    Method 3 - Use an XMLReader object to add a row to a repeating table in InfoPath:-

    <my:group2 xmlns:my="the_xml_namespace_of_your_form_template_goes_here">
      <my:field1 xmlns:my="the_xml_namespace_of_your_form_template_goes_here">Cell 1</my:field1>
      <my:field2 xmlns:my="the_xml_namespace_of_your_form_template_goes_here">Cell 2</my:field2>
      <my:field3 xmlns:my="the_xml_namespace_of_your_form_template_goes_here">Cell 3</my:field3>
    </my:group2>
    Code to add a row to the repeating table in InfoPath:
    using (FileStream fs = new FileStream(@"C:\row.xml", FileMode.Open))
    {
      using (XmlReader reader = XmlReader.Create(fs))
      {
        MainDataSource.CreateNavigator().SelectSingleNode(
          "/my:myFields/my:group1", NamespaceManager).AppendChild(reader);
        reader.Close();
      }
      fs.Close();
    }

    Method 4 - Use an XmlWriter object to add a row to a repeating table in Infopath:-

    string myNamespace = NamespaceManager.LookupNamespace("my");
    using (XmlWriter writer = MainDataSource.CreateNavigator().SelectSingleNode(
    "/my:myFields/my:group1", NamespaceManager).AppendChild())
    {
    writer.WriteStartElement("group2", myNamespace);
    writer.WriteElementString("field1", myNamespace, "Cell 1");
    writer.WriteElementString("field2", myNamespace, "Cell 2");
    writer.WriteElementString("field3", myNamespace, "Cell 3");
    writer.WriteEndElement();
    writer.Close();
    }

    Programmatically select all items in a multiple-selection (multi-select) list box

    Following the code:_

    XPathNodeIterator players = DataSources["players"].CreateNavigator().Select(
    "//player", NamespaceManager);
    foreach (XPathNavigator player in players)
    {
    string number = player.SelectSingleNode("number", NamespaceManager).Value;
    AddItem(number);
    }

    Programmatically add lines of text to a Rich Text Box field on an InfoPath form using C# code

    Following the Code:-

    XPathNavigator nav = MainDataSource.CreateNavigator();
    XPathNavigator rtfNav = nav.SelectSingleNode("//my:rtfField", NamespaceManager);
    XmlDocument doc = new XmlDocument();
    XmlElement elm = doc.CreateElement("div", "http://www.w3.org/1999/xhtml");
    elm.InnerText = "Line 1";
    doc.AppendChild(elm);
    rtfNav.AppendChild(doc.DocumentElement.CreateNavigator());
    doc = new XmlDocument();
    elm = doc.CreateElement("div", "http://www.w3.org/1999/xhtml");
    elm.InnerText = "Line 2";
    doc.AppendChild(elm);
    rtfNav.AppendChild(doc.DocumentElement.CreateNavigator());

    How to get HTML tags to appear as HTML and not as plain text in a Rich Text Box

    Following the code:-


    MainDataSource.CreateNavigator().SelectSingleNode("//my:rtfField", NamespaceManager).AppendChild("<h2 xmlns=\"http://www.w3.org/1999/xhtml\">Header Text</h2><p xmlns=\"http://www.w3.org/1999/xhtml\">This is some paragraph text.</p>");

    How do I call a web service through code?

    Following the code:_

    // Create an XPathNavigator object to navigate the data source of the web service
    XPathNavigator nav = DataSources["HelloWorld"].CreateNavigator();

    // Set the value of the parameter to pass to the web service
    nav.SelectSingleNode("//dfs:queryFields/tns:HelloWorld/tns:name", NamespaceManager).SetValue("myValue");

    // Call the web service
    DataSources["HelloWorld"].QueryConnection.Execute();

    // Retrieve the results returned by the web service
    string results = nav.SelectSingleNode("//dfs:dataFields/tns:HelloWorldResponse/tns:HelloWorldResult", NamespaceManager).Value;

    How do I set the value of an InfoPath field through code?

    Following the code:-

    XPathNavigator nav = MainDataSource.CreateNavigator();
    nav.SelectSingleNode("//my:field1", NamespaceManager).SetValue("myValue");

    How do I retrieve the value of an InfoPath field through code?

    Following the code:-

    XPathNavigator nav = MainDataSource.CreateNavigator();
    string fieldValue = nav.SelectSingleNode("//my:field1", NamespaceManager).Value;

    Friday 30 November 2012

    Using SharePoint PowerShell, Empty the Recycle Bin.


    $w = get-spweb http://server-name/sites/site-name
    $w.RecycleBin.DeleteAll()

    Using SharePoint PowerShell, Delete Multiple Items form SharePoint 2010 List or Library.

    Batch delete multiple items using power shell in sharepoint 2010 list or library.

    - You provide only server-name and list or library -name.
    - Items delete from list or library.
    - Also Items delete from Recycle Bin.   

    [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    write-host

    $siteUrl = "http://Server-name/sites/site-name"
    $listName = "List/Library-name"
    $batchSize = 1000
    write-host "Opening web at $siteUrl..."
    $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
    $web = $site.OpenWeb()
    write-host "Web is: $($web.Title)"
    $list = $web.Lists[$listName];
    write-host "List is: $($list.Title)"
    while ($list.ItemCount -gt 0)
    {
      write-host "Item count: $($list.ItemCount)"
      $batch = "<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>"
      $i = 0
      foreach ($item in $list.Items)
      {
        $i++
        write-host "`rProcessing ID: $($item.ID) ($i of $batchSize)" -nonewline
        $batch += "<Method><SetList Scope=`"Request`">$($list.ID)</SetList><SetVar Name=`"ID`">$($item.ID)</SetVar><SetVar Name=`"Cmd`">Delete</SetVar><SetVar Name=`"owsfileref`">$($item.File.ServerRelativeUrl)</SetVar></Method>"
        if ($i -ge $batchSize) { break }
      }
      $batch += "</Batch>"
      write-host
      write-host "Sending batch..."
      # We execute it
      $result = $web.ProcessBatchData($batch)
      write-host "Emptying Recycle Bin..."
      # We remove items from recyclebin
      $web.RecycleBin.DeleteAll()
      write-host
      $list.Update()
    }
    write-host "Done."

    Monday 26 November 2012

    Check that Form Out (or in) Automatically! in Infopath 2010 using Web Services

    Following are the steps to create Check-in and Check-out Infopath form:

    1. Create one Infopath Form.
    2. Add Data Connection, select "Recevice Data" then next.
    3. Select "SOAP  Web Service", next,
    4. Enter the location like (http://server-name/_vti_bin/Lists.asmx ), next,
    5. Select "CheckIn", next. ok ( Same steps for "CheckOut").
    6. Add Form Library Data Connection, select "Recevice Data" then next,
    7. Select "SharePoint Library or List", next,
    8. Enter the location like ("http://server-name/CheckInOutLib/Forms/AllItems.aspx"), next
    9. Select the check box of "Check_Out_To" and "Include data for the active form only", next
    10. then Ok.

    Add some controls in infopath form:-
    1. Two buttons for event fire( Check-in and Check-out)
    2. Two Text for message (MessageCheckin and MessageCheckout)

    Process of Call or Use for web service:

    1. Right click, CheckOut  Buttton and add Rule "Action" equal
           Conditions:               
                              AccountID is blank ( CheckOutFile )
                              Title is not blank ( CheckInOutLib )
           Rule Action:
                            PageUrl is concat("http://server-name/CheckInOutLib/", Title, ".xml")     
                            checkoutToLocal is true()
                            Query for data (CheckOutFile)
                            Query for data (CheckInOutLib)
                             MessageCheckOut is concat(DisplayName, "is check out the form")

    2. Right click, Check-In Button and add Rule "Action" equal
                            PageUrl is concat("http://server-name/CheckInOutLib/", Title, ".xml")     
                            comment is "Form is check In"
                            CheckinType is 2
                            Query for data (CheckInFile)
                            Query for data (CheckInOutLib)
                             MessageCheckOut is concat( "the form is Check In")

    Monday 19 November 2012

    Export list or library into Excel using JavaScript

    Using JavaScript, List or Libaray Items export to Excel

    Add one Content Editor in ur pages:

    <script language="javascript" src="/sites/web/SiteAssets/JS/Export.js"></script><input class="ms-rteThemeBackColor-5-4" onclick="exportToExcel();" type="button" value="Export"/>

    function exportToExcel()
    {
    var strTableID = "onetidDoclibViewTbl0";
    var detailsTable = document.getElementById(strTableID);
    var columns = detailsTable.getElementsByTagName("th");
    var oExcel = new ActiveXObject("Excel.Application");
    var oBook = oExcel.Workbooks.Add;
    var oSheet = oBook.Worksheets(1);
    for(i=0;i<columns.length;i++){
           oSheet.cells(1,i+1).value= columns.innerText; //XlSheetHeader;
           oSheet.cells(1,i+1).font.color="6";
           oSheet.cells(1,i+1).font.bold="true";
               oSheet.cells(1,i+1).interior.colorindex="15";
               oSheet.cells(1,i+1).columnwidth =20;
       }
    for (var y=0;y<detailsTable.rows.length;y++)
    {
        for (var x=0;x<detailsTable.rows(y).cells.length;x++)
        {
            oSheet.Cells(y+1,x+1) = detailsTable.rows(y).cells(x).innerText;
        }
    }
    oSheet.columns.autofit;
    oExcel.Visible = true;
    oExcel.UserControl = true;
    }

    Friday 9 November 2012

    Data Migration Excel to Infopath 2010 form in sharepoint 2010 Form Library

    How to data migration from excel to infopath 2010 form in sharepoint 2010 form library?


    Following are the important file:

    First make xml file: sample.xml

    <?xml version="1.0"?>
    <?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:example:-myXSD-2012-03-23T05-13-59" solutionVersion="1.0.0.903" productVersion="14.0.0.0" PIVersion="1.0.0.0" href="https://server-name/sites/site-name/FormServerTemplates/example.xsn"?><?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?>
    <my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-03-23T05:13:59" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
     
    <my:GeneralInfo>
        <my:ddDivision>NameExample_mapped</my:ddDivision>
    </my:GeneralInfo>

    Second make excel file: sources.xlsx

    one column name-NameExample

    Code for Data Migrations:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Client;
    using System.IO;
    using System.Xml;
    using System.Data.OleDb;
    using System.Data;
    using System.Collections;
    using System.Globalization;
    using System.Threading;
    using System.Net;


    namespace Example
    {
    class Program
    {
    static string strURL = "https://app-int.eu.novartis.net/ph/exmaple/";
    static string strFormsFolder = @"D:\datamir\exmaple\Forms\";
    static string strSampleForm = @"D:\datamir\exmaple\Sample.xml";

    static NetworkCredential credentials = new NetworkCredential("test", "test", "server");

    static DataSet dataSet = null;

    static StringBuilder sbSampleForm = null;
    static void Main(string[] args)
    {
    try
    {
    CreateInfoPathForms();
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }
    Console.Read();
    }
    private static void CreateInfoPathForms()
    {
    ReadXLS();
    ReadSampleForm();
    ArrayList arFilename = new ArrayList();
     foreach (DataRow dr in dataSet.Tables[0].Rows)
                {
                   try
                    {
                       
                        string strContract = sbSampleForm.ToString();
                       
                        foreach (DataColumn dc in dataSet.Tables[0].Columns)
                        {
                            strContract = strContract.Replace(dc.ColumnName.ToString() + "_mapped", System.Security.SecurityElement.Escape(dr[dc.ColumnName].ToString()));
                      
                        }
                       
                         string storeDatetime;
                            try
                            {
                                storeDatetime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'.'mm'.'ss.fffffff");
                                string strFileName = dr["NameExample"].ToString() + "-" + storeDatetime + ".xml";
                               if (!arFilename.Contains(strFileName))
                               {
                                   arFilename.Add(strFileName);
                               }
                               else
                               {
                                   storeDatetime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'.'mm'.'ss.fffffff") + intCount.ToString();
                                   strFileName = dr["GEMCountry"].ToString() + "-" + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'.'mm'.'ss.fffffff") + storeDatetime + ".xml";
                                   arFilename.Add(strFileName);
                               }
                            
                                CreateFormFromTemplate(strFileName, strContract);
                                Console.WriteLine("Form is created");
                                ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true;
                               
                                ClientContext context = new ClientContext(strURL);
                                context.Credentials = credentials;
                                Web web = context.Web;
                                FileCreationInformation newFile = new FileCreationInformation();
                                newFile.Content = System.IO.File.ReadAllBytes(strFormsFolder + strFileName);
                                newFile.Url = strFileName;
                                List docs = web.Lists.GetByTitle("Lib");
                               
                                Microsoft.SharePoint.Client.Folder uploadFile = docs.RootFolder.Folders.Add(dr["Country"].ToString());
                                Microsoft.SharePoint.Client.File fileup = uploadFile.Files.Add(newFile);
                                context.Load(fileup);
                                context.ExecuteQuery();
                                WriteLog("Uploaded to SharePoint site is completed.");
                                Console.WriteLine("Form is created");
                            }
                            catch (Exception ex1)
                            {
                              
                            }
                        }
                      
                    }
                    catch(Exception ex)
                    {
                    
                    }
                   
                }
              
            }
            private static void ReadSampleForm()
            {
                StreamReader sr = null;
                sbSampleForm = new StringBuilder();
                try
                {
                    sr = new StreamReader(strSampleForm);
                    sbSampleForm.Append(sr.ReadToEnd());
                }
                catch (Exception ex)
                {
                    WriteLog("Failed");
                    WriteLog(ex.StackTrace);
                }
                finally
                {
                    sr.Close();
                }
            }
            private static void CreateFormFromTemplate(string strFormName, string strFormDetails)
            {
                StreamWriter sw = null;
                try
                {
                    sw = new StreamWriter(strFormsFolder+strFormName);
                    sw.WriteLine(strFormDetails);
                }
                catch (Exception ex)
                {
                    WriteLog("Failed");
                    WriteLog(ex.StackTrace);
                }
                finally
                {
                    sw.Flush();
                    sw.Close();
                }
            }
           
        }
    }




    Monday 8 October 2012

    Infopath 2010 Drop-Down List Box (Get choices from fields in this form)

    Binding Dropdown in infopath form load without using Data Connections ( Dropdown [Get choices from fields in this form]) using code behind.

    • Go to Infopath form, Add one Group (like test),set properties -check (Repeating).
    • Add two fields (like test_displayname and test_value) under Group.
    • Add one Dropdown,set properties (Get choices from fields in this form).
    • set the value as Group [like test_displayname and test_value].
    • go to on form load events write the code.
    public void FormEvents_Loading(object sender, LoadingEventArgs e)
            {
                XPathNavigator myRootNode = MainDataSource.CreateNavigator();
                XPathNavigator userNode = myRootNode.SelectSingleNode("/my:myFields/my:test", NamespaceManager);
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList userlist = web.Lists["Departments"];
                         SPListItemCollection usercollection = userlist.GetItems();
                        if (usercollection.Count > 0)
                        {
                            foreach (SPListItem item in usercollection)
                            {
                                XPathNavigator newNode = null;
                                newNode = userNode.Clone();
                                newNode.SelectSingleNode("/my:myFields/my:test/my:test_displayname", this.NamespaceManager).SetValue(item.Title);
                                newNode.SelectSingleNode("/my:myFields/my:test/my:test_value", this.NamespaceManager).SetValue(item.Title);
                                userNode.InsertAfter(newNode);
                                newNode = null;
                            }
                            userNode.DeleteSelf();
                            userNode = null;
                        }
                    }
                }

    How to submit data from an InfoPath 2010 form to SharePoint 2010 List, using web service.

    Please see the below url :

    It's help to make insert item in sharepoint list using web services.

    http://geekswithblogs.net/KunaalKapoor/archive/2012/04/30/how-to-submit-data-from-an-infopath-2010-form-to.aspx

    Write html (like Hyper Link) in RichText Box in Infopath 2010 for Sharepoint list data.

    1. Take (field1) one Richtext box and  (txturl) one text box fields.
    2. On Form Load, Bind data connection toTextBox Controls.
    3. Go to Infopath 2010 Form load event, write the code.

    public void FormEvents_Loading(object sender, LoadingEventArgs e)
    {
    XPathNavigator attachmentNav = MainDataSource.CreateNavigator();
    string url = attachmentNav.SelectSingleNode("/my:myFields/my:txturl", NamespaceManager).Value;
    attachmentNav.SelectSingleNode("/my:myFields/my:field1", NamespaceManager).InnerXml = "<p xmlns='http://www.w3.org/1999/xhtml'>" + url + "</p>";
    }

    In ulr=" Welcome to the sharepoint 2010 with  <a  href='http:/www.google.com'>Infopath 2010</a>

    Example: Welcome to the sharepoint 2010 with Infopath 2010


    Make Document Set using infopath code in sharepoint 2010.

    1.First create one Document Library and go to library sittings.
    2.Open Advanced setting, then click "Yes" Allow management of centent types.
    3.then Add from existing site content types , select Document Set.
    4.Go to Infopath 2010, add one check box write code one change event in check box.

                XPathNavigator myRootNode = MainDataSource.CreateNavigator();
                 myRootNode.SelectSingleNode(" /my:myFields/my:field4", NamespaceManager).SetValue("rintu");
                try
                {
                   
                    SPWeb web = SPContext.Current.Web;
                    myRootNode.SelectSingleNode(" /my:myFields/my:field4", NamespaceManager).SetValue(web.Url.ToString());
                    SPList list = web.Lists["BriefingDoc"];
                    string sguid = System.Guid.NewGuid().ToString();
                    web.AllowUnsafeUpdates = true;
                    string sDocsetName = string.Empty;
                    sDocsetName = "Document Set";
                    DocumentSet ds = DocumentSet.Create(list.RootFolder, sguid, list.ContentTypes[sDocsetName].Id, null, true);
                    web.AllowUnsafeUpdates = false;
                    string DocUrl = ds.WelcomePageUrl.Replace("Document Set", "Document%20Set");
                    myRootNode.SelectSingleNode("/my:myFields/my:field2/@my:field3", NamespaceManager).SetValue(DocUrl);

                }
                catch (Exception ex)
                {
                    myRootNode.SelectSingleNode("/my:myFields/my:DatadeTérminoMessage", NamespaceManager).SetValue(ex.Message);
                }
                }

    5.see that one hyper link is created, click that and upload the documents.

    Friday 14 September 2012

    Getting Repeater Section current row in InfoPath 2010 using code.

    Using following code:-

    -Take one repeater section under section add one fields to see the item count or  current row value.
    -Then on fire repeater section event change binding.


    XPathNavigator root = this.CreateNavigator();
    XPathNodeIterator nodes = 
       root.Select("/my:myFields/my:group1/my:field1", NamespaceManager);
    int myInt = 1;
    while (nodes.MoveNext())
    {
       nodes.Current.SetValue(myInt.ToString());
       myInt = myInt + 1;
    }
    

    Friday 7 September 2012

    Data Binding with SharePoint 2010 list in InfoPath 2010

    Please see the code:

    public void AddCountries()
            {
                try
                {
                    SPSite site = new SPSite("http://win-67038mbkel7");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Countries"];
                    SPListItemCollection listitems = list.Items;
                    XPathNavigator nav = this.CreateNavigator().
                        SelectSingleNode("/my:myFields/my:Countries", this.NamespaceManager);// Note: "/my:myFields/my:Countries" => Group Countries
                    foreach (SPListItem li in listitems)
                    {
                        XPathNavigator newNode = null;
                        newNode = nav.Clone();
                        newNode.SelectSingleNode("/my:myFields/my:Countries/my:Displayname",
                            this.NamespaceManager).SetValue(li["Title"].ToString());
                        newNode.SelectSingleNode("/my:myFields/my:Countries/my:Value",
                            this.NamespaceManager).SetValue(li["Title"].ToString());
                        nav.InsertAfter(newNode);
                        newNode = null;
                    }
                    nav.DeleteSelf();
                    nav = null;
                }
                catch
                {
                }
            }

    Banding data form sharepoint list and library with using Group and fields into drop down in Infopath 2010

    Please see the code


    sing Microsoft.Office.InfoPath;
    using System;
    using System.Xml;
    using System.Xml.XPath;
    using Microsoft.SharePoint;

    namespace SetValueToDropdownListInfoPathFromChoiceField
    {
        public partial class FormCode
        {
            // NOTE: The following procedure is required by Microsoft InfoPath.
            // It can be modified using Microsoft InfoPath.
            public void InternalStartup()
            {
                EventManager.FormEvents.Loading += new LoadingEventHandler(FormEvents_Loading);
            }

            public void FormEvents_Loading(object sender, LoadingEventArgs e)
            {
                AddStatus();
            }

            public void AddStatus()
            {
                try
                {
                    SPSite site = new SPSite("http://win-67038mbkel7");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Tasks"];
                    SPFieldMultiChoice spFieldMultiChoice = (SPFieldMultiChoice)list.Fields["Status"];
                    XPathNavigator nav = this.CreateNavigator().SelectSingleNode("/my:myFields/my:GroupStatus",
                        this.NamespaceManager);
                    for (int item = 0; item < spFieldMultiChoice.Choices.Count; item++)
                    {
                        XPathNavigator newNode = null;
                        newNode = nav.Clone();
                        newNode.SelectSingleNode("/my:myFields/my:GroupStatus/my:Displayname",
                            this.NamespaceManager).
                            SetValue(spFieldMultiChoice.Choices[item].ToString());
                        newNode.SelectSingleNode("/my:myFields/my:GroupStatus/my:Value",
                            this.NamespaceManager).
                            SetValue(spFieldMultiChoice.Choices[item].ToString());
                        nav.InsertAfter(newNode);
                        newNode = null;
                    }
                    nav.DeleteSelf();
                    nav = null;
                }
                catch
                {

                }
            }
        }
    }

    Tuesday 4 September 2012

    Change View in InfoPath 2010 on Form load event using code

    Following code is using infopath 2010 code behind.

    public void FormEvents_Loading(object sender, LoadingEventArgs e)
    {
        try
        {
            string view = "";
            if (e.InputParameters.ContainsKey("View"))
            {
                view = e.InputParameters["View"];
                e.SetDefaultView(view);
            }
        }
        catch (Exception ex)
        {
            SetValue("/my:myFields/my:FormSettings/my:ErrorLog", ex.Message + ex.StackTrace);
        }
    }

    Submit InfoPath 2010 Form without validation using code

    Following code is using infopath 2010 code behind.

    if (this.Errors.Count > 0)
    DataConnection dcSave = this.DataConnections["SaveAsTemplate"];
    this.Errors.DeleteAll(); 
    dcSave.Execute();

    Upload files using attachment control in infopath 2010 and file are saved in SharePoint 2010 Document Library using code -Submit Form using code

    Following code is using infopath 2010 code behind.


      XPathNavigator attachmentNav = MainDataSource.CreateNavigator();
                // Get the base64 encoded attachment
                string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:attachment", NamespaceManager).Value;
                attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:attachment", NamespaceManager);
                // Delete the encoded file form XML form
                attachmentNav.InnerXml = string.Empty;
                // Get the value of "Title" field
                string reference = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txttitle", NamespaceManager).Value;
                // Convert the base64 encoded string into a byte array
                InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
                byte[] attachment = decoder.DecodedAttachment;
                string fileName = decoder.Filename;
                // Add the file as an attachment to the SharePoint list item
                using (SPSite site = SPContext.Current.Site)
                {
                    if (site != null)
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            // Turn on AllowUnsafeUpdates on the site
                            web.AllowUnsafeUpdates = true;
                            // Add the attached document to "Documents" library
                            // and set the value of "Reference" column to
                            // "Title" filed of the InfoPath form
                            SPFolder lib = web.GetFolder("TestAttachmentdoc");
                            SPFile file = lib.Files.Add(fileName, attachment, true);
                            file.Item["Reference"] = reference;
                            file.Item["Title"] = fileName;
                            file.Item.Update();
                            file.Update();
                            // Add attachment file url to "Url" field in the form
                            // by adding extra "my:group4" element in the form
                            XmlDocument xdoc = new XmlDocument();
                            xdoc.LoadXml(MainDataSource.CreateNavigator().OuterXml);
                            Uri url = new Uri(new Uri(web.Url), file.Url);
                            XmlNode grp4 = xdoc.SelectSingleNode("/my:myFields/my:group1/my:group2", NamespaceManager);
                            XmlNode clonedNode = grp4.CloneNode(true);
                            clonedNode.SelectSingleNode("/my:myFields/my:group1/my:group2/my:url", NamespaceManager).InnerText = url.AbsoluteUri;
                            grp4.ParentNode.InsertAfter(clonedNode, grp4);
                            string formXml = xdoc.OuterXml;
                            // Add the form to "MyForms" library
                            SPFolder formlib = web.GetFolder("MyForms");
                            string formName = string.Format("Request {0}.xml", reference);
                            SPFile form = formlib.Files.Add(formName, Encoding.UTF8.GetBytes(formXml), true);
                            form.Item["Title"] = reference;
                            form.Item.Update();
                            form.Update();
                            // Turn off AllowUnsafeUpdates on the site
                            web.AllowUnsafeUpdates = false;
                            // Close the connection to the site
                            web.Close();
                        }
                        // Close the connection to the site collection
                        site.Close();
                    }

    How to count repeater table row in infopath 2010 using out of box

    Following step are using infopath 2010

    count(preceding-sibling::my:group10) + 1


    - Just add one repeater table in infopath 2010.
    - Add two columns  Field 1 and Field 2 in repeater table.
    - Click right the field 1 column, then set default value (count(preceding-sibling::my:group10) + 1).
    - Just check that and run.

    How to insert hyperlink control in repeater table in repeater section in infopath 2010

    Following code is using infopath 2010 code behind.


     




                XPathNavigator attachmentNav = MainDataSource.CreateNavigator();
                XPathNodeIterator rows1 = attachmentNav.Select("/my:myFields/my:group8/my:group9/my:group10", NamespaceManager);
                if (rows1.Count != 1)
                {
                    string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager).Value;
                    if (attachedFile != string.Empty)
                    {
                        attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager);
                        // Convert the base64 encoded string into a byte array
                        InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
                        byte[] attachment = decoder.DecodedAttachment;
                        string fileName = decoder.Filename;
                        XmlDocument doc = new XmlDocument();
                        XmlNode group = doc.CreateElement("group11", NamespaceManager.LookupNamespace("my"));
                        XmlNode field = doc.CreateElement("url", NamespaceManager.LookupNamespace("my"));
                        XmlNode node = group.AppendChild(field);
                        node.InnerXml = fileName;
                        doc.AppendChild(group);
                        MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:group10", NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());
                        attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9[" + Convert.ToString(rows1.Count) + "]/my:attachment", NamespaceManager).SetValue("");
                    }
                }
                else
                {
                    string attachedFile = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager).Value;
                    if (attachedFile != string.Empty)
                    {
                        attachmentNav = attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager);
                        // Convert the base64 encoded string into a byte array
                        InfoPathAttachmentDecoder decoder = new InfoPathAttachmentDecoder(attachedFile);
                        byte[] attachment = decoder.DecodedAttachment;
                        string fileName = decoder.Filename;

                        XmlDocument doc = new XmlDocument();
                        XmlNode group = doc.CreateElement("group11", NamespaceManager.LookupNamespace("my"));
                        XmlNode field = doc.CreateElement("url", NamespaceManager.LookupNamespace("my"));
                        XmlNode node = group.AppendChild(field);
                        node.InnerXml = fileName;
                        doc.AppendChild(group);
                        MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:group8/my:group9/my:group10", NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());
                        attachmentNav.SelectSingleNode("/my:myFields/my:group8/my:group9/my:attachment", NamespaceManager).SetValue("");
                    }
                }

    Monday 27 August 2012

    SharePoint 2010 - Introduction to Client Object Model

    SharePoint 2010 - Introduction to Client Object Model


    SharePoint 2010 provides a new client object model that enables you to create SharePoint solutions that run remotely from the SharePoint server farm. For example, the client object model enables you to consume and manipulate SharePoint data in Windows Forms applications, Windows Presentation Framework application, console applications, Silverlight applications, and ASP.NET Web applications. 

    For working with client object model you need to get two master dlls:

    ·         Microsoft.SharePoint.Client.dll

    ·         Microsoft.SharePoint.Client.Runtime.dll



    These dlls you can find under following path from machine on which you have installed SharePoint 2010.

    Path to get DLL's: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

    The SharePoint Foundation 2010 managed client object model consists of two assemblies that contain five namespaces. If you look at the classes available in those namespaces, you see many classes. Primarily classes that have direct counterparts to some familiar classes in the SharePoint Foundation server object model.
     

    1. Code snippets for How to Load List and List items:
    public void LoadList()
            {
                using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
                {
                    var web = ctx.Web;

                   // Let's only work with the specific List object and save resources
                    // by not fetching any other objects
                    var list = ctx.Web.Lists.GetByTitle("ListName");
     
                    // Load only the list variable and execute the query
                    ctx.Load(list);
                    ctx.ExecuteQuery();
     
                    SP.CamlQuery camlQuery = new SP.CamlQuery();
                     camlQuery.ViewXml =
                                @"<View>
                            <Query>
                                      <Where>
                                    <Eq>
                                      <FieldRef Name='Name'/>
                                      <Value Type='Text'>Shailesh</Value>
                                    </Eq>
                                      </Where>
                            </Query>
                                  </View>";
                    SP.ListItemCollection listItems = list.GetItems(camlQuery);
                    ctx.Load(listItems);
                    ctx.ExecuteQuery();
     
                    //Now you can iterate listitems collection and can get listitems using foreach loop
     
                    foreach (SP.ListItem listItem in listItems)
                    {
                                //you can get value of list column from listitem as follow:
                                //listitem["ID"]
                            //listitem["Name"]
                    }
                }
            }
      2. Code snippets for How to insert  List items to a List:
    public void SaveListItem()
            {
                using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
                {
                    var web = ctx.Web;
                    var list = ctx.Web.Lists.GetByTitle("ListName");
                    ctx.Load(list);
                    ctx.ExecuteQuery();
                    SP.ListItemCreationInformation itemCreateInfo = new SP.ListItemCreationInformation();
                    SP.ListItem listItem = list.AddItem(itemCreateInfo);
                    listItem["Name"] = "Shailesh";
                    listItem["Surname"] = "Soni";
                    listItem.Update();
                   ctx.ExecuteQuery();
                }
            }
      3. Code snippets for update List items in List:
    Public  void UpdateListItem()
            {
                using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
                {
                    var web = ctx.Web;

                   // Let's only work with the specific List object and save resources
                    // by not fetching any other objects
                    var list = ctx.Web.Lists.GetByTitle("ListName");
     
                    // Load only the list variable and execute the query
                    ctx.Load(list);
                    ctx.ExecuteQuery();
     
                    SP.CamlQuery camlQuery = new SP.CamlQuery();
                     camlQuery.ViewXml =
                                @"<View>
                            <Query>
                                      <Where>
                                    <Eq>
                                      <FieldRef Name='Name'/>
                                      <Value Type='Text'>Shailesh</Value>
                                    </Eq>
                                      </Where>
                            </Query>
                                  </View>";
                    SP.ListItemCollection listItems = list.GetItems(camlQuery);
                    ctx.Load(listItems);
                    ctx.ExecuteQuery();
     
                    //Now you can iterate listitems collection and can get listitems using foreach loop
     
                    foreach (SP.ListItem listItem in listItems)
                    {
                                 listitem["Address"] = “blah blah blah”;
                                listitem.Update();
                    }
                    ctx.ExecuteQuery();
                }
            }
      4. Code snippets for delete List items in List:
    Public  void DeleteListItem()
            {
                using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
                {
                    var web = ctx.Web;

                   // Let's only work with the specific List object and save resources
                    // by not fetching any other objects
                    var list = ctx.Web.Lists.GetByTitle("ListName");
     
                    // Load only the list variable and execute the query
                    ctx.Load(list);
                    ctx.ExecuteQuery();
     
                    SP.CamlQuery camlQuery = new SP.CamlQuery();
                     camlQuery.ViewXml =
                                @"<View>
                            <Query>
                                      <Where>
                                    <Eq>
                                      <FieldRef Name='Name'/>
                                      <Value Type='Text'>Shailesh</Value>
                                    </Eq>
                                      </Where>
                            </Query>
                                  </View>";
                    SP.ListItemCollection listItems = list.GetItems(camlQuery);
                    ctx.Load(listItems);
                    ctx.ExecuteQuery();
     
                    //Now you can iterate listitems collection and can get listitems using foreach loop
                    foreach (SP.ListItem listItem in listItems)
                                listItem.DeleteObject();
                    ctx.ExecuteQuery();
                }
            }
     Conclusion: The above code snippets and detail description will help you to understand Client Object Model to begin with SharePoint 2010.