SecurityManager.ConnectTo(Outlook.Application) - problem on server

Add-in Express™ Support Service
That's what is more important than anything else

SecurityManager.ConnectTo(Outlook.Application) - problem on server
 
ZyQuest Inc




Posts: 4
Joined: 2012-03-07
We built an application to read e-mails off an exchange server. It's a .Net console application that is run as a scheduled task. It will be deployed on the client's server, where their default profile is also set up. Due to Microsoft's Object Model Guard we were getting the typical warning messages and ended up purchasing Security Manager. I was able to get everything working on my test pc but ran into a few issues trying to run it on the server, as a background process (ie. "Run only if logged on" = FALSE).

Again, I was able to get it working on my local PC either logged in, or logged off, but when running on the server the 'ConnectTo()' line throws the following exception:


Unhandled Exception: System.ArgumentException: Value does not fall within the expected range.
at AddinExpress.Outlook.IOutlookSecurityManager2.Connect(Object vTarget)
at AddinExpress.Outlook.SecurityManager.OSMThread.ThreadWork()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,< br>ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()


And here is the code for reference:

		
public Outlook.Application OutlookApplicationObject
{
    get
    {
        // Check whether there is an Outlook process running.
        if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
        {
            try
            {
                //If already running, use GetActiveObject to obtain the process
                return Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
            }
            catch (System.Exception)
            {
                //If interop com is not accessible, generally due to permissions, an exception will be thrown - just create a new instance
                return Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Outlook.Application;
            }
        }
        else
        {
            //No outlook process running, create a new instance
            return Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Outlook.Application;
        }
    }
}
		
		
/// <summary>
/// Loop through Exchange Server e-mails parsing customer/address/product information.
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public int ReadEmails()
{
    RegistrationRepository registrationDataAccess = new RegistrationRepository();
    List<CustomerDto> customerList = new List<CustomerDto>();
    CustomerDto customer = new CustomerDto();
    MAPIFolder inboxFolder, targetFolder;
    MailItem mailItem = null;
    int emailsRead = 0;

    Outlook.Application myOutlookApp = OutlookApplicationObject;
    Outlook.NameSpace myNamespace = myOutlookApp.GetNamespace("MAPI");

    AddinExpress.Outlook.SecurityManager secManager = new AddinExpress.Outlook.SecurityManager();

    try
    {
	myNamespace.Logon(ConfigurationManager.AppSettings.Get(PROFILE_USERNAME), ConfigurationManager.AppSettings.Get(PROFILE_PASSWORD), false, Missing.Value);
        inboxFolder = myNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

        secManager.ConnectTo(myOutlookApp.Application);
        secManager.DisableOOMWarnings = true;

        targetFolder = GetTargetFolder(inboxFolder.Parent.Folders);
        string mailSubject = ConfigurationManager.AppSettings.Get(EMAIL_SUBJECT_APP_SETTING);

        for (int i = 1; i <= inboxFolder.Items.Count; i++)
        {
            mailItem = (MailItem)inboxFolder.Items[i];
            if (mailItem.Subject.Contains(mailSubject))
            {
                customer = ParseEmailIntoDTO(mailItem);
                registrationDataAccess.SaveRegistration(customer);
                mailItem.UnRead = false;
                if (targetFolder != null)
                {
                    i--; //'moving' a mail item affects the inbox collection - adjust iterator appropriately
                    mailItem.Move(targetFolder);
                }
                emailsRead++;
            }
        }
    }
    catch (System.Exception ex)
    {
        throw;
    }
    finally
    {
        //Clean-up security manager (NECESSARY!)
        secManager.DisableOOMWarnings = false;
        secManager.Disconnect(myOutlookApp);
        secManager.Dispose();
        secManager = null;

        //Clean-up outloook application objects
        if (myOutlookApp != null)
        {
            Marshal.ReleaseComObject(myOutlookApp);
            myOutlookApp.Quit();
			myOutlookApp = null;
        }

        //Clean-up outloook application objects
        if (myNamespace != null)
        {
            Marshal.ReleaseComObject(myNamespace);
            myNamespace = null;
        }

        //Clean-up mail item
        if (mailItem != null)
        {
            Marshal.ReleaseComObject(mailItem);
            mailItem = null;
        } 

        //clean up mail items
        inboxFolder = null;
        targetFolder = null;
    }

    return emailsRead;
}


It would be awesome if anyone could provide any insight!
Posted 07 Mar, 2012 18:30:20 Top
Eugene Astafiev


Add-in Express team


Posts: 8540
Joined: 2007-07-25
Hi Bill,

I have noticed the following line of code:

secManager.ConnectTo(myOutlookApp.Application); 


Please try to pass just the myOutlookApp object to the ConnectTo method instead:

secManager.ConnectTo(myOutlookApp); 


Does it help?

Also please see the similar forum threads:

SecurityManager.2005 for Office 2007 error: Value does not fall within the expected range
Value does not fall within the expected range
"Value does not fall within expected range" - how to avoid
Loading SecurityManager causes re-installation
.NET, Extended MAPI, Windows Phone & RT
Posted 08 Mar, 2012 00:39:45 Top
ZyQuest Inc




Posts: 4
Joined: 2012-03-07
I was originally using this but it didn't work:
secManager.ConnectTo(myOutlookApp);
After reading a post on here I switched it to:
secManager.ConnectTo(myOutlookApp.Application );
That still didn't work so I also tried the following without success:
secManager.ConnectTo(myOutlookApp.Session.Application );
and
Outlook.Explorer myOutlookExp = myOutlookApp.ActiveExplorer();
secManager.ConnectTo(myOutlookExp);

Have you ever run into any issues using Security Manager on a server? It works on my test PC...

However my environments do differ a little.
TEST PC: Windows XP (x86) / Office 2007 (x86)
SERVER: Windows Server 2008 R2 (x64) / Outlook 2010 (x86)
Posted 08 Mar, 2012 08:59:06 Top
Eugene Astafiev


Add-in Express team


Posts: 8540
Joined: 2007-07-25
Hi Bill,

I have noticed that you run another threads in your application. Am I right? Does your application work as the MTA or STA? Note, you need to mark it as STA. For more information on this please take a look at the similar forum threads:

Value does not fall within expected range
Using secman.dll without registering it
SecurityManager.2005 for Office 2007 error: Value does not fall within the expected range

Is this the case?
.NET, Extended MAPI, Windows Phone & RT
Posted 09 Mar, 2012 03:50:45 Top
ZyQuest Inc




Posts: 4
Joined: 2012-03-07
I am using STA. I modified the code to continue even if the ConnecTo() fails. It appears to successfully disable the OOM warnings without connecting, however it's still breaking - now at this line:
targetFolder = GetTargetFolder(inboxFolder.Parent.Folders); 

The exception is:
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) |Stack Trace: at Microsoft.Office.Interop.Outlook.MAPIFolder.get_Parent()
at Registration.Application.Services.RegistrationService.ReadEmails()

This may be a different error all together but I couldn't find any obvious reason why this is happening.
Posted 09 Mar, 2012 12:59:00 Top
Renat Tlebaldziyeu


Add-in Express team


Posts: 132
Joined: 2010-02-15
Hi Bill,

Looks like you compile your application with the “AnyCPU” target platform.
Please note that the bitness of your application should be the same as Outlook bitness if you use Outlook Security Manager.
Could you please try to compile your application with the “x86” target platform (secman.dll should be registered on the target PC)?
Did it fix the issue?

You may also interested in the Outlook Security Manager 2010 deployment articles on our technical blog, here is the entry point:
http://www.add-in-express.com/creating-addins-blog/2010/06/16/outlook-security-manager2010-deployment/
Posted 12 Mar, 2012 02:16:26 Top
ZyQuest Inc




Posts: 4
Joined: 2012-03-07
I've tried both "AnyCPU" and "x86" with no success. We've been using Outlook 2007 (32-bit) and secman.dll (32-bit) all along.

I've also gone through a number of those technical articles already but unfortunately none of them helped to solve the problem.

At this point I'm out of troubleshooting time and we've begun a different approach using IMAP. It's going to require a little more creativity to do what we need but hopefully without the hiccups that Microsoft Interops bring.

Thanks anyway, for the help.
Posted 14 Mar, 2012 13:25:54 Top
Renat Tlebaldziyeu


Add-in Express team


Posts: 132
Joined: 2010-02-15
Thank you, Bill.

Could you please send me a sample project, which reproduces the issue
(please see readme.txt for the e-mail address and make sure your e-mail contains a link to this topic)?
Posted 15 Mar, 2012 01:58:43 Top
Dmitry Kostochko


Add-in Express team


Posts: 2731
Joined: 2004-04-05
Hi Bill,

This may be a different error all together but I couldn't find any obvious reason why this is happening.


Such unexpected and unexplainable exceptions may be caused by the code that is trying to access the Outlook Object Model from additional/background threads. Microsoft states that "The only threading model supported by the Outlook object model is single-threaded apartment (STA). Calling the Outlook object model from a background thread is not supported.":
Evaluation Criteria for the Outlook Object Model

Please keep this in mind when you try a different approach in your work.
Posted 15 Mar, 2012 11:47:45 Top