Ejemplo n.º 1
0
        private static bool GetMailTipsEWS(string ServerVersion, string SendingAs_EmailAddress, string Mailbox_EmailAddress, string Mailbox_RoutingType, string MailTipsRequested, ref string sXMLResponse)
        {
            bool   bSuccess      = false;
            string sResponseText = string.Empty;

            System.Net.HttpWebRequest oHttpWebRequest = null;
            EwsProxyFactory.CreateHttpWebRequest(ref oHttpWebRequest);

            string EwsRequest = string.Empty;

            EwsRequest = TemplateEwsRequests.GetMailTips;

            EwsRequest = EwsRequest.Replace("##RequestServerVersion##", "Exchange2010");
            EwsRequest = EwsRequest.Replace("##SendingAs.EmailAddress##", SendingAs_EmailAddress);
            EwsRequest = EwsRequest.Replace("##Mailbox.EmailAddress##", Mailbox_EmailAddress);
            EwsRequest = EwsRequest.Replace("##Mailbox.RoutingType##", Mailbox_RoutingType);
            EwsRequest = EwsRequest.Replace("##MailTipsRequested##", MailTipsRequested);



            //string sBase64Data = string.Empty;
            //sBase64Data = EWSEditor.Common.FileHelper.GetBinaryFileAsBase64(sFile);
            //System.Diagnostics.Debug.WriteLine("sBase64: " + sBase64Data);
            // EwsRequest = EwsRequest.Replace("##Data##", sBase64Data); // Convert byte array to base64

            // Now inject the base64 body into the stream:
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(EwsRequest);
                oHttpWebRequest.ContentLength = bytes.Length;

                using (Stream requestStream = oHttpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Flush();
                    requestStream.Close();
                }

                // Get response
                HttpWebResponse oHttpWebResponse = (HttpWebResponse)oHttpWebRequest.GetResponse();

                StreamReader oStreadReader = new StreamReader(oHttpWebResponse.GetResponseStream());
                sResponseText = oStreadReader.ReadToEnd();


                if (oHttpWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    bSuccess = true;
                }
                else
                {
                    bSuccess = false;
                }
            }
            finally
            {
            }
            sXMLResponse = sResponseText;
            return(bSuccess);
        }
Ejemplo n.º 2
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            // Validation for credential input...
            if (rdoCredentialsUserSpecified.Checked && (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SPECIFY_CREDS);
                return;
            }

            // Validation for Autodiscover input...

            if (this.rdoAutodiscoverEmail.Checked && String.IsNullOrEmpty(this.AutodiscoverEmailText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for URL input...
            if (this.rdoServiceUrl.Checked && String.IsNullOrEmpty(this.ExchangeServiceURLText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for Impersonation input...
            if (this.ImpersonationCheck.Checked && (String.IsNullOrEmpty(this.ImpersonatedIdTextBox.Text) || !this.connectingIdCombo.SelectedItem.HasValue))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSON_REQ);
                return;
            }

            try
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;

                EwsProxyFactory.RequestedExchangeVersion = exchangeVersionCombo.SelectedItem;

                EwsProxyFactory.OverrideTimezone   = GlobalSettings.OverrideTimezone;
                EwsProxyFactory.SelectedTimeZoneId = GlobalSettings.SelectedTimeZoneId;

                EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;

                EwsProxyFactory.UseDefaultCredentials = this.rdoCredentialsDefaultWindows.Checked;
                if (this.rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.DefaultAuth;
                }

                EwsProxyFactory.CredentialsUserSpecified = this.rdoCredentialsUserSpecified.Checked;

                if (this.rdoCredentialsUserSpecified.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.SpecifiedCredentialsAuth;
                }

                if (this.rdoCredentialsOAuth.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth;
                }

                // MailboxBeingAccessed
                switch (EwsProxyFactory.AuthenticationMethod)
                {
                case RequestedAuthType.DefaultAuth:
                    AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
                    //if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    //    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    break;

                case RequestedAuthType.SpecifiedCredentialsAuth:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    else
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.txtUserName.Text.Trim();
                    }
                    break;

                case RequestedAuthType.oAuth:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();      // override later in ewsproxyfactory
                    break;
                }

                if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                }
                if (this.ImpersonationCheck.Checked) // Override
                {
                    EwsProxyFactory.MailboxBeingAccessed = ImpersonatedIdTextBox.Text.Trim();
                }


                EwsProxyFactory.UserImpersonationSelected = this.ImpersonationCheck.Checked;
                //EwsProxyFactory.UserToImpersonate = this.ImpersonatedIdTextBox.Text  // set below
                EwsProxyFactory.ImpersonationType = this.connectingIdCombo.SelectedItem.Value.ToString();
                EwsProxyFactory.ImpersonatedId    = this.ImpersonatedIdTextBox.Text.Trim();


                EwsProxyFactory.UseoAuth         = this.rdoCredentialsOAuth.Checked;
                EwsProxyFactory.oAuthRedirectUrl = this.txtOAuthRedirectUri.Text.Trim();
                EwsProxyFactory.oAuthClientId    = this.txtOAuthAppId.Text.Trim();
                EwsProxyFactory.oAuthServerName  = this.txtOAuthServerName.Text.Trim();
                EwsProxyFactory.oAuthAuthority   = this.txtOAuthAuthority.Text.Trim();
                EwsProxyFactory.oBearerToken     = string.Empty;

                EwsProxyFactory.EnableScpLookup = GlobalSettings.EnableScpLookups;
                EwsProxyFactory.PreAuthenticate = GlobalSettings.PreAuthenticate;

                EwsProxyFactory.OverrideTimeout = GlobalSettings.OverrideTimeout;
                EwsProxyFactory.Timeout         = GlobalSettings.Timeout;
                EwsProxyFactory.UserAgent       = GlobalSettings.UserAgent;

                EwsProxyFactory.UserName = this.txtUserName.Text.Trim();
                // EwsProxyFactory.Password = this.txtPassword.Text.Trim();   // Don't keep.
                EwsProxyFactory.Domain = this.txtDomain.Text.Trim();

                EwsProxyFactory.SetDefaultProxy            = GlobalSettings.SetDefaultProxy;
                EwsProxyFactory.BypassProxyForLocalAddress = GlobalSettings.BypassProxyForLocalAddress;
                EwsProxyFactory.SpecifyProxySettings       = GlobalSettings.SpecifyProxySettings;
                EwsProxyFactory.ProxyServerName            = GlobalSettings.ProxyServerName;
                EwsProxyFactory.ProxyServerPort            = GlobalSettings.ProxyServerPort;
                EwsProxyFactory.OverrideProxyCredentials   = GlobalSettings.OverrideProxyCredentials;
                EwsProxyFactory.ProxyServerUser            = GlobalSettings.ProxyServerUser;
                EwsProxyFactory.ProxyServerPassword        = GlobalSettings.ProxyServerPassword;
                EwsProxyFactory.ProxyServerDomain          = GlobalSettings.ProxyServerDomain;



                EwsProxyFactory.EwsUrl = this.rdoAutodiscoverEmail.Checked ?
                                         null : new Uri(ExchangeServiceURLText.Text.Trim());

                EwsProxyFactory.UserToImpersonate = this.ImpersonationCheck.Checked ?
                                                    new ImpersonatedUserId(this.connectingIdCombo.SelectedItem.Value, this.ImpersonatedIdTextBox.Text.Trim()) : null;

                EwsProxyFactory.SetXAnchorMailbox = this.chkSetXAnchorMailbox.Checked;
                EwsProxyFactory.XAnchorMailbox    = this.txtXAnchorMailbox.Text.Trim();

                EwsProxyFactory.SetXPublicFolderMailbox = this.chkSetXPublicFolderMailbox.Checked;
                EwsProxyFactory.XPublicFolderMailbox    = this.txtXPublicFolderMailbox.Text.Trim();



                EwsProxyFactory.EnableAdditionalHeader1 = GlobalSettings.EnableAdditionalHeader1;
                EwsProxyFactory.AdditionalHeader1       = GlobalSettings.AdditionalHeader1;
                EwsProxyFactory.AdditionalHeaderValue1  = GlobalSettings.AdditionalHeaderValue1;
                EwsProxyFactory.EnableAdditionalHeader2 = GlobalSettings.EnableAdditionalHeader2;
                EwsProxyFactory.AdditionalHeader2       = GlobalSettings.AdditionalHeader2;
                EwsProxyFactory.AdditionalHeaderValue2  = GlobalSettings.AdditionalHeaderValue2;
                EwsProxyFactory.EnableAdditionalHeader3 = GlobalSettings.EnableAdditionalHeader3;
                EwsProxyFactory.AdditionalHeader3       = GlobalSettings.AdditionalHeader3;
                EwsProxyFactory.AdditionalHeaderValue3  = GlobalSettings.AdditionalHeaderValue3;

                EwsProxyFactory.AddTimeZoneContext        = GlobalSettings.AddTimeZoneContext;
                EwsProxyFactory.SelectedTimeZoneContextId = GlobalSettings.SelectedTimeZoneContextId;


                EwsProxyFactory.ServiceEmailAddress = this.AutodiscoverEmailText.Text.Trim();
                EwsProxyFactory.UseAutoDiscover     = this.rdoAutodiscoverEmail.Checked;

                //EwsProxyFactory.ServiceCredential = rdoCredentialsUserSpecified.Checked ?
                //   new NetworkCredential(
                //       this.txtUserName.Text.Trim(),
                //       this.txtPassword.Text.Trim(),  // This will fail on passwords ending with whitespace
                //       this.txtDomain.Text.Trim()) :
                //   null;

                // ----- Set Credentials ----
                EwsProxyFactory.ServiceCredential        = null;
                EwsProxyFactory.ServiceNetworkCredential = null;

                if (rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.ServiceCredential = (NetworkCredential)CredentialCache.DefaultCredentials;

                    EwsProxyFactory.ServiceNetworkCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
                }

                if (rdoCredentialsUserSpecified.Checked)
                {
                    NetworkCredential oNetworkCredential = new NetworkCredential(
                        this.txtUserName.Text.Trim(),
                        this.txtPassword.Text.Trim(), // This will fail on passwords ending with whitespace
                        this.txtDomain.Text.Trim());

                    EwsProxyFactory.ServiceCredential = oNetworkCredential;

                    EwsProxyFactory.ServiceNetworkCredential = oNetworkCredential;
                }


                if (this.rdoCredentialsOAuth.Checked)
                {
                    AuthenticationHelper oAH = new AuthenticationHelper();
                    string sBearerToken      = string.Empty;
                    EwsProxyFactory.ServiceCredential = oAH.Do_OAuth(ref EwsProxyFactory.MailboxBeingAccessed, ref EwsProxyFactory.AccountAccessingMailbox,
                                                                     EwsProxyFactory.oAuthAuthority, EwsProxyFactory.oAuthClientId, EwsProxyFactory.oAuthRedirectUrl, EwsProxyFactory.oAuthServerName, ref sBearerToken);

                    EwsProxyFactory.oBearerToken = sBearerToken;

                    //EwsProxyFactory.AccountAccessingMailbox
                    //EwsProxyFactory.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                }

                // ----    Autodiscover    ----

                if (this.rdoAutodiscoverEmail.Checked)
                {
                    EwsProxyFactory.DoAutodiscover();
                }

                // ----    New service & app settings    ----

                CurrentService = EwsProxyFactory.CreateExchangeService();


                // ----    Save settings    ----
                EWSEditor.Common.EwsEditorAppSettings oAppSettings = new EwsEditorAppSettings();
                EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);
                CurrentAppSettings = oAppSettings;



                //CurrentAppSettings.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                // CurrentAppSettings

                // EwsProxyFactory.AccountAccessingMailbox

                // ----    Do a basic test to be sure that the mailbox can be reached with an EWS call   ----
                CurrentService.TestExchangeService();

                CurrentService.OnSerializeCustomSoapHeaders += m_Service_OnSerializeCustomSoapHeaders;


                DialogResult = DialogResult.OK;
            }
            finally
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }
Ejemplo n.º 3
0
        private void lstEvents_DoubleClick(object sender, EventArgs e)
        {
            string ParentFolderName     = string.Empty;
            string ParentFolderClass    = string.Empty;
            string OldParentFolderName  = string.Empty;
            string OldParentFolderClass = string.Empty;

            string ItemName     = string.Empty;
            string ItemClass    = string.Empty;
            string OldItemName  = string.Empty;
            string OldItemClass = string.Empty;

            string FolderEvent_FolderName  = string.Empty;
            string FolderEvent_FolderClass = string.Empty;
            string Folder_OldFolderName    = string.Empty;
            string Folder_OldFolderClass   = string.Empty;

            Folder          oFolderId        = null;
            Item            oItem            = null;
            ExchangeService oExchangeService = null;



            if (lstEvents.SelectedItems.Count > 0)
            {
                if (lstEvents.SelectedItems[0].Tag.ToString().StartsWith("[") == false)
                {
                    NotificationEvent evt = (NotificationEvent)lstEvents.SelectedItems[0].Tag;

                    ItemEvent itemevt = (evt is ItemEvent) ? (ItemEvent)evt : null;

                    FolderEvent folderevt = (evt is FolderEvent) ? (FolderEvent)evt : null;

                    // New service and app settings
                    EWSEditor.Common.EwsEditorAppSettings oCurrentAppSettings = new EWSEditor.Common.EwsEditorAppSettings();
                    oExchangeService = EwsProxyFactory.CreateExchangeService();
                    // Todo: Flush out oCurrentAppSettings
                    CurrentAppSettings = oCurrentAppSettings;

                    if (lstEvents.SelectedItems[0].SubItems[4].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oFolderId = Folder.Bind(oExchangeService, new FolderId(evt.ParentFolderId.UniqueId));
                            if (oFolderId != null)
                            {
                                ParentFolderName  = oFolderId.DisplayName;
                                ParentFolderClass = oFolderId.FolderClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }
                    if (lstEvents.SelectedItems[0].SubItems[5].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oFolderId = Folder.Bind(oExchangeService, new FolderId(evt.OldParentFolderId.UniqueId));
                            if (oFolderId != null)
                            {
                                OldParentFolderName  = oFolderId.DisplayName;
                                OldParentFolderClass = oFolderId.FolderClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }
                    if (lstEvents.SelectedItems[0].SubItems[6].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oItem = Item.Bind(oExchangeService, new ItemId(itemevt.ItemId.UniqueId));
                            if (oItem != null)
                            {
                                ItemName  = oItem.Subject;
                                ItemClass = oItem.ItemClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }
                    if (lstEvents.SelectedItems[0].SubItems[7].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oItem = Item.Bind(oExchangeService, new ItemId(itemevt.OldItemId.UniqueId));
                            if (oItem != null)
                            {
                                OldItemName  = oItem.Subject;
                                OldItemClass = oItem.ItemClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }
                    if (lstEvents.SelectedItems[0].SubItems[8].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oFolderId = Folder.Bind(oExchangeService, new FolderId(folderevt.ParentFolderId.UniqueId));
                            if (oFolderId != null)
                            {
                                FolderEvent_FolderName  = oFolderId.DisplayName;
                                FolderEvent_FolderClass = oFolderId.FolderClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }
                    if (lstEvents.SelectedItems[0].SubItems[9].Text.TrimEnd().Length != 0)
                    {
                        try
                        {
                            oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                            oFolderId = Folder.Bind(oExchangeService, new FolderId(folderevt.OldParentFolderId.UniqueId));
                            if (oFolderId != null)
                            {
                                Folder_OldFolderName  = oFolderId.DisplayName;
                                Folder_OldFolderClass = oFolderId.FolderClass;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: " + ex.ToString());
                        }
                    }

                    StringBuilder oSB = new StringBuilder();
                    oSB.AppendFormat("EventType:                \r\n    {0}\r\n", lstEvents.SelectedItems[0].Text);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("Thread:                   \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[1].Text);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("TimeStamp:                \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[2].Text);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("EventType:                \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[3].Text);
                    oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("ParentFolderId:\r\n");
                    if (evt != null)
                    {
                        if (evt.ParentFolderId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", evt.ParentFolderId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", evt.ParentFolderId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", ParentFolderName);
                            oSB.AppendFormat("    Class:     {0}\r\n", ParentFolderClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("OldParentFolderId:\r\n");
                    if (evt != null)
                    {
                        if (evt.OldParentFolderId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", evt.OldParentFolderId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", evt.OldParentFolderId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", OldParentFolderName);
                            oSB.AppendFormat("    Class:     {0}\r\n", OldParentFolderClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("Item.ItemId:\r\n");
                    if (itemevt != null)
                    {
                        if (itemevt.ItemId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", itemevt.ItemId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", itemevt.ItemId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", ItemName);
                            oSB.AppendFormat("    Class:     {0}\r\n", ItemClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("Item.OldItemId:\r\n");
                    if (itemevt != null)
                    {
                        if (itemevt.OldItemId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", itemevt.OldItemId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", itemevt.OldItemId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", OldItemName);
                            oSB.AppendFormat("    Class:     {0}\r\n", OldItemClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");


                    oSB.AppendFormat("FolderEvent.FolderId:\r\n");
                    if (folderevt != null)
                    {
                        if (folderevt.ParentFolderId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", folderevt.ParentFolderId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", folderevt.ParentFolderId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", FolderEvent_FolderName);
                            oSB.AppendFormat("    Class:     {0}\r\n", FolderEvent_FolderClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("Folder.OldFolderId:\r\n");
                    if (folderevt != null)
                    {
                        if (folderevt.OldParentFolderId != null)
                        {
                            oSB.AppendFormat("    UniqueId:  {0}\r\n", folderevt.OldParentFolderId.UniqueId.ToString());
                            oSB.AppendFormat("    ChangeKey: {0}\r\n", folderevt.OldParentFolderId.ChangeKey.ToString());
                            oSB.AppendFormat("    Name:      {0}\r\n", Folder_OldFolderName);
                            oSB.AppendFormat("    Class:     {0}\r\n", Folder_OldFolderClass);
                        }
                    }
                    oSB.AppendFormat("\r\n");

                    //oSB.AppendFormat("ParentFolderId:           \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[4].Text.TrimEnd().Replace("ChangeKey:", "\r\n    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");
                    //oSB.AppendFormat("OldParentFolderId:        \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[5].Text.TrimEnd().Replace("ChangeKey:", "\r\n    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");

                    //oSB.AppendFormat("Item.ItemId:              \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[6].Text.TrimEnd().Replace("ChangeKey:", "    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");
                    //oSB.AppendFormat("Item.OldItemId:           \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[7].Text.TrimEnd().Replace("ChangeKey:", "    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");

                    //oSB.AppendFormat("FolderEvent.FolderId:     \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[8].Text.TrimEnd().Replace("ChangeKey:", "\r\n    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");
                    //oSB.AppendFormat("Folder.OldFolderId:       \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[9].Text.TrimEnd().Replace("ChangeKey:", "    ChangeKey:"));
                    //oSB.AppendFormat("\r\n");

                    oSB.AppendFormat("FolderEvent.UnreadCount:  \r\n    {0}\r\n", lstEvents.SelectedItems[0].SubItems[10].Text);

                    string sContent = oSB.ToString();

                    ShowTextDocument oForm = new ShowTextDocument();
                    oForm.txtEntry.WordWrap = false;
                    oForm.Text          = "Information";
                    oForm.txtEntry.Text = sContent;
                    oForm.ShowDialog();
                }
            }
        }
Ejemplo n.º 4
0
        ////DJB
        //private void GetGroupingInfo(ExchangeService oExchangeService, string DiscoverMailbox)
        //{
        //    //oExchangeService.get
        //    string UseVersion = oExchangeService.RequestedServerVersion.ToString();
        //    string UseUrl = oExchangeService.Url.ToString();  // djb - need to fix it to the autodiscover url.

        //    string EwsRequest = EwsRequests.GroupingInformationTemplateRequest;
        //    EwsRequest =  EwsRequest.Replace("XXXExchangeVersionXXX",  UseVersion);
        //    EwsRequest =  EwsRequest.Replace("XXXAutoDiscoverServiceServerXXX", UseUrl);
        //    EwsRequest =  EwsRequest.Replace("XXXMailboxSmtpXXX", DiscoverMailbox);

        //    // DO raw post
        //    // string sResponse
        //    // if (DoRawPost(UseUrl, oExchangeService.ServerCredentials, EwsRequest, ref sResponse));
        //    // {
        //    //    Extract GroupingInformation and external url from sResponse);
        //    // }
        //    // else
        //    // {
        //    //    return error;
        //    // }
        //}

        private void StreamingSubscribeWork()
        {
            // djb
            // get a list of maiboxes, thier external ews urls and grouping info
            // list of items = GetGroupingInfo(ExchangeService oExchangeService, string DiscoverMailbox);
            // Sort list of items by url + GroupingInformaiton
            //

            try
            {
                lock (WorkThreads)
                {
                    WorkThreads.Add(Thread.CurrentThread);
                    SetControlText(ThreadCount, WorkThreads.Count.ToString());
                }

                if (chkSerialize.Checked)
                {
                    mutConnection.WaitOne();
                }

                string       TID  = Thread.CurrentThread.ManagedThreadId.ToString("[0]");
                ListViewItem item = new ListViewItem();
                item.Tag  = "[local]ThreadStart";
                item.Text = "[local]ThreadStart";
                item.SubItems.Add(TID);
                item.SubItems.Add(DateTime.Now.ToString());
                AddToDisplay(lstEvents, item);

                // Note that EWS Managed API objects should not beshared accross threads - So, each thread should have its own service object.
                //EWSEditor.Common.EwsEditorServiceInstanceSettings.EwsEditorAppSettings oSettings = new EWSEditor.Common.EwsEditorServiceInstanceSettings.EwsEditorAppSettings();


                EWSEditor.Common.EwsEditorAppSettings oCurrentAppSettings = null;
                ExchangeService ThreadLocalService = EwsProxyFactory.CreateExchangeService( );
                // Todo: Flush out oCurrentAppSettings
                CurrentAppSettings = oCurrentAppSettings;

                List <StreamingSubscription> ThreadLocalSubscriptions = new List <StreamingSubscription>();

                // Create the subscriptions based on the form settings
                for (int i = 0; i < numSubs.Value; i++)
                {
                    try
                    {
                        StreamingSubscription CurrentSubscription = null;
                        if (chkAllFoldes.Checked == false)
                        {
                            CurrentSubscription = ThreadLocalService.SubscribeToStreamingNotifications(
                                new FolderId[] { this.CurrentFolderId },
                                EventTypes.ToArray());
                            //System.Diagnostics.Debug.WriteLine("-");
                            //System.Diagnostics.Debug.WriteLine("Subscribe - ID: " + CurrentSubscription.Id + "  Watermark: " + CurrentSubscription.Watermark);
                            //System.Diagnostics.Debug.WriteLine("-");
                        }
                        else
                        {
                            CurrentSubscription = ThreadLocalService.SubscribeToStreamingNotificationsOnAllFolders(
                                EventTypes.ToArray());
                            //System.Diagnostics.Debug.WriteLine("-");
                            //System.Diagnostics.Debug.WriteLine("Subscribe - ID: " + CurrentSubscription.Id + "  Watermark: " + CurrentSubscription.Watermark);
                            //System.Diagnostics.Debug.WriteLine("-");
                        }

                        ThreadLocalSubscriptions.Add(CurrentSubscription);
                        lock (ActiveSubscriptions)
                        {
                            ActiveSubscriptions.Add(CurrentSubscription);
                            SetControlText(SubscriptionCount, ActiveSubscriptions.Count.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugLog.WriteException("Error Subscribe or Add [TID:" + TID + "]", ex);
                        item             = new ListViewItem();
                        item.Tag         = "[local]SubscribeError";
                        item.Text        = "[local]SubscribeError";
                        item.ToolTipText = ex.ToString();
                        item.SubItems.Add(TID);
                        item.SubItems.Add(DateTime.Now.ToString());
                        AddToDisplay(lstEvents, item);
                    }
                }

                // Create a new StreamingSubscriptionConnection
                StreamingSubscriptionConnection CurrentConnection = new StreamingSubscriptionConnection(ThreadLocalService, (int)SubscriptionLifetime.Value);

                lock (ActiveConnections)
                {
                    ActiveConnections.Add(CurrentConnection);
                    SetControlText(ConnectionCount, ActiveConnections.Count.ToString());
                }

                // Add Handlers
                CurrentConnection.OnDisconnect        += OnDisconnect;
                CurrentConnection.OnSubscriptionError += OnSubscriptionError;
                CurrentConnection.OnNotificationEvent += OnStreamingEvent;


                // Add the Subscriptions to the Connection
                foreach (StreamingSubscription CurrentSubscription in ThreadLocalSubscriptions)
                {
                    CurrentConnection.AddSubscription(CurrentSubscription);
                }

                if (chkSerialize.Checked)
                {
                    mutConnection.ReleaseMutex();
                }

                // Open the Connection
                try
                {
                    if (ThreadLocalService.CookieContainer.Count > 0)
                    {
                        System.Net.CookieCollection MyCookies = ThreadLocalService.CookieContainer.GetCookies(ThreadLocalService.Url);
                    }
                    CurrentConnection.Open();

                    ShutdownThreads.WaitOne();
                }
                catch (Exception ex)
                {
                    DebugLog.WriteException("Error Opening StreamingSubscriptionConnection [TID:"
                                            + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                    item             = new ListViewItem();
                    item.Tag         = "[local]OpenError";
                    item.Text        = "[local]OpenError";
                    item.ToolTipText = ex.ToString();
                    item.SubItems.Add(TID);
                    item.SubItems.Add(DateTime.Now.ToString());
                    AddToDisplay(lstEvents, item);

                    //System.Diagnostics.Debug.WriteLine("-");
                    //System.Diagnostics.Debug.WriteLine("Error Opening StreamingSubscriptionConnection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                    //System.Diagnostics.Debug.WriteLine("-");
                }

                try
                {
                    //  Close Connection
                    if (CurrentConnection.IsOpen)
                    {
                        CurrentConnection.Close();
//                        Thread.Sleep(500);
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.WriteException("Error Closing Streaming Connection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                    item             = new ListViewItem();
                    item.Tag         = "[local]CloseError";
                    item.Text        = "[local]CloseError";
                    item.ToolTipText = ex.ToString();
                    item.SubItems.Add(TID);
                    item.SubItems.Add(DateTime.Now.ToString());
                    AddToDisplay(lstEvents, item);

                    //System.Diagnostics.Debug.WriteLine("-");
                    //System.Diagnostics.Debug.WriteLine("Error Closing Streaming Connection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                    //System.Diagnostics.Debug.WriteLine("-");
                }
                finally
                {
                    lock (ActiveConnections)
                    {
                        ActiveConnections.Remove(CurrentConnection);
                        SetControlText(ConnectionCount, ActiveConnections.Count.ToString());
                    }
                }

                //  Remove Handlers
                CurrentConnection.OnDisconnect        -= OnDisconnect;
                CurrentConnection.OnSubscriptionError -= OnSubscriptionError;
                CurrentConnection.OnNotificationEvent -= OnStreamingEvent;

                foreach (StreamingSubscription CurrentSubscription in ThreadLocalSubscriptions)
                {
                    try
                    {
                        CurrentConnection.RemoveSubscription(CurrentSubscription);
                        CurrentSubscription.Unsubscribe();

                        //System.Diagnostics.Debug.WriteLine("-");
                        //System.Diagnostics.Debug.WriteLine("Unsubscribed - ID: " + CurrentSubscription.Id + "  Watermark: " + CurrentSubscription.Watermark);
                        //System.Diagnostics.Debug.WriteLine("-");
                    }
                    catch (Exception ex)
                    {
                        DebugLog.WriteException("Error Removing/Unsubscribing StreamingSubscription Elements [TID:"
                                                + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                        item             = new ListViewItem();
                        item.Tag         = "[local]UnsubscribeError";
                        item.Text        = "[local]UnsubscribeError";
                        item.ToolTipText = ex.ToString();
                        item.SubItems.Add(TID);
                        item.SubItems.Add(DateTime.Now.ToString());
                        AddToDisplay(lstEvents, item);

                        //System.Diagnostics.Debug.WriteLine("-");
                        //System.Diagnostics.Debug.WriteLine("Error Removing/Unsubscribing StreamingSubscription Elements [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex);
                        //System.Diagnostics.Debug.WriteLine("        ID: " + CurrentSubscription.Id + "  Watermark: " + CurrentSubscription.Watermark);
                        //System.Diagnostics.Debug.WriteLine("-");
                    }
                    finally
                    {
                        lock (ActiveSubscriptions)
                        {
                            //System.Diagnostics.Debug.WriteLine("-");
                            //System.Diagnostics.Debug.WriteLine("Removing subscription - ID: " + CurrentSubscription.Id + "  Watermark: " + CurrentSubscription.Watermark);
                            //System.Diagnostics.Debug.WriteLine("-");

                            ActiveSubscriptions.Remove(CurrentSubscription);
                            SetControlText(SubscriptionCount, ActiveSubscriptions.Count.ToString());
                        }
                    }
                }

                lock (WorkThreads)
                {
                    WorkThreads.Remove(Thread.CurrentThread);
                }
                SetControlText(ThreadCount, WorkThreads.Count.ToString());
            }
            catch (Exception ex) { DebugLog.WriteException("Unexpected Exception in WorkerThread", ex); }
            finally { }
        }
Ejemplo n.º 5
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (rdoCredentialsOAuth2.Checked == true)
            {
                if (txtOAuthApplicationId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Applicaiton Id is required for oAuth.");
                    return;
                }
                if (txtOAuthTenantId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Tenant Id is required for oAuth.");
                    return;
                }
            }


            // Doing App permissions flow?
            if (rdoCredentialsOAuth2.Checked == true && rdoCredentialsOAuthApplication.Checked)
            {
                if (txtOAuthTenantId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Client Secret is required for oAuth Applicaiton permissions flow.");
                    return;
                }

                if (this.ImpersonationCheck.Checked == false || this.ImpersonatedIdTextBox.Text.Trim() == string.Empty)
                {
                    // Impersonation is required for app permissions flow
                    ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSONATION_NEEDED_FOR_APP_PERMISSIONS_FLOW);
                    return;
                }

                // X-AnchorMailbox is required
                if (this.chkSetXAnchorMailbox.Checked == false || this.txtXAnchorMailbox.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo(DisplayStrings.MSG_XANCHORMAILBOX_FOR_APP_PERMISSIONS_FLOW);
                    return;
                }
            }
            // Validation for credential input...
            if (rdoCredentialsUserSpecified.Checked && (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SPECIFY_CREDS);
                return;
            }

            // Validation for Autodiscover input...

            if (this.rdoAutodiscoverEmail.Checked && String.IsNullOrEmpty(this.AutodiscoverEmailText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for URL input...
            if (this.rdoServiceUrl.Checked && String.IsNullOrEmpty(this.ExchangeServiceURLText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for Impersonation input...
            if (this.ImpersonationCheck.Checked && (String.IsNullOrEmpty(this.ImpersonatedIdTextBox.Text) || !this.connectingIdCombo.SelectedItem.HasValue))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSON_REQ);
                return;
            }

            // Impersonation should always need X-AnchorMailbox header set or call will fail at any time.
            if (this.ImpersonationCheck.Checked == true && this.chkSetXAnchorMailbox.Checked == false)
            {
                ErrorDialog.ShowInfo(DisplayStrings.WARN_IMPERSONATION_NEEDS_XANCHORMAILBOX);
            }

            try
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;

                EwsProxyFactory.RequestedExchangeVersion = exchangeVersionCombo.SelectedItem;

                EwsProxyFactory.OverrideTimezone   = GlobalSettings.OverrideTimezone;
                EwsProxyFactory.SelectedTimeZoneId = GlobalSettings.SelectedTimeZoneId;

                EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;

                EwsProxyFactory.UseDefaultCredentials = this.rdoCredentialsDefaultWindows.Checked;
                if (this.rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.DefaultAuth;
                }

                EwsProxyFactory.CredentialsUserSpecified = this.rdoCredentialsUserSpecified.Checked;

                if (this.rdoCredentialsUserSpecified.Checked == true)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.SpecifiedCredentialsAuth;
                }

                if (this.rdoCredentialsOAuth.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth;
                }

                if (this.rdoCredentialsOAuth2.Checked)
                {
                    if (this.rdoCredentialsOAuthDelegated.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Delegate;
                    }

                    if (this.rdoCredentialsOAuthApplication.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Application;
                    }

                    if (this.rdoCredentialsOAuthCertificate.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Certificate;
                    }
                }

                // MailboxBeingAccessed
                EwsProxyFactory.MailboxBeingAccessed = string.Empty;
                switch (EwsProxyFactory.AuthenticationMethod)
                {
                case RequestedAuthType.DefaultAuth:
                    AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
                    break;

                case RequestedAuthType.SpecifiedCredentialsAuth:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    else
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.txtUserName.Text.Trim();
                    }
                    break;

                case RequestedAuthType.oAuth2Application:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    break;

                case RequestedAuthType.oAuth2Delegate:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    break;

                default:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();      // override later in ewsproxyfactory (for oAuth)
                    break;
                }

                if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                }
                if (this.ImpersonationCheck.Checked) // Override
                {
                    EwsProxyFactory.MailboxBeingAccessed = ImpersonatedIdTextBox.Text.Trim();
                }

                if (EwsProxyFactory.MailboxBeingAccessed == string.Empty && this.chkSetXAnchorMailbox.Checked && this.txtXAnchorMailbox.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.txtXAnchorMailbox.Text.Trim();
                }


                EwsProxyFactory.UserImpersonationSelected = this.ImpersonationCheck.Checked;
                //EwsProxyFactory.UserToImpersonate = this.ImpersonatedIdTextBox.Text  // set below
                EwsProxyFactory.ImpersonationType = this.connectingIdCombo.SelectedItem.Value.ToString();
                EwsProxyFactory.ImpersonatedId    = this.ImpersonatedIdTextBox.Text.Trim();


                EwsProxyFactory.UseoAuth         = this.rdoCredentialsOAuth.Checked;
                EwsProxyFactory.oAuthRedirectUrl = this.txtOAuthRedirectUri.Text.Trim();
                EwsProxyFactory.oAuthClientId    = this.txtOAuthAppId.Text.Trim();
                EwsProxyFactory.oAuthServerName  = this.txtOAuthServerName.Text.Trim();
                EwsProxyFactory.oAuthAuthority   = this.txtOAuthAuthority.Text.Trim();

                EwsProxyFactory.UseoAuth2           = this.rdoCredentialsOAuth2.Checked;
                EwsProxyFactory.UseOAuthDelegate    = this.rdoCredentialsOAuthDelegated.Checked;
                EwsProxyFactory.UseOAuthApplication = this.rdoCredentialsOAuthApplication.Checked;
                EwsProxyFactory.oAuthApplicationId  = this.txtOAuthApplicationId.Text.Trim();
                EwsProxyFactory.oAuthTenantId       = this.txtOAuthTenantId.Text.Trim();
                EwsProxyFactory.oAuthClientSecret   = this.txtOAuthClientSecret.Text.Trim();
                // EwsProxyFactory.oAuthCertificate = this.txtAuthCertificate.Text.Trim();
                EwsProxyFactory.oBearerToken     = string.Empty;
                EwsProxyFactory.LogSecurityToken = GlobalSettings.LogSecurityToken;


                EwsProxyFactory.EnableScpLookup = GlobalSettings.EnableScpLookups;
                EwsProxyFactory.PreAuthenticate = GlobalSettings.PreAuthenticate;

                EwsProxyFactory.OverrideTimeout = GlobalSettings.OverrideTimeout;
                EwsProxyFactory.Timeout         = GlobalSettings.Timeout;
                EwsProxyFactory.UserAgent       = GlobalSettings.UserAgent;

                EwsProxyFactory.UserName = this.txtUserName.Text.Trim();
                // EwsProxyFactory.Password = this.txtPassword.Text.Trim();   // Don't keep.
                EwsProxyFactory.Domain = this.txtDomain.Text.Trim();

                EwsProxyFactory.SetDefaultProxy            = GlobalSettings.SetDefaultProxy;
                EwsProxyFactory.BypassProxyForLocalAddress = GlobalSettings.BypassProxyForLocalAddress;
                EwsProxyFactory.SpecifyProxySettings       = GlobalSettings.SpecifyProxySettings;
                EwsProxyFactory.ProxyServerName            = GlobalSettings.ProxyServerName;
                EwsProxyFactory.ProxyServerPort            = GlobalSettings.ProxyServerPort;
                EwsProxyFactory.OverrideProxyCredentials   = GlobalSettings.OverrideProxyCredentials;
                EwsProxyFactory.ProxyServerUser            = GlobalSettings.ProxyServerUser;
                EwsProxyFactory.ProxyServerPassword        = GlobalSettings.ProxyServerPassword;
                EwsProxyFactory.ProxyServerDomain          = GlobalSettings.ProxyServerDomain;



                EwsProxyFactory.EwsUrl = this.rdoAutodiscoverEmail.Checked ?
                                         null : new Uri(ExchangeServiceURLText.Text.Trim());

                EwsProxyFactory.UserToImpersonate = this.ImpersonationCheck.Checked ?
                                                    new ImpersonatedUserId(this.connectingIdCombo.SelectedItem.Value, this.ImpersonatedIdTextBox.Text.Trim()) : null;

                EwsProxyFactory.SetXAnchorMailbox = this.chkSetXAnchorMailbox.Checked;
                EwsProxyFactory.XAnchorMailbox    = this.txtXAnchorMailbox.Text.Trim();

                EwsProxyFactory.SetXPublicFolderMailbox = this.chkSetXPublicFolderMailbox.Checked;
                EwsProxyFactory.XPublicFolderMailbox    = this.txtXPublicFolderMailbox.Text.Trim();



                EwsProxyFactory.EnableAdditionalHeader1 = GlobalSettings.EnableAdditionalHeader1;
                EwsProxyFactory.AdditionalHeader1       = GlobalSettings.AdditionalHeader1;
                EwsProxyFactory.AdditionalHeaderValue1  = GlobalSettings.AdditionalHeaderValue1;
                EwsProxyFactory.EnableAdditionalHeader2 = GlobalSettings.EnableAdditionalHeader2;
                EwsProxyFactory.AdditionalHeader2       = GlobalSettings.AdditionalHeader2;
                EwsProxyFactory.AdditionalHeaderValue2  = GlobalSettings.AdditionalHeaderValue2;
                EwsProxyFactory.EnableAdditionalHeader3 = GlobalSettings.EnableAdditionalHeader3;
                EwsProxyFactory.AdditionalHeader3       = GlobalSettings.AdditionalHeader3;
                EwsProxyFactory.AdditionalHeaderValue3  = GlobalSettings.AdditionalHeaderValue3;

                EwsProxyFactory.AddTimeZoneContext        = GlobalSettings.AddTimeZoneContext;
                EwsProxyFactory.SelectedTimeZoneContextId = GlobalSettings.SelectedTimeZoneContextId;


                EwsProxyFactory.ServiceEmailAddress = this.AutodiscoverEmailText.Text.Trim();
                EwsProxyFactory.UseAutoDiscover     = this.rdoAutodiscoverEmail.Checked;

                //EwsProxyFactory.ServiceCredential = rdoCredentialsUserSpecified.Checked ?
                //   new NetworkCredential(
                //       this.txtUserName.Text.Trim(),
                //       this.txtPassword.Text.Trim(),  // This will fail on passwords ending with whitespace
                //       this.txtDomain.Text.Trim()) :
                //   null;

                // ----- Set Credentials ----
                EwsProxyFactory.ServiceCredential        = null;
                EwsProxyFactory.ServiceNetworkCredential = null;

                if (rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.ServiceCredential = (NetworkCredential)CredentialCache.DefaultCredentials;

                    EwsProxyFactory.ServiceNetworkCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
                }

                if (rdoCredentialsUserSpecified.Checked)
                {
                    NetworkCredential oNetworkCredential = new NetworkCredential(
                        this.txtUserName.Text.Trim(),
                        this.txtPassword.Text.Trim(), // This will fail on passwords ending with whitespace
                        this.txtDomain.Text.Trim());

                    EwsProxyFactory.ServiceCredential = oNetworkCredential;

                    EwsProxyFactory.ServiceNetworkCredential = oNetworkCredential;
                }

                // Delegagte oAuth 1
                if (this.rdoCredentialsOAuth.Checked)
                {
                    AuthenticationHelper oAH = new AuthenticationHelper();
                    string sBearerToken      = string.Empty;
                    EwsProxyFactory.ServiceCredential = oAH.Do_OAuth(ref EwsProxyFactory.MailboxBeingAccessed, ref EwsProxyFactory.AccountAccessingMailbox,
                                                                     EwsProxyFactory.oAuthAuthority, EwsProxyFactory.oAuthClientId, EwsProxyFactory.oAuthRedirectUrl, EwsProxyFactory.oAuthServerName, ref sBearerToken);

                    EwsProxyFactory.oBearerToken = sBearerToken;
                }


                // oAuth2
                if (this.rdoCredentialsOAuth2.Checked)
                {
                    // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
                    // Microsoft.Identity.Client is available under NewGet
                    // https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token?tabs=dotnet

                    // https://www.skylinetechnologies.com/Blog/Skyline-Blog/December_2018/async-await-configureawait

                    // Get Access token -----------------

                    if (this.rdoCredentialsOAuthDelegated.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();
                        AuthenticationResult oResult        = System.Threading.Tasks.Task.Run(async() => await o.GetDelegateToken(EwsProxyFactory.oAuthApplicationId, EwsProxyFactory.oAuthTenantId)).Result;
                        EwsProxyFactory.MsalAuthenticationResult = oResult;
                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;

                        EwsProxyFactory.MailboxBeingAccessed = oResult.Account.Username;
                    }

                    if (this.rdoCredentialsOAuthApplication.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();
                        AuthenticationResult oResult        = System.Threading.Tasks.Task.Run(async() => await o.GetApplicationToken(EwsProxyFactory.oAuthApplicationId,
                                                                                                                                     EwsProxyFactory.oAuthTenantId,
                                                                                                                                     EwsProxyFactory.oAuthClientSecret)).Result;

                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;
                    }

                    if (this.rdoCredentialsOAuthCertificate.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();

                        AuthenticationResult oResult = System.Threading.Tasks.Task.Run(async() => await o.GetCertificateToken(EwsProxyFactory.oAuthApplicationId,
                                                                                                                              EwsProxyFactory.oAuthTenantId,
                                                                                                                              EwsProxyFactory.oAuthClientCertificate)).Result;



                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;
                    }
                }


                // ----    Autodiscover    ----

                if (this.rdoAutodiscoverEmail.Checked)
                {
                    EwsProxyFactory.DoAutodiscover();
                }

                // ----    New service & app settings    ----

                CurrentService = EwsProxyFactory.CreateExchangeService();


                // ----    Save settings    ----
                EWSEditor.Common.EwsEditorAppSettings oAppSettings = new EwsEditorAppSettings();
                EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);
                CurrentAppSettings = oAppSettings;


                //CurrentAppSettings.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                // CurrentAppSettings

                // EwsProxyFactory.AccountAccessingMailbox

                // ----    Do a basic test to be sure that the mailbox can be reached with an EWS call   ----
                CurrentService.TestExchangeService();

                CurrentService.OnSerializeCustomSoapHeaders += m_Service_OnSerializeCustomSoapHeaders;


                DialogResult = DialogResult.OK;
            }
            finally
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get the ExchangeService from a given row.
        /// </summary>
        private ExchangeService LoadExchangeServiceFromProfileRow(
            ServicesProfile.ServiceBindingRow row,
            NetworkCredential cred,
            out EWSEditor.Common.EwsEditorAppSettings oAppSettings)
        {
            // Create the ExchangeService


            if (!row.IsRequestedServerVersionNull())
            {
                // Convert the string to an ExchangeVersion enumeration
                ExchangeVersion req =
                    (ExchangeVersion)System.Enum.Parse(typeof(ExchangeVersion), row.RequestedServerVersion);
                EwsProxyFactory.RequestedExchangeVersion = req;
            }


            // Load autodiscover email if found
            if (!row.IsAutoDiscoverEmailNull())
            {
                EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;
                EwsProxyFactory.ServiceEmailAddress       = new EmailAddress(row.AutoDiscoverEmail);
            }

            if (!row.IsServicesURLNull())
            {
                EwsProxyFactory.EwsUrl = new Uri(row.ServicesURL);
            }


            // If ImpersonationType is specified then we assume an Id is as well
            if (!row.IsImpersonationTypeNull())
            {
                // Convert the string to a ConnectingIdType enumeration
                ConnectingIdType impType =
                    (ConnectingIdType)System.Enum.Parse(typeof(ConnectingIdType), row.ImpersonationType);
                EwsProxyFactory.UserToImpersonate = new ImpersonatedUserId(impType, row.ImpersonationId);
            }

            // If credentials are not required then use DefaultCredentials
            if (row.UsesDefaultCredentials)
            {
                EwsProxyFactory.UseDefaultCredentials = true;
            }
            else
            {
                if (cred != null)
                {
                    EwsProxyFactory.ServiceCredential = cred;
                }
                else
                {
                    throw new ApplicationException("Credentials are required for this binding.");
                }
            }


            ExchangeService oService = EwsProxyFactory.CreateExchangeService();

            oAppSettings = new EWSEditor.Common.EwsEditorAppSettings();
            EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);

            return(oService);
            //return EwsProxyFactory.CreateExchangeService();
        }