Beispiel #1
0
        // POST tables/SensorData
        public async Task <IHttpActionResult> PostSensorData(SensorData item)
        {
            SensorData current = await InsertAsync(item);

            // Create a WNS native toast.
            var message = new WindowsPushMessage();

            // Define the XML paylod for a WNS native toast notification
            // that contains the text of the inserted item.
            message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                 @"<toast><visual><binding template=""ToastText01"">" +
                                 @"<text id=""1"">" + "Temperature: " + item.Temperature + @"</text>" +
                                 @"</binding></visual></toast>";
            try
            {
                NotificationOutcome result = await Services.Push.SendAsync(message);

                Services.Log.Info(result.State.ToString());
            }
            catch (Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
        public async Task<bool> Post(JObject data)
        {
            try
            {
                //TODO: Trzeba rozpoznawać użytkowników i wysyłać do właściwych urzadzeń
                var currentUser = this.User as ServiceUser;
                ////
                NotificationHubClient hub = NotificationHubClient
                    .CreateClientFromConnectionString("Endpoint=sb://karolzakpip.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=J2Rrw4Xt67NADIOprmmEiyPX89LCOrcP+8WkCBMsuXw=", "karolzakpip");
                string wnsToast = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><toast><visual><binding template=\"ToastText01\"><text id=\"1\">{0}</text></binding></visual></toast>", data.GetValue("message").Value<string>());

                WindowsPushMessage message = new WindowsPushMessage();
                message.XmlPayload = wnsToast;
                //var result = await Services.Push.SendAsync(message, currentUser.Id);
                await hub.SendWindowsNativeNotificationAsync(wnsToast,currentUser.Id);

                ////
                string text = data.GetValue("message").Value<string>();              
                string toast = PrepareToastPayload(text, text);
                await hub.SendMpnsNativeNotificationAsync(toast, currentUser.Id);

                


                return true;
            }
            catch
            {
                return false;
            }
        }
        // PATCH tables/Player/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public async Task <Player> PatchPlayer(string id, Delta <Player> patch)
        {
            var currentUser = User as ServiceUser;
            var item        = patch.GetEntity();

            var result = await UpdateAsync(id, patch);

            var players = context.Players.OrderByDescending(player => player.Clicks).ToList();

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]);
                player.Entity.Rank      = i + 1;
                player.Entity.OldClicks = player.Entity.Clicks;
            }

            await context.SaveChangesAsync();

            var message = new WindowsPushMessage();

            message.Headers.Add("X-WNS-Type", "wns/raw");
            message.XmlPayload = JsonConvert.SerializeObject(context.Players.ToList());

            await Services.Push.SendAsync(message);

            return(result);
        }
        // POST tables/Smartphone
        public async Task <IHttpActionResult> PostSmartphone(Smartphone smartphone)
        {
            Smartphone current = await InsertAsync(smartphone);

            // Android (Google)
            var datosGoogle = new Dictionary <string, string>()
            {
                { "mensaje", JsonConvert.SerializeObject(smartphone) }
            };
            var mensajeGoogle = new GooglePushMessage(datosGoogle, TimeSpan.FromHours(1));

            // UWP
            var datosUwp   = @"<?xml version=""1.0"" encoding=""utf - 8""?>
<toast>
    <visual>
        <binding template=""ToastText01"">
            <text id=""1"">Nuevo smartphone</text>
            <text id=""1"">Modelo: " + smartphone.Modelo + @"</text>
            <text id=""1"">Fabricante: " + smartphone.Fabricante + @"</text>
        </binding>
    </visual>
	<actions>
			<action content=""Ver"" arguments=""check"" />
			<action content=""Descartar"" arguments=""cancel""/>
	</actions>
</toast>";
            var mensajeUwp = new WindowsPushMessage()
            {
                XmlPayload = datosUwp
            };

            // Tag
            var tag  = "NuevoSmartphone";
            var tags = new List <string>();

            tags.Add(tag);


            try
            {
                // Android (Google) Push
                var resultadoGoogle = await Services.Push.SendAsync(mensajeGoogle, tags);

                Services.Log.Info("Google - " + resultadoGoogle.State);


                // UWP Push
                var resultadoUwp = await Services.Push.SendAsync(mensajeUwp, tags);

                Services.Log.Info("Microsoft - " + resultadoUwp.State);
            }
            catch (Exception e)
            {
                Services.Log.Error(e.Message);
            }


            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
Beispiel #5
0
        public async override Task ExecuteAsync()
        {
            var players = context.Players.OrderByDescending(player => player.Clicks).ToList();

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]);
                player.Entity.Rank      = i + 1;
                player.Entity.OldClicks = player.Entity.Clicks;
            }

            await context.SaveChangesAsync();

            players = context.Players.OrderByDescending(player => player.Clicks).ToList();
            Player winner = null;

            for (int i = 0; i < players.Count; i++)
            {
                var player = context.Entry <Player>(players[i]).Entity;
                if (i == 0)
                {
                    winner = player;
                    WindowsPushMessage message = new WindowsPushMessage();

                    // Define the XML paylod for a WNS native toast notification
                    // that contains the text of the inserted item.
                    message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                         @"<toast><visual><binding template=""ToastText01"">" +
                                         @"<text id=""1"">" + "Congratulations " + player.Name + "!! You are todays first player with " + player.Clicks + " clicks. " + @"</text>" +
                                         @"</binding></visual></toast>";

                    // Use a tag to only send the notification to the logged-in user.
                    var result = await Services.Push.SendAsync(message, player.UserId);
                }
                else
                {
                    WindowsPushMessage message = new WindowsPushMessage();

                    // Define the XML paylod for a WNS native toast notification
                    // that contains the text of the inserted item.
                    message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                         @"<toast><visual><binding template=""ToastText01"">" +
                                         @"<text id=""1"">" + "Sorry " + player.Name + ". You lost to " + winner.Name + ". Better luck next time." + @"</text>" +
                                         @"</binding></visual></toast>";

                    // Use a tag to only send the notification to the logged-in user.
                    var result = await Services.Push.SendAsync(message, player.UserId);
                }
            }
        }
		// The following call is for illustration purpose only. The function
		// body should be moved to a controller in your app where you want
		// to send a notification.
		public async Task<bool> Post(JObject data)
		{
			try
			{
				string wnsToast = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><toast><visual><binding template=\"ToastText01\"><text id=\"1\">{0}</text></binding></visual></toast>", data.GetValue("toast").Value<string>());
				WindowsPushMessage message = new WindowsPushMessage();
				message.XmlPayload = wnsToast;
				await Services.Push.SendAsync(message);
				return true;
			}
			catch (Exception e)
			{
				Services.Log.Error(e.ToString());
			}
			return false;
		}
        private async Task SendNotification(string message)
        {


           

            try
            {
                #region Windows push notification
                // Create a WNS native toast.
                WindowsPushMessage windowsPushMessage = new WindowsPushMessage
                {
                    XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                 @"<toast><visual><binding template=""ToastText02"">" +
                                 @"<text id=""1"">Blog post</text>" +
                                 @"<text id=""2"">" + message + @"</text>" +
                                 @"</binding></visual></toast>"
                };

                // Define the XML paylod for a WNS native toast notification 
                // that contains the text of the inserted item.

              
                var resultWindows = await Services.Push.SendAsync(windowsPushMessage);
                //await Services.Push.SendAsync(windowsPushMessage,"azure mobile services");
                Services.Log.Info(resultWindows.State.ToString());
                #endregion


                #region Google Push notification
                GooglePushMessage googlePushMessage = new GooglePushMessage();
                googlePushMessage.CollapseKey = "Blog post";
                googlePushMessage.Data.Add("message", message);
                googlePushMessage.DelayWhileIdle = true;
                googlePushMessage.TimeToLiveInSeconds = TimeSpan.FromHours(1).Seconds;

                var resultGoogle = await Services.Push.SendAsync(googlePushMessage);
                Services.Log.Info(resultGoogle.State.ToString());
                #endregion
            }
            catch (System.Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

        }
Beispiel #8
0
 public static async Task SendToastAsync(this ApiServices services, string content, IEnumerable<string> tags)
 {
     WindowsPushMessage message = new WindowsPushMessage
     {
         XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                      @"<toast><visual><binding template=""ToastText01"">" +
                      @"<text id=""1"">" + content + @"</text>" +
                      @"</binding></visual></toast>"
     };
     try
     {
         var result = await services.Push.SendAsync(message, tags);
         services.Log.Info(result.State.ToString());
     }
     catch (System.Exception ex)
     {
         services.Log.Error(ex.Message, null, "Push.SendAsync Error");
     }
 }
Beispiel #9
0
 public static async Task SendToastAsync(this ApiServices services, string title, string content, IEnumerable<string> tags)
 {
     WindowsPushMessage message = new WindowsPushMessage
     {
         XmlPayload = "<toast>\n" +
                      " <visual>\n" +
                      " <binding template=\"ToastText03\">\n" +
                      $" <text id=\"1\">{title}</text>\n" +
                      $" <text id=\"2\">{content}</text>\n" +
                      " </binding> \n" +
                      " </visual>\n" +
                      "</toast>"
     };
     try
     {
         var result = await services.Push.SendAsync(message, tags);
         services.Log.Info(result.State.ToString());
     }
     catch (System.Exception ex)
     {
         services.Log.Error(ex.Message, null, "Push.SendAsync Error");
     }
 }
Beispiel #10
0
        public async Task <W8PushTestEntity> PostW8PushTestEntity(W8PushTestEntity item)
        {
            IPushMessage message = null;
            string       tag     = null;

            if (item.NHNotificationType == "template")
            {
                message = item.TemplateNotification.ToObject <TemplatePushMessage>();
                tag     = "World";
            }
            else
            {
                var windowsMessage = new WindowsPushMessage();
                if (item.NHNotificationType == "raw")
                {
                    windowsMessage.XmlPayload = item.Payload;
                }
                else
                {
                    windowsMessage.XmlPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + item.XmlPayload;
                }

                windowsMessage.Headers.Add("X-WNS-Type", "wns/" + item.NHNotificationType);
                message = windowsMessage;
                tag     = "tag1";
            }

            NotificationOutcome pushResponse = await this.Services.Push.SendAsync(message, tag);

            this.Services.Log.Info("WNS push sent: " + pushResponse, this.Request);
            return(new W8PushTestEntity()
            {
                Id = "1",
                PushResponse = pushResponse.State.ToString() + "-" + pushResponse.TrackingId,
            });
        }
Beispiel #11
0
        // POST tables/Games/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public async Task <IHttpActionResult> PostGame(Game item)
        {
            // Send a push notification to the opponent.
            var dbContext   = new TicTacToeMobileServiceContext();
            var user1Result = from user in dbContext.Users
                              where user.Id == item.User1
                              select user;
            User user1 = user1Result.First();

            var user2Result = from user in dbContext.Users
                              where user.Id == item.User2
                              select user;
            User user2   = user2Result.First();
            Game current = await InsertAsync(item);

            WindowsPushMessage message = new WindowsPushMessage();

            message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                 @"<toast><visual><binding template=""ToastText04"">" +
                                 @"<text id=""1"">" + user1.UserName + " wants to play TicTacToe!" + @"</text>" +
                                 @"</binding></visual></toast>";
            try
            {
                string[] tags = { user2.UserId };

                var result = await Services.Push.SendAsync(message, tags);

                Services.Log.Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
        public async Task<HttpResponseMessage> Post()
        {
            
            var data = await this.Request.Content.ReadAsAsync<JObject>();
            var method = (string) data["method"];

            if (method == null)
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
            }

            if (method == "send")
            {
                var serialize = new JsonSerializer();

                var token = (string)data["token"];

                if (data["payload"] == null || token == null)
                {
                    return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
                }

                // Payload could be a string or a dictionary
                var payloadString = data["payload"].ToString();

                var type = (string)data["type"];
                var tag = (string)data["tag"];

                Services.Log.Info(payloadString);

                if (type == "template") {
                    TemplatePushMessage message = new TemplatePushMessage();
                    var payload = JObject.Parse(payloadString);
                    var keys = payload.Properties();
                    foreach (JProperty key in keys) {
                        Services.Log.Info("Key: " + key.Name);
                        message.Add(key.Name, (string) key.Value);
                    }
                    if (tag != null)
                    {
                        await Services.Push.SendAsync(message, tag);
                    }
                    else
                    {
                        await Services.Push.SendAsync(message);
                    }
                }
                else if (type == "gcm")
                {
                    GooglePushMessage message = new GooglePushMessage();
                    message.JsonPayload = payloadString;
                    var result = await Services.Push.SendAsync(message);
                }
                else if (type == "apns")
                {
                    ApplePushMessage message = new ApplePushMessage();
                    message.JsonPayload = payloadString;
                    var result = await Services.Push.SendAsync(message);
                }
                else if (type == "wns")
                {
                    var wnsType = (string)data["wnsType"];
                    WindowsPushMessage message = new WindowsPushMessage();
                    message.XmlPayload = payloadString;
                    message.Headers.Add("X-WNS-Type", type + '/' + wnsType);
                    if (tag != null)
                    {
                        await Services.Push.SendAsync(message, tag);
                    }
                    else
                    {
                        await Services.Push.SendAsync(message);
                    }
                }
            }
            else 
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
            }

            return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
Beispiel #13
0
 public static async Task SendToastAsync(this ApiServices services, JObject obj, string tags)
 {
     WindowsPushMessage message = new WindowsPushMessage
     {
         XmlPayload = "<toast>\n" +
                      " <visual>\n" +
                      " <binding template=\"ToastImageAndText03\">\n" +
                      $" <image id=\"1\" src=\"{obj["Avatar"].ToString()}\" alt=\"image1\"/>\n" +
                      $" <text id=\"1\">{obj["Username"].ToString()}</text>\n" +
                      $" <text id=\"2\">{obj["Content"].ToString()}</text>\n" +
                      $" <text id=\"3\">{obj["InboxDate"].ToString()}</text>\n" +
                      $" <text id=\"4\">{obj["ID"].ToString()}</text>\n" +
                      $" <text id=\"5\">{obj["MessageID"].ToString()}</text>\n" +
                      $" <text id=\"6\">{obj["UserID"].ToString()}</text>\n" +
                      $" <text id=\"7\">{obj["OwnerID"].ToString()}</text>\n" +
                      " </binding> \n" +
                      " </visual>\n" +
                      "</toast>"
     };
     try
     {
         var result = await services.Push.SendAsync(message, tags);
         services.Log.Info(result.State.ToString());
     }
     catch (System.Exception ex)
     {
         services.Log.Error(ex.Message, null, "Push.SendAsync Error");
     }
 }
        public async Task <HttpResponseMessage> Post()
        {
            var data = await this.Request.Content.ReadAsAsync <JObject>();

            var method = (string)data["method"];

            if (method == null)
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
            }

            if (method == "send")
            {
                var serialize = new JsonSerializer();

                var token = (string)data["token"];


                if (data["payload"] == null || token == null)
                {
                    return(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
                }

                // Payload could be a string or a dictionary
                var payloadString = data["payload"].ToString();

                var type = (string)data["type"];
                var tag  = (string)data["tag"];


                if (type == "template")
                {
                    TemplatePushMessage message = new TemplatePushMessage();
                    var payload = JObject.Parse(payloadString);
                    var keys    = payload.Properties();
                    foreach (JProperty key in keys)
                    {
                        this.traceWriter.Info("Key: " + key.Name);

                        message.Add(key.Name, (string)key.Value);
                    }
                    var result = await this.pushClient.SendAsync(message, "World");
                }
                else if (type == "gcm")
                {
                    GooglePushMessage message = new GooglePushMessage();
                    message.JsonPayload = payloadString;
                    var result = await this.pushClient.SendAsync(message);
                }
                else if (type == "apns")
                {
                    ApplePushMessage message = new ApplePushMessage();
                    this.traceWriter.Info(payloadString.ToString());
                    message.JsonPayload = payloadString.ToString();
                    var result = await this.pushClient.SendAsync(message);
                }
                else if (type == "wns")
                {
                    var wnsType = (string)data["wnsType"];
                    WindowsPushMessage message = new WindowsPushMessage();
                    message.XmlPayload = payloadString;
                    message.Headers.Add("X-WNS-Type", type + '/' + wnsType);
                    if (tag != null)
                    {
                        await this.pushClient.SendAsync(message, tag);
                    }
                    else
                    {
                        await this.pushClient.SendAsync(message);
                    }
                }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest));
            }

            return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
        }
Beispiel #15
0
		/// <summary>
		/// Send a Toast to the device
		/// </summary>
		private async Task SendWncToastAsync(string text1, string text2, string ident)
		{
			try
			{
				var message = new WindowsPushMessage
				{
					XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
								 @"<toast><visual><binding template=""ToastText01"">" +
								 @"<text id=""2"">"+text1+"</text>" +
								 @"<text id=""1"">" + text2 + "</text>" +
								 @"</binding></visual></toast>"
				};
				await Services.Push.SendAsync(message, ident);
			}
			catch (Exception exception)
			{
				base.Services.Log.Error(exception);
			}
		}
Beispiel #16
0
        private async void SendNotificationToClient(Pictures item)
        {
            Services.Log.Info("Sending notification to Client App");

            WindowsPushMessage message = new WindowsPushMessage();
            var tags = new List <string>();

            tags.Add(item.DoorBellID);

            // Define the XML paylod for a WNS native toast notification
            // that contains the text of the inserted item.
            message.XmlPayload = "<toast scenario=\'reminder\' launch =\'deals\'>" +
                                 "<visual>" +
                                 "<binding template =\'ToastGeneric\'>" +
                                 "<text>Door Bell Id</text>" +
                                 "<text>Someone ringing your Door bell with Id: " + item.DoorBellID + "</text>" +
                                 "<image placement=\'inline\' src=\'" + item.Url + "\'/>" +
                                 "</binding></visual>" +
                                 "</toast>";


            try
            {
                var result = await Services.Push.SendAsync(message, tags);

                Services.Log.Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

            message.XmlPayload =
                @"<tile version ='3'>
                                    <visual branding = 'nameAndLogo'>
                                     <binding template = 'TileWide'>
                                      <image src='" + item.Url + @"' placement='background'  hint-overlay='60'/>
                                      <image src='" + item.Url + @"' placement='peek'/>
                                      <group>                                       
                                       <subgroup>
                                        <text hint-style ='body'>Door Bell Id</text>            
                                        <text hint-style ='captionSubtle' hint-wrap = 'true'>" + item.DoorBellID + @"</text>                       
                                       </subgroup>                       
                                      </group>
                                     </binding>
                                    <binding template = 'TileLarge'>
                                      <image src='" + item.Url + @"' placement='background'  hint-overlay='60'/>
                                      <image src='" + item.Url + @"' placement='peek'/>
                                      <group>                                       
                                      <subgroup>
                                       <text hint-style ='body'>Door Bell Id</text>            
                                       <text hint-style ='captionSubtle' hint-wrap = 'true'>" + item.DoorBellID + @"</text>                       
                                      </subgroup>                       
                                     </group>
                                    </binding>
                                    <binding template = 'TileMedium'>
                                      <image src='" + item.Url + @"' placement='background'  hint-overlay='60'/>
                                      <image src='" + item.Url + @"' placement='peek'/>
                                      <group>
                                      <subgroup>
                                       <text hint-style ='body'>Door Bell Id</text>            
                                       <text hint-style ='captionSubtle' hint-wrap = 'true'>" + item.DoorBellID + @"</text>                       
                                      </subgroup>                       
                                     </group>
                                    </binding>
                                  </visual>
                                 </tile>";


            try
            {
                await Services.Push.SendAsync(message, tags);
            }
            catch (System.Exception ex)
            {
                // Write the failure result to the logs.
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }
        }
Beispiel #17
0
        // POST tables/Moves/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public async Task <IHttpActionResult> PostMove(Move item)
        {
            // Find the user and game
            var  dbContext  = new TicTacToeMobileServiceContext();
            var  userResult = dbContext.Users.Where(user => user.Id == item.UserId);
            User user1      = userResult.First();
            var  gameResult = dbContext.Games.Where(game => game.Id == item.GameId);
            Game game1      = gameResult.First();

            // Get the second user.
            string user2Id     = (game1.User1 == user1.Id ? game1.User2 : game1.User1);
            var    userResult2 = dbContext.Users.Where(user => user.Id == user2Id);
            User   user2       = userResult2.First();

            Move current = await InsertAsync(item);

            string pushText = "TicTacToe: ";

            if (item.GameResult == 0) // Game is not over.
            {
                WindowsPushMessage badgeMessage = new WindowsPushMessage();
                badgeMessage.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                          @"<badge value=""alert""/>";

                try
                {
                    var tags = new string[] { user2.UserId };
                    await Services.Push.SendAsync(badgeMessage, tags);
                }
                catch (System.Exception ex)
                {
                    Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
                }

                pushText = pushText + user1.UserName + " played and now it's your turn!";
            }
            else if (item.GameResult == 1) // Game is over, a player won.
            {
                pushText = pushText + user1.UserName + " played and the game is over. " + item.Winner + " won!";
            }
            else if (item.GameResult == 2) // Game ended in a draw.
            {
                pushText = pushText + user1.UserName + " played and the game is over! It's a tie.";
            }

            WindowsPushMessage toastMessage = new WindowsPushMessage();

            toastMessage.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                      @"<toast><visual><binding template=""ToastText01"">" +
                                      @"<text id=""1"">" + pushText + @"</text>" +
                                      @"</binding></visual></toast>";
            try
            {
                var tags   = new string[] { user2.UserId };
                var result = await Services.Push.SendAsync(toastMessage, tags);

                Services.Log.Info(result.State.ToString());
            }
            catch (System.Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }