Click here to Skip to main content
15,894,106 members
Articles / Desktop Programming / Win32

InfoPath 2007 Helper for MOSS 2007

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Feb 2009GPL31 min read 27.9K   151   7  
This article is about how to get or set values of an InfoPath form.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Xml.Serialization;
using Microsoft.SharePoint;

public static class InfoPathHelper
{
    /// <summary>
    /// Nombre del archivo XML donde se encuentra serializado en objeto de InfoPath a manipular.
    /// </summary>
    private static string _fileName;
    public static string FileName
    {
        get { return InfoPathHelper._fileName; }
        set { InfoPathHelper._fileName = value; }
    }

    /// <summary>
    /// Contiene informacion sobre el error que se produce en cualquier instancia de la clase.
    /// </summary>
    private static string _error;
    public static string Error
    {
        get { return InfoPathHelper._error; }
        set { InfoPathHelper._error = value; }
    }

    /// <summary>
    /// El objeto del tipo archivo del SharePoint que contiene el XML del formulario InfoPath.
    /// </summary>
    private static SPListItem _spFileName;
    public static SPListItem SPFileName
    {
        get { return InfoPathHelper._spFileName; }
        set { InfoPathHelper._spFileName = value; }
    }

    /// <summary>
    /// Obtiene el valor de un campo del formulario InfoPath.
    /// </summary>
    /// <param name="Key">Nombre del campo del formulario a obtener su valor</param>
    /// <returns></returns>
    public static string Value(string Key)
    {
        string namespaceName;
        bool foundNamespace;
        string returnValue = string.Empty;

        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            // Leemos el XML que representa al formulario InfoPath.
            // Verificamos si es archivo que viene desde una libreria de MOSS o 
            // desde una ruta fisica especificada.
            if (_spFileName != null)
            {
                xmlDoc.Load(_spFileName.File.OpenBinaryStream());
            }
            else
            {
                xmlDoc.Load(_fileName);
            }
            XPathNavigator myNav = xmlDoc.CreateNavigator();

            ObtenerInfoPathNamespace(myNav, out namespaceName, out foundNamespace);

            var nav2 = myNav.Clone();
            var result = nav2.MoveToFollowing(Key, namespaceName);
            if (result)
            {
                returnValue = nav2.Value;
            }
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }

        return returnValue;
    }

    /// <summary>
    /// Escribe un valor en un campo del formulario InfoPath.
    /// </summary>
    /// <param name="Key">Nombre del campo del formulario.</param>
    /// <param name="Value">Valor que se grabara en el campo del formulario.</param>
    public static void SetValue(string Key, string Value)
    {
        string namespaceName;
        bool foundNamespace;

        try
        {
            // Leemos el XML que representa al formulario InfoPath.
            // Verificamos si es archivo que viene desde una libreria de MOSS o 
            // desde una ruta fisica especificada.
            XmlDocument xmlDoc = new XmlDocument();
            if (_spFileName != null)
            {
                xmlDoc.Load(_spFileName.File.OpenBinaryStream());
            }
            else
            {
                xmlDoc.Load(_fileName);
            }
            XPathNavigator myNav = xmlDoc.CreateNavigator();

            // Seteamos el Namespace y prefijo "my" para poder identificar los nodos.
            ObtenerInfoPathNamespace(myNav, out namespaceName, out foundNamespace);

            // Obtenemos el nodo que representa el control del formulario al cual
            // se desea cambiar su valor
            var nav2 = myNav.Clone();
            var result = nav2.MoveToFollowing(Key, namespaceName);
            if (result)
            {
                nav2.SetValue(Value);
            }

            if (_spFileName != null)
            {
                // Para el caso de que sea una libreria de formularios en MOSS
                string stringSource = xmlDoc.OuterXml;
                MemoryStream backOut = new MemoryStream(Encoding.UTF8.GetBytes(stringSource));
                _spFileName.File.SaveBinary(backOut);                                
            }
            else
            {
                // Si se trata de un archivo comun XML
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = Encoding.UTF8;
                settings.Indent = true;
                settings.ConformanceLevel = ConformanceLevel.Fragment;

                XmlWriter xmlWriter = XmlWriter.Create(_fileName, settings);
                xmlDoc.WriteTo(xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();
            }
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }
    }

    private static void ObtenerInfoPathNamespace(XPathNavigator navigator2, out string sNamespaceXML, out bool bExiste)
    {
        sNamespaceXML = string.Empty;
        bExiste = false;
        if (navigator2.MoveToFirstChild())
        {
            sNamespaceXML = navigator2.LookupNamespace(@"xmlns:my");
            while (sNamespaceXML == null || sNamespaceXML.Length <= 0)
            {
                if (!navigator2.MoveToNext())
                    break;
                sNamespaceXML = navigator2.LookupNamespace(@"my");
            };
        }
        if (sNamespaceXML != null && sNamespaceXML.Length > 0)
            bExiste = true;
    }

    /// <summary>
    /// De-serializa el objeto del formulario InfoPath para acceder a sus propiedades.
    /// </summary>
    /// <param name="myFile">Texto con la ruta fisica donde se encuentra el archivo XML representativo del objeto InfoPath.</param>
    /// <param name="myType">El tipo de objeto donde se de-serializara el XML.</param>
    /// <returns>Devuelve un objeto serializado de los campos del formulario InfoPath.</returns>
    public static object DeserializeFile(string myFile, Type myType)
    {
        FileInfo file = new FileInfo(myFile);
        MemoryStream fileStream = new MemoryStream();

        XmlReader reader = XmlReader.Create(file.OpenText());
        XmlSerializer serializer = new XmlSerializer(myType);
        return serializer.Deserialize(reader);
    }

    /// <summary>
    /// De-serializa el objeto del formulario InfoPath para acceder a sus propiedades.
    /// </summary>
    /// <param name="myFile">El objeto SPFile (File de Sharepoint) que contiene el XML del fomulario InfoPath.</param>
    /// <param name="myType">El tipo de objeto donde se de-serializara el XML.</param>
    /// <returns>Devuelve un objeto serializado de los campos del formulario InfoPath.</returns>
    public static object DeserializeFile(SPFile myFile, Type myType)
    {
        MemoryStream fileStream = new MemoryStream(myFile.OpenBinary());
        XmlReader reader = XmlReader.Create(fileStream);
        XmlSerializer serializer = new XmlSerializer(myType);
        return serializer.Deserialize(reader);
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Systems Engineer San Antonio International - Pride
Argentina Argentina
Desde chico mi fasinacion hacia las computadoras marcaron mi camino profesional que iba a recorrer en los proximos dias de mis vida. Ingeniero en Sistemas, recibido en la UADE en el 2005, mi abocacion hacia la programacion en tecnologias de Microsoft hicieron hoy en dia desarrollarme como Arquitecto o Lider Tecnico en proyectos con tecnologias .Net. No solo la programacion es uno de mis pasiones, sino tambien todo lo referente a Infraestructura con productos de Microsoft. Actualmente estoy desenvolviendome como SharePoint Specialisst en una empresa petrolera lideando con sistemas montados sobre dicha tecnologia. Casado con mi hermosa mujer Cecilia quien es el motor que empuja mis ambiciones y ayuda a mejorarme dia a dia.

Comments and Discussions