Exemplo n.º 1
0
        /// <summary>
        /// Get the default calendar URL for the user
        /// </summary>
        /// <param name="exchangeServer">Exchnage Server to use</param>
        /// <param name="user">The Exchange user to use</param>
        /// <returns>The default calendar URL for the user</returns>
        public static string GetDefaultCalendarUrl( string exchangeServer, ExchangeUser user )
        {
            string path = user.ProxyAddresses;

            if ( path.StartsWith( "SMTP:" ) )
                path = path.Substring( "SMTP:".Length );

            return string.Format( "{0}/exchange/{1}/calendar", exchangeServer, path );
        }
Exemplo n.º 2
0
        private string GetSenderSMTPAddress(MailItem mail)
        {
            string PR_SMTP_ADDRESS =
                @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

            if (mail == null)
            {
                throw new ArgumentNullException();
            }
            if (mail.SenderEmailType == "EX")
            {
                AddressEntry sender =
                    mail.Sender;
                if (sender != null)
                {
                    //Now we have an AddressEntry representing the Sender
                    if (sender.AddressEntryUserType ==
                        OlAddressEntryUserType.
                        olExchangeUserAddressEntry ||
                        sender.AddressEntryUserType ==
                        OlAddressEntryUserType.
                        olExchangeRemoteUserAddressEntry)
                    {
                        //Use the ExchangeUser object PrimarySMTPAddress
                        ExchangeUser exchUser =
                            sender.GetExchangeUser();
                        if (exchUser != null)
                        {
                            return(exchUser.PrimarySmtpAddress);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(sender.PropertyAccessor.GetProperty(
                                   PR_SMTP_ADDRESS) as string);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(mail.SenderEmailAddress);
            }
        }
Exemplo n.º 3
0
        public void TestConvertParticipantStatus()
        {
            EventEntry   googleAppsEvent = new EventEntry("title", "description", "location");
            BusyStatus   status          = BusyStatus.Busy;
            ExchangeUser user            = new ExchangeUser();

            user.Email = "*****@*****.**";

            // The user status with no participants should be busy, since this is how the data
            // comes from the free busy projection
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            Who john = new Who();

            googleAppsEvent.Participants.Add(john);
            john.Email = user.Email;

            // Attendee with no status should be converted to busy.
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            john.Attendee_Status = new Who.AttendeeStatus();

            // Accepted attendee should be converted to busy.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_ACCEPTED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // Declined attendee should be converted to free.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_DECLINED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // Tentative attendee should be converted to tentative.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_TENTATIVE;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // Attendee who hasn't responded yet should be converted to free.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_INVITED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // Attendee with bogus status should be converted to buys.
            john.Attendee_Status.Value = "Abrakadabra";
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);
        }
Exemplo n.º 4
0
        public void TestEmptyBookMarketOrder()
        {
            InitExchange();

            var baseSymbol  = DomainSettings.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            Assert.IsTrue(buyer.OpenMarketOrder(1, Buy) == 0, "Should not have bought anything");
        }
Exemplo n.º 5
0
        public static void Update(this ContactItem thisContactItem, ExchangeUser user)
        {
            thisContactItem.Email1Address           = user.PrimarySmtpAddress;
            thisContactItem.BusinessTelephoneNumber = user.BusinessTelephoneNumber;
            thisContactItem.MobileTelephoneNumber   = user.MobileTelephoneNumber;
            thisContactItem.CompanyName             = user.CompanyName;
            thisContactItem.Department     = user.Department;
            thisContactItem.FirstName      = user.FirstName;
            thisContactItem.LastName       = user.LastName;
            thisContactItem.FullName       = user.Name;
            thisContactItem.JobTitle       = user.JobTitle;
            thisContactItem.OfficeLocation = user.OfficeLocation;

            thisContactItem.Save();
        }
Exemplo n.º 6
0
 public static string GetEmailAddressForExchangeServer(string emailName)
 {
     try
     {
         MailItem  item      = (MailItem)Globals.ThisAddIn.Application.ActiveExplorer().Application.CreateItem(OlItemType.olMailItem);
         Recipient recipient = item.Recipients.Add(emailName);
         recipient.Resolve();
         ExchangeUser exchangeUser = recipient.AddressEntry.GetExchangeUser();
         return(exchangeUser == null ? string.Empty : exchangeUser.PrimarySmtpAddress);
     }
     catch (System.Exception)
     {
         // Swallow exception(!)
         return(string.Empty);
     }
 }
Exemplo n.º 7
0
        public void TestMarketOrderPartialFill()
        {
            InitExchange();

            var baseSymbol  = DomainSettings.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            seller.OpenLimitOrder(0.2m, 1m, Sell);
            Assert.IsTrue(buyer.OpenMarketOrder(0.3m, Buy) == 0.2m, "");
        }
Exemplo n.º 8
0
        public override void RunCommand(object sender)
        {
            var engine          = (AutomationEngineInstance)sender;
            var vRecipients     = v_Recipients.ConvertUserVariableToString(engine);
            var vAttachment     = v_Attachments.ConvertUserVariableToString(engine);
            var vSubject        = v_Subject.ConvertUserVariableToString(engine);
            var vBody           = v_Body.ConvertUserVariableToString(engine);
            var splitRecipients = vRecipients.Split(';');

            Application  outlookApp  = new Application();
            MailItem     mail        = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
            AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry;

            if (currentUser.Type == "EX")
            {
                ExchangeUser manager = currentUser.GetExchangeUser().GetExchangeUserManager();

                foreach (var t in splitRecipients)
                {
                    mail.Recipients.Add(t.ToString());
                }

                mail.Recipients.ResolveAll();

                mail.Subject = vSubject;

                if (v_BodyType == "HTML")
                {
                    mail.HTMLBody = vBody;
                }
                else
                {
                    mail.Body = vBody;
                }

                if (!string.IsNullOrEmpty(vAttachment))
                {
                    var splitAttachments = vAttachment.Split(';');
                    foreach (var attachment in splitAttachments)
                    {
                        mail.Attachments.Add(attachment);
                    }
                }
                mail.Send();
            }
        }
Exemplo n.º 9
0
        public void TestMarketOrderTotalFillNoOrderbookWipe()
        {
            InitExchange();

            var baseSymbol  = Nexus.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            seller.OpenLimitOrder(0.1m, 1m, Sell);
            seller.OpenLimitOrder(0.1m, 2m, Sell);
            Assert.IsTrue(buyer.OpenMarketOrder(0.25m, Buy) == 0.175m, "");
        }
Exemplo n.º 10
0
        private void ProcessExchangeUser(ExchangeUser user)
        {
            if (user == null)
            {
                return;
            }
            var contact = _contacts.FirstOrDefault(c => c.Email1Address == user.PrimarySmtpAddress);

            if (contact == null)
            {
                _folder.AddExchangeUser(user);
            }
            else
            {
                contact.Update(user);
                _contacts.Remove(contact);
            }
        }
        /// O365にある連絡先を全部返す
        public ContactItem getContactItem(Recipient recipient)
        {
            ContactItem contactItem = null;

            /// O365のグループアドレスの場合
            if (OlAddressEntryUserType.olExchangeDistributionListAddressEntry == recipient.AddressEntry.AddressEntryUserType)
            {
                /// グループ名を入れて戻る
                contactItem          = Globals.ThisAddIn.Application.CreateItem(OlItemType.olContactItem);
                contactItem.FullName = recipient.Name;
                return(contactItem);
            }

            /// Exchangeアドレス帳から選択されたユーザーの場合は、ここで取得
            ExchangeUser exchUser = recipient.AddressEntry.GetExchangeUser();

            /// それ以外の場合
            /// (Outlook連絡先フォルダーのアドレスエントリ、もしくはNotesのクラウドメールアドレスからの受信メールに返信する際のアドレスエントリの場合など)
            if (exchUser == null)
            {
                Recipient recResolve = Globals.ThisAddIn.Application.Session.CreateRecipient(recipient.Address);
                /// Exchangeアドレス帳に存在するアドレスなら、exchUserが見つかる
                exchUser = recResolve.AddressEntry.GetExchangeUser();
            }

            /// ExchangeUserが見つかれば、ContactItemに入れる
            if (exchUser != null)
            {
                contactItem             = Globals.ThisAddIn.Application.CreateItem(OlItemType.olContactItem);
                contactItem.FullName    = exchUser.Name;
                contactItem.CompanyName = exchUser.CompanyName;
                contactItem.Department  = exchUser.Department;
                contactItem.JobTitle    = exchUser.JobTitle;
            }
            else
            {
                /// 個人の「連絡先」から取得
                contactItem = recipient.AddressEntry.GetContact();
            }

            return(contactItem);
        }
Exemplo n.º 12
0
        public static string FormatEmailAddress(this MailItem mail)
        {
            AddressEntry sender             = mail.Sender;
            string       SenderEmailAddress = string.Empty;

            if (sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
            {
                ExchangeUser exchUser = sender.GetExchangeUser();
                if (exchUser != null)
                {
                    SenderEmailAddress = exchUser.PrimarySmtpAddress;
                }
            }
            else
            {
                SenderEmailAddress = mail.SenderEmailAddress;
            }

            return(SenderEmailAddress);
        }
        private string GetSenderEmailAddress(MailItem mail)
        {
            AddressEntry sender             = mail.Sender;
            string       senderEmailAddress = "";

            if (sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
            {
                ExchangeUser exchUser = sender.GetExchangeUser();
                if (exchUser != null)
                {
                    senderEmailAddress = exchUser.PrimarySmtpAddress;
                }
            }
            else
            {
                senderEmailAddress = mail.SenderEmailAddress;
            }

            return(senderEmailAddress);
        }
Exemplo n.º 14
0
 public static string GetEmailAddressForExchangeServer(string emailName)
 {
     try
     {
         MailItem  item      = (MailItem)Globals.ThisAddIn.Application.ActiveExplorer().Application.CreateItem(OlItemType.olMailItem);
         Recipient recipient = item.Recipients.Add(emailName);
         recipient.Resolve();
         ExchangeUser exchangeUser = recipient.AddressEntry.GetExchangeUser();
         if (exchangeUser.PrimarySmtpAddress != "")
         {
             return(exchangeUser.PrimarySmtpAddress);
         }
         return(exchangeUser.PrimarySmtpAddress);
     }
     catch (System.Exception exception)
     {
         exception.Data.Clear();
     }
     return("");
 }
Exemplo n.º 15
0
        public void TestIoCLimitOrderUnmatched()
        {
            InitExchange();

            var baseSymbol  = DomainSettings.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            //-----------------------------------------
            //test unmatched IoC orders
            seller.OpenLimitOrder(0.01m, 0.5m, Sell);
            buyer.OpenLimitOrder(0.01m, 0.1m, Buy);
            Assert.IsTrue(buyer.OpenLimitOrder(0.123m, 0.3m, Buy, IoC: true) == 0, "Shouldn't have filled any part of the order");
            Assert.IsTrue(seller.OpenLimitOrder(0.123m, 0.3m, Sell, IoC: true) == 0, "Shouldn't have filled any part of the order");
        }
Exemplo n.º 16
0
        /// <summary>
        /// Convert a Google Calender attendee status to an Exchange status
        /// </summary>
        /// <param name="googleAppsEvent">The Google Calendar event</param>
        /// <param name="user">The user to get the status for</param>
        /// <returns>The Exchange status for the given user</returns>
        public static BusyStatus ConvertParticipantStatus(
            ExchangeUser user,
            EventEntry googleAppsEvent)
        {
            BusyStatus result = BusyStatus.Busy;
            // Default is busy, because in order to make free-buys projections work correctly,
            // since in that case the participants are not set at all.

            string externalEmail = ConfigCache.MapToExternalDomain(user.Email);

            foreach (Who participant in googleAppsEvent.Participants)
            {
                if (!string.IsNullOrEmpty(participant.Email) &&
                    (participant.Email.Equals(user.Email) ||
                     participant.Email.Equals(externalEmail)))
                {
                    switch (SafeGetValue(participant.Attendee_Status))
                    {
                    case Who.AttendeeStatus.EVENT_ACCEPTED:
                        result = BusyStatus.Busy;
                        break;

                    case Who.AttendeeStatus.EVENT_DECLINED:
                        result = BusyStatus.Free;
                        break;

                    case Who.AttendeeStatus.EVENT_INVITED:
                        result = BusyStatus.Tentative;
                        break;

                    case Who.AttendeeStatus.EVENT_TENTATIVE:
                        result = BusyStatus.Tentative;
                        break;
                    }

                    break;
                }
            }

            return(result);
        }
Exemplo n.º 17
0
        public Employee GetManagerOf(Employee employee)
        {
            Recipient    r   = mapi.CreateRecipient(employee.Email);
            ExchangeUser eu  = r.AddressEntry.GetExchangeUser();
            ExchangeUser eum = eu.GetExchangeUserManager();

            Employee manager;
            string   alias = GetAlias(eum);

            if (cache.ContainsKey(alias))
            {
                manager = cache[alias];
            }
            else
            {
                manager      = CreateEmployeeFrom(alias, eum);
                cache[alias] = manager;
            }

            return(manager);
        }
Exemplo n.º 18
0
        private string GetAlias(ExchangeUser eudr)
        {
            if (!string.IsNullOrEmpty(eudr.Alias))
            {
                return(eudr.Alias.ToLower());
            }

            string first  = eudr.FirstName ?? "a";
            string last   = eudr.LastName ?? "b";
            string prefix = first.Substring(0, 1).ToLower() + last.Substring(0, 1).ToLower();
            int    suffix = 0;
            string alias;

            do
            {
                suffix++;
                alias = string.Format("-{0}{1:D6}", prefix, suffix); // '-' stands for virtual (to avoid clashes with future aliasees)
            } while (cache.ContainsKey(alias));

            return(alias);
        }
Exemplo n.º 19
0
        public void TestIoCLimitOrderCompleteFulfilment()
        {
            InitExchange();

            var baseSymbol  = DomainSettings.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            //-----------------------------------------
            //test fully matched IoC orders
            buyer.OpenLimitOrder(0.1m, 1m, Buy, IoC: false);
            Assert.IsTrue(seller.OpenLimitOrder(0.1m, 1m, Sell, IoC: true) == 0.1m, "Unexpected amount of tokens received");

            seller.OpenLimitOrder(0.1m, 1m, Sell, IoC: false);
            Assert.IsTrue(buyer.OpenLimitOrder(0.1m, 1m, Buy, IoC: true) == 0.1m, "Unexpected amount of tokens received");
        }
Exemplo n.º 20
0
        private static string GetFromAddress(MailItem mailItem)
        {
            Application application = null;

            try
            {
                if (!(mailItem.SenderEmailType == "EX"))
                {
                    return(mailItem.SenderEmailAddress);
                }
                application = InitOutlook();
                Recipient    recipient    = application.GetNamespace("MAPI").CreateRecipient(mailItem.SenderEmailAddress);
                AddressEntry addressEntry = recipient.AddressEntry;
                if (addressEntry != null)
                {
                    if (addressEntry.AddressEntryUserType != 0 && addressEntry.AddressEntryUserType != OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                    {
                        return(recipient.Address);
                    }
                    ExchangeUser exchangeUser = addressEntry.GetExchangeUser();
                    if (exchangeUser != null)
                    {
                        return(exchangeUser.PrimarySmtpAddress);
                    }
                }
            }
            catch (System.Exception ex)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个异常产生", ex.Message);
            }
            finally
            {
                if (application != null)
                {
                    Marshal.ReleaseComObject(application);
                }
            }
            return(string.Empty);
        }
Exemplo n.º 21
0
        public void TestLimitMinimumQuantity()
        {
            InitExchange();

            var baseSymbol  = DomainSettings.StakingTokenSymbol;
            var quoteSymbol = maxDivTokenSymbol;

            var buyer  = new ExchangeUser(baseSymbol, quoteSymbol);
            var seller = new ExchangeUser(baseSymbol, quoteSymbol);

            buyer.FundQuoteToken(quantity: 2m, fundFuel: true);
            seller.FundBaseToken(quantity: 2m, fundFuel: true);

            //-----------------------------------------
            //test order amount and prices at the limit

            var minimumBaseToken  = UnitConversion.ToDecimal(simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, "exchange", "GetMinimumTokenQuantity", buyer.baseToken).AsNumber(), buyer.baseToken.Decimals);
            var minimumQuoteToken = UnitConversion.ToDecimal(simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, "exchange", "GetMinimumTokenQuantity", buyer.quoteToken).AsNumber(), buyer.baseToken.Decimals);

            buyer.OpenLimitOrder(minimumBaseToken, minimumQuoteToken, Buy);
            seller.OpenLimitOrder(minimumBaseToken, minimumQuoteToken, Sell);
        }
Exemplo n.º 22
0
        private void btnAddEmailToTfsNewEmail_Click(object sender, RibbonControlEventArgs e)
        {
            var context  = e.Control.Context;
            var mailItem = null as MailItem;


            ExchangeUser currentOutlookUser = outlookApp.Session.CurrentUser.
                                              AddressEntry.GetExchangeUser();

            try
            {
                mailItem = context.CurrentItem as MailItem;
            }
            catch
            {
            }

            if (mailItem != null)
            {
                TfsWorkItemUserForm userForm = new TfsWorkItemUserForm(mailItem, outlookAddin, currentOutlookUser);
                userForm.ShowDialog();
            }
        }
Exemplo n.º 23
0
        private void btnAddEmailToTfs_Click(object sender, RibbonControlEventArgs e)
        {
            ExchangeUser currentOutlookUser = outlookApp.Session.CurrentUser.
                                              AddressEntry.GetExchangeUser();

            var context  = e.Control.Context;
            var mailItem = null as MailItem;

            try
            {
                mailItem = context.CurrentItem as MailItem;
            }
            catch
            {
            }


            if (mailItem == null)
            {
                if (outlookApp.ActiveExplorer().Selection.Count > 0)
                {
                    Object selObject = outlookApp.ActiveExplorer().Selection[1];
                    if (selObject is Microsoft.Office.Interop.Outlook.MailItem)
                    {
                        mailItem =
                            (selObject as Microsoft.Office.Interop.Outlook.MailItem);
                    }
                }
            }

            if (mailItem != null)
            {
                TfsWorkItemUserForm userForm = new TfsWorkItemUserForm(mailItem, outlookAddin, currentOutlookUser);
                userForm.ShowDialog();
            }
        }
Exemplo n.º 24
0
 private static Employee CreateEmployeeFrom(ExchangeUser eu)
 {
     return new Employee(eu, eu.Alias.ToLower(), eu.FirstName, eu.LastName, eu.JobTitle, eu.PrimarySmtpAddress.ToLower());
 }
Exemplo n.º 25
0
 public void Init()
 {
     _requestor = new XmlRequestMock();
     _webdav    = new WebDavQuery(CredentialCache.DefaultCredentials, _requestor);
     _user      = createFauxUser("test", "*****@*****.**");
 }
Exemplo n.º 26
0
        protected bool update_users(ref XmlDocument doc)
        {
            if (!paramsContainer.GBEdit)
            {
                return(false);
            }

            List <ExchangeUser> exUsers = new List <ExchangeUser>();

            List <string> usernames = new List <string>();

            XmlNodeList users = doc.GetElementsByTagName("User");

            foreach (XmlNode _usr in users)
            {
                ExchangeUser eu = new ExchangeUser()
                {
                    UserName = _usr.Attributes["username"] == null ? null :
                               PublicMethods.verify_string(_usr.Attributes["username"].Value.Trim()),
                    NewUserName = _usr.Attributes["newusername"] == null ? null :
                                  PublicMethods.verify_string(_usr.Attributes["newusername"].Value.Trim()),
                    FirstName    = _usr.Attributes["firstname"] == null ? null : _usr.Attributes["firstname"].Value.Trim(),
                    LastName     = _usr.Attributes["lastname"] == null ? null : _usr.Attributes["lastname"].Value.Trim(),
                    DepartmentID = _usr.Attributes["departmentid"] == null ? null : _usr.Attributes["departmentid"].Value.Trim()
                };

                if (!string.IsNullOrEmpty(eu.UserName) && eu.UserName.ToLower() == "admin")
                {
                    eu.NewUserName = null;
                }

                if (string.IsNullOrEmpty(eu.UserName) ||
                    exUsers.Any(u => u.UserName.ToLower() == eu.UserName.ToLower()))
                {
                    continue;
                }

                EmploymentType empType = EmploymentType.NotSet;
                if (_usr.Attributes["employmenttype"] == null ||
                    !Enum.TryParse <EmploymentType>(_usr.Attributes["employmenttype"].Value.Trim(), out empType))
                {
                    empType = EmploymentType.NotSet;
                }
                eu.EmploymentType = empType;

                if (_usr.Attributes["ismanager"] != null)
                {
                    eu.IsManager = PublicMethods.parse_bool(_usr.Attributes["ismanager"].Value);
                }
                if (_usr.Attributes["resetpassword"] != null)
                {
                    eu.ResetPassword = PublicMethods.parse_bool(_usr.Attributes["resetpassword"].Value);
                }
                if (eu.NewUserName == eu.UserName)
                {
                    eu.NewUserName = null;
                }

                string password = eu.UserName;
                while (password.Length < 5)
                {
                    password += eu.UserName;
                }
                eu.Password = new Password(password);

                exUsers.Add(eu);
            }

            bool result = true;

            PublicMethods.split_list <ExchangeUser>(exUsers, 200, items => {
                result = DEController.update_users(paramsContainer.Tenant.Id, items);
            });

            return(result);
        }
Exemplo n.º 27
0
        public Message Create()
        {
            //begin read in xml
            StringWriter sw     = new StringWriter();
            ExchangeUser user = new ExchangeUser();
            XmlTextWriter xtw   = new XmlTextWriter(sw);
            string userResult = "";
            OperationContext.Current.RequestContext.RequestMessage.WriteMessage(xtw);
            xtw.Flush();
            xtw.Close();
            XmlTextReader xtr                     = new XmlTextReader(new StringReader(sw.ToString()));
            string s                              = xtr.ReadElementString("Binary");
            string s1                             = System.Text.ASCIIEncoding.ASCII.GetString(System.Convert.FromBase64String(s));
            Dictionary<string, string> attributes = new Dictionary<string, string>();
            System.Xml.XmlDocument xml_doc        = new System.Xml.XmlDocument();
            xml_doc.LoadXml(@s1);

            //read in attributes from xml_doc, store them in Dictionary variable attributes
            attributes.Add("alias", xml_doc.SelectSingleNode("/ExchSvc/alias") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/alias").InnerText);
            attributes.Add("domain", xml_doc.SelectSingleNode("/ExchSvc/domain") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/domain").InnerText);
            attributes.Add("upn", xml_doc.SelectSingleNode("/ExchSvc/userPrincipalName") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/userPrincipalName").InnerText);
            attributes.Add("cn", xml_doc.SelectSingleNode("/ExchSvc/cn") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/cn").InnerText);
            attributes.Add("name", xml_doc.SelectSingleNode("/ExchSvc/name") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/name").InnerText);
            attributes.Add("displayName", xml_doc.SelectSingleNode("/ExchSvc/displayName") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/displayName").InnerText);
            attributes.Add("dn" , xml_doc.SelectSingleNode("/ExchSvc/distinguishedName") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/distinguishedName").InnerText);
            attributes.Add("givenName", xml_doc.SelectSingleNode("/ExchSvc/givenName") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/givenName").InnerText);
            attributes.Add("samAccountName", xml_doc.SelectSingleNode("/ExchSvc/samAccountName") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/samAccountName").InnerText);
            attributes.Add("password", xml_doc.SelectSingleNode("/ExchSvc/password") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/password").InnerText);
            attributes.Add("sn", xml_doc.SelectSingleNode("/ExchSvc/sn") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/sn").InnerText);
            attributes.Add("changePwd", xml_doc.SelectSingleNode("/ExchSvc/changePwd") == null ? "0" : xml_doc.SelectSingleNode("/ExchSvc/changePwd").InnerText);
            attributes.Add("acctDisabled", xml_doc.SelectSingleNode("/ExchSvc/acctDisabled") == null ? "1" : xml_doc.SelectSingleNode("/ExchSvc/acctDisabled").InnerText);
            attributes.Add("pwdExpires", xml_doc.SelectSingleNode("/ExchSvc/pwdExpires") == null ? "0" : xml_doc.SelectSingleNode("/ExchSvc/pwdExpires").InnerText);
            attributes.Add("ou", xml_doc.SelectSingleNode("/ExchSvc/ou") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/ou").InnerText);
            attributes.Add("securityGroup", xml_doc.SelectSingleNode("/ExchSvc/securityGroup") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/securityGroup").InnerText);
            attributes.Add("useOAB", xml_doc.SelectSingleNode("/ExchSvc/useOAB") == null ? "" : xml_doc.SelectSingleNode("/ExchSvc/useOAB").InnerText);
            attributes.Add("vpnUsr", xml_doc.SelectSingleNode("/ExchSvc/vpnUsr") == null ? "0" : xml_doc.SelectSingleNode("/ExchSvc/vpnUsr").InnerText);

            if (attributes["vpnUsr"] == "true")
            {
                attributes["alias"]          = attributes["alias"] + "-vpn";
                attributes["upn"]            = attributes["upn"].Replace("@", "-vpn@");
                attributes["dn"]             = attributes["dn"].Replace("OU=" + attributes["ou"], "OU=VPN,OU=" + attributes["ou"]);
                attributes["samAccountName"] = attributes["samAccountName"] + "-vpn";
                //Call NewADUser on ExchangeUser class
                userResult                 = ExchangeRepo.NewADUser(attributes);
            }
            else
            {
                //Call NewExchangeUser on ExchangeUser class
                userResult = ExchangeRepo.NewExchangeUser(attributes);
                //Add User to Security Group
                string groupResult = ExchangeRepo.AddGroupMember(attributes);
                if (groupResult.IndexOf("Error") != -1)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
                    return MessageBuilder.CreateResponseMessage(groupResult);
                }
            }

            if (userResult.IndexOf("Error") != -1)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
                return MessageBuilder.CreateResponseMessage(userResult);
            }

            user = XmlSerializationHelper.Deserialize<ExchangeUser>(userResult);
            return MessageBuilder.CreateResponseMessage(user);
        }
Exemplo n.º 28
0
        public void TestConvertParticipantStatus()
        {
            EventEntry googleAppsEvent = new EventEntry("title", "description", "location");
            BusyStatus status = BusyStatus.Busy;
            ExchangeUser user = new ExchangeUser();

            user.Email = "*****@*****.**";

            // The user status with no participants should be busy, since this is how the data
            // comes from the free busy projection
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            Who john = new Who();
            googleAppsEvent.Participants.Add(john);
            john.Email = user.Email;

            // Attendee with no status should be converted to busy.
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            john.Attendee_Status = new Who.AttendeeStatus();

            // Accepted attendee should be converted to busy.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_ACCEPTED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // Declined attendee should be converted to free.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_DECLINED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // Tentative attendee should be converted to tentative.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_TENTATIVE;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // Attendee who hasn't responded yet should be converted to free.
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_INVITED;
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // Attendee with bogus status should be converted to buys.
            john.Attendee_Status.Value = "Abrakadabra";
            status = ConversionsUtil.ConvertParticipantStatus(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);
        }
        /// <summary>
        /// Takes an unknown contact and matches on a number of parameters for that contact in the order of:
        /// email, common name, alias
        /// </summary>
        /// <param name="contactMatch">the expanded contact that we want to try to match on</param>
        /// <returns></returns>
        protected ExchangeUser GetMailContact(ExchangeUser contactMatch)
        {
            ExchangeUser ret = GetMailContact(contactMatch.email);
            if (ret == null && contactMatch.cn != "")
            {
                ret = GetMailContact(contactMatch.cn);
            }
            if (ret == null && contactMatch.alias != "")
            {
                ret = GetMailContact(contactMatch.alias);
            }

            return ret;
        }
        public TfsWorkItemUserForm(Microsoft.Office.Interop.Outlook.MailItem outlookCurrentMailItem, ThisAddIn thisAddIn, ExchangeUser exchangeUser)
        {
            _outlookCurrentMailItem = outlookCurrentMailItem;
            _thisAddIn    = thisAddIn;
            _exchangeUser = exchangeUser;
            InitializeComponent();
            this.CenterToScreen();
            btnSaveNClose.Enabled = false;
            btnSave.Enabled       = false;

            txtTitle.Text = _outlookCurrentMailItem.Subject;

            cbProject.DataSource    = Globals.ThisAddIn.Settings.TfsConfigurations;
            cbProject.DisplayMember = "TfsProject";

            this.LoadOptions();

            txtTitle.Text = _outlookCurrentMailItem.Subject;

            var newLine = "<br/>" + Environment.NewLine;

            StringBuilder bodyText = new StringBuilder();

            bodyText.Append("From : " + (_outlookCurrentMailItem.SenderName ?? "") +
                            " (" + (GetSenderEmailAddress(_outlookCurrentMailItem.Sender) ?? _outlookCurrentMailItem.SenderEmailAddress) + ")" +
                            newLine);
            bodyText.Append("To : " + (_outlookCurrentMailItem.To ?? "") + newLine);
            if (!string.IsNullOrEmpty(_outlookCurrentMailItem.CC))
            {
                bodyText.Append("CC : " + (_outlookCurrentMailItem.CC ?? "") + newLine);
            }
            if (!string.IsNullOrEmpty(_outlookCurrentMailItem.BCC))
            {
                bodyText.Append("BCC : " + (_outlookCurrentMailItem.BCC ?? "") + newLine);
            }
            if (!string.IsNullOrEmpty(_outlookCurrentMailItem.Subject))
            {
                bodyText.Append("Subject : " + (_outlookCurrentMailItem.Subject ?? "") + newLine);
            }
            bodyText.Append("Sent : " + _outlookCurrentMailItem.SentOn + newLine);

            bodyText.Append("-----------------------------------------" + newLine);
            bodyText.Append(_outlookCurrentMailItem.Body.Replace(Environment.NewLine, newLine));


            txtBody.Text = bodyText.ToString();

            lblAttachements.Text = lblAttachements.Text + _outlookCurrentMailItem.Attachments.Count;


            chkLstBoxAttachements.Items.Add("<MSG>, size:" + _outlookCurrentMailItem.Size / 1024 + "K", true);
            for (int i = 1; i <= _outlookCurrentMailItem.Attachments.Count; i++)
            {
                chkLstBoxAttachements.Items.Add(
                    string.Format("{0}, size:{1}K",
                                  _outlookCurrentMailItem.Attachments[i].GetFileName(),
                                  _outlookCurrentMailItem.Attachments[i].Size / 1024),
                    false);
            }

            // check if the subject can parse the regex
            if (!string.IsNullOrEmpty(Globals.ThisAddIn.Settings.RegexToParseEmailSubjects))
            {
                Regex regex = new Regex(Globals.ThisAddIn.Settings.RegexToParseEmailSubjects);
                var   match = regex.Match(_outlookCurrentMailItem.Subject);
                if (match.Success)
                {
                    var   value  = match.Value;
                    Regex regex2 = new Regex("[\\d]+");
                    var   match2 = regex2.Match(value);
                    if (match2.Success)
                    {
                        tabControl1.SelectedIndex = 1;
                        txtExistingItemId.Text    = match2.Value;
                    }
                }
            }
            FindWorkItem(txtExistingItemId.Text, out existingItem, out existingItemValidated);
        }
        public String GetRecipientEmail(Recipient recipient)
        {
            String  retEmail       = "";
            Boolean builtFakeEmail = false;

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry     = null;
            String       addressEntryType = "";

            try {
                try {
                    addressEntry = recipient.AddressEntry;
                } catch {
                    log.Warn("Can't resolve this recipient!");
                    addressEntry = null;
                }
                if (addressEntry == null)
                {
                    log.Warn("No AddressEntry exists!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }
                else
                {
                    try {
                        addressEntryType = addressEntry.Type;
                    } catch {
                        log.Warn("Cannot access addressEntry.Type!");
                    }
                    log.Fine("AddressEntry Type: " + addressEntryType);
                    if (addressEntryType == "EX")   //Exchange
                    {
                        log.Fine("Address is from Exchange");
                        if (addressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry ||
                            addressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                        {
                            ExchangeUser eu = null;
                            try {
                                eu = addressEntry.GetExchangeUser();
                                if (eu != null && eu.PrimarySmtpAddress != null)
                                {
                                    retEmail = eu.PrimarySmtpAddress;
                                }
                                else
                                {
                                    log.Warn("Exchange does not have an email for recipient: " + recipient.Name);
                                    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                                    try {
                                        //Should I try PR_EMS_AB_PROXY_ADDRESSES next to cater for cached mode?
                                        pa       = recipient.PropertyAccessor;
                                        retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                                        log.Debug("Retrieved from PropertyAccessor instead.");
                                    } catch {
                                        log.Warn("Also failed to retrieve email from PropertyAccessor.");
                                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                                    } finally {
                                        pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                                    }
                                }
                            } finally {
                                eu = (ExchangeUser)OutlookOgcs.Calendar.ReleaseObject(eu);
                            }
                        }
                        else if (addressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry)
                        {
                            log.Fine("This is an Outlook contact");
                            ContactItem contact = null;
                            try {
                                try {
                                    contact = addressEntry.GetContact();
                                } catch {
                                    log.Warn("Doesn't seem to be a valid contact object. Maybe this account is no longer in Exchange.");
                                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                                }
                                if (contact != null)
                                {
                                    if (contact.Email1AddressType == "EX")
                                    {
                                        log.Fine("Address is from Exchange.");
                                        log.Fine("Using PropertyAccessor to get email address.");
                                        Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                                        try {
                                            pa       = contact.PropertyAccessor;
                                            retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString();
                                        } finally {
                                            pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                                        }
                                    }
                                    else
                                    {
                                        retEmail = contact.Email1Address;
                                    }
                                }
                            } finally {
                                contact = (ContactItem)OutlookOgcs.Calendar.ReleaseObject(contact);
                            }
                        }
                        else
                        {
                            log.Fine("Exchange type: " + addressEntry.AddressEntryUserType.ToString());
                            log.Fine("Using PropertyAccessor to get email address.");
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = null;
                            try {
                                pa       = recipient.PropertyAccessor;
                                retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                            } finally {
                                pa = (Microsoft.Office.Interop.Outlook.PropertyAccessor)OutlookOgcs.Calendar.ReleaseObject(pa);
                            }
                        }
                    }
                    else if (addressEntryType != null && addressEntryType.ToUpper() == "NOTES")
                    {
                        log.Fine("From Lotus Notes");
                        //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    }
                    else
                    {
                        log.Fine("Not from Exchange");
                        try {
                            if (string.IsNullOrEmpty(addressEntry.Address))
                            {
                                log.Warn("addressEntry.Address is empty.");
                                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                            }
                            else
                            {
                                retEmail = addressEntry.Address;
                            }
                        } catch (System.Exception ex) {
                            log.Fail("Failed accessing addressEntry.Address");
                            log.Fail(ex.Message);
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                        }
                    }
                }

                if (retEmail != null && retEmail.IndexOf("<") > 0)
                {
                    retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                    retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
                }
                log.Fine("Email address: " + retEmail, retEmail);
                if (!EmailAddress.IsValidEmail(retEmail) && !builtFakeEmail)
                {
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    if (!EmailAddress.IsValidEmail(retEmail))
                    {
                        Forms.Main.Instance.Console.Update("Recipient \"" + recipient.Name + "\" with email address \"" + retEmail + "\" is invalid.<br/>" +
                                                           "This must be manually resolved in order to sync this appointment.", Console.Markup.error, notifyBubble: true);
                        throw new ApplicationException("Invalid recipient email for \"" + recipient.Name + "\"");
                    }
                }
                return(retEmail);
            } finally {
                addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry);
            }
        }
        // CreateMailContact()
        // desc: Method creates a new mail contact, returns mail contact alias on success
        // params: string name  - Name of contact
        //         string email - External email of contact
        //         string ou    - Organizational Unit in which to create contact in
        // method: public
        // return: bool
        public bool CreateMailContact(ref ExchangeUser newContact)
        {
            if (newContact.alias == "") // If alias hasn't been set, give a default alias of the name minus any spaces
                newContact.alias = newContact.cn.Replace(" ", "");

            bool Result = false;
            string ErrorSet = "";
            RunspaceConfiguration config = RunspaceConfiguration.Create();
            PSSnapInException warning;
            config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
            if (warning != null) throw warning;
            ExchangeUser contact = GetMailContact(newContact);

            if (contact == null)
            {
                using (Runspace thisRunspace = RunspaceFactory.CreateRunspace(config))
                {
                    try
                    {
                        thisRunspace.Open();

                        using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
                        {
                            try
                            {
                                thisPipeline.Commands.Add("New-MailContact");
                                thisPipeline.Commands[0].Parameters.Add("Name", @newContact.cn);
                                thisPipeline.Commands[0].Parameters.Add("ExternalEmailAddress", @newContact.email);
                                thisPipeline.Commands[0].Parameters.Add("OrganizationalUnit", @newContact.ou);
                                thisPipeline.Commands[0].Parameters.Add("Alias", @newContact.alias);
                                try
                                {
                                    thisPipeline.Invoke();
                                    Result = true;
                                }
                                catch (Exception ex)
                                {
                                    ErrorSet = "Error: " + ex.ToString();
                                    newContact.error += "Error: " + ex.ToString();
                                }
                                // Check for errors in the pipeline and throw an exception if necessary.
                                if (thisPipeline.Error != null && thisPipeline.Error.Count > 0)
                                {
                                    StringBuilder pipelineError = new StringBuilder();
                                    pipelineError.AppendFormat("Error calling New-MailContact.");
                                    foreach (object item in thisPipeline.Error.ReadToEnd())
                                    {
                                        pipelineError.AppendFormat("{0}\n", item.ToString());
                                    }
                                    ErrorSet = ErrorSet + "Error: " + pipelineError.ToString();
                                    newContact.error += "Error: " + pipelineError.ToString();
                                }

                            }
                            catch (Exception ex)
                            {
                                ErrorSet = "Error: " + ex.ToString();
                                newContact.error += "Error: " + ex.ToString();
                            }
                        }
                    }
                    finally
                    {
                        thisRunspace.Close();
                    }
                }
            }

            if (contact != null && contact.email != newContact.email)
            {
                throw new Exception("Contact Conflict");
            }

            if (contact != null) // If at the end of everything
            {
                newContact.alias = contact.alias;
            }

            return Result;
        }
Exemplo n.º 33
0
        public void AddExchangeUser(ExchangeUser user)
        {
            ContactItem newContact = GetSyncFolder().Items.Add("IPM.Contact") as ContactItem;

            newContact.Update(user);
        }
Exemplo n.º 34
0
        public string GetUserIdentification()
        {
            ExchangeUser currentUser = Application.Session.CurrentUser.AddressEntry.GetExchangeUser();

            return($"{currentUser.FirstName}, {currentUser.LastName}, {currentUser.Department}");
        }
 /// <summary>
 /// Reads a user's properties from the PSObject that is provided
 /// </summary>
 /// <param name="result">A powershell object with member elements</param>
 /// <returns>An exchange user with properties filled out</returns>
 private ExchangeUser ReadUserInformation(PSObject result)
 {
     ExchangeUser user = new ExchangeUser();
     foreach (PSMemberInfo member in result.Members)
     {
         switch (member.Name)
         {
             case "Alias":
                 user.alias = member.Value.ToString().Trim();
                 break;
             case "DistinguishedName":
                 user.dn = member.Value.ToString().Trim();
                 break;
             case "DisplayName":
                 user.cn = member.Value.ToString().Trim();
                 break;
             case "UserPrincipalName":
                 user.upn = member.Value.ToString().Trim();
                 break;
             case "SamAccountName":
                 user.login = member.Value.ToString().Trim();
                 break;
             case "OrganizationalUnit":
                 user.ou = member.Value.ToString().Trim();
                 //user.ou = user.ou.Substring(user.ou.IndexOf('/') + 1);
                 break;
             case "PrimarySmtpAddress":
             case "WindowsEmailAddress":
                 user.email = member.Value.ToString().Trim();
                 break;
             case "IsValid":
                 user.mailboxEnabled = (bool)member.Value;
                 break;
             case "RecipientType":
                 user.type = member.Value.ToString().Trim();
                 break;
         }
     }
     return user;
 }
Exemplo n.º 36
0
        public String GetRecipientEmail(Recipient recipient)
        {
            String retEmail = "";

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry;

            try {
                addressEntry = recipient.AddressEntry;
            } catch {
                log.Warn("Can't resolve this recipient!");
                addressEntry = null;
            }
            if (addressEntry == null)
            {
                log.Warn("No AddressEntry exists!");
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                EmailAddress.IsValidEmail(retEmail);
                return(retEmail);
            }
            log.Fine("AddressEntry Type: " + recipient.AddressEntry.Type);
            if (recipient.AddressEntry.Type == "EX")   //Exchange
            {
                log.Fine("Address is from Exchange");
                if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry ||
                    recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                {
                    ExchangeUser eu = recipient.AddressEntry.GetExchangeUser();
                    if (eu != null && eu.PrimarySmtpAddress != null)
                    {
                        retEmail = eu.PrimarySmtpAddress;
                    }
                    else
                    {
                        log.Warn("Exchange does not have an email for recipient: " + recipient.Name);
                        try {
                            //Should I try PR_EMS_AB_PROXY_ADDRESSES next to cater for cached mode?
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                            retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                            log.Debug("Retrieved from PropertyAccessor instead.");
                        } catch {
                            log.Warn("Also failed to retrieve email from PropertyAccessor.");
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                        }
                    }
                }
                else if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry)
                {
                    log.Fine("This is an Outlook contact");
                    ContactItem contact = null;
                    try {
                        contact = recipient.AddressEntry.GetContact();
                    } catch {
                        log.Warn("Doesn't seem to be a valid contact object. Maybe this account is not longer in Exchange.");
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                    }
                    if (contact != null)
                    {
                        if (contact.Email1AddressType == "EX")
                        {
                            log.Fine("Address is from Exchange.");
                            log.Fine("Using PropertyAccessor to get email address.");
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = contact.PropertyAccessor;
                            retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString();
                        }
                        else
                        {
                            retEmail = contact.Email1Address;
                        }
                    }
                }
                else
                {
                    log.Fine("Exchange type: " + recipient.AddressEntry.AddressEntryUserType.ToString());
                    log.Fine("Using PropertyAccessor to get email address.");
                    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                    retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                }
            }
            else if (recipient.AddressEntry.Type.ToUpper() == "NOTES")
            {
                log.Fine("From Lotus Notes");
                //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
            }
            else
            {
                log.Fine("Not from Exchange");
                retEmail = recipient.AddressEntry.Address;
            }

            if (retEmail.IndexOf("<") > 0)
            {
                retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
            }
            log.Fine("Email address: " + retEmail, retEmail);
            EmailAddress.IsValidEmail(retEmail);
            return(retEmail);
        }
 /// <summary>
 /// Function for creating a single contact. Calls CreateMailContact(ref ExchangeUser newContact, int limiter = 1)
 /// </summary>
 /// <param name="name">The contact name, assumed in the form of "First Last"</param>
 /// <param name="email">The contact's email address</param>
 /// <param name="ou">The organizational unit that this contact will belong to</param>
 /// <param name="alias">Optional alias for the user. If not provided, the alias will be set to whatever name was, minus the spaces</param>
 /// <returns>success</returns>
 public bool CreateMailContact(string name, string email, string ou, string alias = "")
 {
     ExchangeUser contact = new ExchangeUser() { cn = name, email = email, ou = ou, alias = alias, type = "MailContact"};
     bool result = CreateMailContact(ref contact);
     if (!result)
         throw new Exception(contact.error);
     else
         return result;
 }
Exemplo n.º 38
0
        public void TestGetUserStatusForEvent()
        {
            EventEntry googleAppsEvent = new EventEntry("title", "description", "location");
            BusyStatus status = BusyStatus.Busy;
            ExchangeUser user = new ExchangeUser();
            DateTime startDate = new DateTime(2007, 07, 1, 10, 0, 0, DateTimeKind.Utc);
            DateTime endDate = new DateTime(2007, 07, 1, 11, 0, 0, DateTimeKind.Utc);
            When when = new When(startDate, endDate);

            user.Email = "*****@*****.**";

            // The user status with no event times should be free
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            googleAppsEvent.Times.Add(when);

            // The user status with no event status should be busy, since this is how the data
            // comes from the free busy projection
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // The user status for confirmed meeting with no participants should be busy
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // The user status for cancelled meeting (with no participants) should be free
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // The user status for tentative meeting with no participants should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for bogus meeting with no participants should be busy
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            Who john = new Who();
            googleAppsEvent.Participants.Add(john);
            john.Email = user.Email;

            // The user status for confirmed meeting with no participant status should be busy
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // The user status for cancelled meeting (no participant status) should be free
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // The user status for tentative meeting with no participant status should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for bogus meeting with no participant status should be busy
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            john.Attendee_Status = new Who.AttendeeStatus();

            // The user status for any meeting if he declined should be free
            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_DECLINED;
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_ACCEPTED;

            // The user status for confirmed meeting if he accepted should be busy
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            // The user status for cancelled meeting if he accepted should be free
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // The user status for tentative meeting if he accepted should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for bogus meeting if he accepted should be busy
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Busy);

            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_TENTATIVE;

            // The user status for confirmed meeting if he is tentative should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for cancelled meeting if he is tentative should be free
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // The user status for tentative meeting if he is tentative should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for bogus meeting if he is tentative should be tentative
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            john.Attendee_Status.Value = Who.AttendeeStatus.EVENT_INVITED;

            // The user status for confirmed meeting if he did not respond should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.CONFIRMED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for cancelled meeting if he he did not respond should be free
            googleAppsEvent.Status = EventEntry.EventStatus.CANCELED;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Free);

            // The user status for tentative meeting if he did not respond should be tentative
            googleAppsEvent.Status = EventEntry.EventStatus.TENTATIVE;
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);

            // The user status for bogus meeting if he he did not respond should be tentative
            googleAppsEvent.Status = new EventEntry.EventStatus();
            googleAppsEvent.Status.Value = "Abrakadabra";
            status = ConversionsUtil.GetUserStatusForEvent(user, googleAppsEvent);
            Assert.AreEqual(status, BusyStatus.Tentative);
        }
Exemplo n.º 39
0
        public Message GetMailContact(string alias, string email, string displayName)
        {
            try
            {
                ExchangeUser user = new ExchangeUser() { alias = alias, email = email, cn = displayName.Replace('+', ' ') };

                ExchangeUser foundUser = ExchangeRepo.GetMailContact(user);

                if (foundUser == null)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
                }

                return MessageBuilder.CreateResponseMessage(foundUser);
            }
            catch(Exception e)
            {
                string message = "";
                while (e != null)
                {
                    message += e.Message;
                    e = e.InnerException;
                }

                return MessageBuilder.CreateResponseMessage(message);
            }
        }
        /// <summary>
        /// Convert a Google Calender attendee status to an Exchange status
        /// </summary>
        /// <param name="googleAppsEvent">The Google Calendar event</param>
        /// <param name="user">The user to get the status for</param>
        /// <returns>The Exchange status for the given user</returns>
        public static BusyStatus ConvertParticipantStatus(
            ExchangeUser user,
            EventEntry googleAppsEvent)
        {
            BusyStatus result = BusyStatus.Busy;
            // Default is busy, because in order to make free-buys projections work correctly,
            // since in that case the participants are not set at all.

            string externalEmail = ConfigCache.MapToExternalDomain(user.Email);

            foreach (Who participant in googleAppsEvent.Participants)
            {
                if (!string.IsNullOrEmpty(participant.Email) &&
                    (participant.Email.Equals(user.Email) ||
                     participant.Email.Equals(externalEmail)))
                {
                    switch (SafeGetValue(participant.Attendee_Status))
                    {
                        case Who.AttendeeStatus.EVENT_ACCEPTED:
                            result = BusyStatus.Busy;
                            break;

                        case Who.AttendeeStatus.EVENT_DECLINED:
                            result = BusyStatus.Free;
                            break;

                        case Who.AttendeeStatus.EVENT_INVITED:
                            result = BusyStatus.Tentative;
                            break;

                        case Who.AttendeeStatus.EVENT_TENTATIVE:
                            result = BusyStatus.Tentative;
                            break;
                    }

                    break;
                }
            }

            return result;
        }
Exemplo n.º 41
0
 public static ExchangeUser GetMailContact(ExchangeUser user)
 {
     PowerShellComponent.ManagementCommands objManage = new PowerShellComponent.ManagementCommands();
     return XmlSerializationHelper.Deserialize<ExchangeUser>(objManage.GetSerializedMailContact(XmlSerializationHelper.Serialize(user)));
 }
Exemplo n.º 42
0
        /// <summary>
        /// Return the user status, with support for tentative, if the event has the needed details.
        /// </summary>
        /// <param name="googleAppsEvent">The Google Calendar event</param>
        /// <param name="user">The user to get the status for</param>
        /// <returns>The Exchange status for the given user</returns>
        public static BusyStatus GetUserStatusForEvent(
            ExchangeUser user,
            EventEntry googleAppsEvent)
        {
            MeetingStatus meetingStatus = MeetingStatus.Confirmed;
            BusyStatus    userStatus    = BusyStatus.Free;

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Looking the status of {0} in {1}",
                                 user.Email,
                                 googleAppsEvent.Title.Text);
            }

            // Treat events w/o proper times as free. There isn't much we can do.
            if (googleAppsEvent.Times == null || googleAppsEvent.Times.Count == 0)
            {
                return(BusyStatus.Free);
            }

            meetingStatus = ConvertGoogleEventStatus(googleAppsEvent.Status);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("The event status is {0}", meetingStatus.ToString());
            }

            // If the meeting is cancelled, treat it as free time.
            if (meetingStatus == MeetingStatus.Cancelled)
            {
                return(BusyStatus.Free);
            }

            // And if it's transparent, also treat it as free.
            if (GoogleEventIsTransparent(googleAppsEvent))
            {
                return(BusyStatus.Free);
            }

            userStatus = ConvertParticipantStatus(user, googleAppsEvent);
            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("The user status is {0}", userStatus.ToString());
            }

            if (userStatus == BusyStatus.Free)
            {
                return(BusyStatus.Free);
            }

            // There is no mapping from GCal to OOF right now. If/when it is added, it should
            // be handled in a manner similar to busy and tentative.
            Debug.Assert(userStatus != BusyStatus.OutOfOffice);

            // If the meeting is set to show as tentative, set the time as tentative, not busy
            // if the user accepted the meeting.
            if (meetingStatus == MeetingStatus.Tentative && userStatus == BusyStatus.Busy)
            {
                userStatus = BusyStatus.Tentative;
            }

            return(userStatus);
        }
        /// <summary>
        /// Return the user status, with support for tentative, if the event has the needed details.
        /// </summary>
        /// <param name="googleAppsEvent">The Google Calendar event</param>
        /// <param name="user">The user to get the status for</param>
        /// <returns>The Exchange status for the given user</returns>
        public static BusyStatus GetUserStatusForEvent(
            ExchangeUser user,
            EventEntry googleAppsEvent)
        {
            MeetingStatus meetingStatus = MeetingStatus.Confirmed;
            BusyStatus userStatus = BusyStatus.Free;

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Looking the status of {0} in {1}",
                                 user.Email,
                                 googleAppsEvent.Title.Text);
            }

            // Treat events w/o proper times as free. There isn't much we can do.
            if (googleAppsEvent.Times == null || googleAppsEvent.Times.Count == 0)
            {
                return BusyStatus.Free;
            }

            meetingStatus = ConvertGoogleEventStatus(googleAppsEvent.Status);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("The event status is {0}", meetingStatus.ToString());
            }

            // If the meeting is cancelled, treat it as free time.
            if (meetingStatus == MeetingStatus.Cancelled)
            {
                return BusyStatus.Free;
            }

            // And if it's transparent, also treat it as free.
            if (GoogleEventIsTransparent(googleAppsEvent))
            {
                return BusyStatus.Free;
            }

            userStatus = ConvertParticipantStatus(user, googleAppsEvent);
            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("The user status is {0}", userStatus.ToString());
            }

            if (userStatus == BusyStatus.Free)
            {
                return BusyStatus.Free;
            }

            // There is no mapping from GCal to OOF right now. If/when it is added, it should
            // be handled in a manner similar to busy and tentative.
            Debug.Assert(userStatus != BusyStatus.OutOfOffice);

            // If the meeting is set to show as tentative, set the time as tentative, not busy
            // if the user accepted the meeting.
            if (meetingStatus == MeetingStatus.Tentative && userStatus == BusyStatus.Busy)
            {
                userStatus = BusyStatus.Tentative;
            }

            return userStatus;
        }