Monday, November 24, 2008

Web Service (Data) Connection & Elevated Permissions

Let's Talk about Dynamically changing the web service's URL before executing and running with Elevated Permissions.

As we know very well by now, grabbing the settings from webconfig allows us seamlessly push code from Dev-QA-Staging-Production, Here I am showing sample code to change the Uri for the webservice as well as running the code with Elevated Privileges. Which allows to executes the specified method with Full Control rights even if the user does not have Full Control.

private void GetUserProfileByNameByChangingURI()
{
WebServiceConnection ws = (WebServiceConnection)this.DataConnections["GetUserProfileByName"];
Uri url = new Uri(ConfigurationManager.AppSettings["UserProfileWS"].ToString());
ws.ServiceUrl = url;
string accountName = "us9\\raja";
XPathNavigator nav = CreateNavigator();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Create the Data Source.
XPathNavigator navDataSource = DataSources["GetUserProfileByName"].CreateNavigator();
//Set or Pass The Query Parameter.
navDataSource.SelectSingleNode("/dfs:myFields/dfs:queryFields/s0:GetUserProfileByName/s0:AccountName", NamespaceManager).SetValue(accountName);
//All Set For Execution.
ws.Execute();
nav = navDataSource;
});

//Grab the Results from the Result Set.
XPathNavigator navFirstName = nav.SelectSingleNode("/dfs:myFields/dfs:dataFields/s0:GetUserProfileByNameResponse/s0:GetUserProfileByNameResult/s0:PropertyData[s0:Name='FirstName']/s0:Values/s0:ValueData[1]/s0:Value", NamespaceManager);
string FirstName = navFirstName.Value;
}
catch { }
}

Note:
a. Add the using System.Configuration Name Space to your solution so that you can read the webconfig.
b. Add fallowing key under in web.config file:
<add key="UserProfileWS" value="http://<site>/<_vti_bin/userprofileservice.asmx>/" />

Dynamically Updating Data Connections:

Wondering how to change Data connections dynamically in InfoPath Forms so that you can deploy the solution seamlessly from DEV-QA-Staging-Production.

Here is Sample Code for MainSubmit()

private void MainSubmit(SubmitEventArgs e)
{
bool bSuccessful = false;
try
{
FileSubmitConnection fc = (FileSubmitConnection)this.DataConnections["MainSubmit"];
Uri url = new Uri(ConfigurationManager.AppSettings["Submit"].ToString());
fc.FolderUrl = url.AbsoluteUri;
fc.Execute();
bSuccessful = true;
}
catch
{
System.Diagnostics.EventLog.WriteEntry("MainSubmit", "MainSubmit: Failed to Submit();");
}
// If the submit operation is successful, set
// e.CancelableArgs.Cancel = false;
e.CancelableArgs.Cancel = !bSuccessful;
}

Note:
a. Add the using System.Configuration Name Space to your solution so that you can read the webconfig.
b. Add fallowing key under in web.config file:
<add key="Submit" value="http://<url>/<LibraryName>/" />