public static void SendAsynchronously(this INotificationContent notification, Uri channelUri, IAccessTokenProvider accessTokenProvider, Action<NotificationSendResult> sent, Action<NotificationSendResult> error, NotificationSendOptions options)
        {
            var payload = notification.GetContent();
            var type = notification.GetNotificationType();

            NotificationSendUtils.SendAsynchronously(channelUri, accessTokenProvider, payload, sent, error, type, options);
        }
        public static NotificationSendResult Send(this INotificationContent notification, Uri channelUri, IAccessTokenProvider accessTokenProvider, NotificationSendOptions options)
        {
            var payload = notification.GetContent();
            var type = notification.GetNotificationType();

            return NotificationSendUtils.Send(channelUri, accessTokenProvider, payload, type, options);
        }
Esempio n. 3
0
 public HttpUserProxy(
     Uri uri,
     IAccessTokenProvider accessTokenProvider)
 {
     _uri = uri;
     _accessTokenProvider = accessTokenProvider;
 }
Esempio n. 4
0
        public FilesCommunicationClientFactory(IServicePartitionResolver resolver, IAccessTokenProvider accessTokenProvider, IOptions <ApiOptions> apiOptions)
            : base(resolver, new[] { new HttpExceptionHandler() })
        {
            if (accessTokenProvider == null)
            {
                throw new ArgumentNullException(nameof(accessTokenProvider));
            }

            this.accessTokenProvider = accessTokenProvider;
            this.apiOptions          = apiOptions.Value;
        }
Esempio n. 5
0
 public TokenService(IAccessTokenProvider accessTokenProvider,
                     IRefreshTokenProvider refreshTokenProvider,
                     ITokensRepository tokensRepository,
                     TokensConfiguration config)
 {
     this._accessTokenProvider  = accessTokenProvider;
     this._refreshTokenProvider = refreshTokenProvider;
     this._tokensRepository     = tokensRepository;
     this._config = config;
     this._claims = ConfigureClaims();
 }
Esempio n. 6
0
 public WorkflowClientController(WorkflowHttpClientProxyProvider workflowHttpClientProxy, IAccessTokenProvider accessToken, IHttpContextAccessor httpContextAccessor)
 {
     httpContext               = httpContextAccessor.HttpContext;
     this.accessToken          = accessToken;
     processInstanceClient     = workflowHttpClientProxy.GetProcessInstanceClient();
     taskClient                = workflowHttpClientProxy.GetTaskClient();
     taskAdminClient           = workflowHttpClientProxy.GetTaskAdminClient();
     deployerClient            = workflowHttpClientProxy.GetDefinitionDeployerClient();
     processDefinitionClient   = workflowHttpClientProxy.GetProcessDefinitionClient();
     processInstanceTaskClient = workflowHttpClientProxy.GetProcessInstanceTasksClient();
 }
Esempio n. 7
0
        public async Task ProvisionAccessTokenAsync_ServiceClaimProvided_ServiceCacheUsed()
        {
            m_serviceTokenCacheMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CacheResponse(true, BuildTestToken(specifyUserClaim: false))));

            IAccessTokenProvider cachedAccessTokenProvider = GetCachedAccessTokenProvider();

            IAccessToken token =
                await cachedAccessTokenProvider.ProvisionAccessTokenAsync(m_claims, m_scopes, m_serviceTokenCacheMock.Object).ConfigureAwait(false);

            Assert.NotNull(token);
        }
Esempio n. 8
0
 public AuthorizedAuthorizationMessageHandler(IAccessTokenProvider provider,
                                              NavigationManager navigationManager)
     : base(provider, navigationManager)
 {
     ConfigureHandler(
         authorizedUrls: new[] { "https://dzigalleryfunctions.azurewebsites.net" },
         scopes: new[]
     {
         "fca594e3-3b1d-460a-b21a-425b32473479/Annotations.Edit",
         "fca594e3-3b1d-460a-b21a-425b32473479/Images.Edit"
     });
 }
        public AzureAccessTokenClientInitializerTests()
        {
            _exportJobConfiguration = new ExportJobConfiguration();
            IOptions <ExportJobConfiguration> optionsExportConfig = Substitute.For <IOptions <ExportJobConfiguration> >();

            optionsExportConfig.Value.Returns(_exportJobConfiguration);

            _accessTokenProvider = Substitute.For <IAccessTokenProvider>();
            _logger = Substitute.For <ILogger <AzureAccessTokenClientInitializer> >();

            _azureAccessTokenClientInitializer = new AzureAccessTokenClientInitializer(_accessTokenProvider, optionsExportConfig, _logger);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="httpClient"></param>
 /// <param name="accessTokenProvider"></param>
 /// <param name="httpContext"></param>
 public DefaultHttpClientProxy(HttpClient httpClient,
                               IAccessTokenProvider accessTokenProvider,
                               IHttpContextAccessor httpContextAccessor,
                               ILoggerFactory loggerFactory)
 {
     this.httpClient         = httpClient;
     this.httpClient.Timeout = TimeSpan.FromMinutes(10);
     this.httpClient.DefaultRequestHeaders.ConnectionClose = false;
     this.accessTokenProvider = accessTokenProvider;
     this.httpContextAccessor = httpContextAccessor;
     this.logger = loggerFactory.CreateLogger <DefaultHttpClientProxy>();
 }
Esempio n. 11
0
    /// <summary>
    /// Initializes the http client for access Bridge API
    /// </summary>
    /// <param name="client">the http client</param>
    /// <param name="accessTokenProvider">The provider giving an access token to use against the brdige API</param>
    /// <param name="platformSettings">the platform settings configured for the authorization functions</param>
    /// <param name="logger">The logger</param>
    public BridgeClient(HttpClient client, IAccessTokenProvider accessTokenProvider, IOptions <PlatformSettings> platformSettings, ILogger <BridgeClient> logger)
    {
        _accessTokenProvider = accessTokenProvider;
        _logger = logger;
        PlatformSettings settings = platformSettings.Value;

        Client             = client;
        Client.BaseAddress = new Uri(settings.BridgeApiEndpoint);
        Client.Timeout     = new TimeSpan(0, 0, 30);
        Client.DefaultRequestHeaders.Clear();
        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
Esempio n. 12
0
 public static IMembersClient CreateMembersClient(
     string baseUrl,
     HttpClient http,
     IAccessTokenProvider tokenProvider,
     Func <IAccessTokenProvider, Task <string> > retrieveAuthorizationToken)
 {
     return(new MembersClient(baseUrl, http)
     {
         AccessTokenProvider = tokenProvider,
         RetrieveAuthorizationToken = retrieveAuthorizationToken
     });
 }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationProvider"/> class.
        /// </summary>
        /// <param name="customerId">Identifier for customer whose resources are being accessed.</param>
        /// <param name="authorizationCode">The authorization code received from service authorization endpoint.</param>
        /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param>
        /// <exception cref="ArgumentException">
        /// <paramref name="customerId"/> is empty or null.
        /// or
        /// <paramref name="authorizationCode"/> is empty or null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="redirectUri"/> is null.
        /// </exception>
        public AuthenticationProvider(string customerId, string authorizationCode, Uri redirectUri)
        {
            customerId.AssertNotEmpty(nameof(customerId));
            authorizationCode.AssertNotNull(nameof(authorizationCode));
            redirectUri.AssertNotNull(nameof(redirectUri));

            this.customerId        = customerId;
            this.authorizationCode = authorizationCode;
            this.redirectUri       = redirectUri;

            tokenProvider = new AccessTokenProvider();
        }
        public void TestAccessTokenProvider_InvalidRSAParameters_TokenIsInvalid()
        {
            var randomRsaParameters = new RSACryptoServiceProvider(OAuth2.Keys.Constants.GENERATED_RSA_KEY_SIZE)
            {
                PersistKeyInCsp = false
            }.ExportParameters(true);

            using (var httpClient = new HttpClient()) {
                IAccessTokenProvider provider = TestAccessTokenProviderFactory.Create(httpClient, DEV_AUTH_URL, Guid.NewGuid(), randomRsaParameters);
                Assert.Throws <AuthServiceException>(async() => await provider.ProvisionAccessTokenAsync(testClaimSet, testScopes).SafeAsync());
            }
        }
 public DigitalTwinsApiConnector(ILogger logger,
                                 IAccessTokenProvider accessTokenProvider,
                                 IConfigurationProvider configurationProvider)
 {
     _logger = logger;
     _accessTokenProvider   = accessTokenProvider;
     _configurationProvider = configurationProvider;
     _httpClient            = new HttpClient()
     {
         BaseAddress = new Uri(_configurationProvider.AzureDigitalTwinsApiUrl)
     };
 }
 public NotificationHub(Uri host, IAccessTokenProvider tokenProvider, AuthenticationStateProvider stateProvider)
 {
     _stateProvider = stateProvider;
     _notifications = new List <NotificationModel>();
     _connection    = new HubConnectionBuilder()
                      .WithUrl(new Uri(host, "/hubs/notification"), options =>
     {
         options.AccessTokenProvider = async() =>
         {
             var result = await tokenProvider.RequestAccessToken();
             return(result.TryGetToken(out var token) ? token.Value : null);
         };
Esempio n. 17
0
        public async Task ProvisionAccessTokenAsync_AlreadyCached_UsesCachedValueAndDoesNotCallThroughToAccessTokenProvider()
        {
            m_serviceTokenCacheMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CacheResponse(true, BuildTestToken())));

            IAccessTokenProvider cachedAccessTokenProvider = GetCachedAccessTokenProvider();

            IAccessToken token =
                await cachedAccessTokenProvider.ProvisionAccessTokenAsync(m_claims, m_scopes, m_serviceTokenCacheMock.Object).ConfigureAwait(false);

            Assert.NotNull(token);
        }
 public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
                                          NavigationManager navigationManager)
     : base(provider, navigationManager)
 {
     ConfigureHandler(
         authorizedUrls: new[]
     {
         "https://localhost:44300",
         "https://localhost:44301",
         "https://localhost:44302"
     },
         scopes: new[] { "api.read.access" });
 }
Esempio n. 19
0
        public async Task ProvisionAccessTokenAsync_UserClaimProvided_UserCacheUsed()
        {
            m_userTokenCacheMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CacheResponse(true, BuildTestToken(specifyUserClaim: true))));

            IAccessTokenProvider cachedAccessTokenProvider = GetCachedAccessTokenProvider();

            Claim        userClaim = new Claim(Constants.Claims.USER_ID, "user");
            IAccessToken token     =
                await cachedAccessTokenProvider.ProvisionAccessTokenAsync(new[] { userClaim }, m_scopes, m_userTokenCacheMock.Object).ConfigureAwait(false);

            Assert.NotNull(token);
        }
        public static Task <Episode> GetFullDetailsAsync(
            this SimplifiedEpisode episode,
            HttpClient httpClient,
            IAccessTokenProvider accessTokenProvider,
            CancellationToken cancellationToken = default)
        {
            if (episode is Episode original)
            {
                return(Task.FromResult(original));
            }

            return(httpClient.GetAsync <Episode>(episode.Href, accessTokenProvider, cancellationToken));
        }
Esempio n. 21
0
        public OrganisationInviteFunctions()
        {
            //var issuerToken = Environment.GetEnvironmentVariable("IssuerToken");
            //var audience = Environment.GetEnvironmentVariable("Audience");
            //var issuer = Environment.GetEnvironmentVariable("Issuer");

            var issuerToken = TemporaryEnvironmentVariables.GetIssuerToken();
            var audience    = TemporaryEnvironmentVariables.GetAudience();
            var issuer      = TemporaryEnvironmentVariables.GetIssuer();

            _tokenCreator  = new AccessTokenCreator(issuerToken, audience, issuer);
            _tokenProvider = new AccessTokenProvider(issuerToken, audience, issuer);
        }
 public AuthorizedAuthorizationMessageHandler(
     IAccessTokenProvider provider,
     NavigationManager navigationManager)
     : base(provider, navigationManager)
 {
     ConfigureHandler(
         authorizedUrls: new[] { "https://serverlesscrud.azurewebsites.net" },
         scopes: new[]
     {
         "db944478-cbda-4214-8ad6-7b310465ce97/BlogPosts.Read",
         "db944478-cbda-4214-8ad6-7b310465ce97/BlogPosts.Write"
     });
 }
        public static Task <Track> GetFullDetailsAsync(
            this SimplifiedTrack track,
            HttpClient httpClient,
            IAccessTokenProvider accessTokenProvider,
            CancellationToken cancellationToken = default)
        {
            if (track is Track original)
            {
                return(Task.FromResult(original));
            }

            return(httpClient.GetAsync <Track>(track.Href, accessTokenProvider, cancellationToken));
        }
Esempio n. 24
0
        public AzureAccessTokenClientInitializer(
            IAccessTokenProvider accessTokenProvider,
            IOptions <ExportJobConfiguration> exportJobConfiguration,
            ILogger <AzureAccessTokenClientInitializer> logger)
        {
            EnsureArg.IsNotNull(accessTokenProvider, nameof(accessTokenProvider));
            EnsureArg.IsNotNull(exportJobConfiguration?.Value, nameof(exportJobConfiguration));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _accessTokenProvider    = accessTokenProvider;
            _exportJobConfiguration = exportJobConfiguration.Value;
            _logger = logger;
        }
        public static Task <Album> GetFullDetailsAsync(
            this SimplifiedAlbum album,
            HttpClient httpClient,
            IAccessTokenProvider accessTokenProvider,
            CancellationToken cancellationToken = default)
        {
            if (album is Album original)
            {
                return(Task.FromResult(original));
            }

            return(httpClient.GetAsync <Album>(album.Href, accessTokenProvider, cancellationToken));
        }
Esempio n. 26
0
        public static async Task UseToken(this IRepository repository, IAccessTokenProvider provider)
        {
            var tokenResult = await provider.RequestAccessToken();

            if (tokenResult.TryGetToken(out var token))
            {
                if (repository.Context is null)
                {
                    repository.Context = new RepositoryAccessContext();
                }
                repository.Context.Token = token.Value;
            }
        }
        public static Task <Show> GetFullDetailsAsync(
            this SimplifiedShow show,
            HttpClient httpClient,
            IAccessTokenProvider accessTokenProvider,
            CancellationToken cancellationToken = default)
        {
            if (show is Show original)
            {
                return(Task.FromResult(original));
            }

            return(httpClient.GetAsync <Show>(show.Href, accessTokenProvider, cancellationToken));
        }
        /// <summary>
        /// Creates a new instance of the <see cref="AzFuncAuthorizationMessageHandler"/>
        /// class.
        /// </summary>
        /// <param name="config"><see cref="IConfiguration"/> to access endpoint.</param>
        /// <param name="provider"><see cref="IAccessTokenProvider"/> service.</param>
        /// <param name="navigation"><see cref="NavigationManager"/> to navigate based on authentication.</param>
        public AzFuncAuthorizationMessageHandler(
            IConfiguration config,
            IAccessTokenProvider provider,
            NavigationManager navigation) : base(provider, navigation)
        {
            var section = config.GetSection(nameof(UrlShortenerSecuredService));

            Endpoint = section.GetValue <string>(nameof(Endpoint));
            ConfigureHandler(
                new[] { Endpoint },
                new[] { string.Concat(Endpoint, "user_impersonation") }
                );
        }
 public VacationController(
     ILogger <VacationController> logger,
     IAccessTokenProvider accessTokenProvider,
     IVacationRepository vacationRepository,
     IUserRepository userRepository,
     IMailHelper mailHelper)
 {
     _logger = logger;
     _accessTokenProvider = accessTokenProvider;
     _vacationRepository  = vacationRepository;
     _userRepository      = userRepository;
     _mailHelper          = mailHelper;
 }
 public ClientHubClientService(
     IAccessTokenProvider tokenProvider,
     NavigationManager navigationManager,
     IWebGroupService groupService,
     IWebUserService userService,
     IWebMessageService messagesService)
 {
     _tokenProvider     = tokenProvider;
     _navigationManager = navigationManager;
     _groupService      = groupService;
     _userService       = userService;
     _messagesService   = messagesService;
 }
Esempio n. 31
0
        public AuthController(GoogleDriveSettings googleDriveSettings)
        {
            settings = googleDriveSettings;

            // WebGL doesn't support loopback method; using redirection scheme instead.
            #if UNITY_WEBGL && !UNITY_EDITOR
            accessTokenProvider = new RedirectAccessTokenProvider(settings);
            #else
            accessTokenProvider = new LoopbackAccessTokenProvider(settings);
            #endif

            accessTokenProvider.OnDone += HandleAccessTokenProviderDone;
        }
        public AzureAccessTokenClientInitializerV2(
            IAccessTokenProvider accessTokenProvider,
            IOptions <IntegrationDataStoreConfiguration> integrationDataStoreConfiguration,
            ILogger <AzureAccessTokenClientInitializerV2> logger)
        {
            EnsureArg.IsNotNull(accessTokenProvider, nameof(accessTokenProvider));
            EnsureArg.IsNotNull(integrationDataStoreConfiguration?.Value, nameof(integrationDataStoreConfiguration));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _accessTokenProvider = accessTokenProvider;
            _integrationDataStoreConfiguration = integrationDataStoreConfiguration.Value;
            _logger = logger;
        }
Esempio n. 33
0
 public PlatformClient(string host, IAccessTokenProvider accessTokenProvider)
     : base(host, accessTokenProvider)
 {
     Clusters     = new ClusterClient(this);
     Domains      = new DomainClient(this);
     Hosts        = new HostClient(this);
     Programs     = new ProgramClient(this);
     Repositories = new RepositoryClient(this);
     Environments = new EnvironmentClient(this);
     Events       = new EventClient(this);
     Exceptions   = new ExceptionClient(this);
     Deployments  = new DeploymentClient(this);
     Users        = new UsersClient(this);
 }
        public OAuth2BearerTokenHandler(IAccessTokenStore tokenStore, IAccessTokenProvider tokenProvider)
        {
            if (tokenStore == null)
            {
                throw new ArgumentNullException("tokenStore");
            }
            if (tokenProvider == null)
            {
                throw new ArgumentNullException("tokenProvider");
            }

            this.TokenStore = tokenStore;
            this.TokenProvider = tokenProvider;
        }
        public PushNotificationController(CloudQueueClient cloudQueueClient, CloudBlobClient cloudBlobClient, IWnsEndpointRepository endpointsRepository, IAccessTokenProvider tokenProvider)
        {
            this.endpointsRepository = endpointsRepository;

            CloudStorageAccount account = null;

            if ((account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString")) == null)
            {
                if (cloudQueueClient == null)
                {
                    throw new ArgumentNullException("cloudQueueClient", "Cloud Queue Client cannot be null if no configuration is loaded.");
                }
            }

            this.cloudQueueClient = cloudQueueClient ?? account.CreateCloudQueueClient();
            this.blobClient = cloudBlobClient ?? account.CreateCloudBlobClient();

            this.tokenProvider = tokenProvider;
        }
 public static void SendAsynchronously(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, Action<NotificationSendResult> sent, Action<NotificationSendResult> error, NotificationType type, NotificationSendOptions options)
 {
     SendAsynchronously(channelUri, accessTokenProvider, payload, sent, error, type, options.SecondsTTL, options.Cache, options.RequestForStatus, options.Tag, options.Priority);
 }
        public static void SendAsynchronously(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, Action<NotificationSendResult> sent, Action<NotificationSendResult> error, NotificationType type, int? secondsTTL = null, bool? cache = null, bool? requestForStatus = null, string tag = null, NotificationPriority priority = NotificationPriority.Normal, int tokenRetry = 0)
        {
            byte[] payloadBytes;

            try
            {
                WnsDiagnostics.TraceVerbose(
                    DiagnosticsConstants.SendingWNSNotificationID,
                    "Sending WNS notification.\r\n\r\n{0}",
                    NotificationRequestStatus(channelUri.ToString(), payload, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry));

                var accessToken = string.Empty;

                try
                {
                    accessToken = accessTokenProvider.GetAccessToken(true);
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        var accessTokenError = GetAccessTokenError(e.Response);
                        WnsDiagnostics.TraceError(DiagnosticsConstants.WnsAccessTokenSendResultErrorID, AccessTokenLogMessage(e.Response, accessTokenError));
                        error(new WnsAccessTokenSendResult(channelUri, e, accessTokenError));
                    }
                    else
                    {
                        WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                        error(new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable));
                    }
                }

                if (!string.IsNullOrEmpty(accessToken))
                {
                    var request = CreateWebRequest(channelUri, accessToken, payload, type, secondsTTL, cache, requestForStatus, tag, priority, out payloadBytes);

                    // Get the request stream asynchronously.
                    request.BeginGetRequestStream(
                        requestAsyncResult =>
                        {
                            try
                            {
                                using (Stream requestStream = request.EndGetRequestStream(requestAsyncResult))
                                {
                                    // Start writing the payload to the stream.
                                    requestStream.Write(payloadBytes, 0, payloadBytes.Length);
                                }

                                // Switch to receiving the response from WNS asynchronously.
                                request.BeginGetResponse(
                                    responseAsyncResult =>
                                    {
                                        try
                                        {
                                            using (
                                                var response =
                                                    (HttpWebResponse)request.EndGetResponse(responseAsyncResult))
                                            {
                                                var result = new NotificationSendResult(channelUri, response);
                                                if (result.StatusCode == HttpStatusCode.OK)
                                                {
                                                    WnsDiagnostics.TraceInformation(DiagnosticsConstants.SentWNSNotificationID, NotificationLogMessage("Sent WNS notification", result.NotificationStatus.ToString(), result, payload, request, response));
                                                    sent(result);
                                                }
                                                else
                                                {
                                                    error(result);
                                                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, "WNS notification failure:\r\n\r\n{0}", result);
                                                }
                                            }
                                        }
                                        catch (WebException e)
                                        {
                                            if (e.Response != null)
                                            {
                                                var result = new NotificationSendResult(channelUri, e);

                                                string exceptionDetails = e.Response.Headers[WnsHeaders.WWWAuthenticate];
                                                if (!string.IsNullOrWhiteSpace(exceptionDetails) &&
                                                    exceptionDetails.Contains("Token expired"))
                                                {
                                                    accessTokenProvider.ResetCachedToken();

                                                    tokenRetry++;
                                                    if (tokenRetry <= MaxSendRetries)
                                                    {
                                                        SendAsynchronously(channelUri, accessTokenProvider, payload, sent, error, type, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry);
                                                    }
                                                    else
                                                    {
                                                        WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                                                        error(result);
                                                    }
                                                }
                                                else
                                                {
                                                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                                                    error(result);
                                                }
                                            }
                                            else
                                            {
                                                WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                                                error(new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable));
                                            }
                                        }
                                        catch (Exception ex3)
                                        {
                                            var result = new NotificationSendResult(channelUri, ex3);
                                            WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex3, "WNS notification failure: {0}\r\n\r\n{1}", ex3.Message, result);
                                            error(result);
                                        }
                                    },
                                    null);
                            }
                            catch (Exception ex2)
                            {
                                var result = new NotificationSendResult(channelUri, ex2);
                                WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex2, "WNS notification failure: {0}\r\n\r\n{1}", ex2.Message, result);
                                error(result);
                            }
                        },
                        null);
                }
            }
            catch (Exception ex1)
            {
                var result = new NotificationSendResult(channelUri, ex1);
                WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex1, "WNS notification failure: {0}\r\n\r\n{1}", ex1.Message, result);
                error(result);
            }
        }
 public static NotificationSendResult Send(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, NotificationType type, NotificationSendOptions options)
 {
     return Send(channelUri, accessTokenProvider, payload, type, options.SecondsTTL, options.Cache, options.RequestForStatus, options.Tag, options.Priority);
 }
        public static NotificationSendResult Send(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, NotificationType type, int? secondsTTL = null, bool? cache = null, bool? requestForStatus = null, string tag = null, NotificationPriority priority = NotificationPriority.Normal, int tokenRetry = 0)
        {
            NotificationSendResult result;
            byte[] payloadBytes;
            HttpWebRequest request = null;

            try
            {
                WnsDiagnostics.TraceVerbose(
                       DiagnosticsConstants.SendingWNSNotificationID,
                       "Sending WNS notification.\r\n\r\n{0}",
                       NotificationRequestStatus(channelUri.ToString(), payload, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry));

                var accessToken = string.Empty;

                try
                {
                    accessToken = accessTokenProvider.GetAccessToken(true);
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        var accessTokenError = GetAccessTokenError(e.Response);
                        WnsDiagnostics.TraceError(DiagnosticsConstants.WnsAccessTokenSendResultErrorID, AccessTokenLogMessage(e.Response, accessTokenError));
                        return new WnsAccessTokenSendResult(channelUri, e, accessTokenError);
                    }
                    else
                    {
                        WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                        return new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable);
                    }
                }

                request = CreateWebRequest(channelUri, accessToken, payload, type, secondsTTL, cache, requestForStatus, tag, priority, out payloadBytes);

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(payloadBytes, 0, payloadBytes.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();
                result = new NotificationSendResult(channelUri, response);

                WnsDiagnostics.TraceInformation(DiagnosticsConstants.SentWNSNotificationID, NotificationLogMessage("Sent WNS notification", result.NotificationStatus.ToString(), result, payload, request, response));
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    string exceptionDetails = e.Response.Headers[WnsHeaders.WWWAuthenticate];
                    if (!string.IsNullOrWhiteSpace(exceptionDetails) && exceptionDetails.Contains("Token expired"))
                    {
                        accessTokenProvider.ResetCachedToken();

                        tokenRetry++;
                        if (tokenRetry <= MaxSendRetries)
                        {
                            result = Send(channelUri, accessTokenProvider, payload, type, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry);
                        }
                        else
                        {
                            result = new NotificationSendResult(channelUri, e);
                        }
                    }
                    else
                    {
                        result = new NotificationSendResult(channelUri, e);
                    }

                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                }
                else
                {
                    WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                    return new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable);
                }
            }
            catch (Exception e)
            {
                result = new NotificationSendResult(channelUri, e);

                WnsDiagnostics.TraceException(DiagnosticsConstants.WNSNotificationFailureID, e, "WNS notification failure: {0}\r\n\r\n{1}", e.Message, result);
            }

            return result;
        }