/// <summary> /// Serialize an OWMailConfiguration instance to a XML file on disk. /// </summary> /// <param name="configuration">An OWMailConfiguration instance to serialize.</param> /// <param name="configurationFilePath">Full file path for the XML file to be created/saved.</param> public static void Serialize(OWMailConfiguration configuration, string configurationFilePath) { // Checks permissions before proceeding if (File.Exists(configurationFilePath)) { CheckFilePermissions(configurationFilePath); } XmlTextWriter writer = null; try { writer = new XmlTextWriter(configurationFilePath, Encoding.UTF8); XmlSerializer serializer = new XmlSerializer(typeof(OWMailConfiguration)); serializer.Serialize(writer, configuration); } finally { // Clean up memory if (writer != null) { writer.Close(); } } }
/// <summary> /// Loads an OWMailConfiguration instance with settings stored in a XML file. /// </summary> /// <param name="configurationFilePath">OWMail 2.0 configuration file path to use when loading settings.</param> public void Read(string configurationFilePath) { OWMailConfiguration configuration = new OWMailConfiguration(); configuration = OWMailSerializer.Deserialize(configurationFilePath); // As this method could be called at runtime, this call ensures data is actual Refresh(configuration); }
/// <summary> /// Deserialize a XML file on disk to an instance of OWMailConfiguration. /// </summary> /// <param name="configurationFilePath">Full file path for the XML file to be read and deserialized.</param> /// <returns>A deserialized OWMailConfiguration instance.</returns> public static OWMailConfiguration Deserialize(string configurationFilePath) { OWMailConfiguration configuration = null; if (File.Exists(configurationFilePath)) { FileStream stream = null; XmlReader reader = null; try { CheckFilePermissions(configurationFilePath); stream = new FileStream(configurationFilePath, FileMode.Open, FileAccess.ReadWrite); reader = new XmlTextReader(stream); XmlSerializer serializer = new XmlSerializer(typeof(OWMailConfiguration)); configuration = (OWMailConfiguration)serializer.Deserialize(reader); } finally { // Clean up memory if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } } return(configuration); }
/// <summary> /// Overrides Equals to allow checking configuration changes. /// </summary> /// <param name="obj">An OWMailConfiguration instance that will be compared against current instance.</param> /// <returns>TRUE in case objects compared are Equal, otherwise FALSE will be returned.</returns> public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return(false); } OWMailConfiguration configuration = (OWMailConfiguration)obj; if (this.WebServiceUrl != configuration.WebServiceUrl) { return(false); } if (this.TempDirectoryPath != configuration.TempDirectoryPath) { return(false); } if (!this.From.Equals(configuration.From)) { return(false); } for (int x = 0; x < From.Values.Count; x++) { if (!((FromValues)this.From).Values[x].Equals(((FromValues)configuration.From).Values[x])) { return(false); } } if (!this.To.Equals(configuration.To)) { return(false); } for (int x = 0; x < To.Values.Count; x++) { if (!((ToValues)this.To).Values[x].Equals(((ToValues)configuration.To).Values[x])) { return(false); } } if (!this.Cc.Equals(configuration.Cc)) { return(false); } for (int x = 0; x < Cc.Values.Count; x++) { if (!((CcValues)this.Cc).Values[x].Equals(((CcValues)configuration.Cc).Values[x])) { return(false); } } if (!this.Subject.Equals(configuration.Subject)) { return(false); } for (int x = 0; x < Subject.Values.Count; x++) { if (!((SubjectValues)this.Subject).Values[x].Equals(((SubjectValues)configuration.Subject).Values[x])) { return(false); } } if (!this.Body.Equals(configuration.Body)) { return(false); } for (int x = 0; x < Body.Values.Count; x++) { if (!((BodyValues)this.Body).Values[x].Equals(((BodyValues)configuration.Body).Values[x])) { return(false); } } if (!this.Received.Equals(configuration.Received)) { return(false); } if (this.Mailboxes.Count != configuration.Mailboxes.Count) { return(false); } for (int x = 0; x < Received.Values.Count; x++) { if (!((ReceivedValues)this.Received).Values[x].Equals(((ReceivedValues)configuration.Received).Values[x])) { return(false); } } for (int x = 0; x < Mailboxes.Count; x++) { if (((Mailbox)this.Mailboxes[x]).BookId != ((Mailbox)configuration.Mailboxes[x]).BookId) { return(false); } if (((Mailbox)this.Mailboxes[x]).DocumentTypeId != ((Mailbox)configuration.Mailboxes[x]).DocumentTypeId) { return(false); } if (((Mailbox)this.Mailboxes[x]).MailboxName != ((Mailbox)configuration.Mailboxes[x]).MailboxName) { return(false); } if (((Mailbox)this.Mailboxes[x]).UserLogin != ((Mailbox)configuration.Mailboxes[x]).UserLogin) { return(false); } if (((Mailbox)this.Mailboxes[x]).ExtractAttachments != ((Mailbox)configuration.Mailboxes[x]).ExtractAttachments) { return(false); } if (((Mailbox)this.Mailboxes[x]).FromDefault != ((Mailbox)configuration.Mailboxes[x]).FromDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).ToDefault != ((Mailbox)configuration.Mailboxes[x]).ToDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).CcDefault != ((Mailbox)configuration.Mailboxes[x]).CcDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).BccDefault != ((Mailbox)configuration.Mailboxes[x]).BccDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).SubjectDefault != ((Mailbox)configuration.Mailboxes[x]).SubjectDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).BodyDefault != ((Mailbox)configuration.Mailboxes[x]).BodyDefault) { return(false); } if (((Mailbox)this.Mailboxes[x]).ReceivedDefault != ((Mailbox)configuration.Mailboxes[x]).ReceivedDefault) { return(false); } } return(true); }
/// <summary> /// Keeps instance data settings synchronized with XML file data values /// </summary> /// <param name="configuration">An OWMailConfiguration instance to keep synchronized with the XML configuration file.</param> private void Refresh(OWMailConfiguration configuration) { WebServiceUrl = configuration.WebServiceUrl; TempDirectoryPath = configuration.TempDirectoryPath; Mailboxes = configuration.Mailboxes; }
/// <summary> /// Makes a call to OWApi web service InsertRegistry method given some OWMailConfiguration parameters. /// </summary> /// <param name="userLogin">OWApi web service user login.</param> /// <param name="password">OWApi web service password.</param> /// <param name="contacts">MailContact list.</param> /// <param name="configuration">OWMailConfiguration instance to assign local variables.</param> /// <param name="guid">System.Guid string to name temporary attachments directory.</param> /// <param name="directoryName">Temporary attachments directory name.</param> /// <param name="filePath">File path for mail message file.</param> /// <param name="attachments">IBodyParts collection of mail message attachments.</param> /// <param name="subject">Mail message subject string.</param> /// <param name="mailDate">Mail message received time.</param> /// <param name="body">Mail messge body content string.</param> /// <returns>An integer corresponding to a created record id in tblRegistry or zero if record creation does not succeeds</returns> public static int InsertRegistry(string userLogin, string password, ArrayList contacts, OWMailConfiguration configuration, string guid, string directoryName, string filePath, IBodyParts attachments, string subject, DateTime mailDate, string body ) { int result = 0; OWApi OWApi = null; stRegistry registry = null; try { // Initializes and loads values for a stRegistry instance and all its nested types registry = new stRegistry(); // Assigns stUser instance data registry.User = new stUser(); registry.User.UserLogin = userLogin; //registry.User.UserMail = ((MailContact)contacts[1]).Mail; registry.User.UserMail = configuration.GetMailboxNameByUserLogin(userLogin); registry.Year = DateTime.Now.Year; // If insert subject if (configuration.GetSubjectMappingByMailboxName(registry.User.UserMail) == MappingOptions.Assunto) { if (subject.Length >= 250) { registry.Subject = string.Format("{0}(...)", subject.Substring(0, 245)); } else { registry.Subject = subject; } } // if Insert mailDate if (configuration.GetReceivedMappingByMailboxName(registry.User.UserMail) == MappingOptions.DataDocumento) { registry.DocumentDate = mailDate; } else if (configuration.GetReceivedMappingByMailboxName(registry.User.UserMail) == MappingOptions.DataRegisto) { registry.RegistryDate = mailDate; } //if Insert Body if (configuration.GetBodyMappingByMailboxName(registry.User.UserMail) == MappingOptions.Observacoes) { if (body.Length >= 250) { registry.Observations = string.Format("{0}(...)", body.Substring(0, 245)); } else { registry.Observations = body; } } int attachmentsCount = 0; // If message has attachments then keep track of its number to use in extracting loop below if (attachments != null && attachments.Count > 0) { attachmentsCount = attachments.Count; } // Mail message file itself always will be stored as an attachment to the new OfficeWorks record registry.Files = new stFile[attachmentsCount + 1]; registry.Files[0] = new stFile(); FileStream fsFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); // This is hard-coded by convention. Could come from a const. registry.Files[0].FileName = "Mail.eml"; registry.Files[0].FileArray = new byte[fsFile.Length]; fsFile.Read(registry.Files[0].FileArray, 0, (int)fsFile.Length); // Clean up unmanaged resources. fsFile.Close(); // Gets extract attachments flag from configuration. // This funcionality is implemented but was not made available for OWMail 2.0. bool extract = configuration.GetExtractAttachmentsByMailboxName(((MailContact)contacts[0]).Mail); // If there are attachments if (attachments != null && extract) { int counter = 0; // Loop through attachments collection and save each one to its file in message temporary directory foreach (IBodyPart attachment in attachments) { // Checks for a good working environment before trying to use resources from it if (Directory.Exists(directoryName)) { string fileName = attachment.FileName; string path = directoryName + @"\" + fileName; attachment.SaveToFile(path); counter++; // Stores each attachment in a stFile instance registry.Files[counter] = new stFile(); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); registry.Files[counter].FileName = fs.Name; registry.Files[counter].FileArray = new byte[fs.Length]; fs.Read(registry.Files[counter].FileArray, 0, (int)fs.Length); // Cleans up unmanaged resources memory fs.Close(); } } } // Assigns stBook instance data registry.Book = new stBook(); registry.Book.BookID = configuration.GetBookIdByMailboxName(registry.User.UserMail); // Assigns stDocumentType instance data registry.DocumentType = new stDocumentType(); registry.DocumentType.DocumentTypeID = configuration.GetDocumentTypeIdByMailboxName(registry.User.UserMail); // If there is more than one contact then stRegistry will contain // an array of MoreEntities which will be also recorded and shown if (contacts.Count > 1) /* + Entidades. */ { ArrayList arrmoreEntities = new ArrayList(); // Loops through all contacts in list for (int x = 0; x < contacts.Count; x++) { //moreEntities[x] = new stEntity(); stEntity contactEntity = new stEntity(); switch (((MailContact)contacts[x]).Type) { case enumMailBoxMapping.Cc: if (configuration.GetCcMappingByMailboxName(registry.User.UserMail) == MappingOptions.MaisEntidadesDes) { contactEntity.EntityName = ((MailContact)contacts[x]).Name; contactEntity.EntityExchangeID = ((MailContact)contacts[x]).Mail; contactEntity.EntityType = enumEntityType.EntityTypeDestiny; arrmoreEntities.Add(contactEntity); } break; case enumMailBoxMapping.From: if (configuration.GetFromMappingByMailboxName(registry.User.UserMail) == MappingOptions.MaisEntidadesOri) { contactEntity.EntityName = ((MailContact)contacts[x]).Name; contactEntity.EntityExchangeID = ((MailContact)contacts[x]).Mail; contactEntity.EntityType = enumEntityType.EntityTypeOrigin; arrmoreEntities.Add(contactEntity); } else if (configuration.GetFromMappingByMailboxName(registry.User.UserMail) == MappingOptions.EntPrincipal) { // Assigns main stEntity instance data /*EntidadePrincipal*/ registry.Entity = new stEntity(); registry.Entity.EntityName = ((MailContact)contacts[x]).Name; registry.Entity.EntityExchangeID = ((MailContact)contacts[x]).Mail; registry.Entity.EntityType = enumEntityType.EntityTypeOrigin; } break; case enumMailBoxMapping.To: if (configuration.GetToMappingByMailboxName(registry.User.UserMail) == MappingOptions.MaisEntidadesDes) { contactEntity.EntityName = ((MailContact)contacts[x]).Name; contactEntity.EntityExchangeID = ((MailContact)contacts[x]).Mail; contactEntity.EntityType = enumEntityType.EntityTypeDestiny; arrmoreEntities.Add(contactEntity); } break; } } // Assigns the extracted list of stEntities to stRegistry.MoreEntities property registry.MoreEntities = (stEntity[])arrmoreEntities.ToArray(typeof(stEntity)); } OWApi = new OWApi(); // Override OWApi proxy with URL value from configuration before making the call OWApi.Url = configuration.WebServiceUrl; // Call OWApi web service and gets returned integer result = (int)OWApi.InsertRegistry(userLogin, password, ref registry); } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// Implementation of a Synchronous Event. This event will be triggered every time a /// mail message arrives at the mailbox where it is registered. It is synchronous because /// message will wait for the code here implemented to end execution before beeing available in mailbox. /// </summary> /// <param name="pEventInfo">A pointer to an IExStoreEventInfo interface that can be used to obtain further information related to the event.</param> /// <param name="bstrURLItem">A string containing the URL of the item on which the event is occurring.</param> /// <param name="lFlags">Bitwise AND flag gives further information about the save event.</param> public void OnSyncSave(IExStoreEventInfo pEventInfo, string bstrURLItem, int lFlags) { // Initialize local variables OWMailConfiguration configuration = null; EventLog log = null; Stream stream = null; Record recItem = null; try { // These values are checked to identify a saving event before beeing commited // Exchange Server SDK value and Exchange Server 2003 have presented different values // so both were included in this implementation. The enum is also checked here, just in case... if (lFlags == 33554440 || lFlags == 33554432 || lFlags == (int)EVT_SINK_FLAGS.EVT_SYNC_COMMITTED) { // These two must have the same value string sourceApplication = "OWMail"; //string logName = "OWMail"; // If Event Viewer entry does not exists (e.g., first time), then create it if (!EventLog.SourceExists(sourceApplication)) { EventLog.CreateEventSource(sourceApplication, sourceApplication); } log = new EventLog(sourceApplication); log.Log = sourceApplication; log.Source = sourceApplication; // Get settings from OWMail 2.0 XML configuration file configuration = new OWMailConfiguration(ConfigurationFilePath); // Get a ADO Record object from pEventInfo parameter IExStoreDispEventInfo pDispEventInfo = (IExStoreDispEventInfo)pEventInfo; recItem = (Record)pDispEventInfo.EventRecord; // Get a ADO Stream object from ADO Record stream = new StreamClass(); stream.Open(recItem, ConnectModeEnum.adModeRead, StreamOpenOptionsEnum.adOpenStreamFromRecord, string.Empty, string.Empty); // Creates a new Guid to use when saving message and attachments to TEMP directory. // TEMP directory path is stored in configuration file. string guid = Guid.NewGuid().ToString(); string filePath = configuration.TempDirectoryPath + @"\" + guid + ".eml"; // Saves the ADO Stream to TEMP directory stream.SaveToFile(filePath, SaveOptionsEnum.adSaveCreateNotExist); // Creates a CDO Message object Message message = new MessageClass(); // Gets message data loaded from ADO Record object message.DataSource.OpenObject(recItem, "_Record"); // Assigns local variables from loaded message fields string from = message.From; string to = message.To; string cc = message.CC; string subject = (string)message.Fields["urn:schemas:httpmail:normalizedsubject"].Value; DateTime mailDate = message.ReceivedTime; string body = (string)message.Fields["urn:schemas:httpmail:textdescription"].Value; // Use event source URL to extract mailbox name string[] urlElements = bstrURLItem.Split('/'); string mailboxName = urlElements[urlElements.Length - 3]; // Use mailbox name to extract its operation settings from configuration string userLogin = configuration.GetUserLoginByMailboxName(mailboxName, '@'); // OWApi Web Service accepts blank credentials string password = string.Empty; //string entityName = string.Empty; // This list will hold all message entities encapsulated in MailContact objects ArrayList list = new ArrayList(); // This object has functions to ease the extraction of message entity fields MailContactHelper mailContactHelper = new MailContactHelper(); // Get a list with all entities referred in FROM, TO, CC, BCC message fields list = mailContactHelper.GetMailContactsList(from, to, cc); // Directory name to be created in case Extract Attachments option is activated string directoryName = configuration.TempDirectoryPath + @"\" + guid; // OWApiHelper is a wrapper for OWApi Web Service InsertRegistry method. // If call is successfull, result will contain the ID of record created in tblEntities int result = OWApiHelper.InsertRegistry(userLogin, password, list, configuration, directoryName, guid, filePath, message.Attachments, subject, mailDate, body); //Not Register if (result == 0) { throw new Exception("Não é possivel inserir o registo."); } // Clean up temporary message file if (File.Exists(filePath)) { File.Delete(filePath); } // Clean up temporary attachments directory if (Directory.Exists(directoryName)) { Directory.Delete(directoryName, true); } } } catch (Exception ex) { Exception ex2 = null; log.WriteEntry(ex.Message + " " + ex.StackTrace, EventLogEntryType.Error); ex2 = ex.InnerException; while (ex2 != null) { log.WriteEntry(ex2.Message + " " + ex2.StackTrace, EventLogEntryType.Error); ex2 = ex.InnerException; } throw ex; } finally { // Always cleans up unmanaged resources if (stream != null) { stream.Close(); } if (recItem != null) { recItem.Close(); } } }