virang_21 0 Light Poster

Hi,
I am trying to create a mailbox on exchange server 2007 using power shell command via ASP.NET page. I am using windows impersonation to do this. I ma able to connect to my exchange server box but when I try to invoke the Mailbox-Create command the webpage displays "Connection was reset while page was loading". Bellow is my code... Please suggest the potential cause of it and any solution.... Trying to figure out why it is happening ....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;



namespace BBCApplication.Admin
{
    public partial class EnableMailbox : System.Web.UI.Page
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        // Holds the new impersonation token.
        private IntPtr _userToken = IntPtr.Zero;
        private WindowsImpersonationContext _impersonationContext = null;


        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private void EnableMailbox1(string domain, string domainController)
        {

        RunspaceConfiguration config = RunspaceConfiguration.Create();
        PSSnapInException warning;

        // This is where be begin the Impersonation
        BeginImpersonation(domain);
       
        // Load Exchange PowerShell snap-in.
        config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
        if (warning != null) throw warning;

        // This is where be begin the Impersonation
        BeginImpersonation(domain);
       
        using (Runspace thisRunspace = RunspaceFactory.CreateRunspace(config))
        {
            try
            {
                thisRunspace.Open();
                using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
                {
                    //Please change parameter values.
                    thisPipeline.Commands.Add("Enable-Mailbox");
                    thisPipeline.Commands[0].Parameters.Add("Identity", @"coms.local/Student/0909020");
                    thisPipeline.Commands[0].Parameters.Add("Database", @"comsexchange\First Storage Group\Mailbox Database");
                    // Need the line below when impersonating. KB943937. Need rollup 1 for sp1.
                    thisPipeline.Commands[0].Parameters.Add("DomainController", domainController); 

                    try
                    {
                        thisPipeline.Invoke(); // My page got this "Connection was reset while page was loading" error here
                    }
                    catch (Exception exx)
                    {
                        Response.Write("Error: " + exx.ToString());
                    }

                    // Check for errors in the pipeline and throw an exception if necessary.
                    if (thisPipeline.Error != null && thisPipeline.Error.Count > 0)
                    {
                        StringBuilder pipelineError = new StringBuilder();
                        pipelineError.AppendFormat("Error calling Enable-Mailbox.");
                        foreach (object item in thisPipeline.Error.ReadToEnd())
                        {
                            pipelineError.AppendFormat("{0}\n", item.ToString());
                        }

                        throw new Exception(pipelineError.ToString());
                    }
                }
            }

            finally
            {
                thisRunspace.Close();
                EndImpersonation();
            }
        }

    }

    private void BeginImpersonation(string domain)
    {
        //Please change the User Name and Password
        string UserName = "Administrator";
        string Password = "c@pta1n";

        EndImpersonation();

        Response.Write("User Before Impersonation: " + WindowsIdentity.GetCurrent().Name + "</BR>");
                
        bool success = LogonUser(
                UserName,
                domain,
                Password,
                2,
                0,
                ref _userToken);

        // Did it work?
        if (!success) throw new Exception(string.Format("LogonUser returned error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));

        WindowsIdentity fakeId = new WindowsIdentity(_userToken);
        _impersonationContext = fakeId.Impersonate();
        Response.Write("User After Impersonation: " + WindowsIdentity.GetCurrent().Name + "</BR>");

    }
    
    private void EndImpersonation()
    {
        if (_impersonationContext != null)
        {
            try
            {
                _impersonationContext.Undo();
            }
            finally
            {
                _impersonationContext.Dispose();
                _impersonationContext = null;
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // Use the current domain and domain controller. The domain controller parameter is needed for Impersonation to work
        // Please change ualues to suit you needs.
        string domain = "coms.local";
        string domainController = "comstest";
        try
        {
            EnableMailbox1(domain, domainController);
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        finally
        {
            Response.Write("Done..");
        }

    }

    



    }
}

Any help appreciated .... A weeks worth of effort and still I am not getting anywhere....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.