Monday, August 26, 2013

InfoPath 2010 Programmatically set web service parameters for Data Connection (WebServiceConnection)

When developing InfoPath forms, have you ever needed to dynamically set the parameters of a web service during run time?
I have.

Using the SharePoint Taxonomy web service as an example., here's what I did:
First, I create a Data Connection which points to the TaxonomyClientService web service found in _vtu_bin/TaxonomyClientService.asmx. I am calling the web method GetTermSets.

For this particular web service, there are several parameters that need to be passed in.
You can refer to the other article for more details InfoPath 2010: Populating a dropdown with SharePoint Metadata Termstore

I opt not to automatically retrieve data when form is opened.

For each Data Connection that was created, there will be a corresponding secondary Data Source. I am going to make use of the XML for my dynamic updates.




Next, I am going to add some code-behind to my InfoPath 2010 form. This function will set some variables dynamically and update the query fields for the Data Connection before making a call to the web service to receive data.

      private void preLoadMetadata(string serverName)  
     {  
       // Different set of term set IDs for production and development  
       string serviceId = "";  
       string entityId = "";  
       if (serverName.EndsWith("dev"))  
       {  
           // Development term store id 
         serviceId = "6ed7b86c-239b-4b5f-8604-5f1770a20578";  
         entityId = "b3478271-a53a-425b-a96d-d56b40eb1c74";  
       }  
       else  
       {  
         serviceId = "b2fd7923-39df-40b1-bcec-a4d906d8b0f0";  
         entityId = "7c8da2bf-c2eb-424d-81eb-5805a5d0cbf3";  
       }  
       try  
       {  
         XPathNavigator secNav = this.DataSources["GetTermSets"].CreateNavigator();  
         secNav.SelectSingleNode("/dfs:myFields/dfs:queryFields/ns1:GetTermSets/ns1:sharedServiceIds", this.NamespaceManager).SetValue(serviceId);  
         secNav.SelectSingleNode("/dfs:myFields/dfs:queryFields/ns1:GetTermSets/ns1:termSetIds", this.NamespaceManager).SetValue(entityId);  
         this.DataConnections["GetTermSets"].Execute();  
       }  
       catch (Exception ex)  
       {  
         errorLog(ex.ToString());  
       }  
     }  

And then in my Form_Loading function I add these 2 lines of code:

     public void FormEvents_Loading(object sender, LoadingEventArgs e)  
     {  
       string serverName = System.Environment.MachineName.ToLower();  
       preLoadMetadata(serverName);  
     }  

This is a solution very specific to my needs but I hope you will find it helpful.

Related Posts Plugin for WordPress, Blogger...