/// <summary> /// Unregisters a user in Azure Notifcations Hub. /// </summary> /// <remarks> /// This will log a warning if the user is registered multiple times /// in the Azure Notification Hub. This will always remove ALL existing /// registrations. /// </remarks> /// <param name="internalRegistration">Internal registration object.</param> public async Task UnregisterAsync(NotificationRegistration internalRegistration) { if (internalRegistration is null) { throw new ArgumentNullException(nameof(internalRegistration)); } // Log and exit if no registration exists if (!await IsRegisteredAsync(internalRegistration.Id)) { _logger.LogWarning("User is not registered in Azure Notification Hub but does have an internal notification registration, doing nothing."); return; } else { var externalRegistrations = await _hubClient.GetRegistrationsByTagAsync(internalRegistration.Id.ToString(), 0); // Having multiple registrations should never happen, log a warning and skip. if (externalRegistrations.Count() > 1) { _logger.LogWarning("User is registered multiple times in Azure Notification Hub, cleaning up all of them before making new registration"); } // Remove all existing registrations await Task.WhenAll(externalRegistrations.Select(x => _hubClient.DeleteRegistrationAsync(x.RegistrationId))); } }
/// <summary> /// Maps a registration to a context. /// </summary> /// <param name="context">The context to map to.</param> /// <param name="entity">The entity to map from.</param> private static void MapToWriter(DatabaseContext context, NotificationRegistration entity) { context.AddParameterWithValue("external_id", entity.ExternalId); context.AddParameterWithValue("handle", entity.Handle); context.AddParameterWithValue("id", entity.Id); context.AddParameterWithValue("push_notification_platform", entity.PushNotificationPlatform); }
public Task Register(ApiServices services, HttpRequestContext context, NotificationRegistration registration) { try { // Perform a check here for user ID tags, which are not allowed. if (!ValidateTags(registration)) { throw new InvalidOperationException( "You cannot supply a tag that is a user ID."); } // Get the logged-in user. var currentUser = context.Principal as ServiceUser; // Add a new tag that is the user ID. registration.Tags.Add(currentUser.Id); //services.Log.Info("Registered tag for userId: " + currentUser.Id); } catch (Exception ex) { //services.Log.Error(ex.ToString()); } return Task.FromResult(true); }
/// <summary> /// Creates a new notification registration. /// </summary> /// <remarks> /// The notification registration id will be assigned /// to the current user id. /// </remarks> /// <param name="entity">The populated entity.</param> /// <returns>The created id.</returns> public async Task <Guid> CreateAsync(NotificationRegistration entity) { if (entity is null) { throw new ArgumentNullException(nameof(entity)); } var sql = @" INSERT INTO application.notification_registration( external_id, handle, id, push_notification_platform ) VALUES ( @external_id, @handle, @id, @push_notification_platform ) RETURNING id"; await using var context = await CreateNewDatabaseContext(sql); MapToWriter(context, entity); // TODO Correct? // Note: This call can be called with or without an appcontext // user. The entity itself always contains the user id. context.AddParameterWithValue("id", entity.Id); await using var reader = await context.ReaderAsync(); return(reader.GetGuid(0)); }
public Task Register(ApiServices services, HttpRequestContext context, NotificationRegistration registration) { try { // Perform a check here for user ID tags, which are not allowed. if (!ValidateTags(registration)) { throw new InvalidOperationException( "You cannot supply a tag that is a user ID."); } // Get the logged-in user. var currentUser = context.Principal as ServiceUser; // Add a new tag that is the user ID. registration.Tags.Add(currentUser.Id); services.Log.Info("Registered tag for userId: " + currentUser.Id); } catch (Exception ex) { services.Log.Error(ex.ToString()); } return(Task.FromResult(true)); }
/// <param name='operations'> /// Reference to the Rg.ClientApp.INotification. /// </param> /// <param name='registration'> /// Required. /// </param> public static object PostByRegistration(this INotification operations, NotificationRegistration registration) { return(Task.Factory.StartNew((object s) => { return ((INotification)s).PostByRegistrationAsync(registration); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
public static Task <bool> RegisterAsync(UserInfo user, NotificationRegistration registration) { Trace.TraceInformation("RegisterAsync"); Trace.TraceInformation($"RegisterAsync: {user.UserInfoId} ({user.Name}), {registration.Platform}: {registration.Handle}"); // TBD return(Task.FromResult(true)); }
public async Task Register(ApiServices services, HttpRequestContext context, NotificationRegistration registration) { //Register Tag: UserId to push to users ServiceUser user = (ServiceUser)context.Principal; AzureActiveDirectoryCredentials creds = (await user.GetIdentitiesAsync()).OfType <AzureActiveDirectoryCredentials>().FirstOrDefault(); registration.Tags.Add(creds.ObjectId); services.Log.Info("Registered tag for userId: " + creds.ObjectId); }
public async Task Post(NotificationRegistration registration) { UserInfo user = await GetUserInfoAsync(); if (!await NotificationOperations.RegisterAsync(user, registration)) { throw new HttpResponseException(HttpStatusCode.BadRequest); } }
public async Task Post(NotificationRegistration registration) { Trace.TraceInformation("Notification Register POST"); UserInfo user = await GetUserInfoAsync(); Trace.TraceInformation($"Register found user {user.UserInfoId}"); if (!await NotificationOperations.RegisterAsync(user, registration)) { throw new HttpResponseException(HttpStatusCode.BadRequest); } }
private bool ValidateTags(NotificationRegistration registration) { // Create a regex to search for disallowed tags. System.Text.RegularExpressions.Regex searchTerm = new System.Text.RegularExpressions.Regex(@"facebook:|google:|twitter:|microsoftaccount:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); foreach (string tag in registration.Tags) { if (searchTerm.IsMatch(tag)) { return(false); } } return(true); }
private bool ValidateTags(NotificationRegistration registration) { // Create a regex to search for disallowed tags. System.Text.RegularExpressions.Regex searchTerm = new System.Text.RegularExpressions.Regex(@"facebook:|google:|twitter:|microsoftaccount:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); foreach (string tag in registration.Tags) { if (searchTerm.IsMatch(tag)) { return false; } } return true; }
public static async Task AcquirePushChannel() { // -- Channel CurrentChannel = HttpNotificationChannel.Find(ChannelName); if (CurrentChannel == null) { CurrentChannel = new HttpNotificationChannel(ChannelName); CurrentChannel.Open(); CurrentChannel.BindToShellTile(); CurrentChannel.BindToShellToast(); } CurrentChannel.ShellToastNotificationReceived += ShellToastNotificationReceived; // -- NotificationRegistration var registrationsTable = MobileService.GetTable <NotificationRegistration>(); var registration = new NotificationRegistration { ChannelUri = CurrentChannel.ChannelUri.AbsoluteUri, UserId = StaticData.UserData.UserId, }; var existingRegistrations = await registrationsTable .Where(nr => nr.ChannelUri == registration.ChannelUri || nr.UserId == registration.UserId) .ToListAsync(); if (existingRegistrations.Any()) // update { registration.Id = existingRegistrations[0].Id; await registrationsTable.UpdateAsync(registration); // If there are other records, those are out of date for (int i = 1; i < existingRegistrations.Count; i++) { await registrationsTable.DeleteAsync(existingRegistrations[i]); } } else // insert { await registrationsTable.InsertAsync(registration); } // -- NotificationData await ResetNotificationData(); }
/// <summary> /// Registers a user in Azure Notifications Hub. /// </summary> /// <remarks> /// Check <see cref="IsRegisteredAsync(Guid)"/> first to avoid duplicate /// registrations. /// </remarks> /// <param name="internalRegistration">Our internal registration object.</param> public async Task <NotificationRegistration> RegisterAsync(NotificationRegistration internalRegistration) { if (internalRegistration is null) { throw new ArgumentNullException(nameof(internalRegistration)); } // Create new registration and return the converted result var externalRegistration = await _hubClient.CreateRegistrationAsync(ExtractForCreation(internalRegistration)); return(new NotificationRegistration { ExternalId = externalRegistration.RegistrationId, Handle = internalRegistration.Handle, Id = internalRegistration.Id, PushNotificationPlatform = internalRegistration.PushNotificationPlatform, }); }
/// <summary> /// Creates a platform specific <see cref="RegistrationDescription"/>. /// </summary> /// <param name="notificationRegistration">Our internal registration.</param> /// <returns>Notification hub registration.</returns> private static RegistrationDescription ExtractForCreation(NotificationRegistration notificationRegistration) { if (notificationRegistration is null) { throw new ArgumentNullException(nameof(notificationRegistration)); } // Use the user id as tag (as recommended by Azure Notification Hub docs) var tags = new List <string> { notificationRegistration.Id.ToString() }; return(notificationRegistration.PushNotificationPlatform switch { PushNotificationPlatform.APNS => new AppleRegistrationDescription(notificationRegistration.Handle, tags), PushNotificationPlatform.FCM => new FcmRegistrationDescription(notificationRegistration.Handle, tags), _ => throw new InvalidOperationException(nameof(notificationRegistration.PushNotificationPlatform)), });
public async Task <bool> Handle( AddNotificationRegistrationCommandRequest request, CancellationToken cancellationToken ) { var currentRegistrations = await RegisteredBusinessRepository.GetNotificationRegistrationsForEmailAsync(request.Email); // TODO - limit the number of registrations var entity = new NotificationRegistration() { Email = request.Email, SearchText = request.SearchText, NotifyOnOpen = request.NotifyOnOpen ?? true, NotifyOnClose = request.NotifyOnClose ?? true, NotifyOnModified = request.NotifyOnModified ?? true, }; await RegisteredBusinessRepository.AddAsync(entity); return(true); }
static void Queue(Func <ExecutionEnvironment> environment, IFile descriptorPath, IPackageRepository packageRepository) { ResharperLogger.Debug("Queue: queued registration"); _queuedRegistration = new NotificationRegistration(environment, descriptorPath, packageRepository); }
/// <param name='registration'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task <HttpOperationResponse <object> > PostByRegistrationWithOperationResponseAsync(NotificationRegistration registration, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Validate if (registration == null) { throw new ArgumentNullException("registration"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("registration", registration); ServiceClientTracing.Enter(invocationId, this, "PostByRegistrationAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/api/Notification/Register"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Serialize Request string requestContent = null; JToken requestDoc = registration.SerializeJson(null); requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); if (statusCode != HttpStatusCode.NoContent) { HttpOperationException <object> ex = new HttpOperationException <object>(); ex.Request = httpRequest; ex.Response = httpResponse; ex.Body = null; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result HttpOperationResponse <object> result = new HttpOperationResponse <object>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response object resultModel = default(object); result.Body = resultModel; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }
/// <param name='operations'> /// Reference to the Rg.ClientApp.INotification. /// </param> /// <param name='registration'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task <object> PostByRegistrationAsync(this INotification operations, NotificationRegistration registration, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse <object> result = await operations.PostByRegistrationWithOperationResponseAsync(registration, cancellationToken).ConfigureAwait(false); return(result.Body); }
/// <summary> /// Returns a <c>null</c> object. /// </summary> public Task <NotificationRegistration> RegisterAsync(NotificationRegistration internalRegistration) => Task.FromResult <NotificationRegistration>(null);
/// <summary> /// Creates or updates a notification registration. /// </summary> /// <param name='providerNamespace'> /// The name of the resource provider hosted within ProviderHub. /// </param> /// <param name='notificationRegistrationName'> /// The notification registration. /// </param> /// <param name='properties'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <NotificationRegistration> > CreateOrUpdateWithHttpMessagesAsync(string providerNamespace, string notificationRegistrationName, NotificationRegistrationPropertiesModel properties = default(NotificationRegistrationPropertiesModel), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (providerNamespace == null) { throw new ValidationException(ValidationRules.CannotBeNull, "providerNamespace"); } if (notificationRegistrationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "notificationRegistrationName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } NotificationRegistration properties1 = new NotificationRegistration(); if (properties != null) { properties1.Properties = properties; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("providerNamespace", providerNamespace); tracingParameters.Add("notificationRegistrationName", notificationRegistrationName); tracingParameters.Add("properties1", properties1); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.ProviderHub/providerRegistrations/{providerNamespace}/notificationRegistrations/{notificationRegistrationName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{providerNamespace}", System.Uri.EscapeDataString(providerNamespace)); _url = _url.Replace("{notificationRegistrationName}", System.Uri.EscapeDataString(notificationRegistrationName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (properties1 != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(properties1, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <NotificationRegistration>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <NotificationRegistration>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Does nothing and returns <see cref="Task.CompletedTask"/>; /// </summary> public Task UnregisterAsync(NotificationRegistration internalRegistration) => Task.CompletedTask;
public Task Register(ApiServices services, HttpRequestContext context, NotificationRegistration registration) { // other another tag registration.Tags.Add(SomeTag); return(Task.FromResult(true)); }
static void Queue(Func<ExecutionEnvironment> environment, IFile descriptorPath, IPackageRepository packageRepository) { ResharperLogger.Debug("Queue: queued registration"); _queuedRegistration = new NotificationRegistration(environment, descriptorPath, packageRepository); }