private async void sendButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
         string username = ApplicationData.Current.LocalSettings.Values["Username"] as String;
         string password = ApplicationData.Current.LocalSettings.Values["Password"] as String;
         if (!String.IsNullOrEmpty(messageTextBox.Text.Trim()))
         {
             if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
             {
                 await client.SendNotificationAsync(username, password, messageTextBox.Text);
                 MessageDialog messageDialog = new MessageDialog("Message sent successfully.");
                 await messageDialog.ShowAsync();
                 messageTextBox.Text = String.Empty;
             }
             else
             {
                 MessageDialog messageDialog = new MessageDialog("Please verify credentials are set in the settings.");
                 await messageDialog.ShowAsync();
             }
         }
         else
         {
             await new MessageDialog("Please ensure that you enter a message").ShowAsync();
         }
     }
     catch
     {
         MessageDialog messageDialog = new MessageDialog("Unable to send message. Please verify credentials are set in the settings and you have an internet connection.");
         messageDialog.ShowAsync();
     }
 }
Exemplo n.º 2
0
        private void Connect()
        {
            channel            = new Channel($"{ServiceAddress}:{ServicePort}", ChannelCredentials.Insecure);
            notificationClient = new NotificationService.NotificationServiceClient(channel);

            var request = new NotificationSubscribeRequest {
                Extension = extension
            };
            var response = notificationClient.Subscribe(request);
            var watcher  = new NotificationConnectionWatcher(channel, OnChanalStateChanged);

            var responseReaderTask = Task.Run(async() =>
            {
                while (await response.ResponseStream.MoveNext(token))
                {
                    FailSince   = null;
                    var message = response.ResponseStream.Current;
                    logger.Debug($"extension:{extension} Received:{message}");
                    OnAppearedMessage(message);
                }
                logger.Warn($"Соединение с NotificationService[{extension}] завершено.");
            }, token).ContinueWith(task =>
            {
                if (task.IsCanceled || (task.Exception?.InnerException as RpcException)?.StatusCode == StatusCode.Cancelled)
                {
                    logger.Info($"Соединение с NotificationService[{extension}] отменено.");
                }
                else if (task.IsFaulted)
                {
                    if (FailSince == null)
                    {
                        FailSince = DateTime.Now;
                    }
                    var failedTime = (DateTime.Now - FailSince).Value;
                    if (failedTime.Seconds < 10)
                    {
                        Thread.Sleep(1000);
                    }
                    else if (failedTime.Minutes < 10)
                    {
                        Thread.Sleep(4000);
                    }
                    else
                    {
                        Thread.Sleep(30000);
                    }
                    logger.Error(task.Exception);
                    logger.Info($"Соединение с NotificationService[{extension}] разорвано... Пробуем соединиться.");
                    Connect();
                }
            })
            ;
        }
Exemplo n.º 3
0
        private void ScheduleDelivery(DeliveryInfo pDeliveryInfo)
        {
            Console.WriteLine("Delivering to" + pDeliveryInfo.DestinationAddress);
            Thread.Sleep(1000);
            //notifying of delivery completion
            using (TransactionScope lScope = new TransactionScope())
            using (DeliveryDataModelContainer lContainer = new DeliveryDataModelContainer())
            {
                pDeliveryInfo.Status = 1;

                /**
                INotificationService lService = DeliveryNotificationServiceFactory.GetDeliveryNotificationService(pDeliveryInfo.DeliveryNotificationAddress);
                lService.NotifyDeliveryCompletion(pDeliveryInfo.DeliveryIdentifier, DeliveryInfoStatus.Delivered);
                **/

                NotificationService.NotificationServiceClient IClient = new NotificationService.NotificationServiceClient();
                IClient.NotifyDeliveryCompletion(pDeliveryInfo.DeliveryIdentifier, DeliveryStatus.Delivered);

                lScope.Complete();
            }
        }
Exemplo n.º 4
0
        public void Transfer(double pAmount, int pFromAcctNumber, int pToAcctNumber, Guid pOrderNumber, string pReturnAddress)
        {
            using (TransactionScope lScope = new TransactionScope())
            using (BankEntityModelContainer lContainer = new BankEntityModelContainer())
            {
                //IOperationOutcomeService lOutcomeService = OperationOutcomeServiceFactory.GetOperationOutcomeService(pResultReturnAddress);
                try
                {
                    Account lFromAcct = GetAccountFromNumber(pFromAcctNumber);
                    Account lToAcct = GetAccountFromNumber(pToAcctNumber);
                    lFromAcct.Withdraw(pAmount);
                    lToAcct.Deposit(pAmount);
                    lContainer.Attach(lFromAcct);
                    lContainer.Attach(lToAcct);
                    lContainer.ObjectStateManager.ChangeObjectState(lFromAcct, System.Data.EntityState.Modified);
                    lContainer.ObjectStateManager.ChangeObjectState(lToAcct, System.Data.EntityState.Modified);

                    NotificationService.NotificationServiceClient IClient = new NotificationService.NotificationServiceClient("NetMsmqBinding_INotificationService", pReturnAddress);
                    IClient.NotifyBankTransactionCompleted(pOrderNumber, OperationOutcome.Successful);

                    lContainer.SaveChanges();
                    lScope.Complete();
                    //lOutcomeService.NotifyOperationOutcome(new OperationOutcome() { Outcome = OperationOutcome.OperationOutcomeResult.Successful });
                }
                catch (Exception lException)
                {
                    Console.WriteLine("Error occured while transferring money:  " + lException.Message);

                    NotificationService.NotificationServiceClient IClient = new NotificationService.NotificationServiceClient("NetMsmqBinding_INotificationService", pReturnAddress);
                    IClient.NotifyBankTransactionCompleted(pOrderNumber, OperationOutcome.Failure);

                    lScope.Complete();
                    //throw;
                    //lOutcomeService.NotifyOperationOutcome(new OperationOutcome() { Outcome = OperationOutcome.OperationOutcomeResult.Failure, Message = lException.Message });
                }
            }
        }
Exemplo n.º 5
0
        private static async Task SubscribeToNotificationsAsync(CancellationToken stoppingToken)
        {
            using var channel = CreateAuthenticatedChannel();
            var notificationClient = new NotificationService.NotificationServiceClient(channel);

            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    using var call = notificationClient.Notify(new Empty(), cancellationToken: stoppingToken);

                    Console.WriteLine($"Is subscribed to notify");
                    try
                    {
                        while (call?.ResponseStream != null &&
                               await(call.ResponseStream.MoveNext(stoppingToken) ?? Task.FromResult(false)))
                        {
                            var eventMessage = call.ResponseStream.Current;

                            switch (eventMessage.Type)
                            {
                            case EventType.NewMessage:
                                var message = Message.Parser.ParseFrom(eventMessage.Data);
                                if (message.Login == _login)
                                {
                                    continue;
                                }

                                var left = Console.CursorLeft;
                                var top  = Console.CursorTop;

                                Console.MoveBufferArea(0, top - 1, Math.Max(left, 14), 2, 0, top + 1);
                                Console.SetCursorPosition(0, top - 1);
                                Console.WriteLine(
                                    $"{message.Login}({message.Time.ToDateTime():g}): {message.Content}");
                                Console.SetCursorPosition(left, top + 2);
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.Write(e.Message);
                    }

                    await Task.Delay(1000, stoppingToken);

                    Console.WriteLine($"Is subscribed stopped");
                }
            }
            catch (Exception e)
            {
                Console.Error.Write(e.Message);
            }
            finally
            {
                await notificationClient.UnsubscribeAsync(new Empty());
            }
        }
 public async void UnregisterSubscriber()
 {
     var token = HardwareIdentification.GetPackageSpecificToken(null);
     var hardwareId = token.Id;
     var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);
     byte[] bytes = new byte[hardwareId.Length];
     dataReader.ReadBytes(bytes);
     string deviceId = BitConverter.ToString(bytes);
     NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
     await client.UnregisterSubscriberAsync(username, password, "Win8", deviceId);
 }
 private async void CreatAndSendPushChannel()
 {
     PushNotificationChannel channel = null;
     try
     {
         channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
         channel.PushNotificationReceived += channel_PushNotificationReceived;
         NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
         string deviceType = "Win8";
         var token = HardwareIdentification.GetPackageSpecificToken(null);
         var hardwareId = token.Id;
         var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);
         byte[] bytes = new byte[hardwareId.Length];
         dataReader.ReadBytes(bytes);
         string deviceId = BitConverter.ToString(bytes);
         await client.RegisterSubscriberAsync(username, password, channel.Uri, deviceType, deviceId);
         
     }
     catch(Exception ex)
     {
         //do nothing
     }
     
 }
        async void timer_Tick(object sender, object e)
        {
            try
            {
                NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
                if (await client.AuthenticateUserAsync(username, password))
                {
                    var data = await client.GetNotificationsAsync(username);
                    if (data.Count != ((ObservableCollection<object>)listView.ItemsSource).Count)
                    {
                        listView.ItemsSource = data;
                    }

                }
            }
            catch
            {
                new MessageDialog("Unable to connect to Riveu server. Please verify internet connection and re-launch application").ShowAsync();
            }
        }
 async void MainPage_Loaded(object sender, RoutedEventArgs e)
 {
     if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("EnablePush"))
     {
         MessageDialog messageBox = new MessageDialog("Push Notifications");
         messageBox = new MessageDialog("This application supports Push Notifications. Please go to the settings charm to configure credentials and push notification settings.");
         await messageBox.ShowAsync();
     }
     else if (ApplicationData.Current.LocalSettings.Values.ContainsKey("Username") && ApplicationData.Current.LocalSettings.Values.ContainsKey("Password"))
     {
         statusLabel.Text = "Retrieving Messages...";
         NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
         username = ApplicationData.Current.LocalSettings.Values["Username"] as String;
         password = ApplicationData.Current.LocalSettings.Values["Password"] as String;
         listView.ItemsSource = null;
         try
         {
             if (await client.AuthenticateUserAsync(username, password))
             {
                 var data = await client.GetNotificationsAsync(username);
                 listView.ItemsSource = data;
                 statusLabel.Text = String.Empty;
                 if (timer.IsEnabled)
                 {
                     timer.Stop();
                 }
                 try
                 {
                     int interval = Int32.Parse(ApplicationData.Current.LocalSettings.Values["RefreshRate"].ToString());
                     if (interval == 0)
                     {
                         interval = 30;
                     }
                     timer = new DispatcherTimer();
                     timer.Interval = new TimeSpan(0, 0, interval);
                     timer.Tick += timer_Tick;
                     timer.Start();
                 }
                 catch
                 {
                     MessageDialog dialog = new MessageDialog("Please set refresh rate in settings");
                     dialog.ShowAsync();
                 }
                 if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["EnablePush"]) == true)
                 {
                     CreatAndSendPushChannel();
                 }
                 else
                 {
                     UnregisterSubscriber();
                 }
             }
             else
             {
                 statusLabel.Text = "Invalid Credentials";
             }
         }
         catch
         {
             new MessageDialog("Unable to connect to Riveu server. Please verify internet connection and re-launch application").ShowAsync();
         }
     }
     else
     {
         statusLabel.Text = "Please configure settings";
     }
 }
 async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
 {
     if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
     {
         _settingsPopup.IsOpen = false;
         statusLabel.Text = "Retrieving Messages...";
         NotificationService.NotificationServiceClient client = new NotificationService.NotificationServiceClient();
         username = ApplicationData.Current.LocalSettings.Values["Username"] as String;
         password = ApplicationData.Current.LocalSettings.Values["Password"] as String;
         listView.ItemsSource = null;
         try
         {
             if (await client.AuthenticateUserAsync(username, password))
             {
                 var data = await client.GetNotificationsAsync(username);
                 listView.ItemsSource = data;
                 statusLabel.Text = String.Empty;
                 if (timer.IsEnabled)
                 {
                     timer.Stop();
                 }
                 try
                 {
                     int interval = Int32.Parse(ApplicationData.Current.LocalSettings.Values["RefreshRate"].ToString());
                     if (interval == 0)
                     {
                         interval = 30;
                     }
                     timer = new DispatcherTimer();
                     timer.Interval = new TimeSpan(0, 0, interval);
                     timer.Tick += timer_Tick;
                     timer.Start();
                 }
                 catch
                 {
                     try
                     {
                         MessageDialog dialog = new MessageDialog("Please set refresh rate in settings");
                         dialog.ShowAsync();
                     }
                     catch
                     {
                         //do nothing
                     }
                 }
                 if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["EnablePush"]) == true)
                 {
                     CreatAndSendPushChannel();
                 }
                 else
                 {
                     UnregisterSubscriber();
                 }
             }
             else
             {
                 statusLabel.Text = "Invalid Credentials";
             }
         }
         catch
         {
             new MessageDialog("Unable to connect to Riveu server. Please verify internet connection and re-launch application").ShowAsync();
         }
     }
 }