示例#1
0
        static async Task MainAsync(string[] args)
        {
            char direction = '-';

            try
            {
                IMobileServiceTable <NightScoutReading> table = MobileService.GetTable <NightScoutReading>();
                //NightScoutReading reading = await table.LookupAsync("5484f78529b19f32387ffa07");
                //Console.WriteLine(reading.sgv);
                //Console.Read();
                List <NightScoutReading> items = await table.Where(O => O.type == "sgv").OrderByDescending(O => O.date).ToListAsync();

                if (items[0].direction.ToLower().Contains("up"))
                {
                    direction = '\x25B2';
                }
                else
                if (items[0].direction.ToLower().Contains("down"))
                {
                    direction = '\x25BC';
                }
                string notification       = String.Format("Current bg: {0} Trend: {1}", items[0].sgv, direction.ToString());
                NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://nightscoutmobilehub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=xl1zRhF0EKmoZdkHdvzGT+RCx7YpzGopDnRjrDpp6QA=", "nightscoutmobilehub");
                var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" + notification + "</text></binding></visual></toast>";
                await hub.SendWindowsNativeNotificationAsync(toast);
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                Console.WriteLine(ex.Request);
                Console.WriteLine(ex.Response);
            }
            Console.Read();
        }
示例#2
0
        static async Task DoIt()
        {
            var hubConnection = "Endpoint=sb://thnotify1.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=Z2Xpa9dMYJLipI26LS1hltCZw8U4KI41NfnPucWkWqw=";
            var hubName       = "not1";
            var hubClient     = NotificationHubClient.CreateClientFromConnectionString(hubConnection, hubName);

            string chromePnsHandle  = "APA91bEGv8n_2g_5wv1Cxj6Q9KumQZdLp8uoSzAtdhIJW27cGglow33CDHqpDFEXhae5dwRVN-m99W_tiHBriMmC5DDRxd_vR-uQPNiOdPDt2XK4qLtMMO2aJQlGq1wMihx-b7IcDZl528Ocx6I_x5ug4e6UVkPYbQ";
            var    deviceIdentifier = "device4567";
            var    userIdentifier   = "user1234";

            // Register a device and tag it with who it belongs to
            var regSvc = new AzureRegistrationService(hubClient);

            var registration = new Registration
            {
                DeviceIdentifier = deviceIdentifier,
                PnsHandle        = chromePnsHandle,
                Platform         = Platform.Google
            };

            regSvc.CreateRegistration(registration, new string[] { userIdentifier, deviceIdentifier });

            // Send a notification to a user (will go to all the devices they have registered on)
            var notifySvc = new AzureNotificationService(hubClient);
            await notifySvc.SendTextNotification("Hello, Gearstone!", userIdentifier);
        }
示例#3
0
 private static async Task SendWindowsNotificationAsync(string msg)
 {
     NotificationHubClient hub = NotificationHubClient
                                 .CreateClientFromConnectionString(nhConnectionString, hubName);
     var toast   = $"<toast launch=\"launch_arguments\"><visual><binding template=\"ToastText01\"><text id=\"1\">{msg}</text></binding></visual></toast>";
     var results = await hub.SendWindowsNativeNotificationAsync(toast);
 }
        private static async Task SendTemplateNotificationsAsync()
        {
            NotificationHubClient       hub = NotificationHubClient.CreateClientFromConnectionString(DispatcherConstants.FullAccessConnectionString, DispatcherConstants.NotificationHubName);
            Dictionary <string, string> templateParameters = new Dictionary <string, string>();

            messageCount++;

            // Send a template notification to each tag. This will go to any devices that
            // have subscribed to this tag with a template that includes "messageParam"
            // as a parameter
            foreach (var tag in DispatcherConstants.SubscriptionTags)
            {
                templateParameters["messageParam"] = $"Notification #{messageCount} to {tag} category subscribers!";
                try
                {
                    await hub.SendTemplateNotificationAsync(templateParameters, tag);

                    Console.WriteLine($"Sent message to {tag} subscribers.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to send template notification: {ex.Message}");
                }
            }

            Console.WriteLine($"Sent messages to {DispatcherConstants.SubscriptionTags.Length} tags.");
            WriteSeparator();
        }
示例#5
0
        public async Task <NotificationOutcomeState> SendAppleNotification(string title, string subTitle, int unitId, string eventCode, string type, bool enableCustomSounds, int count, string color)
        {
            try
            {
                var    hubClient         = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureUnitNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureUnitNotificationHub_PushUrl);
                string appleNotification = null;

                if (type == ((int)PushSoundTypes.CallEmergency).ToString() ||
                    type == ((int)PushSoundTypes.CallHigh).ToString() ||
                    type == ((int)PushSoundTypes.CallMedium).ToString() ||
                    type == ((int)PushSoundTypes.CallLow).ToString())
                {
                    appleNotification = "{\"aps\" : { \"alert\" : \"" + subTitle + "\", \"content-available\": 1, \"category\" : \"CALLS\", \"badge\" : " + count + ", \"sound\" : \"" + GetSoundFileNameFromType(Platforms.iPhone, type, enableCustomSounds) + "\" }, \"eventCode\": \"" + eventCode + "\" }";
                }
                else
                {
                    appleNotification = "{\"aps\" : { \"alert\" : \"" + subTitle + "\", \"badge\" : " + count + ", \"sound\" : \"" + GetSoundFileNameFromType(Platforms.iPhone, type, enableCustomSounds) + "\" }, \"eventCode\": \"" + eventCode + "\" }";
                }


                var appleOutcome = await hubClient.SendAppleNativeNotificationAsync(appleNotification, string.Format("unitId:{0}", unitId));

                return(appleOutcome.State);
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
            }

            return(NotificationOutcomeState.Unknown);
        }
示例#6
0
        public ServiceManager(ApiDbContext _ctx,
                              UserManager <User> _userManager,
                              SignInManager <User> _signInManager,
                              IMapper _mapper,
                              IOptions <PushNotificationOptions> pushNotificationOptions,
                              IOptions <AuthenticationOptions> authenticationOptions,
                              IOptions <EmailOptions> _emailOptions,
                              IOptions <GoogleOptions> _googleOptions,
                              ILogger <ServiceManager> _logger,
                              IConfiguration configuration,
                              IWebHostEnvironment hostingEnvironment,
                              IHttpClientFactory httpClientFactory,
                              IHttpContextAccessor httpContextAccessor)
        {
            repositoryManager       = new Lazy <IRepositoryManager>(() => new RepositoryManager(_ctx));
            facebookAuthService     = new Lazy <IFacebookAuthService>(() => new FacebookAuthService(configuration, httpClientFactory));
            googleAuthService       = new Lazy <IGoogleAuthService>(() => new GoogleAuthService(httpClientFactory));
            emailService            = new Lazy <IEmailService>(() => new EmailService(_emailOptions, _logger));
            authentificationService = new Lazy <IAuthenticationService>(() => new AuthenticationService(_ctx, _userManager, _signInManager, httpContextAccessor, googleAuthService.Value, facebookAuthService.Value, emailService.Value, authenticationOptions, _googleOptions, _mapper));
            postService             = new Lazy <IPostService>(() => new PostService(_mapper, repositoryManager.Value.PostRepository, _ctx, _userManager, hostingEnvironment));
            friendService           = new Lazy <IFriendService> (() => new FriendService(repositoryManager.Value.FriendRepository, repositoryManager.Value.ProfileRepository, _userManager, _mapper));
            var notificationHub = NotificationHubClient.CreateClientFromConnectionString(
                configuration["ConnectionStrings:AzureNotificationHubConnection"],
                configuration["NotificationHub:HubName"]);

            registerDeviceService = new Lazy <IRegisterDeviceService>(() => new RegisterDeviceService(notificationHub));
        }
示例#7
0
        public async Task UnRegisterPushByUserDeviceId(PushUri pushUri)
        {
            var hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureUnitNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureUnitNotificationHub_PushUrl);

            var registrations = await hubClient.GetRegistrationsByTagAsync(string.Format("userId:{0}", pushUri.UserId), 50);

            // Step 1: Remove the devices that have a hashed deviceId
            try
            {
                List <Task> tasksWithHashedDeviceId = registrations.Where(x => x.Tags.Contains(pushUri.DeviceId.GetHashCode().ToString())).Select(registration => hubClient.DeleteRegistrationAsync(registration)).ToList();
                await Task.WhenAll(tasksWithHashedDeviceId.ToArray());
            }
            catch { }

            // Step 2: Remove the devices that have a non-hashsed device id (the old style)
            try
            {
                List <Task> tasksWithNormalDeviceId = registrations.Where(x => x.Tags.Contains(pushUri.DeviceId)).Select(registration => hubClient.DeleteRegistrationAsync(registration)).ToList();
                await Task.WhenAll(tasksWithNormalDeviceId.ToArray());
            }
            catch { }

            // Step 3: Remove the devices that have that PushUriId
            try
            {
                List <Task> tasksWithHashedDeviceId = registrations.Where(x => x.Tags.Contains(string.Format("pushUriId:{0}", pushUri.PushUriId))).Select(registration => hubClient.DeleteRegistrationAsync(registration)).ToList();
                await Task.WhenAll(tasksWithHashedDeviceId.ToArray());
            }
            catch (Exception ex)
            {
                Framework.Logging.LogException(ex, string.Format("PushUriId: {0}", pushUri.PushUriId));
            }
        }
示例#8
0
        private static async void SendTemplateNotificationAsync()
        {
            // Define the notification hub.
            string Hubname            = "tripnotification";
            string Connectionstring   = "Endpoint=sb://moognotificationhub.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=ukXpfw/GWF//fy6plp+yYdkSE+KYMhImcZ5hA0e2jHw=";
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(Connectionstring, Hubname);

            // Apple requires the apns-push-type header for all requests
            var headers = new Dictionary <string, string> {
                { "apns-push-type", "alert" }
            };

            // Create an array of breaking news categories.
            var categories = new string[] { "World", "Politics", "Business", "Technology", "Science", "Sports" };

            // Send the notification as a template notification. All template registrations that contain
            // "messageParam" and the proper tags will receive the notifications.
            // This includes APNS, GCM/FCM, WNS, and MPNS template registrations.

            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            foreach (var category in categories)
            {
                templateParams["messageParam"] = "Breaking " + category + " News!";
                await hub.SendTemplateNotificationAsync(templateParams, category);

                Console.WriteLine("sent notification of category :{0}", category);
            }
        }
示例#9
0
 static async void test()
 {
     NotificationHubClient hub = NotificationHubClient
                                 .CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
     var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>";
     await hub.SendWindowsNativeNotificationAsync(toast);
 }
示例#10
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestMessage req,
            [Table("AgentCooldowns")] CloudTable agentCooldowns,
            IBinder binder,
            TraceWriter log)
        {
            var query = req.GetQueryNameValuePairs();

            string character      = query.FirstOrDefault(kv => kv.Key == "char").Value;
            string agentName      = query.FirstOrDefault(kv => kv.Key == "agent").Value;
            string missionName    = query.FirstOrDefault(kv => kv.Key == "mission").Value;
            string timeLeftString = query.FirstOrDefault(kv => kv.Key == "timeLeft").Value;

            if (string.IsNullOrWhiteSpace(character) ||
                string.IsNullOrWhiteSpace(agentName) ||
                string.IsNullOrWhiteSpace(missionName) ||
                !int.TryParse(timeLeftString, out int timeLeft))
            {
                log.Info("Invalid request received.");
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var existingCooldown = (await agentCooldowns.ExecuteAsync(TableOperation.Retrieve <AgentMissionCooldown>(character, agentName))).Result as AgentMissionCooldown;

            var cooldown = new AgentMissionCooldown
            {
                PartitionKey  = character,
                RowKey        = agentName,
                CharacterName = character,
                AgentName     = agentName,
                MissionName   = missionName,
                EndDate       = DateTime.UtcNow.AddSeconds(timeLeft),
            };

            await agentCooldowns.ExecuteAsync(TableOperation.InsertOrReplace(cooldown));

            if (existingCooldown == null || Math.Abs((existingCooldown.EndDate - cooldown.EndDate).TotalMinutes) > 5)
            {
                //Trigger an push if the cooldown end dates differ
                log.Info("New mission cooldown, sending push notification");

                var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["NotificationHub"].ConnectionString;
                var hubClient        = NotificationHubClient.CreateClientFromConnectionString(connectionString, "swlcooldownshub");

                var message = JsonConvert.SerializeObject(new
                {
                    data = new
                    {
                        character,
                        messageType = "NewMissions"
                    }
                });

                var outcome = await hubClient.SendGcmNativeNotificationAsync(message, character);

                log.Info("Notification sent, result: " + outcome.State);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
示例#11
0
        // Push notifications
        private async Task PushToSyncAsync(string message)
        {
            var appSettings  = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
            var nhName       = appSettings.NotificationHubName;
            var nhConnection = appSettings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            // Create a new Notification Hub client
            var hub = NotificationHubClient.CreateClientFromConnectionString(nhConnection, nhName);

            // Create a template message
            var templateParams = new Dictionary <string, string>();

            templateParams["op"]      = "eventsync";
            templateParams["message"] = message;

            // Send the template message
            try
            {
                var result = await hub.SendTemplateNotificationAsync(templateParams);

                Configuration.Services.GetTraceWriter().Info(result.State.ToString());
            }
            catch (Exception ex)
            {
                Configuration.Services.GetTraceWriter().Error(ex.Message, null, "PushToSync Error");
            }
        }
示例#12
0
        private async Task <NotificationOutcome> TriggerPushNotification(bool eventType)
        {
            string windowsToastPayload;
            // Get the Notification Hubs credentials for the Mobile App.
            string notificationHubName       = Keys.NhName;
            string notificationHubConnection = Keys.NhFullConnection;

            // Create the notification hub client.
            var hub = NotificationHubClient
                      .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            // Define a WNS payload
            if (eventType == true)
            {
                windowsToastPayload = @"<toast><visual><binding template=""ToastText01""><text id=""1"">"
                                      + "Someone has entered the store" + @"</text></binding></visual></toast>";
            }
            else
            {
                windowsToastPayload = @"<toast><visual><binding template=""ToastText01""><text id=""1"">"
                                      + "Someone has exited the store" + @"</text></binding></visual></toast>";
            }

            return(await hub.SendWindowsNativeNotificationAsync(windowsToastPayload));
        }
        private static async void SendTemplateNotificationAsync()
        {
            // Define the notification hub.
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");

            // Apple requires the apns-push-type header for all requests
            var headers = new Dictionary <string, string> {
                { "apns-push-type", "alert" }
            };

            // Create an array of different areas the average temperature notficiations should go for.
            var areas = new string[] { "Oslo", "Stockholm", "Copenhagen" };

            // Send the notification as a template notification. All template registrations that contain
            // "messageParam" and the proper tags will receive the notifications.
            // This includes APNS, GCM/FCM, WNS, and MPNS template registrations.

            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            foreach (var area in areas)
            {
                templateParams["messageParam"] = "Area " + area + " Temperature Update!";
                await hub.SendTemplateNotificationAsync(templateParams, area);
            }
        }
        // POST tables/TodoItem
        public async Task <IHttpActionResult> PostTodoItem(TodoItem item)
        {
            TodoItem current = await InsertAsync(item);

            HttpConfiguration           config   = this.Configuration;
            MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

            string notificationHubName = settings.NotificationHubName;

            string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            templateParams["messageParam"] = item.Text + " was added to the list";

            try
            {
                var result = await hub.SendTemplateNotificationAsync(templateParams);

                config.Services.GetTraceWriter().Info(result.State.ToString());
            }
            catch
            {
            }

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
示例#15
0
        public async Task <List <PushRegistrationDescription> > GetRegistrationsByUUID(string uuid)
        {
            var registrations = new List <PushRegistrationDescription>();

            try
            {
                var hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureUnitNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureUnitNotificationHub_PushUrl);

                var registraions = await hubClient.GetRegistrationsByTagAsync(string.Format("uuid:{0}", uuid), 50);

                if (registraions != null && registraions.Any())
                {
                    foreach (var registraion in registraions)
                    {
                        var pushReg = new PushRegistrationDescription();
                        pushReg.ETag           = registraion.ETag;
                        pushReg.ExpirationTime = registraion.ExpirationTime;
                        pushReg.RegistrationId = registraion.RegistrationId;
                        pushReg.Tags           = registraion.Tags;

                        registrations.Add(pushReg);
                    }
                }
            }
            catch (Exception ex)
            {
                string test = ex.ToString();
                /* We can get some timeout errors, aggregate errors, etc from here. For right now, lets just return an empty list on any error. -SJ (12-13-2015) */
            }

            return(registrations);
        }
示例#16
0
        public IHttpActionResult NotifyHub(PushMessage msg)
        {
            try
            {
                var connStr = "Endpoint=sb://azdevelop.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=XquAb+oTzm4huD0htIMeV+mCG/o8ekm6958RTPvYCpQ=";
                var hubName = "referenceguide";
                hub = NotificationHubClient.CreateClientFromConnectionString(connStr, hubName);
                NotificationOutcome outcome = null;
                if (msg.DeviceType == 1)
                {
                    outcome = SendAPNS(msg);
                }
                else
                {
                    outcome = SendGCM(msg);
                }
                msg.Success = outcome.State == NotificationOutcomeState.Completed ? true : false;
            }
            catch (Exception ex)
            {
                var x = ex.Message;
            }

            return(Ok(msg));
        }
示例#17
0
 private static async void SendNotificationAsync(string BlobName)
 {
     NotificationHubClient hub = NotificationHubClient
                                 .CreateClientFromConnectionString("Endpoint=sb://smarthomenamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=+nY8fngDiGjuWma5CTi3KxEUV/jwyE9GAxv7Nrf4FW0=", "SmartHomeNotificationHub");
     var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">New Visitor at your House!! Please Check " + BlobName + "</text></binding></visual></toast>";
     await hub.SendWindowsNativeNotificationAsync(toast);
 }
        public async Task <string> RegisterDevice(Installation installation)
        {
            var hub = NotificationHubClient.CreateClientFromConnectionString(Constants.NotificationAccessKey, Constants.NotificationHubName);
            await hub.CreateOrUpdateInstallationAsync(installation);

            return(installation.InstallationId);
        }
示例#19
0
        public static async Task <bool> SendNotificationAsync(string message, System.Collections.Generic.IEnumerable <string> tags, string to, string tipo, int idCompra, string idDistribuidor)
        {
            try
            {
                hub = NotificationHubClient.CreateClientFromConnectionString(ListenConnectionString, NotificationHubName);

                var notif = ("{\"data\":{\"message\":\"" + message + "\"}}");

                if (to != "" && to != null)
                {
                    notif = ("{\"to\":\"" + to.ToString() +
                             "\",\"data\":" +
                             "{\"message\":\"" + message + "\",\"tipo\":\"" + tipo + "\",\"idCompra\":\"" + idCompra + "\",\"idDistribuidor\":\"" + idDistribuidor + "\"}" +
                             "}");
                }
                await hub.SendGcmNativeNotificationAsync(notif, tags);

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);

                return(true);
            }
        }
示例#20
0
        // POST tables/User
        public async Task <IHttpActionResult> PostUser(User item)
        {
            User current = await InsertAsync(item);


            HttpConfiguration           config   = this.Configuration;
            MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

            string notificationHubName       = settings.NotificationHubName;
            string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName, true);

            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            templateParams["messageParam"] = item.Username + " was added to the list.";

            try
            {
                // Send the push notification and log the results.
                var result = await hub.SendTemplateNotificationAsync(templateParams);

                // Write the success result to the logs.
                config.Services.GetTraceWriter().Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                // Write the failure result to the logs.
                config.Services.GetTraceWriter()
                .Error(ex.Message, null, "Push.SendAsync Error");
            }


            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var hubConnection   = "Endpoint=sb://thnotify1.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=Z2Xpa9dMYJLipI26LS1hltCZw8U4KI41NfnPucWkWqw=";
            var hubName         = "not1";
            var hubClient       = NotificationHubClient.CreateClientFromConnectionString(hubConnection, hubName);
            var registrationSvc = new AzureRegistrationService(hubClient);

            services.AddSingleton <IRegistrationService>(registrationSvc);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "yourdomain.com",
                    ValidAudience    = "yourdomain.com",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))
                };
            });

            services.AddMvc();
        }
        protected void btnSendNotifications_Click(object sender, EventArgs e)
        {
            // Get the Notification Hubs credentials for the Mobile App.
            string notificationHubName       = "devxamarin";
            string notificationHubConnection = "Connection String for DefaultFullSharedAccessSignature";

            // Create a new Notification Hub client.
            NotificationHubClient hub = NotificationHubClient
                                        .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            templateParams["messageParam"] = txtToSend.Text;

            try
            {
                // Send the push notification and log the results.
                hub.SendTemplateNotificationAsync(templateParams).Wait();

                // Write the success result to the logs.
                // config.Services.GetTraceWriter().Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                /* Write the failure result to the logs.
                 * config.Services.GetTraceWriter()
                 *  .Error(ex.Message, null, "Push.SendAsync Error");
                 */
            }
        }
示例#23
0
        public static async Task <bool> SendNotificationAsync(string message, string idNotificacao, bool broadcast = false)
        {
            string[] userTag = new string[1];

            // Obs importantíssima: O username tá na primeira parte do id da
            // notificação antes do ":"(dois pontos). Para mandar broadcast é só
            //enviar o username em branco
            userTag[0] = string.Empty;


            string defaultFullSharedAccessSignature = util.configTools.getConfig("hubnotificacao");
            string hubName = util.configTools.getConfig("hubname");
            string handle  = idNotificacao;//hubName;

            NotificationHubClient _hub = NotificationHubClient.CreateClientFromConnectionString(defaultFullSharedAccessSignature, hubName);
            //await _hub.DeleteRegistrationAsync(idNotificacao);

            //Excluindo registros
            var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100);

            foreach (RegistrationDescription xregistration in registrations)
            {
                try
                {
                    await _hub.DeleteRegistrationAsync(xregistration);
                }
                catch (Exception ex) { string sm = ex.Message; }
            }


            if (!broadcast)
            {
                string to_tag = idNotificacao.Split(':')[0];
                userTag[0] = "username:"******"{ \"data\" : {\"message\":\"" + message + "\"}}";

            outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag);

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                      (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    return(true);
                }
            }
            return(false);
        }
        public AzureNotificationHubDecorator(ILogger log)
        {
            _log = log;
            string connectionString = Environment.GetEnvironmentVariable("AzureNotificationHubs");
            string hubName          = Environment.GetEnvironmentVariable("AzureNotificationHubName");

            _hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
        }
示例#25
0
        static async Task SendNotificationAsync(SimpleModel model)
        {
            NotificationHubClient hub = NotificationHubClient
                                        .CreateClientFromConnectionString("Endpoint=sb://cincyazure.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=HDCgcWXf9CLsdmgvnNzfSqy66ZRLC++E07yzG1BRxkg=", "CincyAzure");

            var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">The report you requested has been processed and is now available for viewing!</text></binding></visual></toast>";
            await hub.SendWindowsNativeNotificationAsync(toast, "Azure");
        }
 private NotificationHubClient GetNotificationHubClient()
 {
     if (_notificationHubClient == null)
     {
         _notificationHubClient = NotificationHubClient.CreateClientFromConnectionString(_connectionString, _hubName);
     }
     return(_notificationHubClient);
 }
        private NotificationHubClient GetNhClient()
        {
            var    settings                  = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
            string notificationHubName       = settings.NotificationHubName;
            string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            return(NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName));
        }
示例#28
0
        public NotificationsProvider()
        {
            MobileAppSettingsDictionary settings = Startup.Config.GetMobileAppSettingsProvider().GetMobileAppSettings();
            var notificationHubName       = settings.NotificationHubName;
            var notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
        }
示例#29
0
 private async Task SendPushNotification(string notification)
 {
     string NHConnection       = this.Services.Settings.Connections["NHConnectionString"].ConnectionString;
     string NHPath             = this.Services.Settings["NHPath"].ToString();
     NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(NHConnection, NHPath);
     var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" + notification + "</text></binding></visual></toast>";
     await hub.SendWindowsNativeNotificationAsync(toast);
 }
 public PushNotificationController()
 {
     _notificationHubClient =
         NotificationHubClient.CreateClientFromConnectionString(
             ConfigurationManager.AppSettings["AzureNotificationHubConnectionString"],
             ConfigurationManager.AppSettings["AzureNotificationHubName"]);
     _pushNotificationService = new PushNotificationService();
 }