I have the function GetDocumentLibrary which must return a libray from sharepoint site. When I execute it from a Visual Studio Console Application it works and return the library with all informations. But when I execute it from a CRM Plugin in CRM Server the query variable contains one result (that is right) but this result is null. Why it is null ? The two code are same.
protected void ExecutePostContactCreate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
var candidatFirstName = "TestFN";
var candidatLastName = "TestLN";
string sharepointFolderName = candidatLastName + " " + candidatFirstName;
//Site details
string shpSite = "https://org.sharepoint.com/sites/website";
string login = "login";
string password = "password";
string libName = "LibName";
var securePassword = new SecureString();
foreach (char c in password) securePassword.AppendChar(c);
var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
using (ClientContext clientContext = new ClientContext(shpSite))
{
clientContext.Credentials = onlineCredentials;
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
//Créate sharepoint folder
CreateFolder(clientContext, web, libName, sharepointFolderName);
}
}
private void CreateFolder(ClientContext clientContext, Web web, string libraryName, string folder)
{
try
{
var list = GetDocumentLibrary(clientContext, web, libraryName);
if (list != null)
{
var folders = list.RootFolder.Folders;
clientContext.Load(folders);
clientContext.ExecuteQuery();
var newFolder = folders.Add(folder);
clientContext.ExecuteQuery();
}
else
throw new Exception("Test");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private List GetDocumentLibrary(ClientContext clientContext, Web web, string libraryName)
{
try
{
if (web != null)
{
var query = clientContext.LoadQuery(
web.Lists.Where(p => p.Title == libraryName));
clientContext.ExecuteQuery();
return query.FirstOrDefault(); //Returns Null when exectude from CRM plugin but works from VS Console App;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return null;
}