void Start() { manager = GameObject.Find("Manager").GetComponent<Manager>(); nwm = manager.GetComponent<NetworkManager>(); nm = manager.GetComponent<NotificationManager>(); cm = manager.GetComponent<CollisionManager>(); }
public void TestHandleBuildNotification() { UserCache userCache = null; NotificationManager notificationManager = null; try { userCache = new UserCache(); notificationManager = new NotificationManager(0, 0, userCache, false); string username = "******"; string[] recipients = { username }; BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding; string projectId = "project1"; string buildConfigId = "buildconfig1"; IBuildServerNotification buildServerNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients); string buildKey = Utils.CreateBuildKey(buildServerNotification); notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty); User user = userCache.GetUser(username); Assert.That(user.Username, Is.EqualTo(username)); Assert.That(user.ActiveBuilds.Contains(buildKey)); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
/// <summary> /// The main method. /// </summary> private static void Main() { UserCache userCache = null; NotificationManager notificationManager = null; try { userCache = new UserCache(5000, new TimeSpan(0, 5, 0)); notificationManager = new NotificationManager(Config.GetNotificationManagerPort(), Config.GetLightsManagerPort(), userCache, Config.GetInitializationEnabled()); Thread thread = new Thread(notificationManager.Start); thread.Start(); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(true); notificationManager.Stop(); thread.Join(); Console.WriteLine("Press any key to close..."); Console.ReadKey(true); } catch (Exception e) { Console.Error.WriteLine(e); Console.ReadKey(true); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
void Start() { if(nm == null) { nm = FindObjectOfType<NotificationManager>(); } }
public void AddNotification_Adds_Notification() { var manager = new NotificationManager(); Assert.IsTrue(manager.GetNotifications().Count == 0); manager.AddNotification(new DummyError()); Assert.IsTrue(manager.GetNotifications().Count == 1); }
public static NotificationManager GetNotificationManager() { if (notificationManager == null) { notificationManager = new NotificationManager(); notificationManager.androidJavaObject = currentActivity.Call<AndroidJavaObject>("getSystemService", "notification"); } return notificationManager; }
public LoginService(IServerConfiguration configuration) { _configuration = configuration; _loginStorage = new LoginStorage(_configuration); _store = NotificationManager<LoginService>.Instance.RegisterDuplexService<UserIdentity, ILoginNotifier>( NotifierBehaviour.OneInstance); _loginStorage.OnAddItem += new EventHandler<KeyCollection<UserIdentity>.KeyEventArgs>(_loginStorage_OnAddItem); _loginStorage.OnRemoveItem += new EventHandler<KeyCollection<UserIdentity>.KeyEventArgs>(_loginStorage_OnRemoveItem); }
public void HasError_Returns_True_On_Error() { var manager = new NotificationManager(); Assert.IsFalse(manager.HasError()); manager.AddNotifications(new List<INotification>{ new DummyError() }); Assert.IsTrue(manager.HasError()); }
public void HasError_Returns_False_on_Warnings() { var manager = new NotificationManager(); Assert.IsFalse(manager.HasError()); manager.AddNotifications(new List<INotification>{ new DummyWarning() }); Assert.IsFalse(manager.HasError()); }
public void Publish_with_null_message_throws_exception() { var notificationCenter = new NotificationManager(); notificationCenter.Subscribe<ShoutMessage>((msg, sub) => { }); // Act notificationCenter.Publish<ShoutMessage>(null); // Assert Assert.Fail(); }
public void AddNotifications_Adds_Notifications() { var manager = new NotificationManager(); Assert.IsTrue(manager.GetNotifications().Count == 0); manager.AddNotifications(new List<INotification>{ new DummyError(), new DummyError(), new DummyWarning() }); Assert.IsTrue(manager.GetNotifications().Count == 3); }
public void WhenSubscribed_ShouldPass() { var mockOfObserver = new Mock<INotificationObserver<string>>(); var notifier = new NotificationManager(); var res = notifier.Subscribe(topciKey, mockOfObserver.Object); Assert.NotNull(res); Assert.Equal(1, notifier.SubscriptionsByTopic.Values.Count); Assert.True(notifier.SubscriptionsByTopic.Values.SelectMany(e=>e).Contains(mockOfObserver.Object)); Assert.IsType<Unsubscriber>(res); }
public void WhenSameTopic_ShouldNotifyAll() { var mockOfObserver1 = new Mock<INotificationObserver<string>>(); var mockOfObserver2 = new Mock<INotificationObserver<string>>(); var notifier = new NotificationManager(); var res1 = notifier.Subscribe(topciKey, mockOfObserver1.Object); var res2 = notifier.Subscribe(topciKey, mockOfObserver2.Object); notifier.Notify(topciKey); Assert.NotNull(notifier.SubscriptionsByTopic.Values.SelectMany(e => e).Count() == 0); }
public void Publish_invokes_callbacks() { bool callbackCalled = false; string messageContent = "Test"; var notificationCenter = new NotificationManager(); ISubscription subscription = notificationCenter.Subscribe<ShoutMessage>((msg, sub) => callbackCalled = msg.Content == messageContent); // Act notificationCenter.Publish(new ShoutMessage(messageContent, null)); // Assert Assert.IsTrue(callbackCalled, "The subscriber did not have its callback invoked."); }
void Start() { if (nm != null && nm != this) { Destroy(gameObject); return; } notiIdSet = new HashSet<int>(); Random.seed = System.DateTime.Now.Millisecond; DontDestroyOnLoad(gameObject); nm = this; LanguageManager languageManager = LanguageManager.Instance; languageManager.OnChangeLanguage += OnChangeLanguage; OnChangeLanguage(languageManager); }
void Awake() { World = _World; LandWaterMask = _LandWaterMask; GT = transform.GetComponent<GameTime>(); WM = transform.GetComponent<WorldManager>(); AEM = transform.GetComponent<AnomalousEventManager>(); TEM = transform.GetComponent<TimedEventManager>(); CM = transform.GetComponent<ColorManager>(); NM = transform.GetComponent<NotificationManager>(); GOI = transform.GetComponent<GoIManager>(); POI = transform.GetComponent<PoIManager>(); WC = transform.GetComponent<WebController>(); }
public void Handler_receives_only_its_message() { // Arrange // Set up the first handler var notificationCenter = new NotificationManager(); notificationCenter.Subscribe<MessageFixture>( (message, sub) => ExceptionFactory .ThrowIf<InvalidOperationException>(message.GetType() != typeof(MessageFixture))); notificationCenter.Subscribe<SecondaryMessageFixture>( (message, sub) => ExceptionFactory .ThrowIf<InvalidOperationException>(message.Content.GetType() != typeof(DefaultPlayer))); // Act notificationCenter.Publish(new MessageFixture("Test")); //notificationCenter.Publish(new SecondaryMessageFixture(new DefaultPlayer(null, notificationCenter))); }
public void Combine_combines_Notifications() { var manager1 = new NotificationManager(); var manager2 = new NotificationManager(); manager1.AddNotifications(new List<INotification>{ new DummyError(), new DummyError(), new DummyError() }); manager2.AddNotifications(new List<INotification>{ new DummyError(), new DummyError() }); int count1 = manager1.GetNotifications().Count; int count2 = manager2.GetNotifications().Count; manager1.Combine(manager2); int countComb = manager1.GetNotifications().Count; Assert.IsTrue(countComb == count1 + count2); }
protected internal override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.main_layout; ActionBar actionBar = ActionBar; actionBar.HomeButtonEnabled = true; actionBar.DisplayHomeAsUpEnabled = true; mPublisherViewContainer = (RelativeLayout) findViewById(R.id.publisherview); mSubscriberViewContainer = (RelativeLayout) findViewById(R.id.subscriberview); mLoadingSub = (ProgressBar) findViewById(R.id.loadingSpinner); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mStreams = new List<Stream>(); sessionConnect(); }
public void Handler_can_unsubscribe() { var notificationCenter = new NotificationManager(); int callCount = 0; // Build our notification. ISubscription subscriber = notificationCenter.Subscribe<MessageFixture>( (message, sub) => callCount++); // Subscribe our notification and publish a new message notificationCenter.Publish(new MessageFixture("Test")); // Act // Unsubscribe the notification and attempt a new publish subscriber.Unsubscribe(); notificationCenter.Publish(new MessageFixture("Test")); // Assert Assert.AreEqual(1, callCount, "The callbacks were not fired properly"); }
public void Awake() { if (!menuManager) menuManager = GameObject.FindObjectOfType<MenuManager>(); if (!notificationManager) notificationManager = GameObject.FindObjectOfType<NotificationManager>(); if (!spellHistoryMenu) spellHistoryMenu = GameObject.FindObjectOfType<SpellHistoryMenu>(); if (!regionDetailsMenu) regionDetailsMenu = GameObject.FindObjectOfType<RegionDetailsMenu>(); if (!wizardIcon) wizardIcon = GameObject.FindObjectOfType<WizardIcon>(); spellManager = GetComponent<SpellManager>(); wizardManager = GetComponent<WizardManager>(); regionManager = GetComponent<RegionManager>(); }
protected internal override void onCreate(Bundle savedInstanceState) { Log.i(LOGTAG, "ONCREATE"); base.onCreate(savedInstanceState); ContentView = R.layout.screensharing_layout; ActionBar actionBar = ActionBar; actionBar.HomeButtonEnabled = true; actionBar.DisplayHomeAsUpEnabled = true; //We are using a webView to show the screensharing action //If we want to share our screen we could use: mView = ((Activity)this.context).getWindow().getDecorView().findViewById(android.R.id.content); mPubScreenWebView = (WebView) findViewById(R.id.webview_screen); mSubscriberViewContainer = (RelativeLayout) findViewById(R.id.subscriberview); mLoadingSub = (ProgressBar) findViewById(R.id.loadingSpinner); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mStreams = new List<Stream>(); sessionConnect(); }
// Use this for initialization void Start () { var repo = ConsoleCommandsRepository.Instance; try{ noteman = GameObject.Find ("Notification Canvas").GetComponent<NotificationManager> (); }catch (Exception e){ } repo.RegisterCommand ("addItem", additem); repo.RegisterCommand ("debug", DebugOn); repo.RegisterCommand ("exit", Exit); repo.RegisterCommand ("help", Help); repo.RegisterCommand ("load", Load); repo.RegisterCommand ("noclip", noClip); repo.RegisterCommand ("notification", notification); repo.RegisterCommand ("removeItem", removeitem); repo.RegisterCommand ("removeItemName", removeItemName); repo.RegisterCommand ("resetAll", resetAll); repo.RegisterCommand ("resetEverything", resetEverything); repo.RegisterCommand ("resetInvData", resetdata); repo.RegisterCommand ("resetQuestData", resetQuestData); repo.RegisterCommand ("saveGame", savegame); repo.RegisterCommand("setGold", setGold); repo.RegisterCommand ("setTime", setTime); }
public void TestHandleRegistrationRequest() { UserCache userCache = null; NotificationManager notificationManager = null; try { userCache = new UserCache(); notificationManager = new NotificationManager(0, 0, userCache, false); string username = "******"; string hostname = username + "-ws"; IRequest registrationRequest = new RegistrationRequest(hostname, username); // Check that the user doesn't exist prior to the registration request try { userCache.GetUser(username); Assert.Fail(); } catch (KeyNotFoundException) { } notificationManager.HandleCommand(registrationRequest, EventArgs.Empty); User user = userCache.GetUser(username); Assert.That(user.Username, Is.EqualTo(username)); Assert.That(user.Hostname, Is.EqualTo(hostname)); // Registering the same user a second time shouldn't fail notificationManager.HandleCommand(registrationRequest, EventArgs.Empty); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
public NotificationServices() { _notificationManager = new NotificationManager(); }
void Awake() { Instance = this; _internalList = new Dictionary <EventNotification, List <EventReceiver> >(); }
public void Setup() { _notify = new NotificationManager(_liveMode); }
public void notificationThreadFunctie() { int aantalNieuweKlanten = 0; int vorigAantalNieuweKlanten = 0; List <Klant> serverKlanten = new List <Klant>(); List <Klant> geweigerdeKlanten = new List <Klant>(); KlantDataService dataService = new KlantDataService(); //while (threadRunning == true) //zorg voor een eeuwige lus while (true) //zorg voor een eeuwige lus { if (threadRunning == true) { Thread.Sleep(7000); using (WebClient wc = new WebClient()) { var json = wc.DownloadString("http://35.165.103.236:80/unhandledclients"); serverKlanten = JsonConvert.DeserializeObject <List <Klant> >(json); } //serverKlanten = dataService.GeefAlleKlantenFromServer(); geweigerdeKlanten = dataService.getGewijgerdeKlanten(); aantalNieuweKlanten = serverKlanten.Count; //maximum aantal nieuwe klanten (gelijk aan server klanten) if (geweigerdeKlanten[0].Username != "XXXXGEENKLANTENXXXX") //wanneer er nog geen gewijgerde klanten zijn { for (int i = 0; i < serverKlanten.Count; i++) { for (int j = 0; j < geweigerdeKlanten.Count; j++) { if (serverKlanten == geweigerdeKlanten) //als bepaalde klant op de server == aan de reeds geweigerde klant { aantalNieuweKlanten--; //wordt maximum aantal klanten verminderd met 1 } } } } if (aantalNieuweKlanten != 0 && aantalNieuweKlanten != vorigAantalNieuweKlanten) { vorigAantalNieuweKlanten++; //voor het maken van de klik event // When the user clicks the notification, SecondActivity will start up. Intent resultIntent = new Intent(this, typeof(AccepteerActivity)); // Construct a back stack for cross-task navigation: TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(AccepteerActivity))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); Android.Net.Uri alarmSound = Android.Media.RingtoneManager.GetDefaultUri(Android.Media.RingtoneType.Notification); Notification.Builder builder = new Notification.Builder(this) .SetContentTitle("Nieuwe klanten") .SetContentText("Er zijn " + aantalNieuweKlanten + " nieuwe klanten") .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetSmallIcon(Android.Resource.Drawable.IcDialogAlert) .SetSound(alarmSound) .SetVibrate(new long[] { 500, 500, 500, 500, 500 }) .SetPriority(10); // Build the notification: Notification nieuweKlantNotification = builder.Build(); // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: const int notificationId = 0; notificationManager.Notify(notificationId, nieuweKlantNotification); } } } }
/// <summary> /// Allows files to be dropped into the window. /// </summary> internal static void OnFileDropped(object sender, string e) { var game = GameBase.Game as QuaverGame; var screen = game.CurrentScreen; // Mapset files if (e.EndsWith(".qp") || e.EndsWith(".osz") || e.EndsWith(".sm")) { Queue.Add(e); var log = $"Scheduled {Path.GetFileName(e)} to be imported!"; NotificationManager.Show(NotificationLevel.Info, log); if (screen.Exiting) { return; } if (screen.Type == QuaverScreenType.Select) { if (OnlineManager.CurrentGame != null) { var mpScreen = ScreenManager.Screens.ToList().Find(x => x is MultiplayerScreen); screen.Exit(() => new ImportingScreen(mpScreen as MultiplayerScreen), 0, QuaverScreenChangeType.AddToStack); return; } screen.Exit(() => new ImportingScreen()); return; } if (screen.Type == QuaverScreenType.Multiplayer) { screen.Exit(() => new ImportingScreen((MultiplayerScreen)screen), 0, QuaverScreenChangeType.AddToStack); return; } } // Quaver Replay else if (e.EndsWith(".qr")) { try { switch (screen.Type) { case QuaverScreenType.Menu: case QuaverScreenType.Results: case QuaverScreenType.Select: break; default: NotificationManager.Show(NotificationLevel.Error, "Please exit this screen before loading a replay"); return; } var replay = new Replay(e); // Find the map associated with the replay. var mapset = MapManager.Mapsets.Find(x => x.Maps.Any(y => y.Md5Checksum == replay.MapMd5)); if (mapset == null) { NotificationManager.Show(NotificationLevel.Error, "You do not have the map associated with this replay."); return; } MapManager.Selected.Value = mapset.Maps.Find(x => x.Md5Checksum == replay.MapMd5); screen.Exit(() => { if (AudioEngine.Track != null) { lock (AudioEngine.Track) AudioEngine.Track.Fade(10, 300); } return(new ResultScreen(replay)); }); } catch (Exception ex) { Logger.Error(ex, LogType.Runtime); NotificationManager.Show(NotificationLevel.Error, "Error reading replay file."); } // Skins } else if (e.EndsWith(".qs")) { switch (screen.Type) { case QuaverScreenType.Menu: case QuaverScreenType.Results: case QuaverScreenType.Select: SkinManager.Import(e); break; default: NotificationManager.Show(NotificationLevel.Error, "Please exit this screen before importing a skin"); return; } } else if (e.EndsWith(".mp3") || e.EndsWith(".ogg")) { switch (screen.Type) { case QuaverScreenType.Select: EditorScreen.HandleNewMapsetCreation(e); break; default: NotificationManager.Show(NotificationLevel.Error, "Go to the song select screen first to create a new mapset!"); return; } } }
public void TestStopAndStopAgain() { NotificationManager notificationManager = null; try { notificationManager = new NotificationManager(0, 0, new UserCache(), false); notificationManager.Start(); Assert.That(notificationManager.Running, Is.True); notificationManager.Stop(); Assert.That(notificationManager.Running, Is.False); notificationManager.Stop(); Assert.That(notificationManager.Running, Is.False); } finally { if (notificationManager != null) { notificationManager.Dispose(); } } }
public NotificationsMessageService(ConnectionsHub hub, NotificationsDataUnitOfWork db, NotificationManager notificationManager, ILogger <NotificationsMessageService> logger, MediaConverter mediaConverter) { Db = db; Hub = hub; NotificationManager = notificationManager; Logger = logger; MediaConverter = mediaConverter; }
public static void ShowRefresh(bool show) { // Gets an instance of the NotificationManager service NotificationManager mNotifyMgr = (NotificationManager)App.Context.GetSystemService(App.NotificationService); InitChannel(mNotifyMgr); if (mNotification == null) { try { StatusBarNotification statNot = null; if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { var statNots = mNotifyMgr.GetActiveNotifications(); if (statNots?.Length > 0) { statNot = statNots.FirstOrDefault(not => not.Id == PERSISTENT_NOT_ID); } } if (statNot != null && statNot.Notification != null) { mNotification = statNot.Notification; } else { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID) .SetSmallIcon(Resource.Drawable.ic_logo) .SetPriority(NotificationCompat.PriorityLow) .SetOngoing(true) as NotificationCompat.Builder; mNotification = mBuilder.Build(); } } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Debug, ex, "SimpleWeather: {0}: error access notifications"); } } // Build update RemoteViews updateViews = null; if (mNotification.ContentView == null) { updateViews = new RemoteViews(App.Context.PackageName, Resource.Layout.notification_layout); } else { updateViews = mNotification.ContentView; } updateViews.SetViewVisibility(Resource.Id.refresh_button, show ? ViewStates.Gone : ViewStates.Visible); updateViews.SetViewVisibility(Resource.Id.refresh_progress, show ? ViewStates.Visible : ViewStates.Gone); mNotification.ContentView = updateViews; // Builds the notification and issues it. mNotifyMgr.Notify(PERSISTENT_NOT_ID, mNotification); IsShowing = true; }
public static void UpdateNotification(Weather weather) { // Gets an instance of the NotificationManager service NotificationManager mNotifyMgr = (NotificationManager)App.Context.GetSystemService(App.NotificationService); InitChannel(mNotifyMgr); var wm = WeatherManager.GetInstance(); // Build update RemoteViews updateViews = new RemoteViews(App.Context.PackageName, Resource.Layout.notification_layout); string temp = (Settings.IsFahrenheit ? Math.Round(weather.condition.temp_f) : Math.Round(weather.condition.temp_c)) + "º"; string condition = weather.condition.weather; string hitemp = (Settings.IsFahrenheit ? Math.Round(double.Parse(weather.forecast[0].high_f)) : Math.Round(double.Parse(weather.forecast[0].high_c))) + "º"; string lotemp = (Settings.IsFahrenheit ? Math.Round(double.Parse(weather.forecast[0].low_f)) : Math.Round(double.Parse(weather.forecast[0].low_c))) + "º"; // Weather icon updateViews.SetImageViewResource(Resource.Id.weather_icon, wm.GetWeatherIconResource(weather.condition.icon)); // Location Name updateViews.SetTextViewText(Resource.Id.location_name, weather.location.name); // Condition text updateViews.SetTextViewText(Resource.Id.condition_weather, string.Format("{0} - {1}", temp, condition)); // Details updateViews.SetTextViewText(Resource.Id.condition_details, string.Format("{0} / {1}", hitemp, lotemp)); // Update Time string timeformat = DateTime.Now.ToString("h:mm tt"); if (DateFormat.Is24HourFormat(App.Context)) { timeformat = DateTime.Now.ToString("HH:mm"); } updateViews.SetTextViewText(Resource.Id.update_time, timeformat); // Progress bar updateViews.SetViewVisibility(Resource.Id.refresh_button, ViewStates.Visible); updateViews.SetViewVisibility(Resource.Id.refresh_progress, ViewStates.Gone); Intent refreshClickIntent = new Intent(App.Context, typeof(Widgets.WeatherWidgetBroadcastReceiver)) .SetAction(Widgets.WeatherWidgetService.ACTION_REFRESHNOTIFICATION); PendingIntent prgPendingIntent = PendingIntent.GetBroadcast(App.Context, 0, refreshClickIntent, 0); updateViews.SetOnClickPendingIntent(Resource.Id.refresh_button, prgPendingIntent); if (!int.TryParse(temp.Replace("º", ""), out int level)) { level = 0; } int resId = level < 0 ? Resource.Drawable.notification_temp_neg : Resource.Drawable.notification_temp_pos; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID) .SetContent(updateViews) .SetPriority(NotificationCompat.PriorityLow) .SetOngoing(true) as NotificationCompat.Builder; if (Settings.NotificationIcon == Settings.TEMPERATURE_ICON) { mBuilder.SetSmallIcon(resId, Math.Abs(level)); } else if (Settings.NotificationIcon == Settings.CONDITION_ICON) { mBuilder.SetSmallIcon(wm.GetWeatherIconResource(weather.condition.icon)); } Intent onClickIntent = new Intent(App.Context, typeof(MainActivity)) .SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask | ActivityFlags.ClearTask); PendingIntent clickPendingIntent = PendingIntent.GetActivity(App.Context, 0, onClickIntent, 0); mBuilder.SetContentIntent(clickPendingIntent); // Builds the notification and issues it. mNotification = mBuilder.Build(); mNotifyMgr.Notify(PERSISTENT_NOT_ID, mNotification); IsShowing = true; }
public void CancelNotificaton(Alarm alarm) { var manager = NotificationManager.FromContext(Forms.Context); manager.Cancel(alarm.Id); }
public void Update() { NotificationManager.Update(); }
private bool CheckOnGithub() { try { //If the app was installed by Chocolatey, avoid this. if (AppDomain.CurrentDomain.BaseDirectory.EndsWith(@"Chocolatey\lib\screentogif\content\")) { return(true); } //GraphQL equivalent. //query { // repository(owner: "NickeManarin", name: "ScreenToGif") { // releases(first: 1, orderBy: { field: CREATED_AT, direction: DESC}) { // nodes { // name // tagName // createdAt // url // isPrerelease // description // releaseAssets(last: 2) { // nodes { // name // downloadCount // downloadUrl // size // } // } // } // } // } //} var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/NickeManarin/ScreenToGif/releases/latest"); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; request.Proxy = WebHelper.GetProxy(); var response = (HttpWebResponse)request.GetResponse(); using (var resultStream = response.GetResponseStream()) { if (resultStream == null) { return(false); } using (var reader = new StreamReader(resultStream)) { var result = reader.ReadToEnd(); var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result), new System.Xml.XmlDictionaryReaderQuotas()); var release = XElement.Load(jsonReader); var version = Version.Parse(release.XPathSelectElement("tag_name")?.Value ?? "0.1"); if (version.Major == 0 || version <= Assembly.GetExecutingAssembly().GetName().Version) { return(true); } Global.UpdateAvailable = new UpdateAvailable { Version = version, Description = release.XPathSelectElement("body")?.Value ?? "", PortableDownloadUrl = release.XPathSelectElement("assets/item[1]/browser_download_url")?.Value ?? "", PortableSize = Convert.ToInt64(release.XPathSelectElement("assets/item[1]/size")?.Value ?? "0"), InstallerDownloadUrl = release.XPathSelectElement("assets/item[2]/browser_download_url")?.Value ?? "", InstallerSize = Convert.ToInt64(release.XPathSelectElement("assets/item[2]/size")?.Value ?? "0"), InstallerName = release.XPathSelectElement("assets/item[2]/name")?.Value ?? "ScreenToGif.Setup.msi", }; Application.Current.Dispatcher?.Invoke(() => NotificationManager.AddNotification(string.Format(LocalizationHelper.Get("S.Updater.NewRelease.Info"), Global.UpdateAvailable.Version), StatusType.Update, "update", PromptUpdate)); //Download update to be installed when the app closes. if (UserSettings.All.InstallUpdates && !string.IsNullOrEmpty(Global.UpdateAvailable.InstallerDownloadUrl)) { DownloadUpdate(); } } } return(true); } catch (Exception ex) { LogWriter.Log(ex, "Impossible to check for updates on Github"); return(false); } finally { GC.Collect(); } }
public void TestHandleResponsibilityNotification() { UserCache userCache = null; NotificationManager notificationManager = null; try { userCache = new UserCache(); notificationManager = new NotificationManager(0, 0, userCache, false); string username = "******"; BuildServerNotificationType notificationType = BuildServerNotificationType.BuildResponsibilityAssigned; string state = BuildServerResponsibilityState.Taken; string projectId = "project1"; string buildConfigId = "buildconfig1"; IBuildServerNotification buildServerNotification = new ResponsibilityNotification(notificationType, projectId, buildConfigId, username, state); string buildKey = Utils.CreateBuildKey(buildServerNotification); notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty); User user = userCache.GetUser(username); Assert.That(user.Username, Is.EqualTo(username)); Assert.That(user.BuildsResponsibleFor.Contains(buildKey)); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
public NotificationSender(Context context, string category) { mCategory = category; mContext = context; notificationManager = NotificationManager.FromContext(context); }
public void TestInitialize() { UserCache userCache = null; NotificationManager notificationManager = null; try { userCache = new UserCache(); notificationManager = new NotificationManager(0, 0, userCache, true); notificationManager.Start(); Assert.That(notificationManager.Running, Is.True); notificationManager.Stop(); Assert.That(notificationManager.Running, Is.False); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
private static void InitializePlatform(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string connectionString, HangfireLauncher hangfireLauncher, string modulesPath) { container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager()); container.RegisterType <IUserNameResolver, UserNameResolver>(); #region Setup database using (var db = new SecurityDbContext(connectionString)) { new IdentityDatabaseInitializer().InitializeDatabase(db); } using (var context = new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor())) { new PlatformDatabaseInitializer().InitializeDatabase(context); } hangfireLauncher.ConfigureDatabase(); #endregion Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()); container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory())); container.RegisterInstance(platformRepositoryFactory); var moduleCatalog = container.Resolve <IModuleCatalog>(); #region Caching //Cure for System.Runtime.Caching.MemoryCache freezing //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol app.SanitizeThreadCulture(); ICacheManager <object> cacheManager = null; //Try to load cache configuration from web.config first //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs) var cacheManagerSection = ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) as CacheManagerSection; if (cacheManagerSection != null && cacheManagerSection.CacheManagers.Any(p => p.Name.EqualsInvariant("platformCache"))) { var configuration = ConfigurationBuilder.LoadConfiguration("platformCache"); if (configuration != null) { configuration.LoggerFactoryType = typeof(CacheManagerLoggerFactory); configuration.LoggerFactoryTypeArguments = new object[] { container.Resolve <ILog>() }; cacheManager = CacheFactory.FromConfiguration <object>(configuration); } } if (cacheManager == null) { cacheManager = CacheFactory.Build("platformCache", settings => { settings.WithUpdateMode(CacheUpdateMode.Up) .WithSystemRuntimeCacheHandle("memCacheHandle") .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5)); }); } container.RegisterInstance(cacheManager); #endregion #region Settings var platformModuleManifest = new ModuleManifest { Id = "VirtoCommerce.Platform", Version = PlatformVersion.CurrentVersion.ToString(), PlatformVersion = PlatformVersion.CurrentVersion.ToString(), Settings = new[] { new ModuleSettingsGroup { Name = "Platform|Notifications|SendGrid", Settings = new [] { new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey", ValueType = ModuleSetting.TypeSecureString, Title = "SendGrid API key", Description = "Your SendGrid API key" } } }, new ModuleSettingsGroup { Name = "Platform|Notifications|SendingJob", Settings = new [] { new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount", ValueType = ModuleSetting.TypeInteger, Title = "Job Take Count", Description = "Take count for sending job" } } }, new ModuleSettingsGroup { Name = "Platform|Notifications|SmtpClient", Settings = new [] { new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SmptClient.Host", ValueType = ModuleSetting.TypeString, Title = "Smtp server host", Description = "Smtp server host" }, new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SmptClient.Port", ValueType = ModuleSetting.TypeInteger, Title = "Smtp server port", Description = "Smtp server port" }, new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SmptClient.Login", ValueType = ModuleSetting.TypeString, Title = "Smtp server login", Description = "Smtp server login" }, new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SmptClient.Password", ValueType = ModuleSetting.TypeSecureString, Title = "Smtp server password", Description = "Smtp server password" }, new ModuleSetting { Name = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl", ValueType = ModuleSetting.TypeBoolean, Title = "Use SSL", Description = "Use secure connection" }, } }, new ModuleSettingsGroup { Name = "Platform|Security", Settings = new [] { new ModuleSetting { Name = "VirtoCommerce.Platform.Security.AccountTypes", ValueType = ModuleSetting.TypeString, Title = "Account types", Description = "Dictionary for possible account types", IsArray = true, ArrayValues = Enum.GetNames(typeof(AccountType)), DefaultValue = AccountType.Manager.ToString() } } }, new ModuleSettingsGroup { Name = "Platform|User Profile", Settings = new[] { new ModuleSetting { Name = "VirtoCommerce.Platform.UI.MainMenu.State", ValueType = ModuleSetting.TypeJson, Title = "Persisted state of main menu" }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.Language", ValueType = ModuleSetting.TypeString, Title = "Language", Description = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de", DefaultValue = "en" }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.RegionalFormat", ValueType = ModuleSetting.TypeString, Title = "Regional format", Description = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS", DefaultValue = "en" }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.TimeZone", ValueType = ModuleSetting.TypeString, Title = "Time zone", Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow" }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.UseTimeAgo", ValueType = ModuleSetting.TypeBoolean, Title = "Use time ago format when is possible", Description = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible", DefaultValue = true.ToString() }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.FullDateThreshold", ValueType = ModuleSetting.TypeInteger, Title = "Full date threshold", Description = "Number of units after time ago format will be switched to full date format" }, new ModuleSetting { Name = "VirtoCommerce.Platform.UI.FullDateThresholdUnit", ValueType = ModuleSetting.TypeString, Title = "Full date threshold unit", Description = "Unit of full date threshold", DefaultValue = "Never", AllowedValues = new[] { "Never", "Seconds", "Minutes", "Hours", "Days", "Weeks", "Months", "Quarters", "Years" } } } }, new ModuleSettingsGroup { Name = "Platform|User Interface", Settings = new[] { new ModuleSetting { Name = "VirtoCommerce.Platform.UI.Customization", ValueType = ModuleSetting.TypeJson, Title = "Customization", Description = "JSON contains personalization settings of manager UI", DefaultValue = "{\n" + " \"title\": \"Virto Commerce\",\n" + " \"logo\": \"Content/themes/main/images/logo.png\",\n" + " \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\"\n" + "}" } } } } }; var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) }); container.RegisterInstance <ISettingsManager>(settingsManager); #endregion #region Dynamic Properties container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager()); #endregion #region Notifications var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>(); var notifier = new InMemoryPushNotificationManager(hubSignalR); container.RegisterInstance <IPushNotificationManager>(notifier); var resolver = new LiquidNotificationTemplateResolver(); container.RegisterInstance <INotificationTemplateResolver>(resolver); var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory); container.RegisterInstance <INotificationTemplateService>(notificationTemplateService); var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService); container.RegisterInstance <INotificationManager>(notificationManager); IEmailNotificationSendingGateway emailNotificationSendingGateway = null; var emailNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Gateway", "Default"); if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase)) { emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager); } else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase)) { emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager); } if (emailNotificationSendingGateway != null) { container.RegisterInstance(emailNotificationSendingGateway); } var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway(); container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway); #endregion #region Assets var blobConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("AssetsConnectionString")); if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(pathMapper, blobConnectionString.RootPath), blobConnectionString.PublicUrl); container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider); container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider); } else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString); container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider); container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider); } #endregion #region Modularity var modulesDataSources = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:ModulesDataSources"); var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>()); container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager)); #endregion #region ChangeLogging var changeLogService = new ChangeLogService(platformRepositoryFactory); container.RegisterInstance <IChangeLogService>(changeLogService); #endregion #region Security container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService()); container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager()); var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager); container.RegisterInstance <IApiAccountProvider>(apiAccountProvider); container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager()); container.RegisterInstance(app.GetDataProtectionProvider()); container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionString)); container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>(); container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication)); container.RegisterType <ApplicationUserManager>(); container.RegisterType <ApplicationSignInManager>(); var nonEditableUsers = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty); container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers)); container.RegisterType <ISecurityService, SecurityService>(); #endregion #region ExportImport container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>(); #endregion #region Serialization container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>(); #endregion }
public INotificationResult Notify(Activity activity, INotificationOptions options) { var notificationId = _count; var id = _count.ToString(); _count++; Intent dismissIntent = new Intent(DismissedClickIntent); dismissIntent.PutExtra(NotificationId, notificationId); PendingIntent pendingDismissIntent = PendingIntent.GetBroadcast(activity.ApplicationContext, 123, dismissIntent, 0); Intent clickIntent = new Intent(OnClickIntent); clickIntent.PutExtra(NotificationId, notificationId); // Add custom args if (options.CustomArgs != null) { foreach (var arg in options.CustomArgs) { clickIntent.PutExtra(arg.Key, arg.Value); } } PendingIntent pendingClickIntent = PendingIntent.GetBroadcast(activity.ApplicationContext, 123, clickIntent, 0); int smallIcon; if (options.AndroidOptions.SmallDrawableIcon.HasValue) { smallIcon = options.AndroidOptions.SmallDrawableIcon.Value; } else if (_androidOptions.SmallIconDrawable.HasValue) { smallIcon = _androidOptions.SmallIconDrawable.Value; } else { smallIcon = Android.Resource.Drawable.IcDialogInfo; // As last resort } Android.App.Notification.Builder builder = new Android.App.Notification.Builder(activity) .SetContentTitle(options.Title) .SetContentText(options.Description) .SetSmallIcon(smallIcon) // Must have small icon to display .SetPriority((int)NotificationPriority.High) // Must be set to High to get Heads-up notification .SetDefaults(NotificationDefaults.All) // Must also include vibrate to get Heads-up notification .SetAutoCancel(true) // To allow click event to trigger delete Intent .SetContentIntent(pendingClickIntent) // Must have Intent to accept the click .SetDeleteIntent(pendingDismissIntent); Android.App.Notification notification = builder.Build(); NotificationManager notificationManager = activity.GetSystemService(Context.NotificationService) as NotificationManager; notificationManager.Notify(notificationId, notification); var timer = new Timer(x => TimerFinished(activity, id, options.ClearFromHistory), null, TimeSpan.FromSeconds(7), TimeSpan.FromSeconds(100)); var resetEvent = new ManualResetEvent(false); ResetEvent.Add(id, resetEvent); resetEvent.WaitOne(); // Wait for a result var notificationResult = EventResult[id]; if (!options.IsClickable && notificationResult.Action == NotificationAction.Clicked) { notificationResult.Action = NotificationAction.Dismissed; } EventResult.Remove(id); ResetEvent.Remove(id); // Dispose of Intents and Timer pendingClickIntent.Cancel(); pendingDismissIntent.Cancel(); timer.Dispose(); return(notificationResult); }
public void OnReceived(IDictionary <string, object> parameters) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived"); if (parameters.TryGetValue(SilentKey, out object silent) && (silent.ToString() == "true" || silent.ToString() == "1")) { return; } Context context = Application.Context; int notifyId = 0; string title = context.ApplicationInfo.LoadLabel(context.PackageManager); var message = string.Empty; var tag = string.Empty; if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTextKey, out object notificationContentText)) { message = notificationContentText.ToString(); } else if (parameters.TryGetValue(AlertKey, out object alert)) { message = $"{alert}"; } else if (parameters.TryGetValue(BodyKey, out object body)) { message = $"{body}"; } else if (parameters.TryGetValue(MessageKey, out object messageContent)) { message = $"{messageContent}"; } else if (parameters.TryGetValue(SubtitleKey, out object subtitle)) { message = $"{subtitle}"; } else if (parameters.TryGetValue(TextKey, out object text)) { message = $"{text}"; } if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTitleKey, out object notificationContentTitle)) { title = notificationContentTitle.ToString(); } else if (parameters.TryGetValue(TitleKey, out object titleContent)) { if (!string.IsNullOrEmpty(message)) { title = $"{titleContent}"; } else { message = $"{titleContent}"; } } if (parameters.TryGetValue(IdKey, out object id)) { try { notifyId = Convert.ToInt32(id); } catch (Exception ex) { // Keep the default value of zero for the notify_id, but log the conversion problem. System.Diagnostics.Debug.WriteLine($"Failed to convert {id} to an integer {ex}"); } } if (parameters.TryGetValue(TagKey, out object tagContent)) { tag = tagContent.ToString(); } try { if (parameters.TryGetValue(SoundKey, out object sound)) { var soundName = sound.ToString(); int soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName); if (soundResId == 0 && soundName.IndexOf(".") != -1) { soundName = soundName.Substring(0, soundName.LastIndexOf('.')); soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName); } FirebasePushNotificationManager.SoundUri = new Android.Net.Uri.Builder() .Scheme(ContentResolver.SchemeAndroidResource) .Path($"{context.PackageName}/{soundResId}") .Build(); } } catch (Resources.NotFoundException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } if (FirebasePushNotificationManager.SoundUri == null) { FirebasePushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); } try { if (parameters.TryGetValue(IconKey, out object icon) && icon != null) { try { FirebasePushNotificationManager.IconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName); } catch (Resources.NotFoundException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } if (FirebasePushNotificationManager.IconResource == 0) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } else { string name = context.Resources.GetResourceName(FirebasePushNotificationManager.IconResource); if (name == null) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } } } catch (Resources.NotFoundException ex) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; System.Diagnostics.Debug.WriteLine(ex.ToString()); } if (parameters.TryGetValue(ColorKey, out object color) && color != null) { try { FirebasePushNotificationManager.Color = Color.ParseColor(color.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to parse color {ex}"); } } Intent resultIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : context.PackageManager.GetLaunchIntentForPackage(context.PackageName); //Intent resultIntent = new Intent(context, typeof(T)); Bundle extras = new Bundle(); foreach (var p in parameters) { extras.PutString(p.Key, p.Value.ToString()); } if (extras != null) { extras.PutInt(ActionNotificationIdKey, notifyId); extras.PutString(ActionNotificationTagKey, tag); resultIntent.PutExtras(extras); } if (FirebasePushNotificationManager.NotificationActivityFlags != null) { resultIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value); } var pendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); var notificationBuilder = new NotificationCompat.Builder(context) .SetSmallIcon(FirebasePushNotificationManager.IconResource) .SetContentTitle(title) .SetContentText(message) .SetAutoCancel(true) .SetContentIntent(pendingIntent); if (parameters.TryGetValue(PriorityKey, out object priority) && priority != null) { var priorityValue = $"{priority}"; if (!string.IsNullOrEmpty(priorityValue)) { switch (priorityValue.ToLower()) { case "max": notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Max); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "high": notificationBuilder.SetPriority((int)Android.App.NotificationPriority.High); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "default": notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Default); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "low": notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Low); break; case "min": notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Min); break; default: notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Default); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; } } else { notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); } } else { notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); } try { notificationBuilder.SetSound(FirebasePushNotificationManager.SoundUri); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to set sound {ex}"); } // Try to resolve (and apply) localized parameters ResolveLocalizedParameters(notificationBuilder, parameters); if (FirebasePushNotificationManager.Color != null) { notificationBuilder.SetColor(FirebasePushNotificationManager.Color.Value); } if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean) { // Using BigText notification style to support long message var style = new NotificationCompat.BigTextStyle(); style.BigText(message); notificationBuilder.SetStyle(style); } string category = string.Empty; if (parameters.TryGetValue(CategoryKey, out object categoryContent)) { category = categoryContent.ToString(); } if (parameters.TryGetValue(ActionKey, out object actionContent)) { category = actionContent.ToString(); } var notificationCategories = CrossFirebasePushNotification.Current?.GetUserNotificationCategories(); if (notificationCategories != null && notificationCategories.Length > 0) { IntentFilter intentFilter = null; foreach (var userCat in notificationCategories) { if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0) { foreach (var action in userCat.Actions) { if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase)) { Intent actionIntent = null; PendingIntent pendingActionIntent = null; if (action.Type == NotificationActionType.Foreground) { actionIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : context.PackageManager.GetLaunchIntentForPackage(context.PackageName); if (FirebasePushNotificationManager.NotificationActivityFlags != null) { actionIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value); } actionIntent.SetAction($"{action.Id}"); extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetActivity(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); } else { actionIntent = new Intent(); //actionIntent.SetAction($"{category}.{action.Id}"); actionIntent.SetAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}"); extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetBroadcast(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); } notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent); } if (FirebasePushNotificationManager.ActionReceiver == null) { if (intentFilter == null) { intentFilter = new IntentFilter(); } if (!intentFilter.HasAction(action.Id)) { intentFilter.AddAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}"); } } } } } if (intentFilter != null) { FirebasePushNotificationManager.ActionReceiver = new PushNotificationActionReceiver(); context.RegisterReceiver(FirebasePushNotificationManager.ActionReceiver, intentFilter); } } OnBuildNotification(notificationBuilder, parameters); NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(tag, notifyId, notificationBuilder.Build()); }
void Update() { if (player != null && !playerWithCam.GetComponent <PlayerManager>().playerDead) { Vector3 newPosition = player.transform.position; transform.position = newPosition; hitColliders = Physics.OverlapBox(transform.position + transform.forward, new Vector3(1f, 1f, 1), transform.rotation); //hitColliders = Physics.OverlapCapsule(transform.position, transform.position + transform.forward,1.5f); string text = string.Empty; foreach (Collider col in hitColliders) { if (col.gameObject.CompareTag(useableItemTag)) { //highlight if (currentItem == null) { currentItemDefaultMaterial = col.gameObject.GetComponentInChildren <Renderer>().material; col.gameObject.transform.gameObject.GetComponentInChildren <Renderer>().material = highlightMaterial; currentItem = col.gameObject.transform.gameObject; } else if (col.Equals(currentItem) && col.gameObject.GetComponentInChildren <Renderer>().material != highlightMaterial) { currentItemDefaultMaterial = col.gameObject.GetComponentInChildren <Renderer>().material; col.gameObject.transform.gameObject.GetComponentInChildren <Renderer>().material = highlightMaterial; } //solar panel if (col.GetComponent <SolarPanelDust>() != null) { var solarPanel = col.GetComponent <SolarPanelDust>(); text = "'E' To Remove Dust"; if (Input.GetKey(KeyCode.E)) { solarPanel.RemoveDust(); col.gameObject.transform.gameObject.GetComponentInChildren <Renderer>().material = highlightMaterial; } } if (col.GetComponent <Storage>() != null) { var storage = col.GetComponent <Storage>(); text = storage.IsOpen ? "'E' To Close Storage" : "'E' To Open Storage"; if (Input.GetKeyUp(KeyCode.E)) { storage.ToggleInventory(); } if (col.GetComponentInParent <Storage>().name.Contains("Cube")) { NotificationManager.CompleteNotification(EventName.OpenDrop); } } if (col.GetComponent <RockGrinder>() != null) { var rockGrinder = col.GetComponent <RockGrinder>(); text = "Select a Rock and Press 'E' To Grind"; if (Input.GetKeyUp(KeyCode.E)) { rockGrinder.TradeRock(); if (NotificationManager.Notifications.Any(q => q.EventName == EventName.GrindRock)) { NotificationManager.CompleteNotification(EventName.GrindRock); NotificationManager.AddNotification(new NotificationEvent(EventName.OpenCraftingMenu, "Go to the 3D Printer and Open Crafting Menu")); } } } if (col.GetComponentInChildren <Printer>() != null) { var printer = col.GetComponentInChildren <Printer>(); text = printer.IsOpen ? "'E' Close Crafting" : "'E' Begin Crafting With 3D Printer"; if (Input.GetKeyUp(KeyCode.E)) { printer.ToggleCrafting(); if (NotificationManager.Notifications.Any(q => q.EventName == EventName.OpenCraftingMenu)) { NotificationManager.CompleteNotification(EventName.OpenCraftingMenu); NotificationManager.AddNotification(new NotificationEvent(EventName.GatherBrokenCommsResources, "Gather Resources To Craft Communications Device")); } } } if (col.GetComponentInParent <RockInteraction>() != null) { var rock = col.GetComponentInParent <RockInteraction>(); var name = rock.name.Replace("(Clone)", ""); //if (name == "Rock1" || name == "Rock2" || name == "Rock3") //{ // text = "'E' To Pick Up Common Moon Rock"; //} //else // text = "'E' To Pick Up Rare Moon Rock"; text = "'E' To Pick Up Moon Rock"; if (Input.GetKey(KeyCode.E)) { rock.PickUpRock(); if (NotificationManager.Notifications.Any(a => a.EventName == EventName.PickUpRock)) { NotificationManager.CompleteNotification(EventName.PickUpRock); NotificationManager.AddNotification(new NotificationEvent(EventName.SelectHotbarSlot, "Select Rock with 2")); } } } if (col.GetComponentInParent <ElementInteraction>() != null) { var element = col.GetComponentInParent <ElementInteraction>(); text = "'E' To Pick Up " + Regex.Replace(col.transform.parent.name.Replace("(Clone)", ""), "(\\B[A-Z])", " $1"); if (Input.GetKey(KeyCode.E)) { element.PickUpElement(); } } if (col.GetComponentInParent <DropUsableInteraction>() != null) { var prefab = col.GetComponentInParent <DropUsableInteraction>(); text = "'E' To Pick Up " + Regex.Replace(col.transform.parent.name.Replace("Drop(Clone)", ""), "(\\B[A-Z])", " $1"); if (Input.GetKey(KeyCode.E)) { prefab.PickUpUsable(); } } if (col.GetComponentInParent <SuitPowerInteraction>() != null) { var prefab = col.GetComponentInParent <SuitPowerInteraction>(); text = "'E' To Recharge Suit"; if (Input.GetKey(KeyCode.E)) { prefab.RechargeSuit(); } } } } if (currentItem != null && !hitColliders.Contains(currentItem.GetComponent <Collider>())) { currentItem.GetComponentInChildren <Renderer>().material = currentItemDefaultMaterial; var solar = currentItem.GetComponent <SolarPanelDust>(); if (solar != null) { solar.SetMaterial(); } var storage = currentItem.GetComponent <Storage>(); if (storage != null) { storage.CloseInventory(); } var printer = currentItem.GetComponent <Printer>(); if (printer != null) { printer.CloseCrafting(); } currentItem = null; currentItemDefaultMaterial = null; } InstructionText.text = text; } }
private async Task <NotificationEntity> GetNotifications(UserAccountEntity userAccountEntity) { var notificationManager = new NotificationManager(); return(await notificationManager.GetNotifications(userAccountEntity.GetUserEntity().OnlineId, userAccountEntity)); }
public NotificationArea() { NotificationManager.AddArea(this); }
public Notification.Builder CreateNotificationBuilder(SensusNotificationChannel channel) { global::Android.Net.Uri notificationSoundURI = RingtoneManager.GetDefaultUri(RingtoneType.Notification); AudioAttributes notificationAudioAttributes = new AudioAttributes.Builder() .SetContentType(AudioContentType.Unknown) .SetUsage(AudioUsageKind.NotificationEvent).Build(); long[] vibrationPattern = { 0, 250, 50, 250 }; bool silent = GetChannelSilent(channel); Notification.Builder builder; // see the Backwards Compatibility article for more information #if __ANDROID_26__ if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { NotificationManager notificationManager = Application.Context.GetSystemService(global::Android.Content.Context.NotificationService) as NotificationManager; string channelId = channel.ToString(); if (notificationManager.GetNotificationChannel(channelId) == null) { NotificationChannel notificationChannel = new NotificationChannel(channelId, GetChannelName(channel), GetChannelImportance(channel)) { Description = GetChannelDescription(channel) }; if (silent) { notificationChannel.SetSound(null, null); notificationChannel.EnableVibration(false); } else { notificationChannel.SetSound(notificationSoundURI, notificationAudioAttributes); notificationChannel.EnableVibration(true); notificationChannel.SetVibrationPattern(vibrationPattern); } notificationManager.CreateNotificationChannel(notificationChannel); } builder = new Notification.Builder(Application.Context, channelId); } else #endif { #pragma warning disable 618 builder = new Notification.Builder(Application.Context); if (silent) { builder.SetSound(null); builder.SetVibrate(null); } else { builder.SetSound(notificationSoundURI, notificationAudioAttributes); builder.SetVibrate(vibrationPattern); } #pragma warning restore 618 } return(builder); }
/// <summary> /// Registers resources that classes will depend on /// </summary> /// <returns>Task.</returns> protected override async Task RegisterResources(IProgress <double> progress) { await base.RegisterResources(progress).ConfigureAwait(false); RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer)); RegisterSingleInstance <IServerApplicationHost>(this); RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths); RegisterSingleInstance(ServerConfigurationManager); LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer); RegisterSingleInstance(LocalizationManager); RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer()); UserDataManager = new UserDataManager(LogManager); RegisterSingleInstance(UserDataManager); UserRepository = await GetUserRepository().ConfigureAwait(false); RegisterSingleInstance(UserRepository); DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(DisplayPreferencesRepository); ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager); RegisterSingleInstance(ItemRepository); ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager); RegisterSingleInstance(ProviderRepository); FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false); RegisterSingleInstance(FileOrganizationRepository); AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false); RegisterSingleInstance(AuthenticationRepository); //SyncRepository = await GetSyncRepository().ConfigureAwait(false); //RegisterSingleInstance(SyncRepository); UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager); RegisterSingleInstance(LibraryManager); var musicManager = new MusicManager(LibraryManager); RegisterSingleInstance <IMusicManager>(new MusicManager(LibraryManager)); LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager); RegisterSingleInstance(LibraryMonitor); ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager); RegisterSingleInstance(ProviderManager); SeriesOrderManager = new SeriesOrderManager(); RegisterSingleInstance(SeriesOrderManager); RegisterSingleInstance <ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager)); HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html"); RegisterSingleInstance(HttpServer, false); progress.Report(10); ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager); RegisterSingleInstance(ServerManager); var innerProgress = new ActionableProgress <double>(); innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15)); await RegisterMediaEncoder(innerProgress).ConfigureAwait(false); progress.Report(90); ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder); RegisterSingleInstance(ImageProcessor); SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager")); RegisterSingleInstance(SyncManager); DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager); RegisterSingleInstance(DtoService); var encryptionManager = new EncryptionManager(); RegisterSingleInstance <IEncryptionManager>(encryptionManager); ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager); RegisterSingleInstance(ConnectManager); SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository); RegisterSingleInstance(SessionManager); var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer); RegisterSingleInstance <INewsService>(newsService); var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager); RegisterSingleInstance <IFileOrganizationService>(fileOrganizationService); progress.Report(15); ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager); RegisterSingleInstance(ChannelManager); TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager); RegisterSingleInstance(TVSeriesManager); var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger); RegisterSingleInstance <IAppThemeManager>(appThemeManager); var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer); RegisterSingleInstance <IDlnaManager>(dlnaManager); var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient); RegisterSingleInstance <IConnectionManager>(connectionManager); var collectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager")); RegisterSingleInstance <ICollectionManager>(collectionManager); var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager); RegisterSingleInstance <IPlaylistManager>(playlistManager); LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer); RegisterSingleInstance(LiveTvManager); UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager); RegisterSingleInstance(UserViewManager); var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient); RegisterSingleInstance <IContentDirectory>(contentDirectory); NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager); RegisterSingleInstance(NotificationManager); SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository); RegisterSingleInstance(SubtitleManager); ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); EncodingManager = new EncodingManager(ServerConfigurationManager, FileSystemManager, Logger, MediaEncoder, ChapterManager); RegisterSingleInstance(EncodingManager); var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false); RegisterSingleInstance(activityLogRepo); RegisterSingleInstance <IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo)); var authContext = new AuthorizationContext(); RegisterSingleInstance <IAuthorizationContext>(authContext); RegisterSingleInstance <ISessionContext>(new SessionContext(UserManager, authContext, SessionManager)); RegisterSingleInstance <IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager)); RegisterSingleInstance <ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer)); var displayPreferencesTask = Task.Run(async() => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false)); var itemsTask = Task.Run(async() => await ConfigureItemRepositories().ConfigureAwait(false)); var userdataTask = Task.Run(async() => await ConfigureUserDataRepositories().ConfigureAwait(false)); await ConfigureNotificationsRepository().ConfigureAwait(false); progress.Report(92); await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false); progress.Report(100); SetStaticProperties(); await((UserManager)UserManager).Initialize().ConfigureAwait(false); SetKernelProperties(); }
internal void UpdateTask() { Global.UpdateModel = null; if (!UserSettings.All.CheckForUpdates) { return; } #if !UWP try { var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/NickeManarin/ScreenToGif/releases/latest"); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; request.Proxy = WebHelper.GetProxy(); var response = (HttpWebResponse)request.GetResponse(); using (var resultStream = response.GetResponseStream()) { if (resultStream == null) { return; } using (var reader = new StreamReader(resultStream)) { var result = reader.ReadToEnd(); var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result), new System.Xml.XmlDictionaryReaderQuotas()); var release = XElement.Load(jsonReader); var version = Version.Parse(release.XPathSelectElement("tag_name")?.Value ?? "0.1"); if (version.Major == 0 || version <= Assembly.GetExecutingAssembly().GetName().Version) { return; } Global.UpdateModel = new UpdateModel { Version = version, Description = release.XPathSelectElement("body")?.Value ?? "", InstallerDownloadUrl = release.XPathSelectElement("assets/item[2]/browser_download_url")?.Value ?? "", InstallerSize = Convert.ToInt64(release.XPathSelectElement("assets/item[2]/size")?.Value ?? "0"), PortableDownloadUrl = release.XPathSelectElement("assets/item[1]/browser_download_url")?.Value ?? "", PortableSize = Convert.ToInt64(release.XPathSelectElement("assets/item[1]/size")?.Value ?? "0") }; Application.Current.Dispatcher.Invoke(() => NotificationManager.AddNotification(string.Format(LocalizationHelper.Get("Update.NewRelease.Verbose"), Global.UpdateModel.Version), StatusType.Update, "update", UpdateAction)); } } } catch (Exception ex) { LogWriter.Log(ex, "Check for update task"); } #endif GC.Collect(); }
protected override void LoadComplete() { base.LoadComplete(); AddRange(new Drawable[] { new VolumeControlReceptor { RelativeSizeAxes = Axes.Both, ActionRequested = delegate(InputState state) { volume.Adjust(state); } }, mainContent = new Container { RelativeSizeAxes = Axes.Both, }, volume = new VolumeControl(), overlayContent = new Container { RelativeSizeAxes = Axes.Both }, new OnScreenDisplay(), new GlobalHotkeys //exists because UserInputManager is at a level below us. { Handler = globalHotkeyPressed } }); LoadComponentAsync(screenStack = new Loader(), d => { screenStack.ModePushed += screenAdded; screenStack.Exited += screenRemoved; mainContent.Add(screenStack); }); //overlay elements LoadComponentAsync(direct = new DirectOverlay { Depth = -1 }, mainContent.Add); LoadComponentAsync(social = new SocialOverlay { Depth = -1 }, mainContent.Add); LoadComponentAsync(chat = new ChatOverlay { Depth = -1 }, mainContent.Add); LoadComponentAsync(settings = new SettingsOverlay { Depth = -1 }, overlayContent.Add); LoadComponentAsync(musicController = new MusicController { Depth = -2, Position = new Vector2(0, Toolbar.HEIGHT), Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, overlayContent.Add); LoadComponentAsync(notificationManager = new NotificationManager { Depth = -2, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, overlayContent.Add); LoadComponentAsync(dialogOverlay = new DialogOverlay { Depth = -4, }, overlayContent.Add); Logger.NewEntry += entry => { if (entry.Level < LogLevel.Important) { return; } notificationManager.Post(new SimpleNotification { Text = $@"{entry.Level}: {entry.Message}" }); }; Dependencies.Cache(settings); Dependencies.Cache(social); Dependencies.Cache(chat); Dependencies.Cache(musicController); Dependencies.Cache(notificationManager); Dependencies.Cache(dialogOverlay); // ensure both overlays aren't presented at the same time chat.StateChanged += (container, state) => social.State = state == Visibility.Visible ? Visibility.Hidden : social.State; social.StateChanged += (container, state) => chat.State = state == Visibility.Visible ? Visibility.Hidden : chat.State; LoadComponentAsync(Toolbar = new Toolbar { Depth = -3, OnHome = delegate { intro?.ChildScreen?.MakeCurrent(); }, }, overlayContent.Add); settings.StateChanged += delegate { switch (settings.State) { case Visibility.Hidden: intro.MoveToX(0, SettingsOverlay.TRANSITION_LENGTH, EasingTypes.OutQuint); break; case Visibility.Visible: intro.MoveToX(SettingsOverlay.SIDEBAR_WIDTH / 2, SettingsOverlay.TRANSITION_LENGTH, EasingTypes.OutQuint); break; } }; Cursor.State = Visibility.Hidden; }
// Use this for initialization void Start() { NotificationManager.SendWithAppIcon(System.TimeSpan.FromSeconds(0), "Welcome to the game", "test notification", Color.red); }
public MainWindowViewModel(IManagedNotificationManager notificationManager) { _notificationManager = notificationManager; ShowCustomManagedNotificationCommand = MiniCommand.Create(() => { NotificationManager.Show(new NotificationViewModel(NotificationManager) { Title = "Hey There!", Message = "Did you know that Avalonia now supports Custom In-Window Notifications?" }); }); ShowManagedNotificationCommand = MiniCommand.Create(() => { NotificationManager.Show(new Avalonia.Controls.Notifications.Notification("Welcome", "Avalonia now supports Notifications.", NotificationType.Information)); }); ShowNativeNotificationCommand = MiniCommand.Create(() => { NotificationManager.Show(new Avalonia.Controls.Notifications.Notification("Error", "Native Notifications are not quite ready. Coming soon.", NotificationType.Error)); }); AboutCommand = MiniCommand.CreateFromTask(async() => { var dialog = new AboutAvaloniaDialog(); if ((App.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow is { } mainWindow) { await dialog.ShowDialog(mainWindow); } }); ExitCommand = MiniCommand.Create(() => { (App.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown(); }); ToggleMenuItemCheckedCommand = MiniCommand.Create(() => { IsMenuItemChecked = !IsMenuItemChecked; }); WindowState = WindowState.Normal; WindowStates = new WindowState[] { WindowState.Minimized, WindowState.Normal, WindowState.Maximized, WindowState.FullScreen, }; this.WhenAnyValue(x => x.SystemTitleBarEnabled, x => x.PreferSystemChromeEnabled) .Subscribe(x => { var hints = ExtendClientAreaChromeHints.NoChrome | ExtendClientAreaChromeHints.OSXThickTitleBar; if (x.Item1) { hints |= ExtendClientAreaChromeHints.SystemChrome; } if (x.Item2) { hints |= ExtendClientAreaChromeHints.PreferSystemChrome; } ChromeHints = hints; }); SystemTitleBarEnabled = true; TitleBarHeight = -1; }
public FleetController(ApplicationDbContext context) { _context = context; NotificationManager = new NotificationManager(); }
public void TestHandleRegistrationRequestAfterBuildNotification() { UserCache userCache = null; NotificationManager notificationManager = null; try { // Setup userCache = new UserCache(); notificationManager = new NotificationManager(0, 0, userCache, false); string username = "******"; string[] recipients = { username }; BuildServerNotificationType notificationType = BuildServerNotificationType.BuildBuilding; string projectId = "project1"; string buildConfigId = "buildconfig1"; IBuildServerNotification buildServerNotification = new BuildNotification(notificationType, projectId, buildConfigId, recipients); string buildKey = Utils.CreateBuildKey(buildServerNotification); // Check that the user doesn't exist prior to the notification try { userCache.GetUser(username); Assert.Fail(); } catch (KeyNotFoundException) { // Expected } // This will create a user in the cache, but without a hostname notificationManager.HandleCommand(buildServerNotification, EventArgs.Empty); User user = userCache.GetUser(username); Assert.That(user.Username, Is.EqualTo(username)); Assert.That(user.ActiveBuilds.Contains(buildKey)); Assert.That(string.IsNullOrEmpty(user.Hostname)); // Now we create a registration request, which should update the existing user with a hostname string hostname = username + "-ws"; IRequest registrationRequest = new RegistrationRequest(hostname, username); notificationManager.HandleCommand(registrationRequest, EventArgs.Empty); user = userCache.GetUser(username); Assert.That(user.Username, Is.EqualTo(username)); Assert.That(user.Hostname, Is.EqualTo(hostname)); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
public void CreateNotification(string sub, string titel, string message, int progress) { try { var mBuilder = new NotificationCompat.Builder(mContext); ////Create intent for action 1(TAKE) //var actionIntent1 = new Intent(); //actionIntent1.SetAction(action_sjklf) //var pIntent1 = PendingIntent.GetBroadcast(mContext, 0, actionIntent1, PendingIntentFlags.CancelCurrent); //// var intsas = PendingIntent.GetActivity(mContext, 0, actionIntent1, 0); if (Countdown.TimerTick == true) { mBuilder//.AddAction(Resource.Mipmap.icon, "Stop", pIntent1) .SetContentText(message) .SetProgress(1000, progress, false); } else if (Countdown.TimerTick == false) { //mBuilder.AddAction(Resource.Mipmap.icon, "Start", pIntent1); } mBuilder.SetAutoCancel(true) .SetContentTitle(titel) .SetSubText(sub) .SetChannelId(NOTIFICATION_CHANNAL_ID) .SetPriority((int)NotificationPriority.Low) .SetVisibility((int)NotificationVisibility.Public) .SetSmallIcon(Resource.Mipmap.icon); //// Add intent filters for each action and register them on a broadcast receiver //var intentFilter = new IntentFilter(); //intentFilter.AddAction("Start"); //intentFilter.AddAction("Stop"); //var customReceiver = new CustomActionReceiver(); //mContext.RegisterReceiver(customReceiver, intentFilter); //// NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager; if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O) { NotificationImportance importance = global::Android.App.NotificationImportance.Default; NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNAL_ID, titel, importance); notificationChannel.SetShowBadge(true); if (notificationManager != null) { mBuilder.SetChannelId(NOTIFICATION_CHANNAL_ID); notificationManager.CreateNotificationChannel(notificationChannel); } } notificationManager.Notify(0, mBuilder.Build()); } catch (Exception ex) { // } }
public void TestHandleUpdate() { NotificationManager notificationManager = null; UserCache userCache = null; try { // Setup the basics object syncRoot = new object(); int serverPort = 30001; int clientPort = 30002; userCache = new UserCache(); notificationManager = new NotificationManager(serverPort, clientPort, userCache, false); string buildKey1 = "buildkey1"; string buildKey2 = "buildkey2"; string username = "******"; string hostname = "localhost"; // Create a user that has one build building and is responsible for one other build User user = new User(username) { Hostname = hostname }; user.ActiveBuilds.Add(buildKey1); user.BuildsResponsibleFor.Add(buildKey2); // A dummy client which the notification manager will notify Listener listener = new Listener(IPAddress.Any, clientPort); Dictionary<RequestType, IRequest> requests = new Dictionary<RequestType, IRequest>(); listener.OnCommandReceived += (sender, args) => { requests.Add(((IRequest)sender).Type, (IRequest)sender); lock (syncRoot) { Monitor.Pulse(syncRoot); } }; listener.Start(); Assert.That(listener.Running, Is.True); // Raise an update for this user and wait until all events caused have been raised lock (syncRoot) { notificationManager.HandleUpdate(user, EventArgs.Empty); ////Monitor.Wait(syncRoot, 5000); Monitor.Wait(syncRoot, 5000); } listener.Stop(); Assert.That(listener.Running, Is.False); // Test Assert.That(requests.ContainsKey(RequestType.BuildActive)); BuildActiveRequest buildActiveRequest = (BuildActiveRequest)requests[RequestType.BuildActive]; Assert.That(buildActiveRequest.IsBuildsActive, Is.True); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
public ContentsController(IOptions <PostgresqlConfig> dbOptions, IOptions <Config> config, NotificationManager notifier) : base(config) { mNotifier = notifier; }
void CreateNotification(string title, string message, int notifyId, string tag, Bundle extras) { System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - PushNotification - Message {title} : {message}"); NotificationCompat.Builder builder = null; Context context = Android.App.Application.Context; if (CrossPushNotification.SoundUri == null) { CrossPushNotification.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); } try { if (CrossPushNotification.IconResource == 0) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; } else { string name = context.Resources.GetResourceName(CrossPushNotification.IconResource); if (name == null) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; } } } catch (Android.Content.Res.Resources.NotFoundException ex) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; System.Diagnostics.Debug.WriteLine(ex.ToString()); } Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName); //Intent resultIntent = new Intent(context, typeof(T)); if (extras != null) { resultIntent.PutExtras(extras); } // Create a PendingIntent; we're only using one PendingIntent (ID = 0): const int pendingIntentId = 0; var currentMillis = (long)DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); resultPendingIntent.SetAction($"{currentMillis}"); // Build the notification builder = new NotificationCompat.Builder(context) .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it .SetContentIntent(resultPendingIntent) // start up this activity when the user clicks the intent. .SetContentTitle(title) // Set the title .SetSound(CrossPushNotification.SoundUri) .SetSmallIcon(CrossPushNotification.IconResource) // This is the icon to display .SetContentText(message); // the message to display. if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean) { // Using BigText notification style to support long message var style = new NotificationCompat.BigTextStyle(); style.BigText(message); builder.SetStyle(style); } NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(tag, notifyId, builder.Build()); }
/// <summary> /// Goes through all the mapsets in the queue and imports them. /// </summary> public static void ImportMapsetsInQueue() { Map selectedMap = null; if (MapManager.Selected.Value != null) { selectedMap = MapManager.Selected.Value; } for (var i = 0; i < Queue.Count; i++) { var file = Queue[i]; var time = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Milliseconds; var extractDirectory = $@"{ConfigManager.SongDirectory}/{Path.GetFileNameWithoutExtension(file)} - {time}/"; try { ImportingMapset?.Invoke(typeof(MapsetImporter), new ImportingMapsetEventArgs(Queue, Path.GetFileName(file), i)); if (file.EndsWith(".qp")) { ExtractQuaverMapset(file, extractDirectory); File.Delete(file); } else if (file.EndsWith(".osz")) { Osu.ConvertOsz(file, extractDirectory); File.Delete(file); } else if (file.EndsWith(".sm")) { Stepmania.ConvertFile(file, extractDirectory); } selectedMap = InsertAndUpdateSelectedMap(extractDirectory); Logger.Important($"Successfully imported {file}", LogType.Runtime); } catch (Exception e) { Logger.Error(e, LogType.Runtime); NotificationManager.Show(NotificationLevel.Error, $"Failed to import file: {Path.GetFileName(file)}"); } } MapDatabaseCache.OrderAndSetMapsets(); var mapset = MapManager.Mapsets.Find(x => x.Maps.Any(y => y.Md5Checksum == selectedMap?.Md5Checksum)); if (mapset == null) { mapset = MapManager.Mapsets.First(); MapManager.Selected.Value = mapset.Maps.First(); } else { MapManager.Selected.Value = mapset.Maps.Find(x => x.Md5Checksum == selectedMap?.Md5Checksum); } Queue.Clear(); }
public void TestHandleCommandForPriorityAttentionRequest() { UserCache userCache = null; NotificationManager notificationManager = null; try { // Setup the notification manager object syncRoot = new object(); int serverPort = 20000; int clientPort = 20001; // If the timer's expiry (trigger) period is too fast, the test will fail in step 2. // We set this (hopefully) sufficiently slow so that we can properly test the // sequence of events. int priorityTimerPeriod = 10000; // Any user's attention required will immediately be set as a priority. TimeSpan priorityPeriod = TimeSpan.Zero; // Note: The cache's timer starts upon construction userCache = new UserCache(priorityTimerPeriod, priorityPeriod); notificationManager = new NotificationManager(serverPort, clientPort, userCache, false); // A dummy client which the notification manager will notify Listener listener = new Listener(IPAddress.Any, clientPort); // We only want the attention requests AttentionRequest attentionRequest = null; listener.OnCommandReceived += (sender, args) => { if (sender.GetType() == typeof(AttentionRequest)) { attentionRequest = (AttentionRequest)sender; } lock (syncRoot) { Monitor.Pulse(syncRoot); } }; // Create the requests and notifications string username = "******"; string hostname = "localhost"; string projectId = "project1"; string buildConfigId = "buildConfig1"; string state = BuildServerResponsibilityState.Taken; RegistrationRequest registrationRequest = new RegistrationRequest(hostname, username); ResponsibilityNotification responsibilityNotification = new ResponsibilityNotification(BuildServerNotificationType.BuildResponsibilityAssigned, projectId, buildConfigId, username, state); // Start the server and the client notificationManager.Start(); Assert.That(notificationManager.Running, Is.True); listener.Start(); Assert.That(listener.Running, Is.True); // STEP 1 // Register the dummy client with the server lock (syncRoot) { // This will cause one attention request and one build active request Utils.SendCommand(hostname, serverPort, Parser.Encode(registrationRequest)); Monitor.Wait(syncRoot); } Assert.That(attentionRequest, Is.Not.Null); Assert.That(attentionRequest.IsAttentionRequired, Is.False); Assert.That(attentionRequest.IsPriority, Is.False); // STEP 2 attentionRequest = null; lock (syncRoot) { // This will cause another attention request and another build active request notificationManager.HandleCommand(responsibilityNotification, EventArgs.Empty); Monitor.Wait(syncRoot); } Assert.That(attentionRequest, Is.Not.Null); Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True); Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.False); // STEP 3 // The next two pulses (again for an attention and a build active request) must // be because of the timer that expired attentionRequest = null; lock (syncRoot) { Monitor.Wait(syncRoot); } // Shut down notificationManager.Stop(); Assert.That(notificationManager.Running, Is.False); listener.Stop(); Assert.That(listener.Running, Is.False); // Test Assert.That(attentionRequest, Is.Not.Null); Assert.That(attentionRequest != null && attentionRequest.IsAttentionRequired, Is.True); Assert.That(attentionRequest != null && attentionRequest.IsPriority, Is.True); } finally { if (notificationManager != null) { notificationManager.Dispose(); } if (userCache != null) { userCache.Dispose(); } } }
private void load(NotificationManager notification, OsuColour colours, TextureStore textures, OsuGameBase game) { notificationManager = notification; AutoSizeAxes = Axes.Both; Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; Alpha = 0; Children = new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Children = new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(5), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Children = new Drawable[] { new OsuSpriteText { Font = @"Exo2.0-Bold", Text = game.Name }, new OsuSpriteText { Colour = game.IsDebug ? colours.Red : Color4.White, Text = game.Version }, } }, new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, TextSize = 12, Colour = colours.Yellow, Font = @"Venera", Text = @"Development Build" }, new Sprite { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Texture = textures.Get(@"Menu/dev-build-footer"), }, } } }; if (game.IsDeployedBuild) { checkForUpdateAsync(); } }