O365 via PowerShell in ASP.NET MVC 3: MicrosoftOnlineException was thrown

asp.net-mvc-3, c#, office365, powershell

Solution

I found the solution!

I don't know the reason, but on the target server, the app pool's advanced settings for my app had set Load User Profile to `False`. I changed it back to `True` (which should be default) and voilà, it works!

Edit: The Load User Profile setting was apparently automatically set to `False` by default because the IIS 6.0 Manager was installed and `False` was the default behavior until IIS 6.0.

Problem

I have an ASP.NET MVC 3 application which uses PowerShell to connect to Office 365 to retrieve some details about user licenses. The code itself works in many cases: - The project in my local IIS works - A piece of code in LINQPad using the library works on my machine - A piece of code in LINQPad using the library works on the target server And where it doesn't work is of course the only place it really should work: The IIS on the target server. I always get an Exception when calling the `Connect-MsolService` cmdlet. The problem is that the Exception doesn't tell me anything. The Exception type is `Microsoft.Online.Administration.Automation.MicrosoftOnlineException` and the message is Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown which is pretty useless. The Office 365 user account I use in my code is always the same. The user account used to start the IIS is always the same, too (Local System). I wrapped the PowerShell code execution in a class named `PowerShellInvoker`. Its code can be found here. And here is the code that connects to Office 365: ``` var cred = new PSCredential(upn, password); _psi = new PowerShellInvoker("MSOnline"); _psi.ExecuteCommand("Connect-MsolService", new { Credential = cred }); ``` There is no Exception actually thrown, the error is found in the `Error` property of the pipeline. (See lines 50ff. of the `PowerShellInvoker` class.) The problem is that I don't know what could be wrong, especially because the same code works when I use LINQPad. The search results by Google couldn't help me either. The server runs on Windows Server 2008 R2 Datacenter SP1 with IIS 7.5.

Original source