Esempio n. 1
0
        public override void OnReceive(Context context, Intent intent)
        {
            base.OnReceive(context, intent);

            if ((intent.Action != null) && (intent.Action == Android.Content.Intent.ActionBootCompleted))
            {
                PushNotificationService.ShowNotification(context, typeof(SplashScreen), "Tollminder - open for tracking", "Tollminder is not started");
                //Toast.MakeText(context, “Received intent!”, ToastLength.Short).Show();

                //if ((intent.Action != null) &&
                //(intent.Action ==
                //Android.Content.Intent.ActionBootCompleted))
                //{ // Start the service or activity
                //  //context.ApplicationContext.StartService(new Intent(context, typeof(MainActivity)));

                //    Android.Content.Intent start = new Android.Content.Intent(context, typeof(HomeDebugView));

                //    // my activity name is MainActivity replace it with yours
                //    start.AddFlags(ActivityFlags.NewTask);
                //    context.ApplicationContext.StartActivity(start);
                //}
            }
            //new Handler(context.MainLooper).Post(() =>
            //            {
            //                Toast.MakeText(context, "Tollminder not started.", ToastLength.Short).Show();
            //            });
        }
        public void SendLocalNotification(string title, string message)
        {
            //var notificationIntent = new Intent (Application.Context, typeof(HomeDebugView));

            //var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create (Application.Context);
            //stackBuilder.AddParentStack (Java.Lang.Class.FromType (typeof(HomeDebugView)));
            //stackBuilder.AddNextIntent (notificationIntent);

            //var notificationPendingIntent =	stackBuilder.GetPendingIntent (0, (int)PendingIntentFlags.UpdateCurrent);

            //var builder = new NotificationCompat.Builder (Application.Context);
            //         builder.SetSmallIcon (Resource.Mipmap.icon)
            //	.SetLargeIcon (BitmapFactory.DecodeResource (Application.Context.Resources, Resource.Mipmap.icon))
            //	.SetColor (Color.Red)
            //	.SetContentTitle (title)
            //	.SetContentText (message)
            //	.SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Notification))
            //	.SetContentIntent (notificationPendingIntent);

            //builder.SetAutoCancel (true);

            //var mNotificationManager = (NotificationManager)Application.Context.GetSystemService (Context.NotificationService);
            //mNotificationManager.Notify (0, builder.Build ());
            PushNotificationService.ShowNotification(Application.Context, typeof(HomeDebugView), title, message);
        }
 public PushNotificationController(ILogger <PushNotificationController> logger,
                                   PushNotificationService pushNotificationService, IFeatureManager featureManager)
 {
     _logger = logger;
     _pushNotificationService = pushNotificationService;
     _featureManager          = featureManager;
 }
    void OnGUI()
    {
        if (Time.time % 2 < 1) {
            success = callBack.getResult ();
        }

        // For Setting Up ResponseBox.
        GUI.TextArea (new Rect (10, 5, 500, 175), success);

        //=========================================================================
        if (GUI.Button (new Rect (50, 200, 200, 30), "Create Channel ForApp")) {
            pushNotificationService = sp.BuildPushNotificationService (); // Initializing PushNotification Service.
            pushNotificationService.CreateChannelForApp (cons.channelName, cons.description, callBack);
        }

        //=========================================================================
        if (GUI.Button (new Rect (250, 200, 200, 30), "Subscribe To Channel ")) {
            pushNotificationService = sp.BuildPushNotificationService (); // Initializing PushNotification Service.
            pushNotificationService.SubscribeToChannel (cons.channelName, cons.userName, callBack);
        }

        //=========================================================================
        if (GUI.Button (new Rect (50, 250, 200, 30), "Send Push Message ToChannel ")) {
            pushNotificationService = sp.BuildPushNotificationService (); // Initializing PushNotification Service.
            pushNotificationService.SendPushMessageToChannel (cons.channelName, cons.message, callBack);
        }

        //===================================###################=========================================
        if (GUI.Button (new Rect (250, 250, 200, 30), "Unsubscribe From Channel")) {
            pushNotificationService = sp.BuildPushNotificationService (); // Initializing PushNotification Service.
            pushNotificationService.UnsubscribeFromChannel (cons.channelName, cons.userName, callBack);
        }
    }
        public IActionResult NotificationToUser([FromBody] NotificationRequest notif)
        {
            try {
                if (notif.To == null || notif.To.Count == 0)
                {
                    return(BadRequest());
                }
            } catch {
                return(BadRequest());
            }
            notif.To.ForEach(item => {
                var userId   = _context.MUser.FirstOrDefault(x => x.PushId == item).Id;
                var newNotif = new Notification(notif)
                {
                    To       = userId,
                    PushDate = DateTime.UtcNow
                };
                _context.Notification.Add(newNotif);
            });

            _context.Commit();
            NotificationRequestToMultipleUser body = new NotificationRequestToMultipleUser(notif);
            string jsonBody = JsonConvert.SerializeObject(body);

            return(Ok(PushNotificationService.sendPushNotification(jsonBody)));
        }
Esempio n. 6
0
        public bool SendPush(string PushID)
        {
            //Set array of IDs, just one here :)
            string[] id = { PushID };

            var requestMessage = new RequestMessage
            {
                Body =
                {
                    RegistrationIds = id,

                    /*Notification = new CrossPlatformNotification
                     * {
                     *  Title = "Important Notification",
                     *  Body = "This is a notification send from Firebase.NET"
                     * },*/
                    Data            = new Payload()
                    {
                        { "mobiledownload", "Available" },
                    }
                }
            };

            //your implemented functions that will be send to Firebase.NET as parameters
            Func <string, string, bool> updateFunc = new Func <string, string, bool>(Update);
            Func <string, bool>         deleteFunc = new Func <string, bool>(Delete);

            string mysecrettoken = "AAAATEVUNGI:APA91bFP8O_MD7hpxpUeS8yNtAupv9FxXBvtipd9SeQGURKRJFHUod6VC4Hu8Bif4_3RJbht1EKvuOePGCxOtLa9UAlI6yup99vz9mOWcNWUXqmF2YxUt1H62AusDoM1Q2rhWcwHPbaH";

            PushNotificationService pushService = new PushNotificationService(mysecrettoken, updateFunc, deleteFunc);

            pushService.MAX_RETRIES = 5;
            ResponseMessage responseMessage = (ResponseMessage)pushService.PushMessage(requestMessage).Result;

            string error = "";

            if (responseMessage.Body != null)
            {
                for (int i = 0; i < responseMessage.Body.Results.Length; i++)
                {
                    if (responseMessage.Body.Results[i].RequestRetryStatus != PushMessageStatus.NULL)
                    {
                        Console.WriteLine(((PushMessageStatus)responseMessage.Body.Results[i].RequestRetryStatus).ToString());
                    }
                    error = responseMessage.Body.Results[i].Error != null ? ((ResponseMessageError)responseMessage.Body.Results[i].Error).ToString() : "";
                    if (error.Length == 0)
                    {
                        error = "None";
                    }
                    Console.WriteLine("Error: {0};  MessageId: {1};  RegistrationId: {2}", error, responseMessage.Body.Results[i].MessageId, responseMessage.Body.Results[i].RegistrationId);
                }
            }

            //Easy handle?
            if (error.Length != 0)
            {
                return(false);
            }
            return(true);
        }
        public async Task SendPushNotification_GIVEN_Invalid_Message_RETURNS_Null(string message)
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:Url"] = "https://www.test.com";

            var tokenType   = "bearer";
            var accessToken =
                "nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM";

            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = "9009165023080",
                Title    = "Test Title",
                Message  = message
            };

            var httpClientOperations    = Substitute.For <IHttpClientOperations>();
            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.SendPushNotification(accessToken, tokenType, pushNotificationRequest, CancellationToken.None);

            // Assert.
            Assert.IsNull(actual);
        }
        public async Task SendPushNotification_GIVEN_Valid_Inputs_RETURNS_Valid_PushNotificationResponse_SuccessFalse()
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:Url"] = "https://www.test.com";

            var tokenType   = "bearer";
            var accessToken =
                "nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM";
            var authorizationHeader = new AuthenticationHeaderValue(tokenType.Trim(), accessToken);

            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = "9009165023080",
                Title    = "Test Title",
                Message  = "Test Message"
            };

            var httpClientOperations = Substitute.For <IHttpClientOperations>();

            httpClientOperations.SendHttpRequestAsync(HttpMethod.Post, authorizationHeader, Arg.Any <Dictionary <string, string> >(),
                                                      "https://www.test.com", Arg.Any <HttpContent>(), CancellationToken.None).Returns(Task.FromResult("{\r\n    \"success\": false,\r\n    \"message\": \"Could not find user with ID Number: 9009165023080\"\r\n}"));

            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.SendPushNotification(accessToken, tokenType, pushNotificationRequest, CancellationToken.None);

            // Assert.
            Assert.IsNotNull(actual);
            Assert.AreEqual(false, actual.Success);
            Assert.AreEqual("Could not find user with ID Number: 9009165023080", actual.Message);
        }
        public async Task GetAccessTokenAsync_GIVEN_Valid_Settings_RETURNS_Valid_PushNotificationWebTokenResponse()
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:WebTokenUrl"]          = "https://www.test.com";
            settings["PushNotification:WebTokenClientSecret"] = "dgfdggdfgdgfgfdgdg";
            settings["PushNotification:WebTokenGrantType"]    = "client_credentials";
            settings["PushNotification:WebTokenClientId"]     = "push-user";

            var httpClientOperations = Substitute.For <IHttpClientOperations>();

            httpClientOperations.SendHttpRequestAsync(HttpMethod.Post, null, Arg.Any <Dictionary <string, string> >(),
                                                      "https://www.test.com", Arg.Any <HttpContent>(), CancellationToken.None).Returns(
                Task.FromResult(
                    "{\r\n    \"access_token\": \"nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM\",\r\n    \"token_type\": \"bearer\",\r\n    \"expires_in\": 315359999,\r\n    \".issued\": \"Tue, 08 Jan 2019 07:46:40 GMT\",\r\n    \".expires\": \"Fri, 05 Jan 2029 07:46:40 GMT\"\r\n}")
                );

            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.GetAccessTokenAsync(CancellationToken.None);

            // Assert.
            Assert.IsNotNull(actual);
            Assert.AreEqual(
                "nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM",
                actual.AccessToken);
            Assert.AreEqual("bearer", actual.TokenType);
            Assert.AreEqual(315359999, actual.ExpiresIn);
            Assert.AreEqual(DateTimeOffset.Parse("Tue, 08 Jan 2019 07:46:40 GMT").UtcDateTime, actual.Issued);
            Assert.AreEqual(DateTimeOffset.Parse("Fri, 05 Jan 2029 07:46:40 GMT").UtcDateTime, actual.Expires);
        }
Esempio n. 10
0
        public async Task <IActionResult> DeleteDevice([FromRoute] string deviceId)
        {
            var user = await UserManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound());
            }
            var device = DbContext.UserDevices.SingleOrDefault(x => x.UserId == user.Id && x.DeviceId == deviceId);

            if (device is null)
            {
                return(NotFound());
            }
            try {
                await PushNotificationService.UnRegister(deviceId);
            } catch (Exception exception) {
                Logger.LogError("An exception occurred when connection to Azure Notification Hubs. Exception is '{Exception}'. Inner Exception is '{InnerException}'.", exception.Message, exception.InnerException?.Message ?? "N/A");
                throw;
            }
            DbContext.UserDevices.Remove(device);
            await DbContext.SaveChangesAsync();

            var @event = new DeviceDeletedEvent(DeviceInfo.FromUserDevice(device), SingleUserInfo.FromUser(user));
            await EventService.Publish(@event);

            return(NoContent());
        }
        public async void AddProduct(Product newProduct)
        {
            ProductItem newItem = new ProductItem
            {
                Product  = newProduct,
                isHidden = false
            };

            _saveProducts.Add(newItem);

            //Thêm product ở database local
            DataUpdater.AddProduct(newProduct);
            //Thêm product ở database server
            await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "product/insert", newProduct);

            LoadProducts(false);
            var StoreDashBoardVM = TabbarStoreManager.GetInstance().Children.ElementAt(1).BindingContext as StoreDashBoardViewModel;

            StoreDashBoardVM.LoadData();

            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataAddProduct(newProduct);

            PushNotificationService.Push(NotiNumber.AddProduct, datas, true);
        }
Esempio n. 12
0
        public async void SendReview()
        {
            //TEST INTERNET CONNECTTION
            var httpClient = new HttpClient();

            try
            {
                var testInternet = await httpClient.GetStringAsync(ServerDatabase.localhost + "store/getstorebyid/test");
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }

            using (UserDialogs.Instance.Loading("Sending.."))
            {
                order.Review = Review;
                DataUpdater.ReceiveOder(order);
                //call api update orderbill
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "orderbill/update", order);

                //reload list orders view
                (TabBarCustomer.GetInstance().Children.ElementAt(3).BindingContext as ListOrdersViewModel).LoadData();

                await PopupNavigation.Instance.PopAllAsync();
            }

            MessageService.Show("Received successfully", 0);
            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataWrireReview(order);

            PushNotificationService.Push(NotiNumber.SendReview, datas, false);
        }
Esempio n. 13
0
        private async void SendClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(AnswerEntry.Text))
            {
                await DisplayAlert("Error", "Your answer must not be blank!", "OK");

                return;
            }

            //call api update orderbill
            ReviewItem   reviewItem   = this.BindingContext as ReviewItem;
            DataProvider dataProvider = DataProvider.GetInstance();
            OrderBill    order        = dataProvider.GetOrderBillByIDOrderBill(reviewItem.IDOrderBill);

            order.StoreAnswer = AnswerEntry.Text;

            //update orderbill ở database local
            DataUpdater.UpdateStoreAnswerOrderbill(order);
            //update orderbill ở database server
            var httpClient = new HttpClient();
            await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "orderbill/update", order);

            await PopupNavigation.Instance.PopAsync();

            //RELOAD REVIEW MANAGER VIEW
            var ReviewVM = TabbarStoreManager.GetInstance().Children.ElementAt(3).BindingContext as ReviewManagerViewModel;

            ReviewVM.LoadData();

            MessageService.Show("Send answer successfully", 0);
            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataAnswerFeedback(order);

            PushNotificationService.Push(NotiNumber.AnswerFeedback, datas, true);
        }
 public PushNotificationServiceTests()
 {
     _service = new PushNotificationService(
         _auditPublisherMock.Object,
         _pushProviderMock.Object,
         EmptyLogFactory.Instance);
 }
Esempio n. 15
0
        public IActionResult NewProduct([FromBody] ProductRequest productRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!productRequest.Foto.Any())
            {
                return(BadRequest("At least 1 image required."));
            }

            var interval = _context.SysParam.FirstOrDefault(x => x.ParamCode.Equals("DEFAULT_PRODUCT_INTERVAL"));

            _context.Product.Add(new Product(productRequest, interval.ParamValue));
            _context.Commit();

            var productId = _context.Product.LastOrDefault(x =>
                                                           x.ProductName == productRequest.ProductName && x.CategoryId == productRequest.CategoryId &&
                                                           x.ContactId == productRequest.ContactId && x.PosterId == productRequest.PosterId).Id;

            foreach (var foto in productRequest.Foto)
            {
                _context.FotoUpload.Add(new FotoUpload(foto, productId));
                _context.Commit();
            }

            foreach (var foto in productRequest.ProductCertificate)
            {
                _context.FotoUpload.Add(new FotoUpload(foto, productId));
                _context.Commit();
            }

            foreach (var foto in productRequest.ProductClient)
            {
                _context.FotoUpload.Add(new FotoUpload(foto, productId));
                _context.Commit();
            }

            foreach (var foto in productRequest.ProductImplementation)
            {
                _context.FotoUpload.Add(new FotoUpload(foto, productId));
                _context.Commit();
            }

            if (productRequest.Attachment.Any())
            {
                foreach (var file in productRequest.Attachment)
                {
                    _context.AttachmentFile.Add(new AttachmentFile(file, productId));
                    _context.Commit();
                }
            }

            var body     = new NotificationEmptyRequest();
            var jsonBody = JsonConvert.SerializeObject(body);

            PushNotificationService.sendPushNotification(jsonBody);
            return(Ok(new { msg = "Post Published" }));
        }
 public PushNotificationController()
 {
     _notificationHubClient =
         NotificationHubClient.CreateClientFromConnectionString(
             ConfigurationManager.AppSettings["AzureNotificationHubConnectionString"],
             ConfigurationManager.AppSettings["AzureNotificationHubName"]);
     _pushNotificationService = new PushNotificationService();
 }
Esempio n. 17
0
    //	Sends push to a given user
    public void SendPushToUser(string userName, string message)
    {
//		Debug.Log ("SendPushToUser Called");
        ServiceAPI serviceAPI = new ServiceAPI(api_key, secret_key);
        PushNotificationService pushService = serviceAPI.BuildPushNotificationService();

        pushService.SendPushMessageToUser(userName, message, callBack);
    }
Esempio n. 18
0
    //Registers a user with the given device token to APP42 push notification service
    void registerDeviceTokenToApp42PushNotificationService(string devToken, string userName)
    {
//		Debug.Log ("registerDeviceTokenToApp42PushNotificationService   Called");
        ServiceAPI serviceAPI = new ServiceAPI(api_key, secret_key);
        PushNotificationService pushService = serviceAPI.BuildPushNotificationService();

        pushService.StoreDeviceToken(userName, devToken, "iOS", callBack);
    }
Esempio n. 19
0
        public async Task Notification2()
        {
            using (var repo = MainRepository.WithRead())
            {
                var admins = await repo.Character.GetAdministratorsAsync();

                await PushNotificationService.SendCharactersAsync(repo, "通知テスト", "これは通知のテストです", admins.Select(c => c.Id));
            }
        }
Esempio n. 20
0
    public void AsyncApp42Api()
    {
        ServiceAPI sp = new ServiceAPI("43f6b65747952492b5e30056ac9539ef7c50b44c4178e7c361cfa3b20ee52095", "e09348180158fb9304906d696dec68b3e2f074747a09ec93284271627f7c2599");

        this.userService    = sp.BuildUserService();
        this.storageService = sp.BuildStorageService();
        this.pushService    = sp.BuildPushNotificationService();
        this.socialService  = sp.BuildSocialService();
    }
Esempio n. 21
0
    //Registers a user with the given device token to APP42 push notification service
    void registerDeviceTokenToApp42PushNotificationService(string devToken, string userName)
    {
        Debug.Log("registerDeviceTokenToApp42PushNotificationService   Called");
        ServiceAPI serviceAPI = new ServiceAPI(api_key, secret_key);
        PushNotificationService pushService = serviceAPI.BuildPushNotificationService();

        pushService.StoreDeviceToken(userName, devToken, "iOS", callBack);
        //pushService.StoreDeviceToken(userName,devToken,com.shephertz.app42.paas.sdk.csharp.pushNotification.DeviceType.iOS);
    }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            PushNotificationService pushNotificationService = new PushNotificationService();
            //FcmSender.SendAndroidNotification("hello", "fdsfdg3");
            //ApnService apnService = new ApnService("decodedString", "asffpaerero343", "asffpaerero343", "asffpaerero343", ApnServerType.Development);

            string title = "";
            string body  = "";
            var    data  = new { action = "Play", userID = 5 };

            Console.WriteLine("Hello Everyone!");
            Console.WriteLine("Let's send push notifications!!!");

            Console.WriteLine("Title of Notification: ");
            title = Console.ReadLine();

            Console.WriteLine();

            Console.WriteLine("Description of the notification: ");
            body = Console.ReadLine();

            Console.WriteLine();

            Console.Write("Number of devices that receive this notification? ");
            int.TryParse(Console.ReadLine(), out int deviceCount);
            var tokens = new string[deviceCount];

            Console.WriteLine();

            for (int i = 0; i < deviceCount; i++)
            {
                Console.WriteLine($"Token for device number {i + 1}: ");
                tokens[i] = Console.ReadLine();
                Console.WriteLine();
            }

            Console.WriteLine("Do you want to send notifications?");
            Console.WriteLine("1 - Yes!!!");
            Console.WriteLine("0 - No!!!");
            int.TryParse(Console.ReadLine(), out int sendNotification);

            if (sendNotification == 1)
            {
                var fcmPush = pushNotificationService.SendPushNotification(tokens, title, body, data);
                //var apnPush = apnService.ApnSender("sfdghjg", "3456fdgdsdawere");
                pushNotificationService.Dispose();
                //apnService.Dispose();
                Console.WriteLine($"Notification sent!");
            }
            else
            {
                Console.WriteLine("Failed to send notification!");
            }
            Console.ReadKey();
        }
Esempio n. 23
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();
            using (UserDialogs.Instance.Loading("Loging.."))
            {
                if (!dataProvider.CheckAccountExist(this.Username, this.Password))
                {
                    OneSignal.Current.SetExternalUserId("");

                    var loginpage = LoginView.GetInstance();
                    Application.Current.MainPage = new NavigationPage(LoginView.GetInstance());
                    await Application.Current.MainPage.DisplayAlert("Account not exist", "Wrong username or password, please try again", "OK");

                    return;
                }
                ;
                User user = dataProvider.GetUserByIDUser(this.Username);
                user.IsLogined = 1;
                Infor.IDUser   = this.Username;
                Infor.IDStore  = dataProvider.GetIDStoreByIDUser(this.Username);
                Infor.IDCart   = this.Username;
                Infor.Password = this.Password;

                if (!isAlreadyLogined)
                {
                    //UserID_RandomStr
                    string ExternalStr = "UserID_" + DateTime.Now.ToString("ddMMyyyyHHmmss");
                    user.ExternalId = ExternalStr;
                    Preferences.Set("IDLogin", ExternalStr);

                    OneSignal.Current.SetExternalUserId("");
                    //PUSH NOTI TRƯỚC KHI SET ONESIGNAL
                    string datas = PushNotificationService.ConvertDataLogin(user);
                    PushNotificationService.Push(NotiNumber.Login, datas, false);

                    OneSignal.Current.SetExternalUserId(user.IDUser);
                    //OneSignal.Current.SendTag("IsLogined", "1");
                    var httpClient = new HttpClient();
                    await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "user/update", user);
                }


                App.Current.MainPage = AppDrawer.GetInstance();
                if (dataProvider.IsLackOfInfor())
                {
                    bool result = await DisplayAlert("Notice", "Update your infor to use our services!", "Go", "Later");

                    if (result)
                    {
                        var shell = AppDrawer.GetInstance();
                        shell.CurrentItem = shell.flyoutUserSetting;
                    }
                }

                MessageService.Show("Login success", 1);
            }
        }
        public async void DeleteOrder(OrderBill orderBill)
        {
            //TEST INTERNET CONNECTTION
            var    httpClient = new HttpClient();
            string x          = "";

            try
            {
                var testInternet = await httpClient.GetStringAsync(ServerDatabase.localhost + "store/getstorebyid/test");

                x = testInternet;
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }

            using (UserDialogs.Instance.Loading("Canceling order"))
            {
                List <Product> productInOrder = dataProvider.GetProductsInBillByIDBill(orderBill.IDOrderBill);
                //update quantityinventory ở local
                List <Product> sourceProducts = DataUpdater.ReturnListProductToSource(productInOrder);
                //api update quantityinventory ở server
                foreach (Product product in sourceProducts)
                {
                    await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "product/update", product);
                }

                //api delete products trong order bị xóa (ở server)
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "product/deletebyidorderbill/" + orderBill.IDOrderBill, new { });

                //delete product ở local
                DataUpdater.DeleteProducts(productInOrder);

                //delete orderbill server
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "orderbill/deleteorderbillbyid/" + orderBill.IDOrderBill, new { });

                //delete orderbill local
                DataUpdater.DeleteOrderBillByID(orderBill.IDOrderBill);


                //reload ListOrdersView
                LoadData();
            }

            MessageService.Show("Cancel order successfully", 0);

            //PUSH NOTI
            string datas = PushNotificationService.ConvertDataCancelOrder(orderBill);

            PushNotificationService.Push(NotiNumber.CancelOrderForStore, datas, false);
            PushNotificationService.Push(NotiNumber.CancelOrderForOther, datas, true);
        }
        public async Task <HttpResponseMessage> Post([FromBody] ShopSensorEvent newEvent)
        {
            await DocDBRepository <ShopSensorEvent> .CreateItemAsync(newEvent);

            var pushNotificationResponse = await PushNotificationService.TriggerPushNotification(newEvent.EventType,
                                                                                                 config.Notifications.HubName, config.Notifications.FullListener);

            HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK);

            return(res);
        }
 public ReactionAddedFunction(
     IActivityRepository activityRepository,
     IUserRepository userRepository,
     PushNotificationService pushNotificationService,
     ActivityDistributionService activityDistributionService)
 {
     this.activityRepository          = activityRepository ?? throw new ArgumentNullException(nameof(activityRepository));
     this.userRepository              = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
     this.pushNotificationService     = pushNotificationService ?? throw new ArgumentNullException(nameof(pushNotificationService));
     this.activityDistributionService = activityDistributionService ?? throw new ArgumentNullException(nameof(activityDistributionService));
 }
Esempio n. 27
0
 static void Main()
 {
     #if DEBUG
     var service = new PushNotificationService();
     service.Debug();
     #else
     System.ServiceProcess.ServiceBase[] ServicesToRun;
     ServicesToRun = new System.ServiceProcess.ServiceBase[] { new PushNotificationService() };
     System.ServiceProcess.ServiceBase.Run(ServicesToRun);
     #endif
 }
 public void TestFCM()
 {
     PushNotificationService ser = new PushNotificationService();
     var s = ser.SendNotification(new FirebaseMessage
     {
         title = "title",
         body  = "body"
     },
                                  topics: new[] { "Offers" }
                                  );
 }
Esempio n. 29
0
        public IActionResult Liked([FromBody] Interaction interaction)
        {
            if (interaction.IsLike == null || interaction.LikedBy == null || interaction.ProductId == 0)
            {
                return(BadRequest(new Exception("Invalid Like")));
            }
            interaction.LikedDate = DateTime.UtcNow;
            var like = _context.Interaction.FirstOrDefault(x => x.LikedBy == interaction.LikedBy && x.ProductId == interaction.ProductId);

            if (like == null)
            {
                _context.Interaction.Add(interaction);
            }
            else
            {
                like.IsLike    = interaction.IsLike;
                like.LikedBy   = interaction.LikedBy;
                like.LikedDate = interaction.LikedDate;
                _context.Interaction.Update(like);
            }
            Product post = _context.Product.Include(x => x.Poster).FirstOrDefault(x => x.Id == interaction.ProductId);

            if (interaction.LikedBy != post.PosterId)
            {
                string likedBy            = _context.MUser.FirstOrDefault(x => x.Id == interaction.LikedBy).Name;
                string postOwner          = post.Poster.Name;
                string postName           = post.ProductName;
                string likeText           = interaction.IsLike == true ? "liked" : "unliked";
                NotificationRequest notif = new NotificationRequest()
                {
                    Body  = "Hi " + postOwner + ", " + likedBy + " " + likeText + " your post.",
                    Title = "Post " + likeText
                };

                Notification newNotif = new Notification(notif)
                {
                    To            = post.Poster.Id,
                    ModuleId      = interaction.ProductId,
                    ModuleName    = "product",
                    ModuleUseCase = "like",
                    PushDate      = DateTime.UtcNow
                };
                _context.Notification.Add(newNotif);

                if (post.Poster.PushId != null)
                {
                    NotificationRequestToTopic body = new NotificationRequestToTopic(notif, post.Poster.PushId);
                    string jsonBody = JsonConvert.SerializeObject(body);
                    PushNotificationService.sendPushNotification(jsonBody);
                }
            }
            _context.Commit();
            return(Ok());
        }
Esempio n. 30
0
        private void Send()
        {
            if (string.IsNullOrEmpty(Title) || string.IsNullOrEmpty(Message))
            {
                Error = "Por favor, verifique todos os campos";
                return;
            }

            PushNotificationService.SendMessage(Title, Message);
            Title   = "";
            Message = "";
        }
Esempio n. 31
0
        public async void ReturnProduct(ProductItemCart productItem)
        {
            //TEST INTERNET CONNECTTION
            var    httpClient = new HttpClient();
            string x          = "";

            try
            {
                var testInternet = await httpClient.GetStringAsync(ServerDatabase.localhost + "store/getstorebyid/test");

                x = testInternet;
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", "Action fail, check your internet connection and try again!", "OK");

                return;
            }

            Product product        = productItem.Product;
            Product deletedProduct = dataProvider.GetProductInCartByIDSourceProduct(product.IDSourceProduct);

            DataUpdater.ReturnProductToSourceProduct(deletedProduct);


            Product changedProduct = dataProvider.GetProductByID(product.IDSourceProduct);

            using (UserDialogs.Instance.Loading("wait.."))
            {
                //Update lại product cho server database
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "product/update", changedProduct);

                //xóa product bị hủy trong cart
                await httpClient.PostAsJsonAsync(ServerDatabase.localhost + "product/deleteproductbyid/" + deletedProduct.IDProduct, new { });


                //load lại data product cho store được trả về VÀ TRONG CART
                DataUpdater.DeletedProductInCart(deletedProduct);
                LoadData();
            }



            //PUSH NOTI
            List <Product> productForPushNoti = new List <Product>();

            productForPushNoti.Add(changedProduct);
            productForPushNoti.Add(deletedProduct);
            string datas = PushNotificationService.ConvertDataReturnProductCart(productForPushNoti);

            PushNotificationService.Push(NotiNumber.ReturnProductCart, datas, true);
        }
        private void deleteWorkspace(object sender, EventArgs e)
        {
            try
            {
                if (sender is StackLayout)
                {
                    var templateGrid = (StackLayout)sender;

                    //var grid = templateGrid.Parent.Parent.Children.IEnumerator.[0];
                    var par  = templateGrid.Parent.Parent;
                    var grid = (SwipeGestureGrid)par;

                    if (grid != null && grid.BindingContext != null)
                    {
                        Workspace item = ((Workspace)grid.BindingContext);
                        grid.IsVisible     = false;
                        grid.HeightRequest = 0;

                        Common.Instance._sqlconnection.Delete(item);
                        string deviceId = CrossDeviceInfo.Current.Id;
                        if (!string.IsNullOrEmpty(deviceId))
                        {
                            PushNotificationService client = new PushNotificationService(item);
                            client.RemovePushNotificationTokenForWorkspace(deviceId);
                        }
                    }
                }
                if (sender is MenuItem)
                {
                    var menuItem = ((MenuItem)sender);
                    if (menuItem != null && menuItem.BindingContext != null)
                    {
                        Workspace ws = ((Workspace)menuItem.BindingContext);
                        if (ws.Id >= 0)
                        {
                            Common.Instance._sqlconnection.Delete(ws);
                            vm.Items.Remove(ws);
                            string deviceId = CrossDeviceInfo.Current.Id;
                            if (!string.IsNullOrEmpty(deviceId))
                            {
                                PushNotificationService client = new PushNotificationService(ws);
                                client.RemovePushNotificationTokenForWorkspace(deviceId);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }