Thursday, 12 July 2012

Insert file attachment control in infopath form and submit that form in form library

 









Design This form using infopath from

1.Open infopath form

2.In  top menu bar u can see controls in tat choose under objects->choose File attachment control

3 .Add 3 buttons named attach,submit and close.

For attachment field we have to write coding otherwise we cannot add attachment field as fields value.

We have to encode and decode and write code for attach & submit button to save attached documents in document library
In infopath form under developer->code editor->visual studio will open->in this create class file.cs as attachment encoding and paste the below coding

 Encoder .cs coding

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace name
{
    class InfoPathAttachmentEncoder
    {
        private string base64EncodedFile = string.Empty;
        private string fullyQualifiedFileName;

        /// <summary>
        /// Creates an encoder to create an InfoPath attachment string.
        /// </summary>
        /// <param name="fullyQualifiedFileName"></param>
        public InfoPathAttachmentEncoder(string fullyQualifiedFileName)
        {
            if (fullyQualifiedFileName == string.Empty)
                throw new ArgumentException("Must specify file name", "fullyQualifiedFileName");

            if (!File.Exists(fullyQualifiedFileName))
                throw new FileNotFoundException("File does not exist: " + fullyQualifiedFileName, fullyQualifiedFileName);

            this.fullyQualifiedFileName = fullyQualifiedFileName;
        }

        /// <summary>
        /// Returns a Base64 encoded string.
        /// </summary>
        /// <returns>String</returns>
        public string ToBase64String()
        {
            if (base64EncodedFile != string.Empty)
                return base64EncodedFile;

            // This memory stream will hold the InfoPath file attachment buffer before Base64 encoding.
            MemoryStream ms = new MemoryStream();

            // Obtain the file information.
            using (BinaryReader br = new BinaryReader(File.Open(fullyQualifiedFileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                string fileName = Path.GetFileName(fullyQualifiedFileName);

                uint fileNameLength = (uint)fileName.Length + 1;

                byte[] fileNameBytes = Encoding.Unicode.GetBytes(fileName);

                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    // Write the InfoPath attachment signature.
                    bw.Write(new byte[] { 0xC7, 0x49, 0x46, 0x41 });

                    // Write the default header information.
                    bw.Write((uint)0x14);    // size
                    bw.Write((uint)0x01);    // version
                    bw.Write((uint)0x00);    // reserved

                    // Write the file size.
                    bw.Write((uint)br.BaseStream.Length);

                    // Write the size of the file name.
                    bw.Write((uint)fileNameLength);

                    // Write the file name (Unicode encoded).
                    bw.Write(fileNameBytes);

                    // Write the file name terminator. This is two nulls in Unicode.
                    bw.Write(new byte[] { 0, 0 });

                    // Iterate through the file reading data and writing it to the outbuffer.
                    byte[] data = new byte[64 * 1024];
                    int bytesRead = 1;

                    while (bytesRead > 0)
                    {
                        bytesRead = br.Read(data, 0, data.Length);
                        bw.Write(data, 0, bytesRead);
                    }
                }
            }


            // This memorystream will hold the Base64 encoded InfoPath attachment.
            MemoryStream msOut = new MemoryStream();

            using (BinaryReader br = new BinaryReader(new MemoryStream(ms.ToArray())))
            {
                // Create a Base64 transform to do the encoding.
                ToBase64Transform tf = new ToBase64Transform();

                byte[] data = new byte[tf.InputBlockSize];
                byte[] outData = new byte[tf.OutputBlockSize];

                int bytesRead = 1;

                while (bytesRead > 0)
                {
                    bytesRead = br.Read(data, 0, data.Length);

                    if (bytesRead == data.Length)
                        tf.TransformBlock(data, 0, bytesRead, outData, 0);
                    else
                        outData = tf.TransformFinalBlock(data, 0, bytesRead);

                    msOut.Write(outData, 0, outData.Length);
                }
            }

            msOut.Close();

            return base64EncodedFile = Encoding.ASCII.GetString(msOut.ToArray());
        }
    }
}

Decoder .cs coding

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace name
{
    class InfoPathAttachmentDecoder
    {
        private const int SP1Header_Size = 20;
        private const int FIXED_HEADER = 16;

        private int fileSize;
        private int attachmentNameLength;
        private string attachmentName;
        private byte[] decodedAttachment;

        /// <summary>
        /// Accepts the Base64 encoded string
        /// that is the attachment.
        /// </summary>
        public InfoPathAttachmentDecoder(string theBase64EncodedString)
        {
            byte[] theData = Convert.FromBase64String(theBase64EncodedString);
            using (MemoryStream ms = new MemoryStream(theData))
            {
                BinaryReader theReader = new BinaryReader(ms);
                DecodeAttachment(theReader);
            }
        }

        private void DecodeAttachment(BinaryReader theReader)
        {
            //Position the reader to obtain the file size.
            byte[] headerData = new byte[FIXED_HEADER];
            headerData = theReader.ReadBytes(headerData.Length);

            fileSize = (int)theReader.ReadUInt32();
            attachmentNameLength = (int)theReader.ReadUInt32() * 2;

            byte[] fileNameBytes = theReader.ReadBytes(attachmentNameLength);
            //InfoPath uses UTF8 encoding.
            Encoding enc = Encoding.Unicode;
            attachmentName = enc.GetString(fileNameBytes, 0, attachmentNameLength - 2);
            decodedAttachment = theReader.ReadBytes(fileSize);
        }

        public void SaveAttachment(string saveLocation)
        {
            string fullFileName = saveLocation;
            if (!fullFileName.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                fullFileName += Path.DirectorySeparatorChar;
            }

            fullFileName += attachmentName;

            if (File.Exists(fullFileName))
                File.Delete(fullFileName);

            FileStream fs = new FileStream(fullFileName, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(decodedAttachment);

            bw.Close();
            fs.Close();
        }

        public string Filename
        {
            get { return attachmentName; }
        }

        public byte[] DecodedAttachment
        {
            get { return decodedAttachment; }
        }
    }
}

Attach and submit button code

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

namespace name
{
    public partial class FormCode
    {
        // Member variables are not supported in browser-enabled forms.
        // Instead, write and read these values from the FormState
        // dictionary using code such as the following:
        //
        // private object _memberVariable
        // {
        //     get
        //     {
        //         return FormState["_memberVariable"];
        //     }
        //     set
        //     {
        //         FormState["_memberVariable"] = value;
        //     }
        // }

        // NOTE: The following procedure is required by Microsoft InfoPath.
        // It can be modified using Microsoft InfoPath.
        public void InternalStartup()
        {
            ((ButtonEvent)EventManager.ControlEvents["btnAttach"]).Clicked += new ClickedEventHandler(btnAttach_Clicked);
            ((ButtonEvent)EventManager.ControlEvents["btnSave"]).Clicked += new ClickedEventHandler(btnSave_Clicked);

            //((ButtonEvent)EventManager.ControlEvents["CTRL5_5"]).Clicked += new ClickedEventHandler(CTRL5_5_Clicked);
            ((ButtonEvent)EventManager.ControlEvents["CTRL11_5"]).Clicked += new ClickedEventHandler(CTRL11_5_Clicked);
        }
//Attach Field code        

public void btnAttach_Clicked(object sender, ClickedEventArgs e)
        {
            //Create an XmlNamespaceManager
            XmlNamespaceManager ns = this.NamespaceManager;

            //Create an XPathNavigator object for the Main data source
            XPathNavigator xnMain = this.MainDataSource.CreateNavigator();

            //Create an XPathNavigator object for the attachment node
            XPathNavigator xnAttNode = xnMain.SelectSingleNode("/my:myFields/my:theAttachmentField", ns);

            //Create an XPathNavigator object for the filename node
            XPathNavigator xnFileName = xnMain.SelectSingleNode("/my:myFields/my:theAttachmentName", ns);

            //Obtain the text of the filename node.
            string fileName = xnFileName.Value;
            if (fileName.Length > 0)
            {
                //Encode the file and assign it to the attachment node.
                InfoPathAttachmentEncoder myEncoder = new InfoPathAttachmentEncoder(fileName);

                //Check for the "xsi:nil" attribute on the file attachment node and remove it
                //before setting the value to attach the filerRemove the "nil" attribute
                if (xnAttNode.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
                    xnAttNode.DeleteSelf();

                //Attach the file
                xnAttNode.SetValue(myEncoder.ToBase64String());
            }
        }

        //public void CTRL5_5_Clicked(object sender, ClickedEventArgs e)
//save button code
        public void btnSave_Clicked(object sender, ClickedEventArgs e)
        {
            // Retrieve the value of the attachment in the InfoPath form
            XPathNavigator ipFormNav = MainDataSource.CreateNavigator();
            XPathNavigator nodeNav = ipFormNav.SelectSingleNode(
            "/my:myFields/my:theAttachmentField", NamespaceManager);

            string attachmentValue = string.Empty;

            if (nodeNav != null && !String.IsNullOrEmpty(nodeNav.Value))
            {
                attachmentValue = nodeNav.Value;

                // Decode the InfoPath file attachment
                InfoPathAttachmentDecoder dec =
                new InfoPathAttachmentDecoder(attachmentValue);
                string fileName = dec.Filename;
                byte[] data = dec.DecodedAttachment;

                // Add the file to a document library

               // using (SPSite site = new SPSite("site collection name"))
                using(SPSite site = SPContext.Current.Site)
                {

                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPFolder docLib = web.Folders["library name];
                        docLib.Files.Add(fileName, data);
                        web.AllowUnsafeUpdates = false;
                        web.Close();
                    }
                    site.Close();
                }

            }

        }


Then save and publish.








To add PDF File as Content type in Sharepoint 2010 Document library

  1. Download and install Adobe’s 64-bit PDF iFilter*1http://www.adobe.com/support/downloads/detail.jsp?ftpID=4025
  2. Download the Adobe PDF icon (select the smaller icon, at time of latest update, it’s called 16 x 16) currently available from – http://www.adobe.com/misc/linking.html
    1. Give the icon a name or accept the default: ‘pdficon_small.gif’
    2. Save the icon (or copy to) C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES
  3. Edit the DOCICON.XML file to include the PDF icon
    1. In Windows Explorer, navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML
    2. Edit the DOCICON.XML file (I open it in NotePad, you can also use the built-in XML Editor)
    3. Ignore the section <ByProgID> and scroll down to the <ByExtension> section of the file
    4. Within the <ByExtension> section, insert a <Mapping Key=”pdf” Value=”pdficon_small.gif” /> attribute. The easiest way is to copy an existing one – I usually just copy the line that starts <Mapping Key=”png”… and replace the parameters for Key and Value (see image below for example).
      Note: Do not take shortcuts and copy/paste from here. 99% of problems with PDF icons not being displayed are due to errors made in the DOCICON.XML file
    5. Save and close the file
      SharePoint 2010 and Adobe PDF DOCICON.XML
  4. Add PDF to the list of supported file types within SharePoint
    1. In the web browser, open SharePoint Central Administration
    2. Under Application Management, click on Manage service applications
    3. Scroll down the list of service apps and click on Search Service Application
    4. Within the Search Administration dashboard, in the sidebar on the left, click File Types
    5. Click ‘New File Type’ and enter PDF in the File extension box. Click OK
    6. Scroll down the list of file types and check that PDF is now listed and displaying the pdf icon.
    7. Close the web browser
  5. Stop and restart Internet Information Server (IIS)*2 Note: this will temporarily take SharePoint offline. Open a command line (Start – Run – enter ‘cmd’) and type ‘iisreset’
  6. Perform a full crawl of your index. Note: An incremental crawl is not sufficient when you have added a new file type. SharePoint only indexes file names with the extensions listed under File Types and ignores everything else. When you add a new file type, you then have to perform a full crawl to forcibly identify all files with the now relevant file extension.
That’s it. If you now perform a search, PDF files should be displayed in results where they match the search query, along with the PDF icon on display in results. The icon should also be visible in any document libraries that contain PDF files.

Welcome Screen Web part to see current login user name and their details from list in sharepoint 2010

  • Create Visual webpart project in visual studio 2010.
  • Open Visual webpart .ascx file and design ur requirement.
  • Here i posted my coding for reference
  • <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="EMPPortalWelcomeScreen.VisualWebPart1.VisualWebPart1UserControl" %>

    <style type="text/css">
    .style3
    {
        font-size:20px;
       
        font-family: Calibri;
       
    }

    .style5
    {
        font-size:20px;
        font-family: Calibri;
       
    }
    .style6
    {
        font-size:20px;
       font-family: Calibri;
       
    }


    </style>
    <table style="background: url('/sites/site collection name/Style%20Library/oie_jpg.png'); background-repeat: no-repeat; width: 610px; height: 480px">
        <tr>
            <td align="center">
                <table style="width: 580px; height: 50px;">
                    <tr>
                        <td>
                            <h1 style="font-family: Calibri; color: #000000; text-align: left; font-size: 20px">Title of ur webpart</h1>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align="center" valign="middle">
                <table style="width: 580px; height: 350px; border: 1px solid #000;">
                    <tr>
                        <td align="left" valign="top">
                            <h1 style="color: #000000; font-size: 20px; font-family: Calibri; text-align: center">WELCOME MESSAGE</h1>
                            <asp:Label ID="Label1" runat="server" Style="font-family: Calibri; color: #000000; text-align: left; font-size: 20px; margin-left: 20px"></asp:Label>
                            <br />
                            <asp:Label ID="Label2" runat="server" Style="font-family: Calibri; color: #000000; text-align: left; font-size: 20px; margin-left: 20px"></asp:Label>
                            <asp:Label ID="Label3" runat="server" Style="font-family: Calibri; color: #000000; text-align: left; font-size: 20px"></asp:Label>
                           </td>
                <tr>
                </table>
                               
                        </td>
                    </tr>
                </table>
           
  • Open visual webpart .cs file and paste the below coding
  • using System;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;


    namespace name.VisualWebPart1
    {
        public partial class VisualWebPart1UserControl : UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {
              
                string username;
                SPSite mySite = SPContext.Current.Site;
                SPWeb web = mySite.OpenWeb();
                SPUser user = web.CurrentUser;
                username = user.LoginName;
                username = user.ToString();
                username = user.Name;
                //
                SPList list = web.Lists["list name"];
                SPListItemCollection listitemcollection = list.Items;
                DataTable table = new DataTable();
                DataTable dtList = list.GetItems().GetDataTable();
                DataRow[] drUser = dtList.Select("[Member] = '" + username + "'");                                      if (drUser.Length > 0)
                {
                    string strUserName = drUser[0]["Member"].ToString();
                    Label1.Text = strUserName;
  • //According to ur requirement u can use ur field
                    string strUserRole = drUser[0]["Role"].ToString();
                    Label2.Text = strUserRole+",";
                    string strUserBoard = drUser[0]["Board"].ToString();
                    Label3.Text = strUserBoard;                                                                                              }}}}
     
  • Then go to ur sharepoint site
  • In that Edit Page->Place the cursor in any of your home page->Add Webpart->Custon->Visual webpart(ur webpart) then give ok now it ll come in your welcome screen
  • You can see ur output now.
  • If u have any doubt in this please post it below.