Пример #1
0
        public ICoreItem OpenAttachedItem(ICollection <PropertyDefinition> propertiesToLoad, AttachmentPropertyBag attachmentBag, bool isNew)
        {
            MapiMessage            mapiMessage            = null;
            PersistablePropertyBag persistablePropertyBag = null;
            CoreItem      coreItem      = null;
            bool          flag          = false;
            StoreObjectId storeObjectId = null;

            byte[]    array = null;
            ICoreItem result;

            try
            {
                StoreObjectPropertyBag storeObjectPropertyBag = (StoreObjectPropertyBag)attachmentBag.PersistablePropertyBag;
                MapiAttach             mapiAttach             = (MapiAttach)storeObjectPropertyBag.MapiProp;
                StoreSession           session           = this.AttachmentCollection.ContainerItem.Session;
                OpenPropertyFlags      openPropertyFlags = isNew ? OpenPropertyFlags.Create : (this.AttachmentCollection.IsReadOnly ? OpenPropertyFlags.BestAccess : OpenPropertyFlags.BestAccess);
                openPropertyFlags |= OpenPropertyFlags.DeferredErrors;
                string text   = storeObjectPropertyBag.TryGetProperty(InternalSchema.ItemClass) as string;
                Schema schema = (text != null) ? ObjectClass.GetSchema(text) : MessageItemSchema.Instance;
                propertiesToLoad = InternalSchema.Combine <PropertyDefinition>(schema.AutoloadProperties, propertiesToLoad);
                StoreSession session2 = this.AttachmentCollection.ContainerItem.Session;
                bool         flag2    = false;
                try
                {
                    if (session2 != null)
                    {
                        session2.BeginMapiCall();
                        session2.BeginServerHealthCall();
                        flag2 = true;
                    }
                    if (StorageGlobals.MapiTestHookBeforeCall != null)
                    {
                        StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                    }
                    mapiMessage = mapiAttach.OpenEmbeddedMessage(openPropertyFlags);
                }
                catch (MapiPermanentException ex)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex, session2, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::OpenAttachedItem", new object[0]),
                        ex
                    });
                }
                catch (MapiRetryableException ex2)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenEmbeddedMessage, ex2, session2, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("MapiAttachmentProvider::OpenAttachedItem", new object[0]),
                        ex2
                    });
                }
                finally
                {
                    try
                    {
                        if (session2 != null)
                        {
                            session2.EndMapiCall();
                            if (flag2)
                            {
                                session2.EndServerHealthCall();
                            }
                        }
                    }
                    finally
                    {
                        if (StorageGlobals.MapiTestHookAfterCall != null)
                        {
                            StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                        }
                    }
                }
                persistablePropertyBag = new StoreObjectPropertyBag(session, mapiMessage, propertiesToLoad);
                if (!isNew)
                {
                    StoreObjectType storeObjectType = ItemBuilder.ReadStoreObjectTypeFromPropertyBag(persistablePropertyBag);
                    ItemCreateInfo  itemCreateInfo  = ItemCreateInfo.GetItemCreateInfo(storeObjectType);
                    propertiesToLoad = InternalSchema.Combine <PropertyDefinition>(itemCreateInfo.Schema.AutoloadProperties, propertiesToLoad);
                    if (this.AttachmentCollection.IsReadOnly)
                    {
                        StoreId.SplitStoreObjectIdAndChangeKey(StoreObjectId.DummyId, out storeObjectId, out array);
                    }
                    persistablePropertyBag = new AcrPropertyBag(persistablePropertyBag, itemCreateInfo.AcrProfile, storeObjectId, new RetryBagFactory(session), array);
                }
                coreItem = new CoreItem(session, persistablePropertyBag, storeObjectId, array, isNew ? Origin.New : Origin.Existing, ItemLevel.Attached, propertiesToLoad, ItemBindOption.None);
                if (text != null && isNew)
                {
                    coreItem.PropertyBag[InternalSchema.ItemClass] = text;
                }
                flag   = true;
                result = coreItem;
            }
            finally
            {
                if (!flag)
                {
                    if (coreItem != null)
                    {
                        coreItem.Dispose();
                        coreItem = null;
                    }
                    if (persistablePropertyBag != null)
                    {
                        persistablePropertyBag.Dispose();
                        persistablePropertyBag = null;
                    }
                    if (mapiMessage != null)
                    {
                        mapiMessage.Dispose();
                        mapiMessage = null;
                    }
                }
            }
            return(result);
        }
        internal ImportResult ImportChange(CreateMessageType createMessageType, bool failOnConflict, IList <PropertyDefinition> propertyDefinitions, IList <object> propertyValues, out MapiMessage mapiMessage)
        {
            this.CheckDisposed(null);
            ImportMessageChangeFlags importMessageChangeFlags = ImportMessageChangeFlags.NewMessage;

            if (failOnConflict)
            {
                importMessageChangeFlags |= ImportMessageChangeFlags.FailOnConflict;
            }
            if (createMessageType == CreateMessageType.Associated)
            {
                importMessageChangeFlags |= ImportMessageChangeFlags.Associated;
            }
            else if (createMessageType != CreateMessageType.Normal)
            {
                throw new ArgumentOutOfRangeException("createMessageType", createMessageType, "Only Normal and Associated messages can be imported");
            }
            PropValue[]  propValues   = base.GetPropValuesFromValues(base.Session.ExTimeZone, propertyDefinitions, propertyValues).ToArray();
            MapiMessage  mapiMessage2 = null;
            bool         flag         = false;
            ImportResult result;

            try
            {
                StoreSession        session = base.Session;
                bool                flag2   = false;
                MapiCollectorStatus mapiCollectorStatus;
                try
                {
                    if (session != null)
                    {
                        session.BeginMapiCall();
                        session.BeginServerHealthCall();
                        flag2 = true;
                    }
                    if (StorageGlobals.MapiTestHookBeforeCall != null)
                    {
                        StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                    }
                    mapiCollectorStatus = base.MapiCollector.ImportMessageChange(propValues, importMessageChangeFlags, out mapiMessage2);
                }
                catch (MapiPermanentException ex)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.CannotImportMessageChange, ex, session, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("Import of the message change failed", new object[0]),
                        ex
                    });
                }
                catch (MapiRetryableException ex2)
                {
                    throw StorageGlobals.TranslateMapiException(ServerStrings.CannotImportMessageChange, ex2, session, this, "{0}. MapiException = {1}.", new object[]
                    {
                        string.Format("Import of the message change failed", new object[0]),
                        ex2
                    });
                }
                finally
                {
                    try
                    {
                        if (session != null)
                        {
                            session.EndMapiCall();
                            if (flag2)
                            {
                                session.EndServerHealthCall();
                            }
                        }
                    }
                    finally
                    {
                        if (StorageGlobals.MapiTestHookAfterCall != null)
                        {
                            StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                        }
                    }
                }
                ImportResult importResult = ContentsSynchronizationUploadContext.ConvertToImportResult(mapiCollectorStatus);
                mapiMessage = mapiMessage2;
                flag        = true;
                result      = importResult;
            }
            finally
            {
                if (!flag)
                {
                    mapiMessage = null;
                    if (mapiMessage2 != null)
                    {
                        mapiMessage2.Dispose();
                    }
                }
            }
            return(result);
        }
Пример #3
0
        /// <summary>
        /// Creates and sends an e-mail message using the Simple MAPI protocol.</summary>
        /// <param name="subject">
        /// The subject line of the e-mail message.</param>
        /// <param name="noteText">
        /// The text of the e-mail message.</param>
        /// <param name="recipients">
        /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names
        /// and SMTP addresses of all message recipients. The protocol identifier "smtp:" is
        /// automatically prepended to any non-empty addresses without this prefix.</param>
        /// <param name="attachments">
        /// An <see cref="Array"/> of <see cref="MapiAddress"/> instances holding the display names
        /// and fully qualified local file paths of any attachment files sent to the <paramref
        /// name="recipients"/>.</param>
        /// <exception cref="MapiException">
        /// <see cref="Mapi.MAPISendMail"/> indicated an error.</exception>
        /// <remarks><para>
        /// <b>SendMail</b> creates and sends an e-mail message with optional file attachments,
        /// using the Win32 API call <see cref="Mapi.MAPISendMail"/> which is part of the Simple
        /// MAPI protocol. The originator is left undefined which will cause Simple MAPI to assert
        /// the user’s default e-mail account as the originator.
        /// </para><para>
        /// The <paramref name="subject"/> and <paramref name="noteText"/> parameters may be a null
        /// reference or an empty string to leave the corresponding field blank. The <paramref
        /// name="recipients"/> and <paramref name="attachments"/> parameters may be null references
        /// or empty arrays to create a message without recipients or file attachments,
        /// respectively.
        /// </para><para>
        /// The e-mail message is presented to the user who can choose to edit (filling in any blank
        /// fields or adding text as desired), send, or cancel the message. User cancellation
        /// generates a <see cref="MapiException"/> whose <see cref="MapiException.Code"/> is <see
        /// cref="MapiException.Abort"/>.</para></remarks>

        public static void SendMail(string subject, string noteText,
                                    MapiAddress[] recipients, MapiAddress[] attachments)
        {
            // remember current working directory
            string currentDir = Directory.GetCurrentDirectory();

            // construct MAPI message descriptor
            MapiMessage message = new MapiMessage();

            message.lpszSubject  = subject;
            message.lpszNoteText = noteText;

            try {
                // create any specified recipients
                if (recipients != null && recipients.Length > 0)
                {
                    // store count of recipient descriptors
                    int count = recipients.Length;
                    message.nRecipCount = (uint)count;

                    // allocate memory for recipient descriptors
                    int size = Marshal.SizeOf(typeof(MapiRecipDesc));
                    message.lpRecips.AllocateHandle(count * size);

                    // construct recipient descriptors
                    MapiRecipDesc recip = new MapiRecipDesc();
                    for (int i = 0; i < count; i++)
                    {
                        // prepend "smtp:" to address if not present
                        string address = recipients[i].Address;
                        if (!String.IsNullOrEmpty(address) &&
                            !address.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
                        {
                            address = "smtp:" + address;
                        }

                        // create MAPI recipient descriptor
                        recip.ulRecipClass = MapiRecipClass.MAPI_TO;
                        recip.lpszName     = recipients[i].Name;
                        recip.lpszAddress  = address;

                        // copy recipient descriptor to unmanaged memory
                        message.lpRecips.SetMemory(recip, i * size, false);
                    }
                }

                // create any specified attachments
                if (attachments != null && attachments.Length > 0)
                {
                    // store count of attachment descriptors
                    int count = attachments.Length;
                    message.nFileCount = (uint)count;

                    // allocate memory for attachment descriptors
                    int size = Marshal.SizeOf(typeof(MapiFileDesc));
                    message.lpFiles.AllocateHandle(count * size);

                    // construct attachment descriptors
                    MapiFileDesc fileDesc = new MapiFileDesc();
                    for (int i = 0; i < count; i++)
                    {
                        // create MAPI file attachment descriptor
                        fileDesc.lpszFileName = attachments[i].Name;
                        fileDesc.lpszPathName = attachments[i].Address;
                        fileDesc.nPosition    = 0xffffffff; // don’t embed files

                        // copy attachment descriptor to unmanaged memory
                        message.lpFiles.SetMemory(fileDesc, i * size, false);
                    }
                }

                // invoke MAPISendMail to deliver this message
                MapiFlags flags = MapiFlags.MAPI_DIALOG | MapiFlags.MAPI_LOGON_UI;
                MapiError code  = Mapi.MAPISendMail(UIntPtr.Zero, UIntPtr.Zero, message, flags, 0);

                // throw exception if MAPI reports failure
                if (code != MapiError.SUCCESS_SUCCESS)
                {
                    ThrowMapiException(code);
                }
            }
            finally {
                // release unmanaged memory blocks
                message.Dispose();

                // restore original working directory
                Directory.SetCurrentDirectory(currentDir);
            }
        }