Monday, 21 December 2009 21:32

Q#15: How to update InfoPath DataSources URL programmatically

Written by 
Rate this item
(0 votes)


>> Hello, I'm using InfoPath with dozen of DataSources that query data from Web Services, lists and etc. I'd like to know how can I update DataSource URL at run-time and use URL from config?


What you asked is very common question when InfoPath form need to be deployed from DEV to Staging and to Production environment and updating the DataSources manually is really daunting task.

The easiest way to achieve desired behavior is using DataConnections class, instead of DataSources. You can access DataConnection SiteURL property casting the object to the right connection object,. for example WebServiceConnection.

Use the following CodeSnippet, that allows you to iterate through all DataConnections and update its URL to the values from config file. This CodeSnippen assumes that only WebServices connections are used. You can extend it to support file object connections and other stuff

Code Snippet
  1. public static void UpdateDataSourceURL(DataConnectionCollection dataConnections)
  2. {
  3. if (SPContext.Current != null)
  4. {
  5. var webServiceURL = WebConfigurationManager.AppSettings["<WSurl>"];
  6. var siteURL = WebConfigurationManager.AppSettings["<siteURL>"];
  7. foreach (var connection in dataConnections)
  8. {
  9. if (connection is WebServiceConnection)
  10. {
  11. Uri webservicePath;
  12. var dataConnection = (connection as WebServiceConnection);
  13. if (dataConnection.ServiceUrl.ToString().Contains("_vti_"))
  14. {
  15. webservicePath = new Uri(string.Format("{0}{1}{2}", siteURL, dataConnection.ServiceUrl.Segments[2], dataConnection.ServiceUrl.Segments[3]));
  16. }
  17. else
  18. {
  19. webservicePath = new Uri(webServiceURL + dataConnection.ServiceUrl.Segments[2]);
  20. }
  21. dataConnection.ServiceUrl = webservicePath;
  22. }}}}


Read 2668 times Last modified on Tuesday, 21 August 2012 12:15

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.