0

The wpf app is working well on a computer where it was developed. The files from bin/Release are used to run the app. There is System.Management.Automation.dll used to work with powershell remotely on the Exchange Server 2010 to create new mailboxes. It's setup with Local = True so the dll is added into the files in the bin/release.

However, if the same files from bin/release are copied on another computer then all functionalities on Active Directory are working well except the mail-box creation part as it gives Error: Common Language Runtime detected an invalid program.

I could find a few advises as to uncheck 'Optimize Code' and rebuild it in VS but it seems as it's not helping.

As I said before all is working well on developer's computer. So, I run the app on another computer where VS 2013 was also installed and got an error:"The term 'Enable-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." Here is the code:

public static class  ManageMailBox
{
    public static bool CreateMailBox(string strUserID, string admin_user, string pword) //, string str_upn)
    {
        try
        {
            string strExchangeServer = Constants.ExchangeServer; 
            Uri uri = new Uri(@"http://" + strExchangeServer + @"/powershell?serializationLevel=Full"); // orig works

            /// must pass secure string
            char[] passwordChars = pword.ToCharArray();
            SecureString password = new SecureString();
            foreach (char c in passwordChars)
            {
                password.AppendChar(c);
            }
            PSCredential credential = new PSCredential("DOMAIN\\" + admin_user, password);
            Runspace runspace = RunspaceFactory.CreateRunspace();
            PowerShell powershell = PowerShell.Create();
            PSCommand command = new PSCommand();

            command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", uri);
            command.AddParameter("Credential", credential);
            command.AddParameter("Authentication", "Default");
            PSSessionOption sessionOption = new PSSessionOption();
            sessionOption.SkipCACheck = true;
            sessionOption.SkipCNCheck = true;
            sessionOption.SkipRevocationCheck = true;
            command.AddParameter("SessionOption", sessionOption);

            powershell.Commands = command;
            try
            {
                // open the remote runspace
                runspace.Open();

                // associate the runspace with powershell
                powershell.Runspace = runspace;

                // invoke the powershell to obtain the results
                Collection<PSSession> result = powershell.Invoke<PSSession>();

                foreach (ErrorRecord current in powershell.Streams.Error)
                {
                    throw new Exception("Exception: " + current.Exception.ToString());
                    throw new Exception("Inner Exception: " + current.Exception.InnerException);
                }

                if (result.Count != 1)
                    throw new Exception("Unexpected number of Remote Runspace connections returned.");

                // Set the runspace as a local variable on the runspace
                powershell = PowerShell.Create();
                command = new PSCommand();
                command.AddCommand("Set-Variable");
                command.AddParameter("Name", "ra");
                command.AddParameter("Value", result[0]);
                powershell.Commands = command;
                powershell.Runspace = runspace;

                powershell.Invoke();

                // First import the cmdlets in the current runspace (using Import-PSSession)
                powershell = PowerShell.Create();
                command = new PSCommand();
                //command.AddScript("Set-ExecutionPolicy -Unrestricted");
                command.AddScript("Import-PSSession -Session $ra");
                powershell.Commands = command;
                powershell.Runspace = runspace;
                powershell.Invoke();

                // Now run get-ExchangeServer
                powershell = PowerShell.Create();
                command = new PSCommand();

                command.AddCommand("Enable-Mailbox");
                command.AddParameter("Identity", strUserID);
                command.AddParameter("Alias", strUserID);
                command.AddParameter("Database", "IAP Mailbox Database 0948752629");
                powershell.Commands = command;
                powershell.Runspace = runspace;
                powershell.Invoke(); // ERROR !!! The term 'Enable-Mailbox' is not recognized as the name of a cmdlet, function

                return true;
            }
            catch(Exception ex) { 
                    throw new Exception(ex.Message.ToString()); }
            finally
            {
                // dispose the runspace and enable garbage collection
                runspace.Dispose();
                runspace = null;

                // Finally dispose the powershell and set all variables to null to free
                // up any resources.
                powershell.Dispose();
                powershell = null;
            }
        }
        catch (Exception argex)
        {
            throw new ArgumentException(argex.Message.ToString());
        }

    }
}
user5237764
  • 31
  • 2
  • 8
  • First guess would be your application is running under different permission set. Try executing it as admin on clients machine. – Karolis Kajenas Sep 08 '17 at 21:34
  • The app is opened as "run as a different user" with the high prevelage account and it's doing all task as creating new users in active directory successfully on different machines with no problems. However, for the creating a new mail-box on the Exhange Server 2010 it's working well on the developer's machine only giving the error on other computers. For this mail-box part a user login and the password are submitted through a pop-up window to pass it to powershell to work with the Exchange Server 2010. – user5237764 Sep 12 '17 at 02:21
  • Add logging. Run it again. Could be network restrictions. – Karolis Kajenas Sep 12 '17 at 05:03

4 Answers4

2

It seems like this could be a few things, it is hard to know what is the cause in your scenario. Firstly i would try running as Admin, failing that i would try these things:


reinstall the .net framework (make sure the version is correct)

Common Language Runtime detected an invalid program in Visual Studio


For C# projects go to the project properties and under the Build tab un-check "Optimize Code".

Common Language Runtime detected an invalid program?


Try enabling 32-bit applications in your application pool advanced settings.

or

I finally managed to solve this issue. I unchecked code optimization in C# Express and that solved the issues.

InvalidProgramException / Common Language Runtime detected an invalid program

axwr
  • 2,118
  • 1
  • 16
  • 29
  • TThank you for your response. As I mentioned in my initial post: a) everything works well in VS on the developer's computer; b) it works well using files from bin/release folder on the developer's computer; c) I did try to un-check the 'optimize code' option buiding and re-building the solution. However, when I copy bin/release files on another computer I'm getting the error. I did check the Framework on that another computer and it's the same. So, I'll try to reinstall the framework on the developer computer and do the 32bit adding and unchecking the 'optimize code' again. – user5237764 Sep 12 '17 at 02:11
  • As it was said before all is working well on a developer computer. So, I did use VS 2013 on another computer and run the app from the VS. I was getting the error: The term 'Enable-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. – user5237764 Sep 21 '17 at 23:31
1

It's solved. It was a matter of permissions for PowerShell script to use cmdlet commands remotely.

Edit: while it could be the case why mail-box could not be created this error was on another computer with a different configuration.

On the computer where we received the “Common language runtime error” the problem was the older versuion of PowerShell.

user5237764
  • 31
  • 2
  • 8
0

I experienced this in a Xamarin Forms app because I had a button click event on an event that didn't exist. Removing the click event from the button resolved the issue.

Lewis Cianci
  • 926
  • 1
  • 13
  • 38
0

I had this issue, published with "Optimize Code" checked in Project > Properties > Build and worked fine then re-published and "Optimize Code" unchecked and work OK again.

Edev
  • 11
  • 6