예제 #1
0
 private static void SetMessageId(SoapHttpClientAuthenticator authenticator, string messageId)
 {
     if (messageId != null)
     {
         authenticator.AdditionalSoapHeaders.Add(WSAddressingMessageIDHeader.Create(messageId));
     }
 }
 // Token: 0x06001C62 RID: 7266 RVA: 0x000714E0 File Offset: 0x0006F6E0
 public FindInGALSpeechRecognitionEWSBinding(SmtpAddress orgMboxSmtpAddress, Uri serviceUri, object state) : base("FindInGALSpeechRecognition", new RemoteCertificateValidationCallback(FindInGALSpeechRecognitionEWSBinding.CertificateErrorHandler))
 {
     ValidateArgument.NotNull(orgMboxSmtpAddress, "orgMboxSmtpAddress");
     ValidateArgument.NotNull(serviceUri, "serviceUri");
     ValidateArgument.NotNull(state, "state");
     base.Url = serviceUri.ToString();
     this.RequestServerVersionValue = FindInGALSpeechRecognitionEWSBinding.RequestServerVersion;
     base.UserAgent     = "FindInGALSpeechRecognition";
     base.Proxy         = new WebProxy();
     base.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
     base.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType
     {
         ConnectingSID = new ConnectingSIDType
         {
             Item = new SmtpAddressType
             {
                 Value = orgMboxSmtpAddress.ToString()
             }
         },
         LogonType           = SpecialLogonType.SystemService,
         BudgetType          = 2,
         BudgetTypeSpecified = true
     });
     this.State = state;
     NetworkServiceImpersonator.Initialize();
 }
 internal MeetingValidatorEwsBinding(ExchangePrincipal principal, Uri endpoint) : base("ExchangeCalendarRepairAssistant", new RemoteCertificateValidationCallback(MeetingValidatorEwsBinding.CertificateErrorHandler))
 {
     this.RequestServerVersionValue = MeetingValidatorEwsBinding.RequestServerVersionExchange2013;
     base.UserAgent = "ExchangeCalendarRepairAssistant";
     base.Url       = endpoint.AbsoluteUri;
     base.Timeout   = (int)TimeSpan.FromSeconds((double)Configuration.WebRequestTimeoutInSeconds).TotalMilliseconds;
     NetworkServiceImpersonator.Initialize();
     if (NetworkServiceImpersonator.Exception == null)
     {
         base.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
         base.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType
         {
             ConnectingSID = new ConnectingSIDType
             {
                 Item = new SmtpAddressType
                 {
                     Value = principal.MailboxInfo.PrimarySmtpAddress.ToString()
                 }
             },
             LogonType           = SpecialLogonType.SystemService,
             BudgetType          = 1,
             BudgetTypeSpecified = true
         });
     }
 }
예제 #4
0
        public static ProxyAuthenticator Create(OAuthCredentials credentials, string messageId, bool isAutodiscoverRequest)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug <object, OAuthCredentials>(0L, "{0}: creating ProxyAuthenticator for OAuthCredentials: {1}", TraceContext.Get(), credentials);
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = isAutodiscoverRequest ? SoapHttpClientAuthenticator.CreateForSoap(credentials) : SoapHttpClientAuthenticator.Create(credentials);

            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.OAuth));
        }
예제 #5
0
        public static ProxyAuthenticator Create(CommonAccessToken commonAccessToken, string messageId)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug <object, CommonAccessToken>(0L, "{0}: creating ProxyAuthenticator for CommonAccessToken: {1}", TraceContext.Get(), commonAccessToken);
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(commonAccessToken);

            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.OAuth));
        }
예제 #6
0
 protected override void SetAuthenticationMechanism(ExchangeServiceBinding ewsBinding)
 {
     if (ADAuthenticationTrackingAuthority.CanImpersonateNetworkService)
     {
         ewsBinding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
         return;
     }
     ewsBinding.Credentials = CredentialCache.DefaultNetworkCredentials;
 }
예제 #7
0
 public ManageDelegation2Client(string domain, string signingDomain, string certificateThumbprint, WriteVerboseDelegate writeVerbose) : base(LiveConfiguration.GetDomainServices2Epr().ToString(), certificateThumbprint, writeVerbose)
 {
     this.manageDelegation = new ManageDelegation2("ManageDelegation2", new RemoteCertificateValidationCallback(ManageDelegationClient.InvalidCertificateHandler));
     this.manageDelegation.Authenticator = SoapHttpClientAuthenticator.Create(base.Certificate);
     this.manageDelegation.DomainOwnershipProofHeaderValue = new DomainOwnershipProofHeader
     {
         Domain        = domain,
         HashAlgorithm = "SHA-512",
         Signature     = Convert.ToBase64String(FederatedDomainProofAlgorithm.GetSignature(base.Certificate, signingDomain))
     };
 }
예제 #8
0
        public static ProxyAuthenticator CreateForSoap(string messageId)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug(0L, "{0}: creating ProxyAuthenticator for network service", new object[]
            {
                TraceContext.Get()
            });
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.CreateNetworkServiceForSoap();

            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.NetworkCredentials));
        }
		private static void SetSecurityHeader(ExchangeServiceBinding binding, string email)
		{
			binding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
			binding.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType
			{
				ConnectingSID = new ConnectingSIDType
				{
					Item = new PrimarySmtpAddressType
					{
						Value = email
					}
				},
				LogonType = SpecialLogonType.SystemService
			});
		}
예제 #10
0
		public ExchangeService(SoapHttpClientAuthenticator authenticator, SharingSubscriptionData subscriptionData, IWebProxy webProxy, string componentId, bool normalization)
		{
			this.folderId = new FolderIdType
			{
				Id = subscriptionData.RemoteFolderId,
				ChangeKey = null
			};
			this.binding = new ExchangeServiceBinding(componentId, new RemoteCertificateValidationCallback(CertificateErrorHandler.CertValidationCallback), normalization);
			this.binding.Url = subscriptionData.SharingUrl.ToString();
			this.binding.RequestServerVersionValue = ExchangeService.RequestServerVersionExchange2010;
			this.binding.Authenticator = authenticator;
			this.binding.Proxy = webProxy;
			this.binding.UserAgent = componentId;
			this.binding.HttpHeaders[WellKnownHeader.AnchorMailbox] = subscriptionData.SharerIdentity;
		}
예제 #11
0
        public static ProxyAuthenticator Create(WSSecurityHeader wsSecurityHeader, SharingSecurityHeader sharingSecurityHeader, string messageId)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug(0L, "{0}: creating ProxyAuthenticator for WS-Security", new object[]
            {
                TraceContext.Get()
            });
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(wsSecurityHeader);

            if (sharingSecurityHeader != null)
            {
                soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(sharingSecurityHeader);
            }
            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.WSSecurity));
        }
 internal UpdateGroupMailboxEwsBinding(ADUser group, Uri ewsEndpoint) : base("GroupMailboxCmdlet", new RemoteCertificateValidationCallback(CommonCertificateValidationCallbacks.InternalServerToServer))
 {
     ArgumentValidator.ThrowIfNull("group", group);
     ArgumentValidator.ThrowIfNull("ewsEndpointUrl", ewsEndpoint);
     base.Url = ewsEndpoint.ToString();
     base.HttpHeaders[WellKnownHeader.EWSTargetVersion] = EwsTargetVersion.V2_14;
     base.UserAgent = "GroupMailboxCmdlet";
     base.Proxy     = new WebProxy();
     base.SetClientRequestIdHeaderFromActivityId();
     using (new StopwatchPerformanceTracker("UpdateGroupMailboxEwsBinding.CreateNetworkService", GenericCmdletInfoDataLogger.Instance))
     {
         base.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
     }
     using (new StopwatchPerformanceTracker("UpdateGroupMailboxEwsBinding.InitNetworkServiceImpersonator", GenericCmdletInfoDataLogger.Instance))
     {
         NetworkServiceImpersonator.Initialize();
     }
 }
예제 #13
0
        public virtual IExchangeService CreateBinding(RemoteCertificateValidationCallback certificateErrorHandler)
        {
            bool flag = true;

            NetworkServiceImpersonator.Initialize();
            if (NetworkServiceImpersonator.Exception != null)
            {
                if (this.IsTraceEnabled(TraceType.ErrorTrace))
                {
                    this.Tracer.TraceError <LocalizedException>(0L, "Unable to impersonate network service to call EWS due to exception {0}", NetworkServiceImpersonator.Exception);
                }
                flag = false;
            }
            ExchangeServiceBinding exchangeServiceBinding = new ExchangeServiceBinding(certificateErrorHandler);

            exchangeServiceBinding.UserAgent = WellKnownUserAgent.GetEwsNegoAuthUserAgent("AuditLog");
            exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion
            {
                Version = ExchangeVersionType.Exchange2013
            };
            if (flag)
            {
                exchangeServiceBinding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
            }
            else
            {
                exchangeServiceBinding.Authenticator = SoapHttpClientAuthenticator.Create(CredentialCache.DefaultCredentials);
            }
            exchangeServiceBinding.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType
            {
                ConnectingSID = new ConnectingSIDType
                {
                    Item = new PrimarySmtpAddressType
                    {
                        Value = this.GetSmtpAddress()
                    }
                },
                LogonType           = SpecialLogonType.SystemService,
                BudgetType          = (int)this.budgetType,
                BudgetTypeSpecified = true
            });
            return(exchangeServiceBinding);
        }
예제 #14
0
        internal MailboxAssociationEwsBinding(ADUser user, OpenAsAdminOrSystemServiceBudgetTypeType budgetType) : base("GroupMailboxAccessLayer", new RemoteCertificateValidationCallback(CommonCertificateValidationCallbacks.InternalServerToServer))
        {
            ArgumentValidator.ThrowIfNull("user", user);
            ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(user, null);

            MailboxAssociationEwsBinding.Tracer.TraceDebug <bool>((long)this.GetHashCode(), "MailboxAssociationEwsBinding.ctor - ExchangePrincipal.MailboxInfo.Location is null? {0}", exchangePrincipal.MailboxInfo.Location == null);
            Uri ewsEndpoint = null;

            MailboxAssociationEwsBinding.ExecuteEwsOperationWithRetry("GetBackEndWebServicesUrl", delegate
            {
                ewsEndpoint = BackEndLocator.GetBackEndWebServicesUrl(exchangePrincipal.MailboxInfo);
            });
            if (ewsEndpoint == null)
            {
                throw new MailboxNotFoundException(Strings.EwsUrlDiscoveryFailed(user.PrimarySmtpAddress.ToString()));
            }
            base.Url = ewsEndpoint.ToString();
            if (string.IsNullOrEmpty(base.Url))
            {
                throw new MailboxNotFoundException(Strings.EwsUrlDiscoveryFailed(user.PrimarySmtpAddress.ToString()));
            }
            base.HttpHeaders[WellKnownHeader.EWSTargetVersion] = EwsTargetVersion.V2_7;
            base.UserAgent = "GroupMailboxAccessLayer";
            base.Proxy     = new WebProxy();
            base.SetClientRequestIdHeaderFromActivityId();
            base.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
            base.Authenticator.AdditionalSoapHeaders.Add(new OpenAsAdminOrSystemServiceType
            {
                ConnectingSID = new ConnectingSIDType
                {
                    Item = new SmtpAddressType
                    {
                        Value = user.PrimarySmtpAddress.ToString()
                    }
                },
                LogonType           = SpecialLogonType.Admin,
                BudgetType          = (int)budgetType,
                BudgetTypeSpecified = true
            });
            NetworkServiceImpersonator.Initialize();
        }
예제 #15
0
        public static ProxyAuthenticator Create(RequestedToken token, SmtpAddress sharingKey, string messageId)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug(0L, "{0}: creating ProxyAuthenticator for WS-Security", new object[]
            {
                TraceContext.Get()
            });
            XmlElement xmlElement = null;

            if (sharingKey != SmtpAddress.Empty)
            {
                xmlElement = SharingKeyHandler.Encrypt(sharingKey, token.ProofToken);
            }
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(token);

            if (xmlElement != null)
            {
                soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(new SharingSecurityHeader(xmlElement));
            }
            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.WSSecurity));
        }
        public static AutoDiscoverUserSettingsClient CreateInstance(ITopologyConfigurationSession topologyConfigurationSession, FedOrgCredentials credentials, SmtpAddress identity, Uri autoDiscoveryEndpoint, string[] requestedSettings)
        {
            Util.ThrowOnNullArgument(credentials, "credentials");
            RequestedToken token;

            try
            {
                token = credentials.GetToken();
            }
            catch (WSTrustException ex)
            {
                string text  = identity.ToString();
                string text2 = ex.ToString();
                StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_AutoDiscoverFailedToAquireSecurityToken, text, new object[]
                {
                    text,
                    text2
                });
                ExTraceGlobals.XtcTracer.TraceError <string, string>(0L, "AutoDiscover request failed for {0}, failed to aquire security token. Exception: {1}.", text, text2);
                throw new AutoDAccessException(ServerStrings.AutoDFailedToGetToken, ex);
            }
            return(new AutoDiscoverUserSettingsClient(topologyConfigurationSession, SoapHttpClientAuthenticator.Create(token), EwsWsSecurityUrl.Fix(autoDiscoveryEndpoint), identity, requestedSettings));
        }
 public MailboxSearchEwsClient(ExchangePrincipal principal, ADUser executingUser)
 {
     try
     {
         string url = null;
         DelegationTokenRequest request = null;
         this.Discover(principal, executingUser, out url, out request);
         RequestedToken token = this.securityTokenService.IssueToken(request);
         SoapHttpClientAuthenticator authenticator = SoapHttpClientAuthenticator.Create(token);
         this.binding     = new MailboxSearchEwsClient.MailboxSearchEwsBinding("ExchangeEDiscovery", new RemoteCertificateValidationCallback(MailboxSearchEwsClient.CertificateErrorHandler));
         this.binding.Url = url;
         this.binding.RequestServerVersionValue = MailboxSearchEwsClient.RequestServerVersionExchange2010;
         this.binding.Authenticator             = authenticator;
         this.binding.Proxy     = this.WebProxy;
         this.binding.UserAgent = "ExchangeEDiscovery";
         this.binding.Timeout   = 600000;
     }
     catch (WSTrustException ex)
     {
         ExTraceGlobals.SessionTracer.TraceError((long)this.GetHashCode(), ex.ToString());
         throw new MailboxSearchEwsFailedException(ex.Message);
     }
 }
예제 #18
0
        protected override IAsyncResult BeginInvoke()
        {
            GetFolderType getFolder = new GetFolderType
            {
                FolderShape = GetFolderRequest.GetFolderShape,
                FolderIds   = new BaseFolderIdType[]
                {
                    new DistinguishedFolderIdType
                    {
                        Id = DistinguishedFolderIdNameType.calendar
                    }
                }
            };

            this.binding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
            this.binding.Authenticator.AdditionalSoapHeaders.Add(new SerializedSecurityContextType
            {
                UserSid             = (this.query.RecipientData.Sid ?? this.query.RecipientData.MasterAccountSid).ToString(),
                GroupSids           = GetFolderRequest.SidStringAndAttributesConverter(ClientSecurityContext.DisabledEveryoneOnlySidStringAndAttributesArray),
                RestrictedGroupSids = null,
                PrimarySmtpAddress  = this.query.RecipientData.PrimarySmtpAddress.ToString()
            });
            return(this.binding.BeginGetFolder(getFolder, new AsyncCallback(base.Complete), null));
        }
예제 #19
0
        public static ProxyAuthenticator Create(CredentialCache cache, SerializedSecurityContext serializedContext, string messageId)
        {
            SoapHttpClientAuthenticator soapHttpClientAuthenticator;

            if (cache == null)
            {
                ProxyAuthenticator.SecurityTracer.TraceDebug(0L, "{0}: creating ProxyAuthenticator for network service", new object[]
                {
                    TraceContext.Get()
                });
                soapHttpClientAuthenticator = SoapHttpClientAuthenticator.CreateNetworkService();
            }
            else
            {
                ProxyAuthenticator.SecurityTracer.TraceDebug <object, CredentialCache>(0L, "{0}: creating ProxyAuthenticator for credential cache: {1}", TraceContext.Get(), cache);
                soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(cache);
            }
            if (serializedContext != null)
            {
                soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(serializedContext);
            }
            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.NetworkCredentials));
        }
예제 #20
0
		public ExchangeService(SoapHttpClientAuthenticator authenticator, SharingSubscriptionData subscriptionData, IWebProxy webProxy, string componentId) : this(authenticator, subscriptionData, webProxy, componentId, true)
		{
		}
 public static AutoDiscoverUserSettingsClient CreateInstance(ITopologyConfigurationSession topologyConfigurationSession, NetworkCredential credentials, SmtpAddress identity, string[] requestedSettings)
 {
     return(new AutoDiscoverUserSettingsClient(topologyConfigurationSession, SoapHttpClientAuthenticator.CreateForSoap(credentials), null, identity, requestedSettings));
 }
예제 #22
0
 private ProxyAuthenticator(SoapHttpClientAuthenticator authenticator, AuthenticatorType authenticatorType)
 {
     this.authenticator     = authenticator;
     this.AuthenticatorType = authenticatorType;
 }
 private AutoDiscoverUserSettingsClient(ITopologyConfigurationSession topologyConfigurationSession, SoapHttpClientAuthenticator authentificator, Uri autoDiscoveryEndpoint, SmtpAddress identity, string[] requestedSettings)
 {
     Util.ThrowOnNullArgument(topologyConfigurationSession, "topologyConfigurationSession");
     Util.ThrowOnNullArgument(identity, "identity");
     Util.ThrowOnNullArgument(requestedSettings, "requestedSettings");
     if (requestedSettings.Length == 0)
     {
         throw new ArgumentException("Requested settings array must be not empty.");
     }
     foreach (string value in requestedSettings)
     {
         if (string.IsNullOrEmpty(value))
         {
             throw new ArgumentException("Cannot use null or empty string as a requested setting.");
         }
     }
     using (DisposeGuard disposeGuard = this.Guard())
     {
         this.requestedSettings             = requestedSettings;
         this.autoDiscoveryUri              = autoDiscoveryEndpoint;
         this.identity                      = identity;
         this.client                        = new AutodiscoverClient();
         this.client.RequestedServerVersion = DefaultBinding_Autodiscover.Exchange2010RequestedServerVersion;
         this.client.UserAgent              = "ExchangeMiddleTierStorage";
         this.client.Authenticator          = authentificator;
         string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters();
         if (autodiscoverTrustedHosters != null)
         {
             this.client.AllowedHostnames.AddRange(autodiscoverTrustedHosters);
         }
         Server localServer = LocalServerCache.LocalServer;
         if (localServer != null && localServer.InternetWebProxy != null)
         {
             this.client.Proxy = new WebProxy(localServer.InternetWebProxy);
         }
         else
         {
             this.client.Proxy = new WebProxy();
         }
         disposeGuard.Success();
     }
 }
예제 #24
0
        private SoapHttpClientAuthenticator CreateAuthenticator(Offer offer)
        {
            DelegationTokenRequest delegationTokenRequest = this.GetDelegationTokenRequest(offer);

            SharingEngine.Tracer.TraceDebug <DelegationTokenRequest>((long)this.GetHashCode(), "Requesting token for: {0}", delegationTokenRequest);
            if (this.adUser == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "adUser is null here");
                throw new ADUserNotFoundException();
            }
            if (this.externalAuthentication == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "externalAuthentication is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("externalAuthentication"));
            }
            SecurityTokenService securityTokenService = this.externalAuthentication.GetSecurityTokenService(this.adUser.OrganizationId);

            if (securityTokenService == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "securityTokenService is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("securityTokenService"));
            }
            Stopwatch      stopwatch = Stopwatch.StartNew();
            bool           flag      = false;
            RequestedToken requestedToken;

            try
            {
                requestedToken = securityTokenService.IssueToken(delegationTokenRequest);
                flag           = true;
            }
            catch (WSTrustException ex)
            {
                SharingEngine.Tracer.TraceError <WSTrustException>((long)this.GetHashCode(), "Unable to request token due exception: {0}", ex);
                throw new FailedCommunicationException(ex, delegationTokenRequest);
            }
            finally
            {
                if (flag)
                {
                    stopwatch.Stop();
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTime.IncrementBy(stopwatch.ElapsedTicks);
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTimeBase.Increment();
                    PerformanceCounters.SuccessfulExternalAuthenticationTokenRequests.Increment();
                }
                else
                {
                    PerformanceCounters.FailedExternalAuthenticationTokenRequests.Increment();
                }
            }
            if (requestedToken == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "token is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("token"));
            }
            if (this.subscription == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "subscription is null here");
                throw new SubscriptionNotFoundException();
            }
            XmlElement any = SharingKeyHandler.Encrypt(new SmtpAddress(this.subscription.SharingKey), requestedToken.ProofToken);
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(requestedToken);

            soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(new SharingSecurityHeader(any));
            return(soapHttpClientAuthenticator);
        }
        private static void SyncInternal(MailboxSession mailboxSession, ExDateTime lastSyncTime, StoreId folderId, string folderDisplayname, SecurityAccessToken securityAccessToken)
        {
            RefreshSharingFolderClient.Tracer.TraceDebug <string, IExchangePrincipal>(0L, "Sync sharing folder {0} from mailbox {1}", folderDisplayname, mailboxSession.MailboxOwner);
            if (!RefreshSharingFolderClient.CanSyncNow(lastSyncTime))
            {
                return;
            }
            NetworkServiceImpersonator.Initialize();
            if (NetworkServiceImpersonator.Exception != null)
            {
                RefreshSharingFolderClient.Tracer.TraceError <LocalizedException>(0L, "Unable to impersonate network service to call EWS due exception {0}", NetworkServiceImpersonator.Exception);
                return;
            }
            string id = StoreId.StoreIdToEwsId(mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, folderId);
            IList <WebServicesService> list;

            try
            {
                ClientAccessType clientAccessType = RefreshSharingFolderClient.ClientAccessType;
                RefreshSharingFolderClient.Tracer.TraceDebug <ClientAccessType>(0L, "Will try to discover the URL for EWS with the following client access type: {0}", clientAccessType);
                ServiceTopology currentServiceTopology = ServiceTopology.GetCurrentServiceTopology("f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\RefreshSharingFolderClient.cs", "SyncInternal", 153);
                list = currentServiceTopology.FindAll <WebServicesService>(mailboxSession.MailboxOwner, clientAccessType, "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\RefreshSharingFolderClient.cs", "SyncInternal", 154);
            }
            catch (LocalizedException arg)
            {
                RefreshSharingFolderClient.Tracer.TraceError <IExchangePrincipal, LocalizedException>(0L, "Unable to discover internal URL for EWS for mailbox {0} due exception {1}", mailboxSession.MailboxOwner, arg);
                return;
            }
            if (list.Count != 0)
            {
                string text = list[0].Url.ToString();
                RefreshSharingFolderClient.Tracer.TraceDebug <string>(0L, "Using {0} to call BeginRefreshSharingFolder", text);
                ExchangeServiceBinding exchangeServiceBinding = new ExchangeServiceBinding("RefreshSharingFolder", new RemoteCertificateValidationCallback(RefreshSharingFolderClient.CertificateErrorHandler));
                exchangeServiceBinding.Url = text;
                exchangeServiceBinding.RequestServerVersionValue         = new RequestServerVersion();
                exchangeServiceBinding.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;
                exchangeServiceBinding.UserAgent     = WellKnownUserAgent.GetEwsNegoAuthUserAgent("RefreshSharingFolder");
                exchangeServiceBinding.Authenticator = SoapHttpClientAuthenticator.CreateNetworkService();
                exchangeServiceBinding.Authenticator.AdditionalSoapHeaders.Add(new SerializedSecurityContextType
                {
                    UserSid             = securityAccessToken.UserSid,
                    GroupSids           = RefreshSharingFolderClient.SidStringAndAttributesConverter(securityAccessToken.GroupSids),
                    RestrictedGroupSids = RefreshSharingFolderClient.SidStringAndAttributesConverter(securityAccessToken.RestrictedGroupSids),
                    PrimarySmtpAddress  = mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString()
                });
                Exception ex = null;
                try
                {
                    exchangeServiceBinding.BeginRefreshSharingFolder(new RefreshSharingFolderType
                    {
                        SharingFolderId = new FolderIdType
                        {
                            Id = id
                        }
                    }, new AsyncCallback(RefreshSharingFolderClient.TraceResponse), exchangeServiceBinding);
                }
                catch (SoapException ex2)
                {
                    ex = ex2;
                }
                catch (WebException ex3)
                {
                    ex = ex3;
                }
                catch (IOException ex4)
                {
                    ex = ex4;
                }
                catch (InvalidOperationException ex5)
                {
                    ex = ex5;
                }
                catch (LocalizedException ex6)
                {
                    ex = ex6;
                }
                if (ex != null)
                {
                    RefreshSharingFolderClient.Tracer.TraceError <StoreId, IExchangePrincipal, Exception>(0L, "Unable to sync sharing folder {0} in mailbox {1}. Exception {2}", folderId, mailboxSession.MailboxOwner, ex);
                }
                return;
            }
            RefreshSharingFolderClient.Tracer.TraceError <IExchangePrincipal>(0L, "Unable to find internal URL for EWS for mailbox {0}", mailboxSession.MailboxOwner);
        }