Ejemplo n.º 1
0
        private void Archive_Startup(object sender, EventArgs e)
        {
            _sentItems = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items;
            _sentItems.ItemAdd += SentItems_ItemAdd;

            _archiveFolder = Application.Session.DefaultStore.GetRootFolder().Folders[ArchiveFolderName];
        }
Ejemplo n.º 2
0
 public Badger(
     Outlook.Application pApplication, 
     int pSpecies,
     string pFolderPath, 
     TimeSpan pInterval)
 {
     mBadgerFolder = Util.InitializeMailFolder(pApplication, pFolderPath);
     BadgerSpecies = pSpecies;
     Interval = pInterval;
 }
Ejemplo n.º 3
0
 public void Dispose()
 {
     helpers.addLog("Disposing...");
     MailNS.Logoff();
     MailNS = null;
     MyInbox = null;
     //InboxMailItem = null;
     ((Microsoft.Office.Interop.Outlook._Application)MyApp).Quit();
     ////MyApp.Quit();
     MyApp = null;
     helpers.addLog("Dispose done.");
 }
		public OutlookMail()
		{
			//http://www.c-sharpcorner.com/uploadfile/casperboekhoudt/sendingemailsthroughoutlook12052005000124am/sendingemailsthroughoutlook.aspx

			oApp = new Outlook.Application();
			oNameSpace = oApp.GetNamespace("MAPI");
			oNameSpace.Logon(null, null, true, true);

			//Calender: Outlook.OlDefaultFolders.olFolderCalendar 
			//Contacts: Outlook.OlDefaultFolders.olFolderContacts 
			//Inbox: Outlook.OlDefaultFolders.olFolderInbox 

			oOutboxFolder = oNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox);
		}
 private void OnPreviewKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Escape)
     {
         this.DialogResult = false;
         this.Close();
     }
     else if (e.Key == Key.Enter)
     {
         this.DialogResult = true;
         this.SelectedFolder = (Outlook.MAPIFolder)tb.SelectedItem;
         this.Close();
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        ///  assigns properties to member fields
        /// </summary>
        /// <param name="outlookFolder"></param>
        /// <param name="outlookExplorer"></param>
        /// <param name="isFolderMappedWithDocLibrary"></param>
        public UploadBrokenUploads(Outlook.MAPIFolder outlookFolder, Outlook.Explorer outlookExplorer, bool isFolderMappedWithDocLibrary)
        {
            try
            {
                FolderName = outlookFolder.Name;
                //Get the details of the folder. Is it is mapped to SP DocLib or SPSIte(Pages)
                isUserDroppedItemsCanUpload = isFolderMappedWithDocLibrary;
                addinExplorer = outlookExplorer;
                activeDroppingFolder = outlookFolder;
                activeDroppingFolderItems = outlookFolder.Items;

            }
            catch (Exception ex)
            { }
        }
Ejemplo n.º 7
0
        public MonitorPath()
        {
            this.m_OutlookApp = new Microsoft.Office.Interop.Outlook.Application();
            this.m_OutlookNameSpace = (Microsoft.Office.Interop.Outlook._NameSpace)this.m_OutlookApp.GetNamespace("MAPI");
            this.m_MAPIFolder = this.m_OutlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            this.m_Explorer = this.m_MAPIFolder.GetExplorer(false);
            this.m_OutlookNameSpace.Logon(System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, true);

            this.m_LastReportDistributionHeartBeat = DateTime.Now.AddMinutes(-5);

            ISubscriber subscriber = Business.RedisConnection.Instance.GetSubscriber();
            subscriber.Subscribe("ReportDistributionHeartBeat", (channel, message) =>
            {
                this.m_LastReportDistributionHeartBeat = DateTime.Now;
            });

            this.m_PageQueue = new Queue<System.Windows.Controls.UserControl>();
            this.m_MonitorPageWindow = new MonitorPageWindow();
        }
Ejemplo n.º 8
0
		protected virtual void Dispose(bool isDisposing)
		{
			if (isDisposing)
			{
				GC.SuppressFinalize(this);
			}

			if (_items != null)
				Marshal.ReleaseComObject(_items);

			if (_ns != null)
				Marshal.ReleaseComObject(_ns);

			if (_sent != null)
				Marshal.ReleaseComObject(_sent);

		    _ns = null;
			_sent = null;
			_items = null;
		}
Ejemplo n.º 9
0
        /// <summary>
        /// <c>MAPIFolderWrapper</c> member function
        /// assigns properties to member fields and register add event on <c> Outlook.Items</c>
        /// </summary>
        /// <param name="outlookFolder"></param>
        /// <param name="outlookExplorer"></param>
        /// <param name="isFolderMappedWithDocLibrary"></param>
        public MAPIFolderWrapper(ref  Outlook.MAPIFolder outlookFolder, Outlook.Explorer outlookExplorer, bool isFolderMappedWithDocLibrary)
        {
            try
            {
                FolderName = outlookFolder.Name;
                //Get the details of the folder. Is it is mapped to SP DocLib or SPSIte(Pages)
                isUserDroppedItemsCanUpload = isFolderMappedWithDocLibrary;
                addinExplorer = outlookExplorer;
                activeDroppingFolder = outlookFolder;

                activeDroppingFolderItems = outlookFolder.Items;
                activeDroppingFolderItems.ItemAdd -= new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(activeDroppingFolderItems_ItemAdd);

                //bw.DoWork += delegate(object sender, DoWorkEventArgs e) { bw_DoWork(sender, e, Item); };

            }
            catch (Exception ex)
            { }

            activeDroppingFolderItems.ItemAdd += new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(activeDroppingFolderItems_ItemAdd);
        }
Ejemplo n.º 10
0
        public OutlookClass()
        {
            try
            {
                //start outlook
                MyApp = new Application();
                MailNS = MyApp.GetNamespace("MAPI");

                string sProfile = "", sPassword="";

                bool bShowDialog = true, bNewSession=false;

                MailNS.Logon(sProfile, sPassword, bShowDialog, bNewSession);

                MyInbox = MailNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

            }
            catch (System.Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
            }
        }
Ejemplo n.º 11
0
		public EmailMessageHelper(string pstFile, string rootFolderName)
		{
			m_sender = new EmailSender();
			m_app = m_sender.Initialise();

			//Create a copy of the PST file and only work with the copy.
			m_pstCopy = String.Format("{0}{1}COPY.PST",
                                        Path.GetTempPath(),
										Path.GetFileNameWithoutExtension(pstFile));
			
			File.Copy(pstFile, m_pstCopy, true);
			Assert.IsTrue( File.Exists( m_pstCopy ));

			m_mounter = new MailFolderMounter(m_app, m_pstCopy);

			MSOutlook.Folders folders = m_mounter.ETFolder.Folders;
			using (new ComObjectGovernor(folders))
			{
				m_rootFolder = folders[rootFolderName];
				Assert.IsNotNull(m_rootFolder, "Cannot find the folder containing the test emails");
			}
		}
Ejemplo n.º 12
0
        /// <summary>
        /// <c>MoveItemIsReportItem</c> member function
        /// move reportItem to the sourcefolder if autodelete option is  not checked
        /// </summary>
        /// <param name="Item"></param>
        /// <returns></returns>
        private bool MoveItemIsReportItem(object Item)
        {
            bool isDroppedItemUplaoded = false;
            try
            {

                //////////
                Outlook.ReportItem oMailItem = (Outlook.ReportItem)Item;
                ItemType = TypeOfMailItem.ReportItem;
                parentfolder = (Outlook.MAPIFolder)oMailItem.Parent;
                try
                {

                    mailitemEntryID = oMailItem.EntryID;

                    string strsubject = oMailItem.EntryID;
                    if (string.IsNullOrEmpty(strsubject))
                    {
                        strsubject = "tempomailcopy";
                    }

                    mailitemEntryID = strsubject;

                    string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg";

                    if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false)
                    {
                        Directory.CreateDirectory(UserLogManagerUtility.RootDirectory);
                    }
                    oMailItem.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG);

                }
                catch (Exception ex)
                {

                }

                string fileName = string.Empty;
                if (!string.IsNullOrEmpty(oMailItem.Subject))
                {
                    //Replce any specila characters in subject
                    fileName = Regex.Replace(oMailItem.Subject, strMailSubjectReplcePattern, " ");
                    fileName = fileName.Replace(".", "_");
                }

                if (string.IsNullOrEmpty(fileName))
                {
                    DateTime dtReceivedDate = Convert.ToDateTime(oMailItem.CreationTime);
                    fileName = "Untitled_" + dtReceivedDate.Day + "_" + dtReceivedDate.Month + "_" + dtReceivedDate.Year + "_" + dtReceivedDate.Hour + "_" + dtReceivedDate.Minute + "_" + dtReceivedDate.Millisecond;
                }

                UploadItemsData newUploadData = new UploadItemsData();
                newUploadData.UploadFileName = fileName;// oMailItem.Subject;
                newUploadData.UploadFileExtension = ".msg";
                newUploadData.UploadingReportItem = oMailItem;
                newUploadData.UploadType = TypeOfUploading.Mail;
                newUploadData.TypeOfMailItem = TypeOfMailItem.ReportItem;
                newUploadData.DisplayFolderName = folderName;
                frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                //Set dropped items is uploaded
                isDroppedItemUplaoded = true;

            }
            catch (Exception ex) { }
            try
            {

                XMLLogOptions userOptions = UserLogManagerUtility.GetUserConfigurationOptions();
                if (userOptions.AutoDeleteEmails == true)
                {
                    for (int i = 0; i <= parentfolder.Items.Count; i++)
                    {
                        try
                        {
                            Outlook.ReportItem me = (Outlook.ReportItem)parentfolder.Items[i];

                            if (me.EntryID == mailitemEntryID)
                            {
                                parentfolder.Items.Remove(i);

                            }
                        }
                        catch (Exception)
                        {

                        }
                    }
                }

            }
            catch (Exception)
            {

            }

            return isDroppedItemUplaoded;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// code written by Joy
        /// excutes ansd the start the timer upload process when the backgoundworkers's do work event fires
        /// </summary>
        /// <param name="Item"></param>
        void doBackGroundUpload(object Item)
        {
            try
              {

              Globals.ThisAddIn.isTimerUploadRunning = true;
              OutlookObj = Globals.ThisAddIn.Application;
              outlookNameSpace = OutlookObj.GetNamespace("MAPI");
              Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
              Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent;
              oMailRootFolders = olMailRootFolder.Folders;
              Outlook.MailItem moveMail = (Outlook.MailItem)Item;
              string newCatName = "Successfully Uploaded";
              if (Globals.ThisAddIn.Application.Session.Categories[newCatName] == null)
              {
                  outlookNameSpace.Categories.Add(newCatName, Outlook.OlCategoryColor.olCategoryColorDarkGreen, Outlook.OlCategoryShortcutKey.olCategoryShortcutKeyNone);
              }

              XmlNode uploadFolderNode = UserLogManagerUtility.GetSPSiteURLDetails("", folderName);

              if (uploadFolderNode != null)
              {
                  bool isDroppedItemUplaoded = false;

                  addinExplorer = ThisAddIn.OutlookObj.ActiveExplorer();

                  //Check the folder mapping with documnet library

                  if (isUserDroppedItemsCanUpload == false)
                  {
                      //Show message
                      try
                      {

                          Outlook.MailItem m = (Outlook.MailItem)Item;
                          mailitemEntryID = m.EntryID;

                          try
                          {
                              mailitem = m;

                              mailitemEntryID = m.EntryID;

                              string strsubject = m.EntryID;
                              if (string.IsNullOrEmpty(strsubject))
                              {
                                  strsubject = "tempomailcopy";
                              }

                              mailitemEntryID = strsubject;

                              string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg";

                              if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false)
                              {
                                  Directory.CreateDirectory(UserLogManagerUtility.RootDirectory);
                              }
                              m.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG);

                          }
                          catch (Exception ex)
                          {

                          }

                          Outlook.MAPIFolder fp = (Outlook.MAPIFolder)m.Parent;
                          DoNotMoveInNonDocLib(mailitemEntryID, fp);

                      }
                      catch (Exception)
                      {
                          NonDocMoveReportItem(Item);
                      }

                      MessageBox.Show("You are attempting to move files to a non document library. This action is not supported.", "ITOPIA", MessageBoxButtons.OK, MessageBoxIcon.Information);

                      return;

                  }

                  if (frmUploadItemsListObject == null || (frmUploadItemsListObject != null && frmUploadItemsListObject.IsDisposed == true))
                  {
                      //frmUploadItemsListObject = new frmUploadItemsList();

                      // myCustomTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(frmUploadItemsListObject, "ITOPIA");
                      //myCustomTaskPane.Visible = true;

                      IAddCustomTaskPane();

                  }
                  //frmUploadItemsListObject.TopLevel = true;
                  //frmUploadItemsListObject.TopMost = true;

                  ////////////////////// frmUploadItemsListObject.Show();

                  try
                  {

                      //////
                      //////////
                      Outlook.MailItem oMailItem = (Outlook.MailItem)Item;
                      parentfolder = (Outlook.MAPIFolder)oMailItem.Parent;
                      try
                      {
                          mailitem = oMailItem;

                          mailitemEntryID = oMailItem.EntryID;

                          string strsubject = oMailItem.EntryID;
                          if (string.IsNullOrEmpty(strsubject))
                          {
                              strsubject = "tempomailcopy";
                          }

                          mailitemEntryID = strsubject;

                          string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg";

                          if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false)
                          {
                              Directory.CreateDirectory(UserLogManagerUtility.RootDirectory);
                          }
                          oMailItem.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG);

                      }
                      catch (Exception ex)
                      {

                      }

                      string fileName = string.Empty;
                      if (!string.IsNullOrEmpty(oMailItem.Subject))
                      {
                          //Replce any specila characters in subject
                          fileName = Regex.Replace(oMailItem.Subject, strMailSubjectReplcePattern, " ");
                          fileName = fileName.Replace(".", "_");
                      }

                      if (string.IsNullOrEmpty(fileName))
                      {
                          DateTime dtReceivedDate = Convert.ToDateTime(oMailItem.ReceivedTime);
                          fileName = "Untitled_" + dtReceivedDate.Day + "_" + dtReceivedDate.Month + "_" + dtReceivedDate.Year + "_" + dtReceivedDate.Hour + "_" + dtReceivedDate.Minute + "_" + dtReceivedDate.Millisecond;
                      }

                      UploadItemsData newUploadData = new UploadItemsData();
                      newUploadData.ElapsedTime = DateTime.Now;
                      newUploadData.UploadFileName = fileName;// oMailItem.Subject;
                      newUploadData.UploadFileExtension = ".msg";
                      newUploadData.UploadingMailItem = oMailItem;
                      newUploadData.UploadType = TypeOfUploading.Mail;
                      newUploadData.DisplayFolderName = folderName;
                      frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                      //Set dropped items is uploaded
                      /////////////////////////updated by Joy on 25.07.2012/////////////////////////////////
                      bool uploadStatus = frmUploadItemsListObject.IsSuccessfullyUploaded;
                      XMLLogOptions userOption = UserLogManagerUtility.GetUserConfigurationOptions();
                      if (uploadStatus == true)
                      {
                          // Globals.ThisAddIn.isTimerUploaded = true;
                          isDroppedItemUplaoded = true;

                          for (int i = 0; i <= activeDroppingFolder.Items.Count; i++)
                          {
                              try
                              {
                                  Outlook.MailItem me = (Outlook.MailItem)activeDroppingFolder.Items[i];

                                  if (me.EntryID == mailitemEntryID)
                                  {
                                      me.Categories.Remove(0);
                                      me.Categories = newCatName;
                                      me.Save();

                                      if (userOption.AutoDeleteEmails == true)
                                      {
                                          UserMailDeleteOption(mailitemEntryID, parentfolder);
                                      }
                                  }
                              }
                              catch (Exception ex)
                              {

                              }
                          }

                          frmUploadItemsListObject.lblPRStatus.Invoke(new updateProgresStatus(() =>
                          {
                              frmUploadItemsListObject.lblPRStatus.Text = Globals.ThisAddIn.no_of_t_item_uploaded.ToString() + " " + "of" + " " + Globals.ThisAddIn.no_of_pending_items_to_be_uploaded.ToString() + " " + "Uploaded";
                          }));
                          frmUploadItemsListObject.progressBar1.Invoke(new updateProgessBar(() =>
                          {
                              frmUploadItemsListObject.progressBar1.Value = (((Globals.ThisAddIn.no_of_t_item_uploaded * 100 / Globals.ThisAddIn.no_of_pending_items_to_be_uploaded)));
                          }));

                      }
                      else
                      {
                          isDroppedItemUplaoded = false;
                      }

                      /////////////////////////updated by Joy on 25.07.2012/////////////////////////////////
                  }
                  catch (Exception ex)
                  {
                      isDroppedItemUplaoded = MoveItemIsReportItem(Item);
                  }

                  try
                  {
                      if (isDroppedItemUplaoded == false)
                      {
                          //string tempName = oDocItem.Subject;
                          string tempName = string.Empty;
                          Outlook.DocumentItem oDocItem = (Outlook.DocumentItem)Item;

                          try
                          {

                              Outlook._MailItem myMailItem = (Outlook.MailItem)addinExplorer.Selection[1];
                              foreach (Outlook.Attachment oAttachment in myMailItem.Attachments)
                              {
                                  if (oAttachment.FileName == oDocItem.Subject)
                                  {
                                      tempName = oAttachment.FileName;
                                      tempName = tempName.Substring(tempName.LastIndexOf("."));
                                      oAttachment.SaveAsFile(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName);

                                      //Read file data to bytes
                                      //byte[] fileBytes = File.ReadAllBytes(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName);
                                      System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                      System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
                                      byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length));
                                      reader.Close();
                                      Strm.Close();

                                      //Replace any special characters are there in file name
                                      string fileName = Regex.Replace(oAttachment.FileName, strAttachmentReplacePattern, " ");

                                      //Add uplaod attachment item data to from list.
                                      UploadItemsData newUploadData = new UploadItemsData();
                                      newUploadData.UploadType = TypeOfUploading.Attachment;
                                      newUploadData.AttachmentData = fileBytes;
                                      newUploadData.DisplayFolderName = activeDroppingFolder.Name;

                                      if (fileName.Contains("."))
                                      {
                                          newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf("."));
                                          newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf("."));

                                          if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim()))
                                          {
                                              //check file name conatins empty add the date time
                                              newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime();

                                          }
                                      }

                                      //Add to form
                                      frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                                      //Set dropped mail attachment items is uploaded.
                                      isDroppedItemUplaoded = true;
                                      newUploadData = null;
                                      //oDocItem.Delete();
                                      break;
                                  }
                              }
                          }
                          catch (InvalidCastException ex)
                          {
                              //Set dropped mail attachment items is uploaded to false
                              isDroppedItemUplaoded = false;
                          }

                          if (isDroppedItemUplaoded == false)
                          {
                              tempName = oDocItem.Subject;
                              tempName = tempName.Substring(tempName.LastIndexOf("."));
                              oDocItem.SaveAs(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, Type.Missing);

                              System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                              System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
                              byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length));
                              reader.Close();
                              Strm.Close();

                              //Replace any special characters are there in file name
                              string fileName = Regex.Replace(oDocItem.Subject, strAttachmentReplacePattern, " ");

                              //Add uplaod attachment item data to from list.
                              UploadItemsData newUploadData = new UploadItemsData();
                              newUploadData.UploadType = TypeOfUploading.Attachment;
                              newUploadData.AttachmentData = fileBytes;
                              newUploadData.DisplayFolderName = activeDroppingFolder.Name;

                              if (fileName.Contains("."))
                              {
                                  newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf("."));
                                  newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf("."));

                                  if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim()))
                                  {
                                      //check file name conatins empty add the date time
                                      newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime();

                                  }
                              }

                              //Add to form
                              frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                              newUploadData = null;
                              //oDocItem.Delete();
                          }

                      }
                  }
                  catch (Exception ex)
                  {
                      //throw ex;
                      //////////////////////////////updated by Joy on 28.07.2012///////////////////////////////////
                      //  EncodingAndDecoding.ShowMessageBox("FolderItem Add Event_DocItem Conv", ex.Message, MessageBoxIcon.Error);
                      //////////////////////////////updated by Joy on 28.07.2012///////////////////////////////////
                  }

                  try
                  {
                      XMLLogOptions userOptions = UserLogManagerUtility.GetUserConfigurationOptions();

                      for (int i = 0; i <= parentfolder.Items.Count; i++)
                      {
                          try
                          {
                              Outlook.MailItem me = (Outlook.MailItem)parentfolder.Items[i];

                              if (me.EntryID == mailitemEntryID)
                              {
                                  ///////////////////////////modified by Joy on 10.08.2012////////////////////////////////////

                                  if (isDroppedItemUplaoded == true)
                                  {

                                      me.Categories.Remove(0);
                                      me.Categories = newCatName;
                                      me.Save();
                                      if (userOptions.AutoDeleteEmails == true)
                                      {
                                          UserMailDeleteOption(mailitemEntryID, parentfolder);
                                      }
                                      //parentfolder.Items.Remove(i);
                                  }
                                  ///////////////////////////modified by Joy on 10.08.2012////////////////////////////////////

                              }
                          }
                          catch (Exception)
                          {

                          }
                      }
                  }

                  catch (Exception)
                  {

                  }
                  if (!string.IsNullOrEmpty(mailitemEntryID))
                  {
                      if (ItemType == TypeOfMailItem.ReportItem)
                      {
                          UserReportItemDeleteOption(mailitemEntryID, parentfolder);
                      }
                      else
                      {
                          ///////////////////////////Updated by Joy on 16.08.2012....to be updated later///////////////////////////////
                          // UserMailDeleteOption(mailitemEntryID, parentfolder);
                          ///////////////////////////Updated by Joy on 16.08.2012....to be updated later///////////////////////////////
                      }
                  }

              }

              }
              catch (Exception ex)
              {
              EncodingAndDecoding.ShowMessageBox("Folder Item Add Event", ex.Message, MessageBoxIcon.Error);

              }

              //AddToUploadList(Item);
        }
Ejemplo n.º 14
0
        private List <Outlook.ContactItem> GetListOfContacts(Outlook._Application Application)
        {
            List <Outlook.ContactItem> contactItemsList = null;

            Outlook.Items      folderItems             = null;
            Outlook.MAPIFolder folderSuggestedContacts = null;
            Outlook.NameSpace  ns             = null;
            Outlook.MAPIFolder folderContacts = null;
            object             itemObj        = null;

            try
            {
                contactItemsList = new List <Outlook.ContactItem>();
                ns = Application.GetNamespace("MAPI");
                // getting items from the Contacts folder in Outlook
                folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
                folderItems    = folderContacts.Items;
                for (int i = 1; folderItems.Count >= i; i++)
                {
                    itemObj = folderItems[i];
                    if (itemObj is Outlook.ContactItem)
                    {
                        contactItemsList.Add(itemObj as Outlook.ContactItem);
                    }
                    else
                    {
                        Marshal.ReleaseComObject(itemObj);
                    }
                }
                Marshal.ReleaseComObject(folderItems);
                folderItems = null;
                //// getting items from the Suggested Contacts folder in Outlook
                //folderSuggestedContacts = ns.GetDefaultFolder(
                //                          Outlook.OlDefaultFolders.olFolderSuggestedContacts);
                //folderItems = folderSuggestedContacts.Items;
                //for (int i = 1; folderItems.Count >= i; i++)
                //{
                //    itemObj = folderItems[i];
                //    if (itemObj is Outlook.ContactItem)
                //        contactItemsList.Add(itemObj as Outlook.ContactItem);
                //    else
                //        Marshal.ReleaseComObject(itemObj);
                //}
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            finally
            {
                if (folderItems != null)
                {
                    Marshal.ReleaseComObject(folderItems);
                }
                if (folderContacts != null)
                {
                    Marshal.ReleaseComObject(folderContacts);
                }
                if (folderSuggestedContacts != null)
                {
                    Marshal.ReleaseComObject(folderSuggestedContacts);
                }
                if (ns != null)
                {
                    Marshal.ReleaseComObject(ns);
                }
            }
            return(contactItemsList);
        }
        protected override SyncState <Outlook.TaskItem> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder tasksFolder,
                                                                                        string crmType, EntryValue crmItem)
        {
            SyncState <Outlook.TaskItem> result = null;

            Log.Debug(
                $"TaskSyncing.AddOrUpdateItemFromCrmToOutlook\n\tSubject: {crmItem.GetValueAsString("name")}\n\tCurrent user id {RestAPIWrapper.GetUserId()}\n\tAssigned user id: {crmItem.GetValueAsString("assigned_user_id")}");

            var syncState = SyncStateManager.Instance.GetExistingSyncState(crmItem) as SyncState <Outlook.TaskItem>;

            result = syncState == null?MaybeAddNewItemFromCrmToOutlook(tasksFolder, crmItem) : UpdateExistingOutlookItemFromCrm(crmItem, syncState);

            return(result);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Update a single item in the specified Outlook folder with changes from CRM. If the item
 /// does not exist, create it.
 /// </summary>
 /// <param name="folder">The folder to synchronise into.</param>
 /// <param name="crmType">The CRM type of the candidate item.</param>
 /// <param name="crmItem">The candidate item from CRM.</param>
 /// <returns>The synchronisation state of the item updated (if it was updated).</returns>
 protected abstract SyncState <OutlookItemType> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem);
Ejemplo n.º 17
0
 protected abstract void SyncFolder(Outlook.MAPIFolder folder, string crmModule);
Ejemplo n.º 18
0
        public void Uninitialize()
        {
            if (_isInitialized)
            {
                try
                {
                    _olNS.Logoff();
                }
                catch
                {
                }

                _olContactsFolder = null;
                _olNS = null;
                _olApp = null;
            }
        }
        private void ProcessFolder(AppContext ctx, Outlook.MAPIFolder folder)
        {
            ProcessFolderItems(ctx, folder);

            ProcessFolders(ctx, folder.Folders);
        }
        public bool TrySetFolder()
        {
            m_rootFolder = m_store.GetRootFolder();

            return(m_rootFolder != null);
        }
        public static void suggestRulesBasedOnCountOfSender(Dictionary <string, int> dictionary)
        {
            Console.WriteLine("hi");

            Outlook.NameSpace  session           = null;
            Outlook.Store      store             = null;
            Outlook.Rules      rules             = null;
            Outlook.MAPIFolder destinationFolder = null;
            Outlook.MAPIFolder rootFolder        = null;
            Outlook.Folders    rootFolderFolders = null;

            Outlook.Rule              rule                     = null;
            Outlook.RuleConditions    ruleConditions           = null;
            Outlook.TextRuleCondition subjectTextRuleCondition = null;

            Outlook.RuleActions          ruleActions    = null;
            Outlook.MoveOrCopyRuleAction moveRuleAction = null;

            string ruleName = string.Empty;

            try
            {
                ruleName = "Move Order Mails Rule";
                //session = Application.Session; // have to correct this error, it was working in 10102017 build when everything was in ThisAddin.cs
                store = session.DefaultStore;
                rules = store.GetRules();

                if (!RuleExist(ruleName, rules))
                {
                    rootFolder = store.GetRootFolder();
                    // destinationFolder = GetFolder(rootFolder.FolderPath + "\\Orders", this);


                    if (destinationFolder == null)
                    {
                        rootFolderFolders = rootFolder.Folders;
                        destinationFolder = rootFolderFolders.Add("Orders");
                    }

                    rule           = rules.Create(ruleName, Outlook.OlRuleType.olRuleReceive);
                    ruleConditions = rule.Conditions;

                    subjectTextRuleCondition      = ruleConditions.Subject;
                    subjectTextRuleCondition.Text = new string[]
                    { "Orders", "orders", "Order", "order" };
                    subjectTextRuleCondition.Enabled = true;

                    ruleActions            = rule.Actions;
                    moveRuleAction         = ruleActions.MoveToFolder;
                    moveRuleAction.Folder  = destinationFolder;
                    moveRuleAction.Enabled = true;

                    ruleActions.DesktopAlert.Enabled = true;

                    rules.Save(true);
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
            }
        }
Ejemplo n.º 22
0
        protected override SyncState <Outlook.AppointmentItem> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem)
        {
            var result = base.AddOrUpdateItemFromCrmToOutlook(folder, crmType, crmItem);

            if (crmItem?.relationships?.link_list != null)
            {
                CacheAddressResolutionData(crmItem);
            }

            return(result);
        }
Ejemplo n.º 23
0
 protected override bool ShouldAddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem)
 {
     return(crmType == "Meetings");
 }
Ejemplo n.º 24
0
        //        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()



        #region action when a new mail is selected
        private void CurrentExplorer_Event()
        {
            //if (currentExplorer == null) return null


            Outlook.MAPIFolder selectedFolder =
                this.Application.ActiveExplorer().CurrentFolder;

            bool SelectedObjectIsMail = false;

            //String expMessage = "Your current folder is " + selectedFolder.Name + ".\n";
            // String itemMessage = "Item is unknown.";
            try
            {
                if (this.Application.ActiveExplorer().Selection.Count > 0)
                {
                    Object selObject = this.Application.ActiveExplorer().Selection[1];


                    if (selObject is Outlook.MailItem)
                    {
                        SelectedObjectIsMail = true;

                        /*
                         * Outlook.MailItem mailItem =
                         *   (selObject as Outlook.MailItem);
                         * itemMessage = "The item is an e-mail message." +
                         *   " The subject is " + mailItem.Subject + ".";
                         * mailItem.Display(false);
                         */
                    }
                    else if (selObject is Outlook.ContactItem)
                    {
                        /*Outlook.ContactItem contactItem =
                         *  (selObject as Outlook.ContactItem);
                         * itemMessage = "The item is a contact." +
                         *  " The full name is " + contactItem.Subject + ".";
                         * contactItem.Display(false);
                         */
                    }
                    else if (selObject is Outlook.AppointmentItem)
                    {
                        /*
                         * Outlook.AppointmentItem apptItem =
                         *  (selObject as Outlook.AppointmentItem);
                         * itemMessage = "The item is an appointment." +
                         *  " The subject is " + apptItem.Subject + ".";
                         */
                    }
                    else if (selObject is Outlook.TaskItem)
                    {
                        /*
                         * Outlook.TaskItem taskItem =
                         *  (selObject as Outlook.TaskItem);
                         * itemMessage = "The item is a task. The body is "
                         + taskItem.Body + ".";
                         */
                    }
                    else if (selObject is Outlook.MeetingItem)
                    {
                        /*
                         * Outlook.MeetingItem meetingItem =
                         *  (selObject as Outlook.MeetingItem);
                         * itemMessage = "The item is a meeting item. " +
                         *   "The subject is " + meetingItem.Subject + ".";
                         */
                    }
                }
                // expMessage = expMessage + itemMessage;

                ThisRibbonCollection ribbonCollection = Globals.Ribbons[Globals.ThisAddIn.Application.ActiveInspector()];
                if (SelectedObjectIsMail)
                {
                    /* Ribbon1.
                     * ribbonCollection.Ribbon1.comboBox1.Text = "Hello World";
                     */
                }
            }
            catch (Exception)
            {
                // expMessage = ex.Message;
            }
            // MessageBox.Show(expMessage);
        }
Ejemplo n.º 25
0
        protected override void DoExecute(ref DateTime start)
        {
            Excel.Application objExl;
            bool   ReadOnly = true, lbExit;
            int    row, i, j;
            string EmailTo, EmailSubject, EmailMessage;

            objExl = new Excel.Application();
            try
            {
                objExl.DisplayAlerts = false;
                objExl.Visible       = true;
                Excel.Workbook wb = objExl.Workbooks.Open(ExcelFile, false, ReadOnly);
                try
                {
                    Excel.Worksheet xlWorkSheet;

                    xlWorkSheet         = wb.Worksheets.get_Item(1);
                    Outlook.VisibleMode = true;
                    // I go through Excel to send all the emails
                    lbExit = false;
                    row    = 2;
                    do
                    {
                        CheckAbort();
                        EmailTo = ToString(xlWorkSheet.Cells[row, "A"].Text).Trim();
                        if (EmailTo.Length == 0)
                        {
                            lbExit = true;
                        }
                        else
                        {
                            Balloon(EmailTo);
                            EmailSubject = ToString(xlWorkSheet.Cells[row, "B"].Text).Trim();
                            EmailMessage = ToString(xlWorkSheet.Cells[row, "C"].Text).Trim();
                            Outlook.SendEmail(EmailTo, EmailSubject, EmailMessage);
                        }
                        row++;
                    } while (!lbExit);
                    // I go through all the emails in the inbox
                    List <Outlook.MAPIFolder> folders = new List <Outlook.MAPIFolder>();
                    folders.Add(Outlook.Inbox);
                    j = 0;
                    i = 0;
                    while ((i < folders.Count) && (j < 200))
                    {
                        CheckAbort();
                        Outlook.MAPIFolder folder = folders.ElementAt(i);
                        row = 1;
                        while (row <= folder.Folders.Count) // I add all the folders
                        {
                            folders.Add(Outlook.Inbox.Folders[row]);
                            row++;
                        }
                        row = 1;
                        while (row <= folder.Items.Count) // I show all the emails
                        {
                            CheckAbort();
                            Outlook.MailItem mail = folder.Items[row];
                            Balloon(folder.Name + LF + mail.SenderEmailAddress + LF + mail.Subject);
                            row++;
                            j++;
                        }
                        i++;
                    }
                }
                finally
                {
                    wb.Close(false);
                }
            }
            finally
            {
                try
                {
                    objExl.Visible = false;
                }
                finally
                {
                    try { objExl.Quit(); } catch { }
                }
            }
        }
Ejemplo n.º 26
0
 void panelManager_KeyDown(object sender, KeyEventArgs e)
 {
     try
     {
     switch (e.KeyCode)
     {
     case Keys.R:
         CurrentFolder = Application.ActiveExplorer().CurrentFolder;
         ShowReader();
         break;
     case Keys.N:
         ShowContactCard(ActiveItem.Sender);
         break;
     case Keys.I:
         var item = ActiveItem;
         StartChatWithUser(Util.GetSmtpAddress(item.Sender), item.Subject);
         break;
     case Keys.K:
         var cal = Calendar;
         var rs = cal.Items;
         MessageBox.Show(cal.Folders.Count.ToString());
                                         for (int i = 150; i <= 161; i++)
         {
             MessageBox.Show((rs[i] as Outlook.AppointmentItem).Subject);
         }
         //Microsoft.Lync.Controls.ContactCard card = new Microsoft.Lync.Controls.ContactCard();
         //card.Source = Util.GetSmtpAddress(ActiveItem.Sender);
         //new Form1(ActiveItem.Sender).Show();
                         //MessageBox.Show(card.DisplayName);
         break;
     }
     }
     catch (Exception ex)
     {
     ExceptionHandler.Catch(ex);
     }
 }
Ejemplo n.º 27
0
 public void BeforeFolderMove(Outlook.MAPIFolder MoveTo, ref bool Cancel)
 {
     Utility.LogFolderEvent(LogType.Diagnostic, (string.Format("{0} in folder {1}{2}", new StackTrace().GetFrame(0).GetMethod().Name, folderName, System.Environment.NewLine)));
 }
Ejemplo n.º 28
0
        /// <summary>
        /// code written by Joy
        /// moves or copies mail items to the selected mapped folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.ValidateChildren() == true)
            {
                if (ThisAddIn.IsUploadingFormIsOpen == true)
                {
                    if (Globals.ThisAddIn.frmlistObject != null)
                    {
                        Globals.ThisAddIn.frmlistObject.progressBar1.Value = Globals.ThisAddIn.frmlistObject.progressBar1.Minimum;
                        Globals.ThisAddIn.frmlistObject.lblPRStatus.Text = "";
                    }

                }
                string selected_mapiFolderName = cmbOptions.Text;
                this.Close();
                if (Globals.ThisAddIn.copy_button_clicked == true)
                {
                    OutlookObj = Globals.ThisAddIn.Application;
                    outlookNameSpace = OutlookObj.GetNamespace("MAPI");
                    olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent;
                    string mappedFolderName = cmbOptions.SelectedItem.ToString();
                    mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName);
                    Outlook.MailItem mItem;
                    Outlook.MailItem copyMail;
                    Globals.ThisAddIn.isCopyRunninng = true;
                    foreach (Object obj in Globals.ThisAddIn.copySelected)
                    {
                        if (obj is Outlook.MailItem)
                        {
                            mItem = (Outlook.MailItem)obj;
                            copyMail = mItem.Copy() as Outlook.MailItem;
                            copyMail.Move(mappedFolder);
                            //doBackGroundUpload(mItem);
                        }
                    }
                }
                else if (Globals.ThisAddIn.move_button_clicked == true)
                {

                        OutlookObj = Globals.ThisAddIn.Application;
                        outlookNameSpace = OutlookObj.GetNamespace("MAPI");
                        olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                        parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent;
                        string mappedFolderName = cmbOptions.SelectedItem.ToString();
                        mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName);
                        Outlook.MailItem mItem;
                        Globals.ThisAddIn.isMoveRunning = true;
                        foreach (Object obj in Globals.ThisAddIn.moveSelected)
                        {
                            if (obj is Outlook.MailItem)
                            {
                                mItem = (Outlook.MailItem)obj;
                                mItem.Move(mappedFolder);
                                //doBackGroundUpload(mItem);
                            }
                        }

                }
            }
            else
                return;
        }
Ejemplo n.º 29
0
        private void AfterReceiveUnsafe(object Item)
        {
            if (!CurrentSettings.AddInEnabled || CurrentSettings.IncomingFirstAction == IncomingFirstAction.DoNothing)
            {
                return;
            }

            Outlook.MailItem mailItem = Item as Outlook.MailItem;

            string senderAddress;

            if (!TryGetSenderAddress(mailItem, out senderAddress))
            {
                return;
            }

            string domain;

            if (!TryGetDomain(senderAddress, out domain))
            {
                return;
            }

            if (CurrentSettings.IncomingExceptions.Contains(domain))
            {
                return;
            }

            var ruleName   = IncomingRulePrefix + domain;
            var initChar   = char.ToUpper(domain.Take(1).First());
            var folderName = initChar.ToString() + domain.Substring(1);

            Outlook.MAPIFolder parentFolder = null;
            if (CurrentSettings.IncomingCreateParentFolders)
            {
                var parentFolderName = GetParentFolderName(initChar);
                if (!TryGetFolder(parentFolderName, Inbox, out parentFolder))
                {
                    parentFolder = CreateFolder(parentFolderName, Inbox);
                }
            }
            else
            {
                parentFolder = Inbox;
            }

            Outlook.MAPIFolder folder = null;
            if (!TryGetFolder(folderName, parentFolder, out folder))
            {
                folder = CreateFolder(folderName, parentFolder);
            }

            if (CurrentSettings.IncomingSecondAction != IncomingSecondAction.DoNothing)
            {
                RefreshSearchFolders();

                Outlook.MAPIFolder searchFolder = null;

                if (CurrentSettings.IncomingCreateParentFolders)
                {
                    searchFolder = parentFolder;
                }
                else
                {
                    searchFolder = folder;
                }

                if (!FolderExists(searchFolder.Name, SearchFolders))
                {
                    CreateSearchFolder(searchFolder);
                }
            }

            try
            {
                mailItem.Move(folder);
            }
            catch
            {
                // try to move, if it does not happen, ignore it
            }

            if (CurrentSettings.IncomingFirstAction == IncomingFirstAction.CreateInboxFolderRule)
            {
                RefreshRules();
                var ruleSet = RuleSet;
                if (!RuleExists(ruleSet, ruleName))
                {
                    CreateIncomingRule(ruleSet, ruleName, domain, folder, mailItem);
                    ruleSet.Save(false);
                }
            }
        }
Ejemplo n.º 30
0
 public override void ProcessFolderRemove()
 {
     Outlook.MAPIFolder parentFolder = (Outlook.MAPIFolder) this.FolderObj;
     MessageBox.Show("A subfolder has been removed from " + parentFolder.FolderPath);
 }
Ejemplo n.º 31
0
 private Outlook.MAPIFolder CreateFolder(string folderName, Outlook.MAPIFolder parentFolder)
 {
     return(parentFolder.Folders.Add(folderName) as Outlook.MAPIFolder);
 }
        // TODO: this is horrible and should be reworked.
        protected override SyncState <Outlook.ContactItem> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem)
        {
            SyncState <Outlook.ContactItem> result = null;

            String id = crmItem.GetValueAsString("id");
            SyncState <Outlook.ContactItem> syncStateForItem = GetExistingSyncState(crmItem);

            if (ShouldSyncContact(crmItem))
            {
                Log.Info(
                    string.Format(
                        "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is true, syncing",
                        id));

                if (syncStateForItem == null)
                {
                    /* check for howlaround */
                    var matches = this.FindMatches(crmItem);

                    if (matches.Count == 0)
                    {
                        /* didn't find it, so add it to Outlook */
                        result = AddNewItemFromCrmToOutlook(folder, crmItem);
                    }
                    else
                    {
                        this.Log.Warn($"Howlaround detected? Contact '{crmItem.GetValueAsString("name")}' offered with id {crmItem.GetValueAsString("id")}, expected {matches[0].CrmEntryId}, {matches.Count} duplicates");
                    }
                }
                else
                {
                    result = UpdateExistingOutlookItemFromCrm(crmItem, syncStateForItem);
                }
            }
            else if (syncStateForItem != null &&
                     syncStateForItem.OutlookItem != null)
            {
                /* The date_modified value in CRM does not get updated when the sync_contact value
                 * is changed. But seeing this value can only be updated at the CRM side, if it
                 * has changed the change must have been at the CRM side. It doesn't change to false,
                 * it simply ceases to be sent. Set the item to Private in Outlook. */
                if (syncStateForItem.OutlookItem.Sensitivity != Outlook.OlSensitivity.olPrivate)
                {
                    Log.Info($"ContactSyncing.UpdateFromCrm: setting sensitivity of contact {crmItem.GetValueAsString("first_name")} {crmItem.GetValueAsString("last_name")} ({crmItem.GetValueAsString("email1")}) to private");
                    syncStateForItem.OutlookItem.Sensitivity = Outlook.OlSensitivity.olPrivate;
                }

                result = syncStateForItem;
            }
            else
            {
                Log.Info(
                    string.Format(
                        "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is false, not syncing",
                        id));

                result = syncStateForItem;
            }

            return(result);
        }
Ejemplo n.º 33
0
 private Outlook.MAPIFolder GetFolder(string folderName, Outlook.MAPIFolder parentFolder)
 {
     return(parentFolder.Folders[folderName] as Outlook.MAPIFolder);
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Get a list of all the unprocess email ids
        /// We don't return the emails as anotehr thread could 'change' those values.
        /// </summary>
        /// <param name="folder">The folder we are working in</param>
        /// <param name="limit"></param>
        /// <param name="includeSubfolders"></param>
        /// <param name="restrictFolder">the filter we want to use to look in the folder.</param>
        /// <param name="token"></param>
        /// <returns></returns>
        private IList <string> GetUnprocessedEmailsInFolder(
            Outlook.MAPIFolder folder,
            int limit,
            bool includeSubfolders,
            string restrictFolder,
            CancellationToken token)
        {
            // do the sub folders.
            var ids = new List <string>();

            if (includeSubfolders)
            {
                ids.AddRange(GetUnprocessedEmailsInFolders(folder.Folders, limit, true, restrictFolder, token));
            }

            // is it a mail folder?
            if (folder.DefaultItemType != Outlook.OlItemType.olMailItem)
            {
                return(ids);
            }

            var restrictedItems = string.IsNullOrWhiteSpace(restrictFolder) ? folder.Items : folder.Items.Restrict(restrictFolder);

            // add an more items to the progress bar
            _progress.AddRange(restrictedItems.Count, limit);

            foreach (var item in restrictedItems)
            {
                if (token.IsCancellationRequested)
                {
                    return(new List <string>());
                }

                // step forward.
                _progress.Step();

                // get the mail item
                if (!(item is Outlook._MailItem mailItem))
                {
                    continue;
                }

                try
                {
                    // add this to the mail processor...
                    ids.Add(mailItem.EntryID);
                    _logger.LogInformation($"Found unprocessed email...{mailItem.Subject}.");

                    if (ids.Count >= limit)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError("There was an exception looking at unprocessed folder");
                    _logger.LogException(e);
                }
            }
            return(ids);
        }
Ejemplo n.º 35
0
 private bool TryGetFolder(string folderName, Outlook.MAPIFolder parentFolder, out Outlook.MAPIFolder folder)
 {
     try
     {
         folder = parentFolder.Folders[folderName] as Outlook.MAPIFolder;
         return(true); // folder exists
     }
     catch
     {
         folder = null; // folder does not exist
         return(false);
     }
 }
Ejemplo n.º 36
0
        protected override SyncState <Outlook.TaskItem> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder tasksFolder, string crmType, EntryValue crmItem)
        {
            SyncState <Outlook.TaskItem> result = null;

            Log.Debug($"TaskSyncing.AddOrUpdateItemFromCrmToOutlook\n\tSubject: {crmItem.GetValueAsString("name")}\n\tCurrent user id {RestAPIWrapper.GetUserId()}\n\tAssigned user id: {crmItem.GetValueAsString("assigned_user_id")}");

            DateTime dateStart = crmItem.GetValueAsDateTime("date_start");
            DateTime dateDue   = crmItem.GetValueAsDateTime("date_due");
            string   timeStart = ExtractTime(dateStart);
            string   timeDue   = ExtractTime(dateDue);

            var syncState = this.GetExistingSyncState(crmItem);

            if (syncState == null)
            {
                /* check for howlaround */
                var matches = this.FindMatches(crmItem);

                if (matches.Count == 0)
                {
                    /* didn't find it, so add it to Outlook */
                    result = AddNewItemFromCrmToOutlook(tasksFolder, crmItem, dateStart, dateDue, timeStart, timeDue);
                }
                else
                {
                    this.Log.Warn($"Howlaround detected? Task '{crmItem.GetValueAsString("name")}' offered with id {crmItem.GetValueAsString("id")}, expected {matches[0].CrmEntryId}, {matches.Count} duplicates");
                }
            }
            else
            {
                result = UpdateExistingOutlookItemFromCrm(crmItem, dateStart, dateDue, timeStart, timeDue, syncState);
            }

            return(result);
        }
Ejemplo n.º 37
0
 private void CreateSearchFolder(Outlook.MAPIFolder folderToSearch)
 {
     Application.AdvancedSearch("\'" + folderToSearch.FolderPath + "\'", null, true, folderToSearch.Name);
 }
Ejemplo n.º 38
0
 protected override bool ShouldAddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem)
 {
     return(RestAPIWrapper.GetUserId() == crmItem.GetValueAsString("assigned_user_id"));
 }
Ejemplo n.º 39
0
        private void AfterSendUnsafe(object Item)
        {
            if (!CurrentSettings.AddInEnabled || CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.DoNothing)
            {
                return;
            }

            Outlook.MailItem mailItem = Item as Outlook.MailItem;

            var domains = new HashSet <string>();

            foreach (Outlook.Recipient recipient in mailItem.Recipients)
            {
                string recipientAddress;
                if (!TryGetRecipientAddress(recipient, out recipientAddress))
                {
                    continue;
                }

                string domain;
                if (!TryGetDomain(recipientAddress, out domain))
                {
                    continue;
                }

                if (!domains.Contains(domain))
                {
                    domains.Add(domain);
                }
            }

            var domainsAllowed = domains.Except(CurrentSettings.OutgoingExceptions);

            Outlook.Rules ruleSet   = null;
            var           needsSave = false;

            if (domainsAllowed.Count() > 0 && CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.CreateSentFolderRule)
            {
                RefreshRules();
                ruleSet = RuleSet;
            }

            foreach (var domain in domainsAllowed)
            {
                var ruleName   = OutgoingRulePrefix + domain;
                var initChar   = char.ToUpper(domain.Take(1).First());
                var folderName = SentboxFolderNamePrefix + initChar.ToString() + domain.Substring(1);

                Outlook.MAPIFolder parentFolder = null;
                if (CurrentSettings.OutgoingCreateParentFolders)
                {
                    var parentFolderName = GetParentFolderName(initChar);
                    if (!TryGetFolder(parentFolderName, Sentbox, out parentFolder))
                    {
                        parentFolder = CreateFolder(parentFolderName, Sentbox);
                    }
                }
                else
                {
                    parentFolder = Sentbox;
                }

                Outlook.MAPIFolder folder = null;
                if (!TryGetFolder(folderName, parentFolder, out folder))
                {
                    folder = CreateFolder(folderName, parentFolder);
                }

                try
                {
                    var copy = mailItem.Copy() as Outlook.MailItem;
                    copy.Move(folder);
                }
                catch
                {
                    // tried to move if it does not happen ignore
                }

                if (CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.CreateSentFolderRule)
                {
                    if (!RuleExists(ruleSet, ruleName))
                    {
                        CreateOutgoingRule(ruleSet, ruleName, domain, folder, mailItem);
                        needsSave = true;
                    }
                }
            }

            if (needsSave && ruleSet != null)
            {
                ruleSet.Save(false);
            }
        }
        public IOfficeConnectAddin(ThisAddIn addin)
        {
            try
            {
                _addin = addin;

                IOfficeConnectGlobals.ErEnUkendtBrugerAktiv = true;

                var outlookInboxFolder = _addin.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

                // Get outlook inbox store ID
                IOfficeConnectGlobals.InboxFolderEntryID = outlookInboxFolder.EntryID;
                IOfficeConnectGlobals.UserStoreID = outlookInboxFolder.StoreID;

                Task.Run(() =>
                {
                    IOfficeConnectGlobals.EnsureCache();

                    log.Info("Cache was built");
                });

                var brugerKendt = IOfficeConnectGlobals.GetCurrentBruger();

                if (brugerKendt == null)
                {
                    var m = string.Format("Brugeren du er logget på windows med ({0}) er ukendt i IOffice", Environment.UserName);

                    log.Warn(m);

                    MessageBox.Show(m, "Ukendt bruger", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    log.InfoFormat("Bruger med ID {0} og navn {1} logget ind", brugerKendt.ID, brugerKendt.Navn);

                    IOfficeConnectGlobals.ErEnUkendtBrugerAktiv = false;

                    if (IOfficeConnectGlobals.ArchiveRootFolderExists(_addin.Application.Session, brugerKendt) == true)
                    {
                        // Hookup on mail received
                        _addin.Application.NewMailEx += Application_NewMailEx;

                        // Hookup item sent
                        // http://stackoverflow.com/questions/23803960/outlook-itemadd-event-not-triggered
                        _sentItemsFolder = _addin.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
                        _sentItems = _sentItemsFolder.Items;
                        _sentItems.ItemAdd -= sentItems_ItemAdd;
                        _sentItems.ItemAdd += sentItems_ItemAdd;

                        log.Info("Events new mail og itemsend hooked up");

                        IOfficeConnectGlobals.ErFuldtInitialiseret = true;
                    }
                    else
                    {
                        var m = string.Format("Mappen til arkivering kunne ikke findes\r\nGå venligst ind i IOffice og vælg Settings\r\nUnder settings vælg fanebladet References\r\nTryk på luppen og vælg mappen \"Kunder\" under offentlige mapper\r\n\r\nGenstart Outlook når mappen er valgt så IOffice connect kan anvende indstillingen");

                        MessageBox.Show(m, "Mappen ikke fundet", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            catch (Exception e)
            {
                var m = string.Format("Generel fejl under opstart: {0}", e.Message);

                log.Error(m, e);

                MessageBox.Show(m, "Ukendt fejl under opstart", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                throw;
            }
        }
Ejemplo n.º 41
0
        private Outlook.Rule CreateOutgoingRule(Outlook.Rules ruleSet, string ruleName, string domain, Outlook.MAPIFolder folder, Outlook.MailItem mailItem)
        {
            Outlook.Rule rule = ruleSet.Create(ruleName, Outlook.OlRuleType.olRuleSend);

            // Rule Conditions
            // To condition
            rule.Conditions.RecipientAddress.Address = new string[] { "@" + domain };
            rule.Conditions.RecipientAddress.Enabled = true;

            // Rule Exceptions
            // nothing yet

            // Rule Actions
            rule.Actions.CopyToFolder.Folder  = folder;
            rule.Actions.CopyToFolder.Enabled = true;

            rule.Enabled = true;

            return(rule);
        }
Ejemplo n.º 42
0
        /// <summary>
        /// FIND THE CONTACT WITH SAME USER PROPERTY VALUE.
        /// </summary>
        /// <param name="contact"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        private OutLook._ContactItem FindContactItemWithPetName(String KeyPetName, /*MyContact contact, */ OutLook.MAPIFolder folder)
        {
            object missing = System.Reflection.Missing.Value;

            foreach (OutLook._ContactItem OutlookContact in folder.Items)
            {
                OutLook.UserProperty userProperty = OutlookContact.UserProperties.Find("myPetName", missing);
                if (userProperty != null)
                {
                    if (userProperty.Value.Equals(KeyPetName))
                    {
                        return(OutlookContact);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// SAVING THE NEW CONTACT TO OUTLOOK.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (rdoCustom.Checked)
            {
                // IF THE CUSTOM FOLDER OPTION IS SELECTED PROMPTING FOR THE NAME.
                if (string.IsNullOrEmpty(txFolder.Text.Trim().ToString()))
                {
                    MessageBox.Show("Please Give Your CustomFolder Name");
                    return;
                }
                // IF WE NEED A CUSTOM FOLDER FOR CREATING CONTACTS .HERE IT CHECKS FOR FOLDER OR OTHER
                // WISE IT CREATES A NEW CUSTOMER FOLDER WITH GIVEN NAME .

                if (!CheckCustomFolderExists(txFolder.Text.Trim().ToString()))
                {
                    CreateCustomFolder(txFolder.Text.Trim().ToString());
                }
                if (chkUpdateExistingContact.Checked)
                {
                    //orig OutLook._Application outlookApplication = new OutLook.Application();
                    /*MyContact contact = new MyContact();*/
                    //orig cntact.CustomProperty = txtProp1.Text.Trim().ToString();

                    // CREATING CONTACT ITEM OBJECT AND FINDING THE CONTACT ITEM
                    String KeyPetName = txtProp1.Text.Trim().ToString();
                    OutLook.ContactItem newContact = (OutLook.ContactItem)FindContactItemWithPetName(KeyPetName, /*contact, */ m_CustomFolder);

                    // THE VALUES WE CAN GET FROM WEB SERVICES OR DATA BASE OR CLASS. WE HAVE TO ASSIGN THE VALUES
                    // TO OUTLOOK CONTACT ITEM OBJECT .
                    if (newContact != null)
                    {
                        newContact.FirstName                = txtFirstName.Text.Trim().ToString();
                        newContact.LastName                 = txtLastName.Text.Trim().ToString();
                        newContact.Email1Address            = txtEmail.Text.Trim().ToString();
                        newContact.Business2TelephoneNumber = txtPhone.Text.Trim().ToString();
                        newContact.BusinessAddress          = txtAddress.Text.Trim().ToString();
                        if (chkAddCustomProperty.Checked)
                        {
                            // HERE WE CAN CREATE OUR OWN CUSTOM PROPERTY TO IDENTIFY OUR APPLICATION.
                            if (string.IsNullOrEmpty(txtProp1.Text.Trim().ToString()))
                            {
                                MessageBox.Show("Please add value to your Custom Property");
                                return;
                            }
                            newContact.UserProperties.Add("myPetName", OutLook.OlUserPropertyType.olText, true, OutLook.OlUserPropertyType.olText);
                            newContact.UserProperties["myPetName"].Value = txtProp1.Text.Trim().ToString();
                        }
                        newContact.Save();
                        this.Close();
                    }
                    else // FindContactItem was not successful
                    {
                        // IF THE CONTACT DOES NOT EXIST WITH SAME CUSTOM PROPERTY CREATES THE CONTACT.
                        newContact                          = (OutLook.ContactItem)m_CustomFolder.Items.Add(OutLook.OlItemType.olContactItem);
                        newContact.FirstName                = txtFirstName.Text.Trim().ToString();
                        newContact.LastName                 = txtLastName.Text.Trim().ToString();
                        newContact.Email1Address            = txtEmail.Text.Trim().ToString();
                        newContact.Business2TelephoneNumber = txtPhone.Text.Trim().ToString();
                        newContact.BusinessAddress          = txtAddress.Text.Trim().ToString();
                        if (chkAddCustomProperty.Checked)
                        {
                            // HERE WE CAN CREATE OUR OWN CUSTOM PROPERTY TO IDENTIFY OUR APPLICATION.
                            if (string.IsNullOrEmpty(txtProp1.Text.Trim().ToString()))
                            {
                                MessageBox.Show("Please add value to your Custom Property");
                                return;
                            }
                            newContact.UserProperties.Add("myPetName", OutLook.OlUserPropertyType.olText, true, OutLook.OlUserPropertyType.olText);
                            newContact.UserProperties["myPetName"].Value = txtProp1.Text.Trim().ToString();
                        }
                        newContact.Save();
                        this.Close();
                    }
                }
                else // chkUpdateExistingContact not Checked
                {
                    //orig OutLook._Application outlookApplication = new OutLook.Application();
                    OutLook.ContactItem newContact = (OutLook.ContactItem)m_CustomFolder.Items.Add(OutLook.OlItemType.olContactItem);
                    newContact.FirstName                = txtFirstName.Text.Trim().ToString();
                    newContact.LastName                 = txtLastName.Text.Trim().ToString();
                    newContact.Email1Address            = txtEmail.Text.Trim().ToString();
                    newContact.Business2TelephoneNumber = txtPhone.Text.Trim().ToString();
                    newContact.BusinessAddress          = txtAddress.Text.Trim().ToString();
                    if (chkAddCustomProperty.Checked)
                    {
                        // HERE WE CAN CREATE OUR OWN CUSTOM PROPERTY TO IDENTIFY OUR APPLICATION.
                        if (string.IsNullOrEmpty(txtProp1.Text.Trim().ToString()))
                        {
                            MessageBox.Show("Please add value to your Custom Property");
                            return;
                        }
                        newContact.UserProperties.Add("myPetName", OutLook.OlUserPropertyType.olText, true, OutLook.OlUserPropertyType.olText);
                        newContact.UserProperties["myPetName"].Value = txtProp1.Text.Trim().ToString();
                    }
                    newContact.Save();
                    this.Close();
                }
            }
            else // rdoCustom is not checked - Save to default folder
            {
                // CREATES THE OUTLOOK CONTACT IN DEFAULT CONTACTS FOLDER.
                OutLook._Application outlookApplication = new OutLook.Application();
                OutLook.MAPIFolder   contactsFolder     = (OutLook.MAPIFolder)outlookApplication.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);
                OutLook.ContactItem  newContact         = (OutLook.ContactItem)contactsFolder.Items.Add(OutLook.OlItemType.olContactItem);
                // THE VALUES WE CAN GET FROM WEB SERVICES OR DATA BASE OR CLASS.
                // WE HAVE TO ASSIGN THE VALUES TO OUTLOOK CONTACT ITEM OBJECT .
                newContact.FirstName                = txtFirstName.Text.Trim().ToString();
                newContact.LastName                 = txtLastName.Text.Trim().ToString();
                newContact.Email1Address            = txtEmail.Text.Trim().ToString();
                newContact.Business2TelephoneNumber = txtPhone.Text.Trim().ToString();
                newContact.BusinessAddress          = txtAddress.Text.Trim().ToString();
                newContact.Save();
                this.Close();
            }
        }
        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            //Executive flag addin
            _outlookNameSpace = Application.GetNamespace("MAPI");
            _inbox = _outlookNameSpace.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderInbox);

            //Generate contacts from email I have received from capSpire
            _contacts = _outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            _items = _inbox.Items;
            _items.ItemAdd +=
                items_ItemAdd;
            AddContactsToItems();

            _selectExplorers = Application.Explorers;
            _selectExplorers.NewExplorer += newExplorer_Event;
            AddToolbar();
        }
Ejemplo n.º 45
0
 protected abstract void GetOutlookItems(Outlook.MAPIFolder folder);
Ejemplo n.º 46
0
        /// <summary>
        /// Initalizes and logs into an Outlook session. Must call this 
        /// before using any of the other methods of this class.
        /// </summary>
        public void Initialize()
        {
            if (_isInitialized)
            {
                // Already initialized. Return silently.
                return;
            }

            _olNS = _olApp.GetNamespace("MAPI");

            _olNS.Logon(Missing.Value, Missing.Value, Missing.Value, true);

            _olContactsFolder = _olNS.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderContacts);

            _isInitialized = true;
        }
Ejemplo n.º 47
0
 public void FolderChange(Outlook.MAPIFolder Folder)
 {
     Utility.LogFoldersEvent(LogType.Event, (string.Format("{0}{1}", new StackTrace().GetFrame(0).GetMethod().Name, System.Environment.NewLine)));
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Specialisations should return false if there's a good reason why we should
 /// NOT sync this item.
 /// </summary>
 /// <param name="folder">The folder to synchronise into.</param>
 /// <param name="crmType">The CRM type of the candidate item.</param>
 /// <param name="crmItem">The candidate item from CRM.</param>
 /// <returns>true</returns>
 protected virtual bool ShouldAddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem)
 {
     return(true);
 }
Ejemplo n.º 49
0
        public void FixUserProperties()
        {
            Outlook.Application outlookApp;
            Outlook.NameSpace   outlookNamespace;
            Outlook.Items       outlookContacts;

            outlookApp = new Outlook.Application();

            outlookNamespace = outlookApp.GetNamespace("mapi");

            outlookNamespace.Logon("Outlook", null, true, false);

            try
            {
                Outlook.MAPIFolder contactsFolder = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
                outlookContacts = contactsFolder.Items;

                string oldPrefixId      = string.Format("google/contacts/{0}/id", ConfigurationManager.AppSettings["Gmail.Username"]);
                string oldPrefixUpdated = string.Format("google/contacts/{0}/updated", ConfigurationManager.AppSettings["Gmail.Username"]);

                int hashCode = ConfigurationManager.AppSettings["Gmail.Username"].GetHashCode();

                int    maxUserIdLength = 32 - ("g/con/" + "/up").Length;
                string userId          = ConfigurationManager.AppSettings["Gmail.Username"];
                if (userId.Length > maxUserIdLength)
                {
                    userId = userId.GetHashCode().ToString("X"); //if a user id would overflow UserProperty name, then use that user id hash code as id.
                }
                string newPrefixId      = "g/con/" + userId + "/id";
                string newPrefixUpdated = "g/con/" + userId + "/up";

                //max property length: 32

                //foreach (Outlook.ContactItem contact in outlookContacts)
                for (int i = 0; i < outlookContacts.Count; i++)
                {
                    try
                    {
                        if (!(outlookContacts[i] is Outlook.ContactItem))
                        {
                            continue;
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    Outlook.ContactItem contact = outlookContacts[i] as Outlook.ContactItem;

                    Outlook.UserProperty updatedProp = contact.UserProperties[newPrefixUpdated];
                    if (updatedProp != null)
                    {
                        string lastUpdatedStr = (string)updatedProp.Value;
                        updatedProp.Delete();

                        updatedProp = contact.UserProperties.Add(newPrefixUpdated, Outlook.OlUserPropertyType.olDateTime, null, null);
                        DateTime lastUpdated = DateTime.Parse(lastUpdatedStr);
                        updatedProp.Value = lastUpdated;

                        if (!contact.Saved)
                        {
                            contact.Save();
                        }

                        continue;
                    }

                    Outlook.UserProperty prop = contact.UserProperties[newPrefixId];
                    if (prop != null)
                    {
                        continue;
                    }

                    prop = contact.UserProperties[oldPrefixId];
                    if (prop != null)
                    {
                        string id = (string)prop.Value;
                        prop.Delete();

                        prop       = contact.UserProperties.Add(newPrefixId, Outlook.OlUserPropertyType.olText, null, null);
                        prop.Value = id;
                    }

                    prop = contact.UserProperties[oldPrefixUpdated];
                    if (prop != null)
                    {
                        DateTime lastUpdated = (DateTime)prop.Value;
                        prop.Delete();

                        prop       = contact.UserProperties.Add(newPrefixUpdated, Outlook.OlUserPropertyType.olDateTime, null, null);
                        prop.Value = lastUpdated;
                    }

                    if (!contact.Saved)
                    {
                        contact.Save();
                    }
                }
            }
            finally
            {
                outlookNamespace.Logoff();
            }
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <exception cref="System.Runtime.InteropServices.COMException"/>
        public OutlookManager()
        {
            var current = System.Security.Principal.WindowsIdentity.GetCurrent();
            m_impContext = current.Impersonate();

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("OUTLOOK");
            int collCount = processes.Length;

            if (collCount != 0)
            {
                #region comment
                //try
                //{
                //    // create an application instance of Outlook
                //    oApp = new Microsoft.Office.Interop.Outlook.Application();
                //}
                //catch (System.Exception ex)
                //{
                //    try
                //    {
                //        // get Outlook in another way
                //        oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //    catch (System.Exception ex2)
                //    {
                //        // try some other way to get the object
                //        oApp = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //}
                #endregion

                try
                {
                    // Outlook already running, hook into the Outlook instance
                    m_outlookApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    if (ex.ErrorCode == -2147221021)
                        m_outlookApp = new Application();
                    else
                        throw;
                }
            }
            else
                m_outlookApp = new Microsoft.Office.Interop.Outlook.Application();

            m_outNameSpace = m_outlookApp.GetNamespace("MAPI");
            m_allFolders = m_outNameSpace.Folders;

            m_outlookApp.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outLookApp_NewMailEx);

            this.FoldersInOutlook = new List<string>();

            m_inboxFolder = m_outNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            m_FoldersToMonitor = new List<string>();
            m_foldToMonitorInstances = new Dictionary<string, MAPIFolder>(StringComparer.OrdinalIgnoreCase);

            MAPIFolder mUserFolder = m_inboxFolder.Parent;
            if (mUserFolder != null)
            {
                foreach (object folder in mUserFolder.Folders)
                {
                    MAPIFolder mapiFolder = folder as MAPIFolder;
                    if (mapiFolder != null)
                    {
                        this.FoldersInOutlook.Add(mapiFolder.Name);
                    }
                }
            }
        }
        public void Dispose()
        {
            if (_disposed)
                return;

            _disposed = true;

            if (m_outlookApp != null)
                m_outlookApp = null;

            if (m_inboxFolder != null)
                m_inboxFolder = null;

            if (m_impContext != null)
            {
                m_impContext.Undo();
                m_impContext.Dispose();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.SuppressFinalize(this);
        }
Ejemplo n.º 52
0
        /// <summary>
        ///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
        ///     Receives notification that the Add-in is being unloaded.
        /// </summary>
        /// <param term='disconnectMode'>
        ///      Describes how the Add-in is being unloaded.
        /// </param>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
        {
            try
            {
                if (disconnectMode != Extensibility.ext_DisconnectMode.ext_dm_HostShutdown)
                {
                    OnBeginShutdown(ref custom);
                }
                if (ContactsFolder != null)
                {
                    // Unregister Events
                   // ContactsFolder.Items.ItemAdd -= new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
                    // Release Reference to COM Object
                    ContactsFolder= null;

                }
                myAddInInstance = null;
                myApplicationObject = null;            }
            catch (System.Exception ex)
            {
                logger.Error(ex.Message);
                logger.Debug(ex.StackTrace.ToString());
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        ///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
        ///      Receives notification that the host application has completed loading.
        /// </summary>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnStartupComplete(ref System.Array custom)
        {
            try
            {
                // Get the ContactsFolder Object
                Config.CheckShowConfig();

                NameSpace nspace = myApplicationObject.GetNamespace("MAPI");
                ContactsFolder = nspace.GetDefaultFolder(OlDefaultFolders.olFolderContacts);

                // Register for It``emAdd Event
                // Note: if more then 16 Items are added, the event doesn't come.
                items = ContactsFolder.Items;
                logger.Debug("Setting ItemAdd Event");
                items.ItemAdd += new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);
                logger.Debug("Setting ItemChange Event");
                items.ItemChange += new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemChangeEventHandler(Items_ItemChange);
                logger.Debug("Setting ItemRemove Event");
                items.ItemRemove += new Microsoft.Office.Interop.Outlook.ItemsEvents_ItemRemoveEventHandler(Items_ItemRemove);
                RefreshContacts();
            }
            catch (System.Exception ex)
            {
                logger.Error(ex.Message);
                logger.Debug(ex.StackTrace.ToString());
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        /// <c>addinExplorer_FolderSwitch</c> Event Handler
        /// Fires when folder  selection is changed . it retrieves the selected folder and its unique id
        /// </summary>
        void addinExplorer_FolderSwitch()
        {
            try
            {

                oCurrentSelectedFolder = addinExplorer.CurrentFolder;

                FromFolderGuid = addinExplorer.CurrentFolder.EntryID;

                //Check selected folder is out Itopia Folder or not

            }
            catch (Exception ex)
            { }
        }
Ejemplo n.º 55
0
        /// <summary>
        /// <c>Application_FolderContextMenuDisplay</c> Event Handler
        /// Folder context menu display event
        /// it is executed when user right clicks on outlook folder to display context menu 
        /// </summary>
        /// <param name="CommandBar"></param>
        /// <param name="Folder"></param>
        void Application_FolderContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar, Microsoft.Office.Interop.Outlook.MAPIFolder Folder)
        {
            try
            {
                currentFolderSelected = Folder.Name;

                currentFolderSelectedGuid = Folder.EntryID;
                AddfFolderinSessionMapi();
                MAPIFolderWrapper folderWrapper = myFolders.Find(delegate(MAPIFolderWrapper p) { return p.FolderName == Folder.Name; });

                if (folderWrapper != null && !string.IsNullOrEmpty(Folder.WebViewURL))
                {

                    oContextMenuFolder = Folder;
                    try
                    {
                        CreateEventToRenameOnFolderContextMenu(CommandBar, Folder);
                        //Remove the click event on the button
                        oFolderMenuButtonEditConnectionProperties.Click -= new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(oFolderMenuButtonEditConnectionProperties_Click);

                    }
                    catch { }

                    //System.Diagnostics.Debugger.Launch();

                    //Add Edit Connection properties button
                    oFolderMenuButtonEditConnectionProperties = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true);
                    oFolderMenuButtonEditConnectionProperties.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    oFolderMenuButtonEditConnectionProperties.Caption = "Edit Connection (ITOPIA)";
                    oFolderMenuButtonEditConnectionProperties.FaceId = 222;
                    oFolderMenuButtonEditConnectionProperties.Tag = Folder.Name;
                    oFolderMenuButtonEditConnectionProperties.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(oFolderMenuButtonEditConnectionProperties_Click);

                    //Add SharePoint View Context Menu button
                    oFolderMenuButtonSharePointView = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true);
                    oFolderMenuButtonSharePointView.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    oFolderMenuButtonSharePointView.Caption = "SharePoint View (ITOPIA)";
                    oFolderMenuButtonSharePointView.FaceId = 223;
                    oFolderMenuButtonSharePointView.Tag = Folder.Name + "A";
                    oFolderMenuButtonSharePointView.Click += new Office._CommandBarButtonEvents_ClickEventHandler(oFolderMenuButtonSharePointView_Click);

                    //Add Outlook View Context Menu button
                    oFolderMenuButtonOutlookView = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true);
                    oFolderMenuButtonOutlookView.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    oFolderMenuButtonOutlookView.Caption = "Outlook View (ITOPIA)";
                    oFolderMenuButtonOutlookView.FaceId = 224;
                    oFolderMenuButtonOutlookView.Tag = Folder.Name + "B";
                    oFolderMenuButtonOutlookView.Click += new Office._CommandBarButtonEvents_ClickEventHandler(oFolderMenuButtonOutlookView_Click);

                    ////Add view Connection properties button
                    //oFolderMenuButtonViewProperties = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true);
                    //oFolderMenuButtonViewProperties.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    //oFolderMenuButtonViewProperties.Caption = "ITOPIA Edit Connection Properties";
                    //oFolderMenuButtonViewProperties.FaceId = 222;
                    //oFolderMenuButtonViewProperties.Tag = Folder.Name;
                    //oFolderMenuButtonViewProperties.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(oFolderMenuButtonEditConnectionProperties_Click);
                    ////

                    Outlook.MAPIFolder myfolder = (Outlook.MAPIFolder)Folder.Parent;
                    try
                    {
                        myfolder.Folders.FolderChange -= new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange);
                    }
                    catch (Exception)
                    {

                    }

                    myfolder.Folders.FolderChange += new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange);

                }
            }
            catch (Exception ex)
            {
                EncodingAndDecoding.ShowMessageBox("Application_FolderContextMenuDisplay", ex.Message, MessageBoxIcon.Error);
            }
        }
        public IOfficeConnectAddin(ThisAddIn addin)
        {
            try
            {
                _addin = addin;

                IOfficeConnectGlobals.ErEnUkendtBrugerAktiv = true;

                var outlookInboxFolder = _addin.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

                // Get outlook inbox store ID
                IOfficeConnectGlobals.InboxFolderEntryID = outlookInboxFolder.EntryID;
                IOfficeConnectGlobals.UserStoreID = outlookInboxFolder.StoreID;

                Task.Run(() =>
                {
                    IOfficeConnectGlobals.EnsureCache();

                    log.Info("Cache was built");
                });

                var brugerKendt = IOfficeConnectGlobals.GetCurrentBruger();

                if (brugerKendt == null)
                {
                    var m = string.Format("Brugeren du er logget på windows med ({0}) er ukendt i IOffice", Environment.UserName);

                    log.Warn(m);

                    MessageBox.Show(m, "Ukendt bruger", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    log.InfoFormat("Bruger med ID {0} og navn {1} logget ind", brugerKendt.ID, brugerKendt.Navn);

                    IOfficeConnectGlobals.ErEnUkendtBrugerAktiv = false;

                    // Hookup on mail received
                    _addin.Application.NewMailEx += Application_NewMailEx;

                    // Hookup item sent
                    // http://stackoverflow.com/questions/23803960/outlook-itemadd-event-not-triggered
                    _sentItemsFolder = _addin.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
                    _sentItems = _sentItemsFolder.Items;
                    _sentItems.ItemAdd -= sentItems_ItemAdd;
                    _sentItems.ItemAdd += sentItems_ItemAdd;

                    log.Info("Events new mail og itemsend hooked up");
                }
            }
            catch (Exception e)
            {
                var m = string.Format("Generel fejl under opstart: {0}", e.Message);

                log.Error(m, e);

                MessageBox.Show(m, "Ukendt fejl under opstart", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                throw;
            }
        }
Ejemplo n.º 57
0
        public bool logon(string sProfile, string sUser, string sPassword, bool bShowDialog)
        {
            bool bRet = false;
            bool bNewSession = true;
            _userData.sUser = sUser;
            try
            {
                MailNS.Logon(sProfile, sPassword, bShowDialog, bNewSession);
                MyInbox = MailNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                OnStateChanged(new StatusEventArgs(StatusType.ews_started, "logon done"));

                getMailsAsync();

                MyItems = MyInbox.Items;
                MyItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(newItem);

                bRet = true;
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            }
            return bRet;
        }
Ejemplo n.º 58
0
        private void DisplayMenuOption(Office.CommandBar commandBar, Outlook.MAPIFolder folder)
        {
            try
            {
                var READOUT_BUTTON_ID = "READOUT_BUTTON_ID";
                if (commandBar.FindControl(Tag: READOUT_BUTTON_ID) != null)
                {
            #if DEBUG
                    Util.AppLogger.WriteLine("Already exists");
            #endif
                    return;
                }

                //var btnInitReadOut = (Office.CommandBarButton)commandBar.Controls.Add(Type: Office.MsoControlType.msoControlButton);
                //btnInitReadOut.Tag = READOUT_BUTTON_ID;
                //                btnInitReadOut.Caption = "Reinitiali&ze ReadOut Key Hook";
                //btnInitReadOut.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(btnInitReadOut_Click);
                var btnReadOut = (Office.CommandBarButton)commandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, missing);
                btnReadOut.Tag = READOUT_BUTTON_ID;
                btnReadOut.Caption = "Read&Out";
                btnReadOut.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(btnReadOut_Click);
                CurrentFolder = folder;
                                                if (folder.Items.Count <= 0)
                    btnReadOut.Enabled = false;

            #if DEBUG
                                                var btnDump = (Office.CommandBarButton)commandBar.Controls.Add(Type: Office.MsoControlType.msoControlButton);
                                                btnDump.Caption = "Dump Key Hook";
                                                btnDump.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(
                                                    (Office.CommandBarButton Ctrl, ref bool CancelDefault) => _panelManager.WriteState()
                );
                #endif
            }
            catch (Exception ex)
            {
                ExceptionHandler.Catch(ex);
            }
        }
Ejemplo n.º 59
-1
		public OutlookPortal()
		{
			oApp = new Microsoft.Office.Interop.Outlook.Application();
			oNameSpace = oApp.GetNamespace("MAPI");
			oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
			oNameSpace.Logon(null, null, false, false);
			oMailItem =	(Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
			
		}
Ejemplo n.º 60
-1
		public OutlookDataSource(IHostApplicationProvider hostAppProvider, IMail mailItem)
		{
			_mailItem = mailItem;
			Logger.LogInfo("OutlookSentItemSource.OutlookDataSource()");

			_ns = hostAppProvider.Host.GetNamespace("MAPI");
			_sent = _ns.GetDefaultFolder(MsOutlook.OlDefaultFolders.olFolderSentMail);

			_items = _sent.Items;
		}