Mostrando entradas con la etiqueta Infopath 2010. Mostrar todas las entradas
Mostrando entradas con la etiqueta Infopath 2010. Mostrar todas las entradas

viernes, 2 de agosto de 2013

Using WCF services and Infopath to insert list items into SharePoint

This post you will show  the way to insert list items into sharepoint using WCF services and Infopath, this is other alternative if you are need in a rare case.

1. Create a project "WCF Service Library".  (see next image).



2. Add the next code into IService1.cs


3. Now add the Microsoft.SharePoint reference.


4. Add the next code into Service1.cs


The WCF service it's ready, now is time to publish.

5. go to internet information services (IIS) .

6. Create new site add the port 666


7. Add Aplication.







8. Publish.






9. now, in IIS manager go to application right click over thus and select Manage application Advance Settings




9. In Application Pool select SharePoint-80



mouse right click over WCFService and select explore.


Open the Web.config. search  "wsHttpBinding" and replace to "basicHttpBinding" save the file



Create a Infopath Form.

10. Open infopath designer and select Blank Form.


11. Add one button and a textbox.


13. In the ribbon select the tab Developer ---> languaje and select C#, then click the button code editor, and appears Visual Studio tools for applications. (if don't appears is neccesary install).

note: save you form as WCFInfopathForm.





Add the web reference to you WCF service.

14. Go to IISManager select WCF service, see in the right side and clic over  Browse, then click over file with the extension .svc





15. Copy the next URL.


16. Return to infopath code and add web reference.


17. Paste the WCFURL into URL field. then click over go button and finally insert: "WCFService" into the field Web Reference name: WCFService





19. Add the next code line.



20. Select Button and click Custom Code button in the ribbon.


30. Add the next code into Click Event.


Note: Change the next parameters.

Application URL: "http://labwfos2010/sites/ejemplossharepoint/"
ListName: ItemsSharePoint.
TextboxValue= ValueText.



31. return to the infopath form select the tab File then click Form Options.


32. Select "Security and Trust" check Full Trust and Ok.


33. test.




WCF Code.

IService.cs


 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Runtime.Serialization;  
 using System.ServiceModel;  
 using System.Text;  
 namespace WCFInsertItem  
 {  
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
   [ServiceContract]  
   public interface IService1  
   {  
     [OperationContract]  
     string GetData(int value);  
     [OperationContract]  
     CompositeType GetDataUsingDataContract(CompositeType composite);  
     [OperationContract]  
     void InsertItemInList(string UrlWebApplication, string ListName, string TitleItem);  
     // TODO: Add your service operations here  
   }  
   // Use a data contract as illustrated in the sample below to add composite types to service operations  
   [DataContract]  
   public class CompositeType  
   {  
     bool boolValue = true;  
     string stringValue = "Hello ";  
     [DataMember]  
     public bool BoolValue  
     {  
       get { return boolValue; }  
       set { boolValue = value; }  
     }  
     [DataMember]  
     public string StringValue  
     {  
       get { return stringValue; }  
       set { stringValue = value; }  
     }  
   }  
 }  

Service1.cs


 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Runtime.Serialization;  
 using System.ServiceModel;  
 using System.Text;  
 using Microsoft.SharePoint;  
 namespace WCFInsertItem  
 {  
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.  
   public class Service1 : IService1  
   {  
     public string GetData(int value)  
     {  
       return string.Format("You entered: {0}", value);  
     }  
     public CompositeType GetDataUsingDataContract(CompositeType composite)  
     {  
       if (composite == null)  
       {  
         throw new ArgumentNullException("composite");  
       }  
       if (composite.BoolValue)  
       {  
         composite.StringValue += "Suffix";  
       }  
       return composite;  
     }  
     public void InsertItemInList(string UrlWebApplication, string ListName, string TitleItem)  
     {  
       using (SPSite site = new SPSite(UrlWebApplication))  
       {  
         using (SPWeb web = site.OpenWeb())  
         {  
           web.AllowUnsafeUpdates = true;  
           SPList oList = web.Lists[ListName];  
           SPItem oItem = oList.Items.Add();  
           oItem["Title"] = TitleItem;  
           oItem.Update();  
           web.AllowUnsafeUpdates = false;  
         }  
       }  
     }  
   }  
 }  


Infopath Code.


 using Microsoft.Office.InfoPath;  
 using System;  
 using System.Xml;  
 using System.Xml.XPath;  
 using WCFInfopathForm.WCFService;  
 namespace WCFInfopathForm  
 {  
   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["CTRL2_5"]).Clicked += new ClickedEventHandler(CTRL2_5_Clicked);  
     }  
     public void CTRL2_5_Clicked(object sender, ClickedEventArgs e)  
     {  
       // Write your code here.  
       Service1 WCFInfopath = new Service1();  
       WCFInfopath.Credentials = System.Net.CredentialCache.DefaultCredentials;  
       XPathNavigator ValueInfo = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:field1", this.NamespaceManager);  
       String ValueText = ValueInfo.Value;  
       WCFInfopath.InsertItemInList("http://labwfos2010/sites/ejemplossharepoint/", "ItemsSharePoint", ValueText);  
     }  
   }  
 }  


easily =)
Regards.
Oscar Miguel Dominguez Acevedo

lunes, 15 de julio de 2013

SharePoint 2010 - Update xml in a SharePoint forms Library programmatically.

It's posible programatically update a xml form in a SharePoint form library, the next post shows the way.




Scenary

In a form library, you need update the field "Email"  value  in all forms at the same time. In this case, the possible solution  open one by one the forms, but this is slow, now the best way is programming.


1. First, locate the form library.



2. Find the field who need update




3. Create a visual webpart  to place the code. Insert one textbx and a Button. See the next image.


4. Now, add the next code in the click event to our button


5. Execute and test.


6. With this, the field "Email" is updated in all forms from our library

Code.

 using System;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Web.UI.WebControls.WebParts;  
 using System.Xml;  
 using Microsoft.SharePoint;  
 using System.IO;  
 namespace ProyectosSharePoint.UpdateXml  
 {  
   public partial class UpdateXmlUserControl : UserControl  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
     }  
     protected void Button1_Click(object sender, EventArgs e)  
     {  
       System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); /// New Xml Document  
       SPWeb web = SPContext.Current.Web; /// current context  
       SPFolder FolderXML = web.GetFolder("Formulaio"); /// folder name  
       foreach (SPFile File in FolderXML.Files)  
       {  
         byte[] XmlFormData = File.OpenBinary();/// open file  
         System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();  
         using (MemoryStream ms = new MemoryStream(XmlFormData))  
         {  
           MemoryStream ms2 = new MemoryStream();  
           xmldoc.Load(ms);/// load Xml  
           XmlNodeList nodes = xmldoc.GetElementsByTagName("my:Email");/// Node  
           nodes.Item(0).InnerText = TextBox1.Text;/// Update Node with textbox value  
           xmldoc.Save(ms2);///Save xmldoc in new MemoryStream ms2  
           ms.Close();/// close  
           File.SaveBinary(ms2);/// save file with new MemoryStream  
         }  
       }  
     }  
   }  
 }  

Regards.
Oscar Miguel Dominguez Acevedo.

miércoles, 3 de julio de 2013

Infopath 2010 y SharePoint 2010 Recorriendo Repeating Tables anidadas. (nested repeating tables infopath 2010)

Trabajar con Infopath es tarea de todos los días para muchos desarrolladores esta vez me encontré con un pequeño problema en el cual tenia una tabla repetida pero dentro de ella existían otras tablas repetidas que contenían información basándose en la primera, el asunto parecía sencillo de resolver, sin embargo algunos detalles de infopath dificultaban ciertos métodos para recorrer las tablas, a continuación explicare un método eficaz para recorrer una tabla repetida de infopath que contiene otras tablas anidadas.


1. Tenemos nuestras tablas en Infopath de la siguiente manera.


si se dan cuenta mi tabla principal es  "Equipo" y debajo de ella existen muchas mas, sin embargo yo necesito datos de la que se llama "Detalle_Activo".

Necesito obtener la información de los siguientes campos para armar una DataTable y después enviar dicha información.


  • Marca
  • Subclasificación
  • Numero de serie equipo
  • Usuario unidad
recordemos que Marca y Subclasificación están en la tabla superior llamada "Equipo" y Numero de serie equipo y Usuario unidad, se encuentran en la ultima tabla que esta anidada en la primera.

2. Pues comenzamos con el código, primero creando nuestro objeto DataTable.


3. Creamos Columnas y les agregamos información que nos servirán como cabeceras.

4. Creamos nuestro XPathNavigator y XPathNodeIterator para poder recorre nuestras Tablas.



5. Y aquí viene la parte medular, donde recorremos las tablas y agregamos los valores a nuestro DataTable. 


Explicación del codigo:

  • Comenzamos con un While que recorre la tabla principal
  •  En este caso obtener los valores de Marca y SubClasificacion no es el problema estos los almacenamos en las variables.(Marca y Modelo).
  • en la fila que revisamos verificamos si tiene hijos usando HasChildren si esta es verdadera entonces nos movemos a la fila hijo usando MoveToFirstChild.
  • Usamos la variable LocalName para obtener el nombre de la fila hijo en la que estamos posicionados.
  • mediante un If verificamos que la fila hijo en la que estamos sea "Detalle_Activo" que es la tabla repetida anidada al final.
  • si entra dentro de nuestro If vamos a almacenar el Current.OuterXml que es un xml que contiene los campos Numero de serie equipo y Usuario unidad, creamos un XmlDocument, luego lo cargamos y buscamos los nodos "my:Usuario_Unidad" y "my:Numero_Serie_Equipo" que contienen los datos que necesitamos, usando InnerText obtenemos los valores  de estos nodos en el actual registro, los guardamos en variables y por ultimo agregamos un row a nuestro Table.

De esta manera podemos recorrer tablas repetidas anidadas.

Saludos.
Oscar Miguel Dominguez Acevedo.