예제 #1
0
        public async Task SetNotificationStatusAsync_StatusSetSuccessfully()
        {
            // Arrange
            var notificationId = 527012;
            var notification   = NotificationClient
                                 .List()
                                 .Filter(e => e.Id.IsEqual(notificationId))
                                 .Get().Data.Items.First();

            var notificationStatus = (NotificationUserStatus) new List <int> {
                0, 1
            }
            .First(e => e != (int)notification.Status);

            var model = new List <NotificationPutModel>()
            {
                new NotificationPutModel
                {
                    Id     = notificationId,
                    Status = notificationStatus
                },
            };

            // Act
            var result = (await NotificationClient.ChangeStatusAsync(model)).AssertResult();

            // Assert
            Assert.IsNotNull(result.First());
            Assert.AreEqual(notificationStatus, result.First().Status);
        }
예제 #2
0
        public async Task <HttpResponseMessage> RegisterClient([FromBody] NotificationClient notificationClient)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("RegisterClient", connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlParameter param = new SqlParameter();
                    param.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add("@NotificationChannel", SqlDbType.VarChar).Value = notificationClient.NotificationChannel.ToString();
                    cmd.Parameters.Add("@ValidUntil", SqlDbType.DateTime).Value         = notificationClient.ValidUntil;
                    cmd.Parameters.Add(param);
                    connection.Open();
                    int rowsAffected = await cmd.ExecuteNonQueryAsync();

                    if (rowsAffected != 1)
                    {
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }

                    return(new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.OK,
                        Content = new StringContent(@"{""clientId"": """ + param.Value + @"""}")
                    });
                }
            }
        }
예제 #3
0
 public AudioStatusDetector(DataFlow type)
 {
     _type               = type;
     _enumerator         = new MMDeviceEnumerator();
     _notificationClient = new NotificationClient(this);
     _enumerator.RegisterEndpointNotificationCallback(_notificationClient);
 }
        public void SendEmailNotificationWithDocumentGeneratesExpectedRequest()
        {
            Dictionary <string, dynamic> personalisation = new Dictionary <string, dynamic>
            {
                { "document", NotificationClient.PrepareUpload(Encoding.UTF8.GetBytes("%PDF-1.5 testpdf")) }
            };
            JObject expected = new JObject
            {
                { "email_address", Constants.fakeEmail },
                { "template_id", Constants.fakeTemplateId },
                { "personalisation", new JObject
                  {
                      { "document", new JObject
                        {
                            { "file", "JVBERi0xLjUgdGVzdHBkZg==" }
                        } }
                  } },
                { "reference", Constants.fakeNotificationReference }
            };

            MockRequest(Constants.fakeTemplatePreviewResponseJson,
                        client.SEND_EMAIL_NOTIFICATION_URL,
                        AssertValidRequest,
                        HttpMethod.Post,
                        AssertGetExpectedContent, expected.ToString(Formatting.None));

            EmailNotificationResponse response = client.SendEmail(Constants.fakeEmail, Constants.fakeTemplateId, personalisation, Constants.fakeNotificationReference);
        }
        private async Task SendMessage(NotifyMessage content, CommunicationType communicationType)
        {
            var notificationsClient = new NotificationClient(_configuration.NotificationServiceApiKey);

            // Needs to be a dictionary<string,dynamic> for the client.....
            var personalisationDictionary = content.Personalisation.ToDictionary(x => x.Key, x => x.Value as dynamic);

            try
            {
                Logger.Info($"Sending communication request to Gov Notify");
                if (communicationType == CommunicationType.Email)
                {
                    var response = await notificationsClient.SendEmailAsync(content.To, content.Template, personalisationDictionary, content.Reference);
                }
                else if (communicationType == CommunicationType.Sms)
                {
                    var response = await notificationsClient.SendSmsAsync(content.To, content.Template, personalisationDictionary, content.Reference);
                }
            }
            catch (NotifyClientException notifyClientException)
            {
                Logger.Error(notifyClientException, $"Error sending communication {communicationType.ToString()} to Gov Notify with Gov.Notify Client");

                if (communicationType != CommunicationType.Sms || !SuppressSmsError(notifyClientException.Message))
                {
                    throw;
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, $"Generic Error sending communication {communicationType.ToString()} to Gov Notify");
                throw;
            }
        }
 public void PrepareUploadWithLargeDocumentGeneratesAnError()
 {
     Assert.That(
         () => { NotificationClient.PrepareUpload(new byte[3 * 1024 * 1024]); },
         Throws.ArgumentException
         );
 }
예제 #7
0
        protected virtual void InitRestClients()
        {
            RestClient = new RestClient(RootUrl + "api/v1/");
            RestClient.AddDefaultHeader("Authentication", ApiKey);
            RestClient.AddDefaultHeader("X-Api-Key", ApiKey);

            Blacklist         = new ClientBase <BlacklistResource>(RestClient, ApiKey);
            Commands          = new CommandClient(RestClient, ApiKey);
            DownloadClients   = new DownloadClientClient(RestClient, ApiKey);
            Albums            = new AlbumClient(RestClient, ApiKey);
            Tracks            = new TrackClient(RestClient, ApiKey);
            History           = new ClientBase <HistoryResource>(RestClient, ApiKey);
            HostConfig        = new ClientBase <HostConfigResource>(RestClient, ApiKey, "config/host");
            Indexers          = new IndexerClient(RestClient, ApiKey);
            Logs              = new LogsClient(RestClient, ApiKey);
            NamingConfig      = new ClientBase <NamingConfigResource>(RestClient, ApiKey, "config/naming");
            Notifications     = new NotificationClient(RestClient, ApiKey);
            Profiles          = new ClientBase <QualityProfileResource>(RestClient, ApiKey);
            Releases          = new ReleaseClient(RestClient, ApiKey);
            ReleasePush       = new ReleasePushClient(RestClient, ApiKey);
            RootFolders       = new ClientBase <RootFolderResource>(RestClient, ApiKey);
            Artist            = new ArtistClient(RestClient, ApiKey);
            Tags              = new ClientBase <TagResource>(RestClient, ApiKey);
            WantedMissing     = new ClientBase <AlbumResource>(RestClient, ApiKey, "wanted/missing");
            WantedCutoffUnmet = new ClientBase <AlbumResource>(RestClient, ApiKey, "wanted/cutoff");
        }
        public async Task SendEmailWithDocumentPersonalisationTest()
        {
            byte[] pdfContents;

            try
            {
                pdfContents = File.ReadAllBytes("../../../IntegrationTests/test_files/one_page_pdf.pdf");
            }
            catch (DirectoryNotFoundException)
            {
                pdfContents = File.ReadAllBytes("IntegrationTests/test_files/one_page_pdf.pdf");
            }

            Dictionary <String, dynamic> personalisation = new Dictionary <String, dynamic>
            {
                { "name", NotificationClient.PrepareUpload(pdfContents) }
            };

            EmailNotificationResponse response =
                await this.client.SendEmailAsync(FUNCTIONAL_TEST_EMAIL, EMAIL_TEMPLATE_ID, personalisation);

            Assert.IsNotNull(response.id);
            Assert.IsNotNull(response.template.id);
            Assert.IsNotNull(response.template.uri);
            Assert.IsNotNull(response.template.version);
            Assert.AreEqual(response.content.subject, TEST_EMAIL_SUBJECT);
            Assert.IsTrue(response.content.body.Contains("https://documents."));
        }
예제 #9
0
        /// <summary>
        ///     コンストラクタ
        /// </summary>
        /// <param name="clientId">Client ID (ライブラリには含まれまていません)</param>
        /// <param name="clientSecret">Client Secret (ライブラリには含まれていません)</param>
        public PixivClient(string clientId, string clientSecret)
        {
            ClientId     = clientId;
            ClientSecret = clientSecret;

            // 2018/03/30
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("App-OS-Version", OsVersion);
            _httpClient.DefaultRequestHeaders.Add("App-OS", "ios");
            _httpClient.DefaultRequestHeaders.Add("App-Version", AppVersion);
            _httpClient.DefaultRequestHeaders.Add("User-Agent", $"PixivIOSApp/{AppVersion} (iOS {OsVersion}; iPhone9,2)");

            // Initialize accesors
            Application    = new ApplicationInfoClient(this);
            Authentication = new AuthenticationClient(this);
            Illust         = new IllustClient(this);
            IllustSeries   = new IllustSeriesClient(this);
            Live           = new LiveClient(this);
            Manga          = new MangaClient(this);
            Mute           = new MuteClient(this);
            Notification   = new NotificationClient(this);
            Novel          = new NovelClient(this);
            Search         = new SearchClient(this);
            Spotlight      = new SpotlightClient(this);
            TrendingTags   = new TrendingTagsClient(this);
            User           = new UserClient(this);
            Walkthrough    = new WalkthroughClient(this);
            File           = new FileClient(this);
        }
        private static NotificationClient InitializeNotifyClient()
        {
            string             apiKey = Configuration.Get("NotifyClientApiKey");
            NotificationClient client = new NotificationClient(apiKey);

            return(client);
        }
예제 #11
0
        public MainWindow()
        {
            InitializeComponent();

            AppDomain.CurrentDomain.UnhandledException += (s, e) => { MessageBox.Show(e.ExceptionObject.ToString()); };

            NotificationClient.NotificationClosed         += NotificationClient_NotificationClosed;
            NotificationClient.NotificationCreated        += NotificationClient_NotificationCreated;
            NotificationClient.NotificationActionOccurred += NotificationClient_NotificationActionOccurred;
            toggleButtons(false);

            NotificationClient.OnInitComplete += async() =>
            {
                toggleButtons(true);

                //var status = await NotificationClient.GetProviderStatusAsync();

                //Dispatcher.Invoke(() =>
                //{
                //    bodyContentTypeSelector.SelectedIndex = 0;

                //    connected.Content = !status.Connected ? "Failed to connect." : "Connected";
                //    if(status.Connected)
                //    {
                //        version.Content = $"(v.{status.Version})";
                //    }
                //});
            };

            NotificationClient.Initialize();
        }
예제 #12
0
		/// <summary>
		/// Создать <see cref="AdvertisePanel"/>.
		/// </summary>
		public AdvertisePanel()
		{
			InitializeComponent();

			if (DesignerProperties.GetIsInDesignMode(this))
				return;

			_client = ConfigManager.TryGetService<NotificationClient>() ?? new NotificationClient();
			_client.NewsReceived += OnNewsReceived;

			var sizes = new[] { 10, 20, 30, 40, 50, 60, 70, 110, 120 };

			_parser = new BBCodeParser(new[]
			{
				new BBTag("b", "<b>", "</b>"),
				new BBTag("i", "<span style=\"font-style:italic;\">", "</span>"),
				new BBTag("u", "<span style=\"text-decoration:underline;\">", "</span>"),
				new BBTag("center", "<div style=\"align:center;\">", "</div>"),
				new BBTag("size", "<span style=\"font-size:${fontSize}%;\">", "</div>", new BBAttribute("fontSize", "", c => sizes[c.AttributeValue.To<int>()].To<string>())),
				new BBTag("code", "<pre class=\"prettyprint\">", "</pre>"),
				new BBTag("img", "<img src=\"${content}\" />", "", false, true),
				new BBTag("quote", "<blockquote>", "</blockquote>"),
				new BBTag("list", "<ul>", "</ul>"),
				new BBTag("*", "<li>", "</li>", true, false),
				new BBTag("url", "<a href=\"${href}\">", "</a>", new BBAttribute("href", ""), new BBAttribute("href", "href")),
			});

			_timer = new DispatcherTimer();
			_timer.Tick += OnTick;
			_timer.Interval = new TimeSpan(0, 1, 0);
			_timer.Start();
		}
예제 #13
0
        private void CreateExpiring_Click(object sender, RoutedEventArgs e)
        {
            var options = new NotificationOptions
            {
                Body     = "# This notification will expire in **10 seconds**.",
                Title    = NOTIFICATION_TITLE,
                Category = "Expiring Notification",
                Buttons  = new[]
                {
                    new ButtonOptions()
                    {
                        Title = "Button1", IconUrl = "https://openfin.co/favicon-32x32.png"
                    },
                    new ButtonOptions()
                    {
                        Title = "Button2"
                    }
                },
                Icon    = "https://openfin.co/favicon-32x32.png",
                Expires = DateTime.Now.AddSeconds(10),
                OnNotificationExpired = new Dictionary <string, object>
                {
                    { "foo", "bar" }
                }
            };

            NotificationClient.CreateNotificationAsync(EXPIRING_NOTIFICATION_ID, options);
        }
예제 #14
0
        protected virtual void InitRestClients()
        {
            RestClient = new RestClient(RootUrl + "api/");
            RestClient.AddDefaultHeader("Authentication", ApiKey);
            RestClient.AddDefaultHeader("X-Api-Key", ApiKey);

            RestClientv3 = new RestClient(RootUrl + "api/v3/");
            RestClientv3.AddDefaultHeader("Authentication", ApiKey);
            RestClientv3.AddDefaultHeader("X-Api-Key", ApiKey);

            Blocklist         = new ClientBase <BlocklistResource>(RestClient, ApiKey);
            Commands          = new CommandClient(RestClient, ApiKey);
            DownloadClients   = new DownloadClientClient(RestClient, ApiKey);
            Episodes          = new EpisodeClient(RestClient, ApiKey);
            History           = new ClientBase <HistoryResource>(RestClient, ApiKey);
            HostConfig        = new ClientBase <HostConfigResource>(RestClient, ApiKey, "config/host");
            Indexers          = new IndexerClient(RestClient, ApiKey);
            Indexersv3        = new IndexerClient(RestClientv3, ApiKey);
            Logs              = new LogsClient(RestClient, ApiKey);
            NamingConfig      = new ClientBase <NamingConfigResource>(RestClient, ApiKey, "config/naming");
            Notifications     = new NotificationClient(RestClient, ApiKey);
            Profiles          = new ClientBase <ProfileResource>(RestClient, ApiKey);
            Releases          = new ReleaseClient(RestClient, ApiKey);
            ReleasePush       = new ReleasePushClient(RestClient, ApiKey);
            RootFolders       = new ClientBase <RootFolderResource>(RestClient, ApiKey);
            Series            = new SeriesClient(RestClient, ApiKey);
            Tags              = new ClientBase <TagResource>(RestClient, ApiKey);
            WantedMissing     = new ClientBase <EpisodeResource>(RestClient, ApiKey, "wanted/missing");
            WantedCutoffUnmet = new ClientBase <EpisodeResource>(RestClient, ApiKey, "wanted/cutoff");
        }
예제 #15
0
        /// <summary>
        /// Создать <see cref="AdvertisePanel"/>.
        /// </summary>
        public AdvertisePanel()
        {
            InitializeComponent();

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            _client = ConfigManager.TryGetService <NotificationClient>() ?? new NotificationClient();
            _client.NewsReceived += OnNewsReceived;

            var sizes = new[] { 10, 20, 30, 40, 50, 60, 70, 110, 120 };

            _parser = new BBCodeParser(new[]
            {
                new BBTag("b", "<b>", "</b>"),
                new BBTag("i", "<span style=\"font-style:italic;\">", "</span>"),
                new BBTag("u", "<span style=\"text-decoration:underline;\">", "</span>"),
                new BBTag("center", "<div style=\"align:center;\">", "</div>"),
                new BBTag("size", "<span style=\"font-size:${fontSize}%;\">", "</div>", new BBAttribute("fontSize", "", c => sizes[c.AttributeValue.To <int>()].To <string>())),
                new BBTag("code", "<pre class=\"prettyprint\">", "</pre>"),
                new BBTag("img", "<img src=\"${content}\" />", "", false, true),
                new BBTag("quote", "<blockquote>", "</blockquote>"),
                new BBTag("list", "<ul>", "</ul>"),
                new BBTag("*", "<li>", "</li>", true, false),
                new BBTag("url", "<a href=\"${href}\">", "</a>", new BBAttribute("href", ""), new BBAttribute("href", "href")),
            });

            _timer          = new DispatcherTimer();
            _timer.Tick    += OnTick;
            _timer.Interval = new TimeSpan(0, 1, 0);
            _timer.Start();
        }
예제 #16
0
 public void SendEmail(NotificationClient client,
                       string email,
                       string templateId,
                       Dictionary <string, dynamic> values)
 {
     client.SendEmail(email, templateId, values);
 }
예제 #17
0
        public void CreateNotification_CreateNotification_ReturnsOptions()
        {
            var are = new AutoResetEvent(false);

            string id = Guid.NewGuid().ToString();

            var options = new NotificationOptions
            {
                Title    = id,
                Body     = id,
                Icon     = id,
                Category = id,
                Buttons  = new ButtonOptions[] { }
            };

            NotificationClient.OnInitComplete += async() =>
            {
                var notification = await NotificationClient.CreateNotificationAsync(id, options);

                Assert.AreEqual(id, notification.Id);
                are.Set();
            };

            NotificationClient.Initialize(uri);
            are.WaitOne();
        }
        public void SetUp()
        {
            handler = new Mock <HttpMessageHandler>();

            var w = new HttpClientWrapper(new HttpClient(handler.Object));

            client = new NotificationClient(w, Constants.fakeApiKey);
        }
 public EmailNotificationResponse SendEmail(string toEmail, string templateId, System.Collections.Generic.Dictionary <string, dynamic> personalisation)
 {
     using (var httpClientWrapper = new HttpClientWrapper(httpClient))
     {
         var notificationClient = new NotificationClient(httpClientWrapper, notifyOptions.ApiKey);
         return(notificationClient.SendEmail(toEmail, templateId, personalisation));
     }
 }
예제 #20
0
 public async void Dispose()
 {
     StateTchatContainer.OnChange -= StateHasChanged;
     if (NotificationClient != null)
     {
         await NotificationClient.DisposeAsync();
     }
 }
예제 #21
0
        public async Task GetNotificationsCountAsync_Success()
        {
            // Act
            var result = (await NotificationClient.GetNewNotificationCountAsync()).AssertResult();

            // Assert
            Assert.Greater(result.NewNotificationsCount, 0);
        }
예제 #22
0
        public Notification SendSms(string mobileNumber, string templateId, Dictionary <string, dynamic> personalisation, bool test = false)
        {
            var client       = new NotificationClient(test && !string.IsNullOrWhiteSpace(_apiTestKey) ? _apiTestKey : _apiKey);
            var result       = client.SendSms(mobileNumber, templateId, personalisation, _clientReference);
            var notification = client.GetNotificationById(result.id);

            return(notification);
        }
예제 #23
0
 private void AddNotificationToRepair(NotificationClient notificationClient)
 {
     notificationClient.Enabled = false;
     lock (_NotificationsToRepair)
     {
         _NotificationsToRepair.Enqueue(notificationClient);
     }
     _TriggerNotificationRepair.Set();
 }
예제 #24
0
        public async Task Fire_OnSignInComplete(bool signedIn, string message, bool signedUp, SignInAErrorType errorType)
        {
            if (signedIn)
            {
#if _IOS_
                if (!remoteNotificationsInitialized)
                {
                    remoteNotificationsInitialized = true;
                    RemoteNotificationsService.Instance.RegisteredForNotifications += async(sender, b) =>
                    {
                        string error = string.Empty;
                        if (b.Success)
                        {
                            await NotificationClient.AddDevice(RemoteNotificationsService.Instance.GetTokenType(), b.Info);
                        }
                        else
                        {
                            error = b.Info;
                        }

                        //Inform user we failed to register for remote notifications
                        if (!string.IsNullOrEmpty(error) && !IsInBackground)
                        {
                            await Application.Current.MainPage.DisplayAlert("Notifications Subscription Error", b.Info, "OK");
                        }
                    };
                }

                if (RemoteNotificationsService.Instance.CanRegisterForNotifications() && RemoteNotificationsService.Instance.IsRegisteredForNotifications())
                {
                    RemoteNotificationsService.Instance.RegisterForNotifications();
                }

                //In case background app refresh is disabled inform the user
                RemoteNotificationsService.Instance.BackgroundRefreshStatusChanged += async(s, enabled) =>
                {
                    if (!enabled && !IsInBackground)
                    {
                        await Application.Current.MainPage.DisplayAlert(string.Empty, "Please enable Background App Refresh for \"PlayOn Cloud\" in Settings-General in order to stay up-to-date with your recordings", "OK");
                    }
                };

                if (!RemoteNotificationsService.Instance.IsBackgoundRefreshEnabled())
                {
                    if (await Application.Current.MainPage.DisplayAlert(string.Empty, "Please enable Background App Refresh for \"PlayOn Cloud\" in Settings-General in order to stay up-to-date with your recordings", "Yes", "No"))
                    {
                        RemoteNotificationsService.Instance.OpenGeneralAppSettings();
                    }
                }
#endif
                //if (signedUp)
                //    await Application.Current.MainPage.DisplayAlert("Account Created!",
                //        "Check your email to receive your free recording credits.", "OK");
            }

            OnSignInComplete?.Invoke(this, new SignInArgs(signedIn, message, errorType));
        }
예제 #25
0
        public async Task <HttpResponseMessage> Update([FromBody] NotificationClient notificationClient)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            throw new NotImplementedException();
        }
예제 #26
0
        public async Task DeleteAsync_NonExistingNotification_Fails()
        {
            // Act
            var result = await NotificationClient.DeleteAsync(NotificationToDeleteId);

            // Assert
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
            Assert.That(result.Message, Is.Not.Null.And.Not.Empty);
        }
예제 #27
0
        private NotificationClient Client(string apiKey)
        {
            if (!_clients.ContainsKey(apiKey))
            {
                _clients[apiKey] = new NotificationClient(apiKey);
            }

            return(_clients[apiKey]);
        }
        private static INotificationClient NotificationClient()
        {
            string baseUrl = Environment.GetEnvironmentVariable("GOV_NOTIFY_URL");
            string apiKey  = Environment.GetEnvironmentVariable("GOV_NOTIFY_API_KEY");

            INotificationClient client = new NotificationClient(baseUrl, apiKey);

            return(client);
        }
        public NotifySendSmsCommandHandler(
            IOptions <Notify> notifyOptions,
            NotificationClient client)
        {
            this.client        = this.InitializeNotifyClient();
            this.notifyOptions = notifyOptions.Value ?? throw new ArgumentNullException(nameof(notifyOptions));

            this.TemplateId  = this.notifyOptions.TemplateId;
            this.SmsSenderId = this.notifyOptions.SmsSenderId;
        }
예제 #30
0
        public NAudioDeviceEnumerationService(ILogger logger)
        {
            _logger = logger;

            _deviceEnumerator = new MMDeviceEnumerator();
            _logger.Verbose("Audio device enumerator service created.");

            _notificationClient = new NotificationClient();
            _deviceEnumerator.RegisterEndpointNotificationCallback(_notificationClient);
            _logger.Verbose("Audio device event interface registered.");
        }
        public ParagonNotificationPlugin()
        {
            _dispatcher = System.Windows.Application.Current.Dispatcher;
            var nsettings      = new NotificationSettings(this);
            var serviceFactory = new LocalServiceFactory(nsettings);

            _notificationClient          = new NotificationClient(serviceFactory);
            _notificationClient.Clicked += NotificationClientOnClicked;
            _notificationClient.Closed  += NotificationClientOnClosed;
            _notificationService         = new LocalNotificationService(serviceFactory, System.Windows.Application.Current.Dispatcher);
        }
예제 #32
0
 private void InitRestClients()
 {
     RestClient = new RestClient("http://localhost:8989/api");
     Series = new SeriesClient(RestClient, _runner.ApiKey);
     Releases = new ReleaseClient(RestClient, _runner.ApiKey);
     RootFolders = new ClientBase<RootFolderResource>(RestClient, _runner.ApiKey);
     Commands = new ClientBase<CommandResource>(RestClient, _runner.ApiKey);
     History = new ClientBase<HistoryResource>(RestClient, _runner.ApiKey);
     Indexers = new IndexerClient(RestClient, _runner.ApiKey);
     Episodes = new EpisodeClient(RestClient, _runner.ApiKey);
     NamingConfig = new ClientBase<NamingConfigResource>(RestClient, _runner.ApiKey, "config/naming");
     Notifications = new NotificationClient(RestClient, _runner.ApiKey);
 }
예제 #33
0
        public static bool PostNotification(Settings settings, string notificatioText)
        {
            var result = false;
            try
            {
                var client = new NotificationClient("BasicHttpBinding_INotification",
                    new EndpointAddress(ServiceUri + "/Notification.svc"));
                result = client.CreateNotification(settings.Customer.RefCode, settings.Customer.RefByCode,
                    notificatioText);

            }
            catch (Exception e)
            {
                Global.Logger.Fatal(e.Message);
            }
            return result;
        }
예제 #34
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AlertSettingsWindow"/>.
		/// </summary>
		public AlertSettingsWindow()
		{
			InitializeComponent();

			_buttons.Add(AlertTypes.Sound, IsSound);
			_buttons.Add(AlertTypes.Speech, IsSpeech);
			_buttons.Add(AlertTypes.Popup, IsPopup);
			_buttons.Add(AlertTypes.Sms, IsSms);
			_buttons.Add(AlertTypes.Email, IsEmail);
			_buttons.Add(AlertTypes.Log, IsLog);

			RulesCtrl.ItemsSource = _rules;

			var client = new NotificationClient();

			if (AuthenticationClient.Instance.IsLoggedIn)
			{
				try
				{
					TestSms.Content = ((string)TestSms.Content).Put(client.SmsCount);
					TestEmail.Content = ((string)TestEmail.Content).Put(client.EmailCount);
					return;
				}
				catch (Exception ex)
				{
					ex.LogError();
				}

				TestSms.Content = TestEmail.Content = LocalizedStrings.Str152;
			}
			else
			{
				TestSms.Content = TestEmail.Content = LocalizedStrings.NotAuthorized;
			}

			TestSms.Foreground = TestEmail.Foreground = Brushes.Red;
			TestSms.FontWeight = TestEmail.FontWeight = FontWeights.Bold;
			IsSms.IsEnabled = IsEmail.IsEnabled = TestSms.IsEnabled = TestEmail.IsEnabled = false;
		}
 private bool SetupNotification(NotificationClient notificationClient, int attemptsCount)
 {
     bool result = false;
     NotificationServer notificationServer = null;
     int count = 0;
     while ((notificationServer == null) && (count < attemptsCount))
     {
         notificationServer = GetNextNotificationServer();
         if ((notificationServer != null) && (notificationServer.AllowConnectionAfter > DateTime.Now))
             notificationServer = null;
         else if ((notificationServer == null) || !notificationServer.Connected || !notificationServer.TcpClient.Connected)
         {
             if (!Connect(notificationServer, true))
                 notificationServer = null;
         }
         if (notificationServer != null)
         {
             byte[] buffer = Encoding.ASCII.GetBytes(string.Concat(SETUP_NOTIFICATION, notificationClient.TableName, "|"));
             try
             {
                 Send(notificationServer.TcpClient, buffer);
                 Interlocked.Increment(ref _NotificationClientCount);
                 notificationClient.Enabled = true;
                 lock (notificationServer)
                 {
                     notificationServer.AddClient(notificationClient);
                 }
                 result = true;
             }
             catch (Exception ex)
             {
                 ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::SetupNotification {0}", ex), System.Diagnostics.EventLogEntryType.Error);
                 notificationServer = null;
             }
         }
         count = (count + 1) % int.MaxValue;
     }
     return result;
 }
 internal void AddClient(NotificationClient notificationClient)
 {
     TableChangeClients.Add(notificationClient);
 }
 internal void RemoveClient(NotificationClient notificationClient)
 {
     for (int index = 0; index < TableChangeClients.Count; index++)
     {
         if (TableChangeClients[index].Key == notificationClient.Key)
         {
             TableChangeClients.RemoveAt(index);
             break;
         }
     }
 }
예제 #38
0
        protected virtual void InitRestClients()
        {
            RestClient = new RestClient(RootUrl + "api/");
            RestClient.AddDefaultHeader("Authentication", ApiKey);
            RestClient.AddDefaultHeader("X-Api-Key", ApiKey);

            Blacklist = new ClientBase<BlacklistResource>(RestClient, ApiKey);
            Commands = new CommandClient(RestClient, ApiKey);
            DownloadClients = new DownloadClientClient(RestClient, ApiKey);
            Episodes = new EpisodeClient(RestClient, ApiKey);
            History = new ClientBase<HistoryResource>(RestClient, ApiKey);
            HostConfig = new ClientBase<HostConfigResource>(RestClient, ApiKey, "config/host");
            Indexers = new IndexerClient(RestClient, ApiKey);
            NamingConfig = new ClientBase<NamingConfigResource>(RestClient, ApiKey, "config/naming");
            Notifications = new NotificationClient(RestClient, ApiKey);
            Profiles = new ClientBase<ProfileResource>(RestClient, ApiKey);
            Releases = new ReleaseClient(RestClient, ApiKey);
            RootFolders = new ClientBase<RootFolderResource>(RestClient, ApiKey);
            Series = new SeriesClient(RestClient, ApiKey);
            Tags = new ClientBase<TagResource>(RestClient, ApiKey);
            WantedMissing = new ClientBase<EpisodeResource>(RestClient, ApiKey, "wanted/missing");
            WantedCutoffUnmet = new ClientBase<EpisodeResource>(RestClient, ApiKey, "wanted/cutoff");
        }
예제 #39
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AlertService"/>.
		/// </summary>
		/// <param name="dumpDir">Temp files directory.</param>
		public AlertService(string dumpDir)
		{
			if (dumpDir.IsEmpty())
				throw new ArgumentNullException("dumpDir");

			ThreadingHelper
				.Thread(() =>
				{
					try
					{
						var player = new MediaPlayer();

						var fileName = Path.Combine(dumpDir, "alert.mp3");

						if (!File.Exists(fileName))
							Properties.Resources.Alert.Save(fileName);

						player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));

						var logManager = ConfigManager.GetService<LogManager>();

						using (var speech = new SpeechSynthesizer())
						using (var client = new NotificationClient())
						using (player.MakeDisposable(p => p.Close()))
						{
							while (!IsDisposed)
							{
								Tuple<AlertTypes, string, string, DateTime> alert;

								if (!_alerts.TryDequeue(out alert))
									break;

								try
								{
									switch (alert.Item1)
									{
										case AlertTypes.Sound:
											player.Play();
											break;
										case AlertTypes.Speech:
											speech.Speak(alert.Item2);
											break;
										case AlertTypes.Popup:
											GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow
											{
												Title = alert.Item2,
												Message = alert.Item3,
												Time = alert.Item4
											}.Show());
											break;
										case AlertTypes.Sms:
											client.SendSms(alert.Item2);
											break;
										case AlertTypes.Email:
											client.SendEmail(alert.Item2, alert.Item3);
											break;
										case AlertTypes.Log:
											logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params
												.Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3));
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
								}
								catch (Exception ex)
								{
									ex.LogError();
								}
							}
						}
					}
					catch (Exception ex)
					{
						ex.LogError();
					}
				})
				.Name("Alert thread")
				.Launch();
		}
 private void AddNotificationToRepair(NotificationClient notificationClient)
 {
     notificationClient.Enabled = false;
     lock (_NotificationsToRepair)
     {
         _NotificationsToRepair.Enqueue(notificationClient);
     }
     _TriggerNotificationRepair.Set();
 }
예제 #41
0
        private void InitRestClients()
        {
            RestClient = new RestClient(RootUrl + "api/");
            RestClient.AddDefaultHeader("Authentication", _runner.ApiKey);
            RestClient.AddDefaultHeader("X-Api-Key", _runner.ApiKey);

            Series = new SeriesClient(RestClient, _runner.ApiKey);
            Releases = new ReleaseClient(RestClient, _runner.ApiKey);
            RootFolders = new ClientBase<RootFolderResource>(RestClient, _runner.ApiKey);
            Commands = new ClientBase<CommandResource>(RestClient, _runner.ApiKey);
            History = new ClientBase<HistoryResource>(RestClient, _runner.ApiKey);
            Indexers = new IndexerClient(RestClient, _runner.ApiKey);
            Episodes = new EpisodeClient(RestClient, _runner.ApiKey);
            NamingConfig = new ClientBase<NamingConfigResource>(RestClient, _runner.ApiKey, "config/naming");
            Notifications = new NotificationClient(RestClient, _runner.ApiKey);
        }
 private bool SetupNotification(int attemptsCount, string tableName, NotificationEventHandler changeEventHandler)
 {
     bool result = false;
     string key = NotificationClient.GetKey(tableName, changeEventHandler);
     NotificationClient notificationClient;
     while (!_NotificationClients.TryGetValue(key, out notificationClient))
     {
         notificationClient = new NotificationClient() { TableName = tableName, EventHandler = changeEventHandler };
         if (AddNotificationClient(notificationClient))
             break;
     }
     result = SetupNotification(notificationClient, attemptsCount);
     if (!result)
     {
         AddNotificationToRepair(notificationClient);
     }
     return result;
 }
 private bool AddNotificationClient(NotificationClient notificationClient)
 {
     bool result = false;
     if (_NotificationClients.TryAdd(notificationClient.Key, notificationClient))
     {
         List<NotificationClient> handlers;
         if (_TableChangeClients.ContainsKey(notificationClient.TableName))
             handlers = _TableChangeClients[notificationClient.TableName];
         else
         {
             handlers = new List<NotificationClient>();
             _TableChangeClients.TryAdd(notificationClient.TableName, handlers);
         }
         handlers.Add(notificationClient);
         result = true;
     }
     return result;
 }
예제 #44
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            notificationClient = new NotificationClient(ApplicationId, DeviceId, ServiceEnpointsUrl);
            var registerOperation = notificationClient.Register();

           registerOperation.Completed = ((info, status) =>
           {
               var channel = info.GetResults();
               var error = notificationClient.Error.ErrorMessage;
           });
            // TODO: Create a data model appropriate for your problem domain to replace the sample data
            string responseText = await GetjsonStream();

            // Get Search Pane object
            searchPane = SearchPane.GetForCurrentView();
            // Register for Search Pane QuerySubmitted event
            //this.searchPane.QuerySubmitted += new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>();

            JsonDataSource sampleData = ParseJson(responseText, "Kjoler");

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application
            }

            // Create a Frame to act navigation context and navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            var rootFrame = new Frame();
            rootFrame.Navigate(typeof (GroupedItemsPage), sampleData.ItemGroups);

            // Place the frame in the current Window and ensure that it is active
            Window.Current.Content = rootFrame;
            Window.Current.Activate();
        }