//------------------------------------------------------------------------- // CLASS METHOD DEFINITIONS //------------------------------------------------------------------------- void Awake() { // position the again button AgainButton.SetScale(0.25f); ExitButton.SetScale(0.25f); float off = 50; Vector2 pos = new Vector2(); pos.x = Screen.width/2.0f - (AgainButton.GetWidth() + ExitButton.GetWidth() + 50)/2.0f; pos.y = 40.0f; AgainButton.SetPosition(pos); // position the exit button pos.x = Screen.width/2.0f + (ExitButton.GetWidth())/2.0f; pos.y = 40.0f; ExitButton.SetPosition(pos); // set the fading parameters for the beginning fade in of the game // over screen fader_ = new Fader(0.0f, 3.0f, 3.0f); fader_.FadeIn(); // set the initial update state to fade in update_ = fadeIn; }
public static DrawHandler DrawHandler(Control c, UpdateHandler updateHandler) { string mode = GetSmallModeName(); string type = "littleRunner.Drawing." + mode + ".DrawHandler_" + mode; return (DrawHandler)getInstance(type, c, updateHandler); }
public SqlPersistenceProviderFactory(string connectionString, bool serializeAsText, TimeSpan lockTimeout) { this.ConnectionString = connectionString; this.LockTimeout = lockTimeout; this.SerializeAsText = serializeAsText; this.loadHandler = new LoadHandler(this); this.createHandler = new CreateHandler(this); this.updateHandler = new UpdateHandler(this); this.unlockHandler = new UnlockHandler(this); this.deleteHandler = new DeleteHandler(this); }
public static void add(IGameControlProxy obj) { AwakeProxy += new AwakeHandler(obj.awake); StartProxy += new StartHandler(obj.start); FixUpdateProxy += new FixUpdateHandler(obj.fixedupdate); UpdateProxy += new UpdateHandler(obj.update); LateUpdateProxy += new LateUpdateHandler(obj.lateupdate); OnGUIProxy += new OnGUIHandler(obj.onGUI); changedTurnStateProxy += new changedTurnStateHandler(obj.changedTurnState); changedGameStateProxy += new changedGameStateHandler(obj.changedGameState); changedFieldModeProxy += new changedFiledModeHandler(obj.changedFieldMode); }
//------------------------------------------------------------------------- private void fadeIn() { fader_.Update(Time.deltaTime); //BackgroundImage.SetAlpha(fader_.GetAlpha()); AgainButton.SetAlpha(fader_.GetAlpha()); ExitButton.SetAlpha(fader_.GetAlpha()); // if everything was faded in set update state to do nothing if (fader_.GetAlpha() == 1.0f) { update_ = doNothing; } }
/// <summary>Make all vector renderers invisible everywhere in the kOS module.</summary> static public void ClearAll(UpdateHandler handler) { // Take a copy of the list because the items will be deleted from the update handler // as SetShow() gets called, and .NET won't let you iterate over the collection // directly while you do that: List <VectorRenderer> allOfMe = new List <VectorRenderer>(); foreach (VectorRenderer item in handler.GetAllUpdatersOfType(typeof(VectorRenderer))) { allOfMe.Add(item); } // Now actually turn them all off: foreach (VectorRenderer vecRend in allOfMe) { vecRend.SetShow(false); } }
private void frmMain_Shown(object sender, EventArgs e) { // Position // TODO: Subtract Vista/Win7 Taskbar height.. //Location = new Point(Location.X, Location.Y + (ClientSize.Height / 2)); mRegistry = new RegHelper(); if (mRegistry.Initialize() == false) { MessageBox.Show("Failed to access the registry!\nPlease check your user access.", "Patch error", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } if (mRegistry.FirstRun) { // First start, reset patches mRegistry.PatchReset(0); } UpdateStatus("Loading server status.."); Application.DoEvents(); CheckStatus(); Application.DoEvents(); if (mRegistry.SearchPatcherUpdates()) { mRegistry.SetLastPatcherUpdate(); UpdateStatus("Searching for patcher updates.."); UpdateHandler uHandler = new UpdateHandler(); var asm = System.Reflection.Assembly.GetExecutingAssembly(); if (uHandler.CheckVersion(asm, URL_PATCHER_UPDATE) == true && uHandler.StartUpdate() == true) { UpdateStatus("Patcher update found. Start download.."); Close(); return; } } btnGameStart.Enabled = false; mPatches = new ClientPatchList(); mPatches.OnPatchProgressComplete += ProgressPatches; mPatches.Download(URL_PATCHER_PATCHES + "Patches.xml"); }
static void Main(string[] args) { var request = new RequestUpdate() { DefaultExtrationZip = true, LinkDownloadNewApp = "http://api.yellrek.com.br/resources/data/search.zip", PathToExtract = @"C:\Users\jonatas.campos\Desktop\searchSmiles", ComandLinesToExecutAfterUpdate = new List <string>() { @"start C:\Users\jonatas.campos\Desktop\searchSmiles\SmilesAutoSearch.exe" } }; var update = new UpdateHandler(request); var json = JsonConvert.SerializeObject(request, Formatting.Indented); update.StartUpdate(); Console.ReadKey(); }
static LandscapeHoleSystem() { LandscapeHoleSystem._Landscape_Holes_Count = Shader.PropertyToID("_Landscape_Holes_Count"); LandscapeHoleSystem._Landscape_Holes_List = Shader.PropertyToID("_Landscape_Holes_List"); LandscapeHoleSystem.landscapeHoles = new Matrix4x4[LandscapeHoleSystem.MAX_LANDSCAPE_HOLES]; LandscapeHoleSystem.holeVisibilityGroup = new VolumeVisibilityGroup("landscape_hole_volumes", new TranslationReference("#SDG::Devkit.Visibility.Landscape_Hole_Volumes"), true); LandscapeHoleSystem.holeVisibilityGroup.color = new Color32(71, 44, 20, byte.MaxValue); LandscapeHoleSystem.holeVisibilityGroup = VisibilityManager.registerVisibilityGroup <VolumeVisibilityGroup>(LandscapeHoleSystem.holeVisibilityGroup); if (LandscapeHoleSystem.< > f__mg$cache0 == null) { LandscapeHoleSystem.< > f__mg$cache0 = new UpdateHandler(LandscapeHoleSystem.handleUpdated); } TimeUtility.updated += LandscapeHoleSystem.< > f__mg$cache0; if (LandscapeHoleSystem.< > f__mg$cache1 == null) { LandscapeHoleSystem.< > f__mg$cache1 = new GLRenderHandler(LandscapeHoleSystem.handleGLRender); } GLRenderer.render += LandscapeHoleSystem.< > f__mg$cache1; }
public StatLabel(string name, UpdateHandler onUpdate) { _layout = Layout.makeHorizontal(); Label nameLabel = new Label(name); nameLabel.area.widthExpandable = true; nameLabel.font.alignment = Alignment.UpperLeft; nameLabel.font.normal = Color.white; nameLabel.font.style = FontStyle.Bold; _layout.views.add(nameLabel); _valueLabel = new Label(); _valueLabel.area.width = 150; _layout.views.add(_valueLabel); _updateHandler = onUpdate; }
//------------------------------------------------------------------------- // CLASS METHOD DEFINITIONS //------------------------------------------------------------------------- void Awake() { manager = GetComponent <InteractableManager>(); manager.Register(this); updateHandler_ = sceneIntro; // play the cell door sound CellDoorSoundSound.Play(); // play background music but set volume to 0. // also set the fader for the bgm BackgroundMusic.Play(); BackgroundMusic.Loop(true); BackgroundMusic.SetVolume(0.0f); bgmFader_ = new Fader(0.0f, 30.0f, 0.0f); // introBgFader_ = new Fader(1.0f, 0.0f, 5.0f); }
public AutoUpdate(TimeSpan interval, UpdateHandler updater, bool runNow = true) { Updater = updater; Timer = new DispatcherTimer(); Timer.Tick += Timer_Tick; if (interval == null) { Timer.Interval = new TimeSpan(0, 0, 1); } else { Timer.Interval = interval; } Timer.Start(); if (runNow) { Updater(this); } }
public TabSettingsGeneral(UpdateHandler updates) { InitializeComponent(); this.updates = updates; this.updates.CheckFinished += updates_CheckFinished; Disposed += (sender, args) => this.updates.CheckFinished -= updates_CheckFinished; comboBoxTrayType.Items.Add("Disabled"); comboBoxTrayType.Items.Add("Display Icon Only"); comboBoxTrayType.Items.Add("Minimize to Tray"); comboBoxTrayType.Items.Add("Close to Tray"); comboBoxTrayType.Items.Add("Combined"); comboBoxTrayType.SelectedIndex = Math.Min(Math.Max((int)Config.TrayBehavior, 0), comboBoxTrayType.Items.Count - 1); checkExpandLinks.Checked = Config.ExpandLinksOnHover; checkSpellCheck.Checked = Config.EnableSpellCheck; checkTrayHighlight.Checked = Config.EnableTrayHighlight; checkUpdateNotifications.Checked = Config.EnableUpdateCheck; }
public override void OnUpdate() { KeyCodeHooks(); if (Game.instance is null) { return; } if (PopupScreen.instance != null && afterTitleScreen) { UpdateHandler.AnnounceUpdates(modsNeedingUpdates, this.GetModDirectory()); } if (InGame.instance is null) { return; } NotificationMgr.CheckForNotifications(); }
private static IUpdateHandler Subscribe(ICollection <IUpdateHandler> handlers, Action callback, int timeout = 0, bool isEnabled = true) { var handler = handlers.FirstOrDefault(h => h.Callback == callback); if (handler == null) { if (timeout > 0) { handler = new UpdateHandler(callback, new TimeoutHandler(timeout), isEnabled); } else { handler = new UpdateHandler(callback, InvokeHandler.Default, isEnabled); } Log.Debug($"Create {handler}"); handlers.Add(handler); } return(handler); }
public bool Invalidate(IState invalidState) { if (base.Invalidate()) { RemoveInfluences(invalidState); var referenceToNotify = Interlocked.Exchange(ref callbackReference, invalidReference); if ((referenceToNotify != null) && referenceToNotify.TryGetTarget(out var objectToNotify)) { Debug.Assert(referenceToNotify != invalidReference, ""); UpdateHandler.RequestUpdate(objectToNotify.Notify); } return(true); } else { return(false); } }
private void Form1_Load(object sender, EventArgs e) { UpdateHandler updateHandler = new UpdateHandler(); if (updateHandler.CheckForUpdate()) { } EventManager eventManager = new EventManager(); StartupHandler startupHandler = new StartupHandler(); startupHandler.Startup(); dataTable.Columns.Add("naam", typeof(string)); dataTable.Columns.Add("referentie nummer", typeof(string)); dataTable.Columns.Add("aantal", typeof(string)); dataTable.Columns.Add("eenheidprijs", typeof(string)); dataTable.Columns.Add("prijs", typeof(double)); eventManager.Setup(); CheckForProfile(); }
public async void UpdateHandler_Should_Work(string id, string description, bool expected) { // Given IMediator mediator = ServiceProvider.GetService <IMediator>(); MockEventPublisher publisher = new MockEventPublisher(mediator); MockSampleRepository repository = new MockSampleRepository( new Dictionary <string, Domain.Sample.Sample> { { "1", new Domain.Sample.Sample("1", "1") } }); Mock <IUnitOfWork> uow = new Mock <IUnitOfWork>(); MockSampleAdapter adapter = new MockSampleAdapter(); Mock <ILogger <UpdateRequest> > logger = new Mock <ILogger <UpdateRequest> >(); UpdateHandler handler = new UpdateHandler(publisher, repository, uow.Object, adapter, logger.Object); UpdateRequest command = new UpdateRequest(id, description); // When Result result = await handler.Handle(command, new CancellationToken()); // Then List <ValidationResult> notValidNotifications = result.Notifications.Where(notification => !notification.IsValid).ToList(); if (expected) { Assert.Empty(notValidNotifications); Assert.True(ContainsType(publisher.Notifications, typeof(DomainEvent <UpdateRequest>))); } else { Assert.NotEmpty(notValidNotifications); Assert.False(ContainsType(publisher.Notifications, typeof(DomainEvent <UpdateRequest>))); } }
private void mBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, mVersionFile.ApplicationName + ".exe"); StatusRtb.Text += "Update complete!\n"; if (File.Exists(fileName) == false) { MessageBox.Show("Unable to find the Path!\n" + fileName, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } // finished, start App and close System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(fileName); if (System.Environment.OSVersion.Version.Major >= 6) { info.Verb = "runas"; // Win7 } System.Diagnostics.Process.Start(info); UpdateHandler.CleanUp(); Close(); }
public override void OnApplicationStart() { MelonLogger.Msg("Mod has finished loading"); MelonLogger.Msg("Checking for updates..."); var updateDir = this.GetModDirectory() + "\\UpdateInfo"; Directory.CreateDirectory(updateDir); UpdateHandler.SaveModUpdateInfo(updateDir); var allUpdateInfo = UpdateHandler.LoadAllUpdateInfo(updateDir); UpdateHandler.CheckForUpdates(allUpdateInfo, modsNeedingUpdates); string settingsDir = this.GetModSettingsDir(createIfNotExists: true); ModSettingsHandler.InitializeModSettings(settingsDir); ModSettingsHandler.LoadModSettings(settingsDir); Schedule_GameModel_Loaded(); Harmony.PatchPostfix(typeof(SettingsScreen), nameof(SettingsScreen.OnShow), typeof(MelonMain), nameof(MelonMain.SettingsPatch)); }
public int AddTask( Action preUpdate, UpdateHandler asyncUpdate, Action postUpdate, Func <bool> useAsync, Func <bool> active ) { int id = taskList.Count; taskList.Add(new Task() { id = id, preUpdate = preUpdate, asyncUpdate = asyncUpdate, postUpdate = postUpdate, useAsync = useAsync, active = active }); return(id); }
public FormSettings(FormBrowser browser, PluginManager plugins, UpdateHandler updates, AnalyticsManager analytics, Type startTab) { InitializeComponent(); Text = Program.BrandName + " Options"; this.browser = browser; this.browser.PauseNotification(); this.plugins = plugins; this.buttonHeight = BrowserUtils.Scale(39, this.GetDPIScale()) | 1; AddButton("General", () => new TabSettingsGeneral(this.browser, updates)); AddButton("System Tray", () => new TabSettingsTray()); AddButton("Notifications", () => new TabSettingsNotifications(new FormNotificationExample(this.browser, this.plugins))); AddButton("Sounds", () => new TabSettingsSounds()); AddButton("Feedback", () => new TabSettingsFeedback(analytics, AnalyticsReportGenerator.ExternalInfo.From(this.browser), this.plugins)); AddButton("Advanced", () => new TabSettingsAdvanced(this.browser.ReinjectCustomCSS)); SelectTab(tabs[startTab ?? typeof(TabSettingsGeneral)]); }
public MyBox(System.Windows.Forms.Panel box, string name) : base() { this.name = name; this.box = box; pushDetector = new PushDetector(); swipeDetector = new SwipeDetector(); steadyDetector = new SteadyDetector(); flowRouter = new FlowRouter(); broadcaster = new Broadcaster(); broadcaster.AddListener(pushDetector); broadcaster.AddListener(flowRouter); pushDetector.Push += new PushDetector.PushHandler(pushDetector_Push); steadyDetector.Steady += new SteadyDetector.SteadyHandler(steadyDetector_Steady); swipeDetector.GeneralSwipe += new SwipeDetector.GeneralSwipeHandler(swipeDetector_GeneralSwipe); PrimaryPointCreate += new PrimaryPointCreateHandler(MyBox_PrimaryPointCreate); PrimaryPointDestroy += new PrimaryPointDestroyHandler(MyBox_PrimaryPointDestroy); OnUpdate += new UpdateHandler(MyBox_OnUpdate); }
/// <summary> /// Checks for program update and notifies the user if found /// </summary> private async void CheckForUpdate() { string result = await updater.GetUpdateUrl(); if (result.StartsWith("https")) { MessageBoxResult mBoxResult = MessageBox.Show( UPDATE_AVAILABLE_TEXT, UPDATE_AVAILABLE_CAPTION, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (mBoxResult == MessageBoxResult.Yes) { UpdateHandler updater = new UpdateHandler(); bool isOkToLaunch = await updater.DownloadUpdate(result); if (isOkToLaunch) { updater.RunUpdate(); } } } }
public void LogicUpdate() { //Logo.Translate(new RenderLocation(1, 0)); //Logo.Location = new RenderLocation(Console.WindowWidth / 2 - 30, 5); if (KeyboardHandler.GetKeyPress(ConsoleKey.F)) { //player1.HighlightCard(player1.CardsInHand[0]); player1.GoThroughHand(); UpdateHandler.Redraw(); } if (KeyboardHandler.GetKeyPress(ConsoleKey.G)) { player1.UnhighlightCard(player1.HighlightedCard); UpdateHandler.Redraw(); } if (KeyboardHandler.GetKeyPress(ConsoleKey.Spacebar)) { UpdateHandler.Redraw(); } }
public TabSettingsGeneral(FormBrowser browser, UpdateHandler updates) { InitializeComponent(); this.browser = browser; this.updates = updates; this.updates.CheckFinished += updates_CheckFinished; Disposed += (sender, args) => this.updates.CheckFinished -= updates_CheckFinished; toolTip.SetToolTip(trackBarZoom, toolTip.GetToolTip(labelZoomValue)); trackBarZoom.SetValueSafe(Config.ZoomLevel); labelZoomValue.Text = trackBarZoom.Value + "%"; checkExpandLinks.Checked = Config.ExpandLinksOnHover; checkSwitchAccountSelectors.Checked = Config.SwitchAccountSelectors; checkOpenSearchInFirstColumn.Checked = Config.OpenSearchInFirstColumn; checkBestImageQuality.Checked = Config.BestImageQuality; checkAnimatedAvatars.Checked = Config.EnableAnimatedImages; checkSpellCheck.Checked = Config.EnableSpellCheck; checkUpdateNotifications.Checked = Config.EnableUpdateCheck; }
private async Task CheckForUpdates() { DownloadButton.Enabled = false; DownloadButton.Text = "Checking for updates..."; var result = await UpdateHandler.CheckForUpdates(); switch (result.Item1) { case true: if (result.Item2 != null) { LatestVersionValueLabel.Text = $"{result.Item2.ToString().Replace(",", ".")}"; LatestVersionValueLabel.Image = Properties.Resources.exclamation; LatestVersionValueLabel.ImageAlign = ContentAlignment.MiddleRight; DownloadButton.Enabled = true; DownloadButton.Text = "Download && Install"; } else { LatestVersionValueLabel.Text = CurrentVersionValueLabel.Text; LatestVersionValueLabel.Image = Properties.Resources.success; LatestVersionValueLabel.ImageAlign = ContentAlignment.MiddleRight; DownloadButton.Text = "No update available"; } break; case false: DownloadButton.Text = "Checking for updates failed"; LatestVersionValueLabel.Image = Properties.Resources.error; LatestVersionValueLabel.ImageAlign = ContentAlignment.MiddleRight; break; default: break; } }
//------------------------------------------------------------------------- private void sceneIntro() { // update intro bg fader and fade the bg accordingly; UGLY introBgFader_.Update(Time.deltaTime); IntroBackground.renderer.material.color = new Color(0.0f, 0.0f, 0.0f, introBgFader_.GetAlpha()); // if the time is greater then 8.0 sec start playing the intro // dialog if (time_ > 8.0f && !hasIntroDialogStarted_) { hasIntroDialogStarted_ = true; Color yellow = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text1 = "You awaken with a start as the guard slams the cold iron bars shut."; string text2 = " He regards you with a look of pity and disgust."; DialogField.Display(text1, yellow, 0.0f, 5.0f); DialogField.Display(text2, yellow, 5.5f, 8.5f); // fade in bgm bgmFader_.FadeIn(); } // fade in the actaul scene (fade out intro background) if (time_ > 14.0f) { introBgFader_.FadeOut(); } // after 17 sec switch to guard dialog state if (time_ > 20.0f) { IntroBackground.SetActive(false); updateHandler_ = guardDialog; } }
public RemoteMinesEvadable(Ability9 ability, IPathfinder pathfinder, IMainMenu menu) : base(ability, pathfinder, menu) { this.techiesRemotesHandler = UpdateManager.CreateIngameUpdate(0, false, this.TechiesRemotesOnUpdate); EntityManager9.UnitAdded += this.OnUnitAdded; EntityManager9.UnitRemoved += this.OnUnitRemoved; this.Blinks.UnionWith(Abilities.Blink); this.Counters.Add(Abilities.PhaseShift); this.Counters.Add(Abilities.SleightOfFist); this.Counters.Add(Abilities.Snowball); this.Counters.UnionWith(Abilities.Invulnerability); this.Counters.Add(Abilities.TricksOfTheTrade); this.Counters.Add(Abilities.Supernova); this.Counters.UnionWith(Abilities.MagicImmunity); this.Counters.Add(Abilities.Mischief); this.Counters.Add(Abilities.MantaStyle); this.Counters.Add(Abilities.AttributeShift); this.Counters.UnionWith(Abilities.Shield); this.Counters.UnionWith(Abilities.StrongMagicShield); this.Counters.UnionWith(Abilities.Suicide); this.Counters.Remove(Abilities.SpikedCarapace); }
private void Main_Loaded(object sender, RoutedEventArgs e) { blinkTimer.Tick += Console_Timer_Tick; blinkTimer.Interval = new TimeSpan(0, 0, 0, 0, 250); BTD6_CrashHandler handler = new BTD6_CrashHandler(); handler.EnableCrashLog(); UpdateHandler update = new UpdateHandler() { GitApiReleasesURL = "https://api.github.com/repos/TDToolbox/BTD6-Mod-Manager/releases", ProjectExePath = Environment.CurrentDirectory + "\\BTD6 Mod Manager.exe", InstallDirectory = Environment.CurrentDirectory, ProjectName = "BTD6 Mod Manager", UpdatedZipName = "BTD6_Mod_Manager.zip", UpdaterExeName = "Updater.exe" }; Thread updater = new Thread(() => update.HandleUpdates()); updater.IsBackground = true; BgThread.AddToQueue(updater); }
/// <summary> /// De register a specific call notification for collection /// </summary> /// <param name="collectionName"></param> /// <param name="handler"></param> public void DeRegisterNotification(string collectionName, UpdateHandler handler) { if (_delegates.ContainsKey(collectionName)) { //Make a copy so we can update the main list var handlers = new List <UpdateHandler>(_delegates[collectionName]); foreach (UpdateHandler lphandler in handlers) { if (lphandler == handler) { _delegates[collectionName].Remove(lphandler); } } //If we don't have any remaining for this collection, remove the collection from the dictionary if (_delegates[collectionName].Count == 0) { _delegates.Remove(collectionName); } } if (handler != null) { _delegates[collectionName].Add(handler); } }
//------------------------------------------------------------------------- public void Notify(int selected, int clicked) { // HANDLE HINTS. if (clicked == 4 && !lockAlreadyClicked_ && selected != 1) { // if lock was clicked first time ... lockAlreadyClicked_ = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "The keyhole of this lock is unusual in that it seems to aim both ways, inside and out."; DialogField.Display(text0, ye, 0.0f, 5.0f); } if (clicked == 6 && !guardAlreadyClicked_) { // if guard was clicked first time ... guardAlreadyClicked_ = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "The soldier appears to be in his mid-20's but despite his youth, you sense he is a competent soldier."; DialogField.Display(text0, ye, 0.0f, 5.0f); } if (clicked == 0 && !stoneAlreadyClicked_) { // if stone was clicked first time ... stoneAlreadyClicked_ = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "You happen upon a stone that has conveniently sharp points."; DialogField.Display(text0, ye, 0.0f, 5.0f); } if (clicked == 3 && !chocoladeAlreadyClicked_) { chocoladeAlreadyClicked_ = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "The guards have confiscated all of your gear except for this piece of chocolate."; DialogField.Display(text0, ye, 0.0f, 5.0f); } if (clicked == 7 && !ratHoleAlreadyClicked_) { ratHoleAlreadyClicked_ = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "A small mouse hole is at the bottom of the Western wall."; DialogField.Display(text0, ye, 0.0f, 5.0f); } // pick up rat bones if (clicked == 1 && !ratBonesAlreadyClicked) { ratBonesAlreadyClicked = true; Color ye = new Color(1.0f, 1.0f, 0.0f, 1.0f); string text0 = "You recall from your training that you can utilize the bones of small creatures to pick locks."; DialogField.Display(text0, ye, 0.0f, 3.5f); } // put chocolate on the ground if (selected == 3 && clicked == 5) { manager.SetIsInventory(3, false); manager.SetPosition(3, new Vector2(-2.2f, - 2.2f)); manager.SetIsActive(5, false); RatAnimation.Play(0.5f, 0); RatMove.MoveTo(new Vector2(-3.5f, - 2.0f), 4.0f); isRatKillable = true; } // kills the rat if (selected == 0 && clicked == 2 && isRatKillable == true) { RatSound.Play(); manager.SetIsActive(2, false); manager.SetIsActive(1, true); manager.SetIsInventory(1, false); manager.SetPosition (1, new Vector2(-3.5f, - 2.0f)); manager.Unselect(); } // opens the door if (selected == 1 && clicked == 4) { Vector2 posGuard = manager.GetPosition(6); if (posGuard.x < 5.5f && posGuard.x > -1.0f) { manager.Unselect(); RatAnimation.Stop(); Patrolling.isPatrolling = false; GuardAnimation.Stop(); updateHandler_ = gotCaught; timeEnd_ = time_ + 7.0f; return; } manager.Unselect(); timeEnd_ = time_ + 2.0f; updateHandler_ = quit; manager.Enable(false); Patrolling.isPatrolling = false; } }
//------------------------------------------------------------------------- private void guardPatrolling() { Vector2 posGuard = manager.GetPosition(6); // choose right animation for the guard if (Patrolling.IsGoingLeft()) { GuardAnimation.Play(1.0f, 1); } else { GuardAnimation.Play(1.0f, 0); } // if the guard is visible if (posGuard.x < 5.5f && posGuard.x > -1.0f) { // and chocolate is not in the inventory if ((!manager.IsInInventory(3) && manager.IsActive(3)) || (!manager.IsInInventory(1) && manager.IsActive(1))) { RatAnimation.Stop(); Patrolling.isPatrolling = false; GuardAnimation.Stop(); updateHandler_ = gotCaught; timeEnd_ = time_ + 7.0f; } } // stop the rat animations when it arrived at its destination if (isRatKillable && !RatMove.IsMoving()) { RatAnimation.Stop(); } }
public DrawHandler_GDI(Control c, UpdateHandler updateHandler) : base(c, updateHandler) { this.c.Paint += new PaintEventHandler(c_Paint); }
public static async Task <int> RunBot(string?botToken, CancellationToken cancellationToken = default) { var(botConfig, loadBotConfigErrMsg) = await BotConfig.LoadBotConfigAsync(cancellationToken); if (loadBotConfigErrMsg is not null) { Console.WriteLine(loadBotConfigErrMsg); return(1); } // Priority: commandline option > environment variable > config file if (string.IsNullOrEmpty(botToken)) { botToken = Environment.GetEnvironmentVariable("TELEGRAM_BOT_TOKEN"); } if (string.IsNullOrEmpty(botToken)) { botToken = botConfig.BotToken; } if (string.IsNullOrEmpty(botToken)) { Console.WriteLine("Please provide a bot token with command line option `--bot-token`, environment variable `TELEGRAM_BOT_TOKEN`, or in the config file."); return(-1); } try { var bot = new TelegramBotClient(botToken); Console.WriteLine("Created Telegram bot instance with API token."); var me = await bot.GetMeAsync(cancellationToken); if (string.IsNullOrEmpty(me.Username)) { throw new Exception("Error: bot username is null or empty."); } await bot.SetMyCommandsAsync(UpdateHandler.BotCommandsPublic, null, null, cancellationToken); Console.WriteLine($"Registered {UpdateHandler.BotCommandsPublic.Length} bot commands for all chats."); var privateChatCommands = UpdateHandler.BotCommandsPrivate.Concat(UpdateHandler.BotCommandsPublic); await bot.SetMyCommandsAsync(privateChatCommands, BotCommandScope.AllPrivateChats(), null, cancellationToken); Console.WriteLine($"Registered {privateChatCommands.Count()} bot commands for private chats."); Console.WriteLine($"Started Telegram bot: @{me.Username} ({me.Id})."); var updateHandler = new UpdateHandler(me.Username, botConfig); var updateReceiver = new QueuedUpdateReceiver(bot, null, UpdateHandler.HandleErrorAsync); await updateHandler.HandleUpdateStreamAsync(bot, updateReceiver, cancellationToken); } catch (ArgumentException ex) { Console.WriteLine($"Invalid access token: {ex.Message}"); } catch (HttpRequestException ex) { Console.WriteLine($"A network error occurred: {ex.Message}"); } catch (Exception ex) { Console.WriteLine(ex); } return(0); }
/// <summary>Executes a function when the state of this action (with the specified inputSource) is updated.</summary> /// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param> /// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param> public void AddOnUpdateListener(UpdateHandler functionToCall, SteamVR_Input_Sources inputSource) { sourceMap[inputSource].onUpdate += functionToCall; }
//public static List<IGameControlProxy> addlist = new List<IGameControlProxy>(8); //public static List<IGameControlProxy> list = new List<IGameControlProxy>(8); void Awake() { AwakeProxy += new AwakeHandler(Dummy); StartProxy += new StartHandler(Dummy); FixUpdateProxy += new FixUpdateHandler(Dummy); UpdateProxy += new UpdateHandler(Dummy); LateUpdateProxy += new LateUpdateHandler(Dummy); OnGUIProxy += new OnGUIHandler(Dummy); changedTurnStateProxy += new changedTurnStateHandler(Dummy); changedGameStateProxy += new changedGameStateHandler(Dummy); changedFieldModeProxy += new changedFiledModeHandler(Dummy); if (gameController==null) gameController = new GameController(); AwakeProxy(); //GameController.gameStateChange(GameController.GameState.PRELOAD); GameObject.DontDestroyOnLoad(this); Instance = this; }
/// <summary> /// This will get called each time an event is added /// </summary> /// <param name="target"></param> public static void AddEventHandler(UpdateHandler target) { UpdateLogEvent += target; }
/// <summary> /// This should be called to correctly remove your event /// </summary> /// <param name="target"></param> public static void RemoveEventHandler(UpdateHandler target) { UpdateLogEvent -= target; }
private void FrmMain_Load(object sender, EventArgs e) { this.transLeftA.Left = this.transAreaA.Width - this.transLeftA.Width; this.transLeftA.Visible = true; this.transRightA.Left = 0; this.transRightA.Visible = false; this.transLeftB.Left = this.transAreaB.Width - this.transLeftB.Width; this.transLeftB.Visible = true; this.transRightB.Left = 0; this.transRightB.Visible = false; this.toolStripStatusLabelUser.Text = "Operator: " + global::PMSInterface.Program._username; frmWorkstation = FrmWorkStation.getFrmWorkstation(); frmWorkstation.Visible = false; frmCommLog = FrmCommunicationLog.getCommunicationLog(); frmCommLog.MdiParent = this; frmCommLog.Left = 10; frmCommLog.Top = this.Height - frmCommLog.Height - 130; frmCommLog.Visible = true; UpdateEvent += new UpdateHandler(frmWorkstation.add); LogEvent += new LogHandler(frmCommLog.safeAdd); Safe safe = new Safe(); Registe = safe.GetDateTimeFromDecrypt(true); StartListen(); string specName; InstructMap = MyXml.GetInstructMap(out specName); if (InstructMap == null) return; }
public DrawHandler(Control c, UpdateHandler updateHandler) { this.c = c; this.updateHandler = updateHandler; }
public SqlPersistenceProviderFactory(NameValueCollection parameters) { if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); } this.connectionString = null; this.LockTimeout = TimeSpan.Zero; this.SerializeAsText = false; foreach (string key in parameters.Keys) { switch (key) { case connectionStringNameParameter: ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[parameters[key]]; if (settings == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( SR2.GetString(SR2.ConnectionStringNameIncorrect, parameters[key])); } this.connectionString = settings.ConnectionString; break; case serializeAsTextParameter: this.SerializeAsText = bool.Parse(parameters[key]); break; case lockTimeoutParameter: this.LockTimeout = TimeSpan.Parse(parameters[key], CultureInfo.InvariantCulture); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( key, SR2.GetString(SR2.UnknownSqlPersistenceConfigurationParameter, key, connectionStringNameParameter, serializeAsTextParameter, lockTimeoutParameter)); } } if (this.connectionString == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( SR2.GetString(SR2.ConnectionStringNameParameterRequired, connectionStringNameParameter)); } this.loadHandler = new LoadHandler(this); this.createHandler = new CreateHandler(this); this.updateHandler = new UpdateHandler(this); this.unlockHandler = new UnlockHandler(this); this.deleteHandler = new DeleteHandler(this); }
/// <summary>Stops executing the function setup by the corresponding AddListener</summary> /// <param name="functionToStopCalling">The local function that you've setup to receive update events</param> /// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param> public void RemoveOnUpdateListener(UpdateHandler functionToStopCalling, SteamVR_Input_Sources inputSource) { sourceMap[inputSource].onUpdate -= functionToStopCalling; }
//------------------------------------------------------------------------- // CLASS METHOD DEFINITIONS //------------------------------------------------------------------------- void Awake() { manager = GetComponent<InteractableManager>(); manager.Register(this); updateHandler_ = sceneIntro; // play the cell door sound CellDoorSoundSound.Play(); // play background music but set volume to 0. // also set the fader for the bgm BackgroundMusic.Play(); BackgroundMusic.Loop(true); BackgroundMusic.SetVolume(0.0f); bgmFader_ = new Fader(0.0f, 30.0f, 0.0f); // introBgFader_ = new Fader(1.0f, 0.0f, 5.0f); }
public static void TeamWinChart(string input, Update u) { //first we need to get the start date / timespan, otherwise default. var start = new DateTime(2016, 5, 15); var mode = ""; if (!string.IsNullOrWhiteSpace(input)) { var args = input.Split(' '); if (int.TryParse(args[0], out var amount) && args.Length >= 2) { //get the interval switch (args[1]) { case "weeks": case "week": start = DateTime.UtcNow.AddDays(-(amount * 7)); break; case "day": case "days": start = DateTime.UtcNow.AddDays(-amount); break; case "hour": case "hours": start = DateTime.UtcNow.AddHours(-amount); break; default: Bot.Api.SendTextMessageAsync(u.Message.Chat.Id, "Acceptable intervals are: hour(s), day(s), week(s)"); break; } } switch (args.Length) { case 3: mode = $"AND gm.MODE = '{args[2]}'"; break; case 1: mode = $"AND gm.MODE = '{args[0]}'"; break; } } var query = $@"SELECT x.Players, Round((COUNT (x.GameId) * 100.0 / sum (count(x.GameId)) OVER (PARTITION BY Players)), 2) AS Wins, sum(count(x.Gameid)) over (partition by players) as Games , X.Winner AS Team FROM (SELECT count (gp.PlayerId) AS Players, gp.GameId, CASE WHEN gm.Winner = 'Wolves' THEN 'Wolf' ELSE gm.Winner END AS Winner FROM Game AS gm INNER JOIN GamePlayer AS gp ON gp.GameId = gm.Id WHERE gm.Winner is not null AND gm.TimeStarted > '{start:yyyy-MM-dd HH:mm:ss}' {mode} GROUP BY gp.GameId, gm.Winner HAVING COUNT (gp.PlayerId)> = 5) AS x GROUP BY x.Winner, x.Players ORDER BY x.Players, Wins DESC"; List <TeamWinResult> result; using (var db = new WWContext()) { result = db.Database.SqlQuery <TeamWinResult>(query).ToListAsync().Result; } //we have our results, now chart it... //build a datatable var dataSet = new DataSet(); var dt = new DataTable(); dt.Columns.Add("Players", typeof(int)); dt.Columns.Add("Wins", typeof(int)); dt.Columns.Add("Games", typeof(int)); dt.Columns.Add("Team", typeof(string)); foreach (var r in result) { var row = dt.NewRow(); row[0] = r.Players; row[1] = (int)r.Wins; row[2] = r.Games; row[3] = r.Team; dt.Rows.Add(row); } dataSet.Tables.Add(dt); //now build the chart var chart = new Chart { Width = 1000, Height = 400 }; //chart.DataSource = dataSet.Tables[0]; var legend = new Legend(); //create serie... foreach (var team in new[] { "Wolf", "Village", "Tanner", "Cult", "SerialKiller", "Lovers" }) { var serie1 = new Series { LegendText = team, Name = team }; //serie1.Label = team; switch (team) { case "Wolf": serie1.Color = Color.SaddleBrown; break; case "Village": serie1.Color = Color.Green; break; case "Tanner": serie1.Color = Color.Red; break; case "Cult": serie1.Color = Color.Blue; break; case "SerialKiller": serie1.Color = Color.Black; break; case "Lovers": serie1.Color = Color.Pink; break; } serie1.MarkerBorderWidth = 2; serie1.BorderColor = Color.FromArgb(164, 164, 164); serie1.ChartType = SeriesChartType.StackedBar100; serie1.BorderDashStyle = ChartDashStyle.Solid; serie1.BorderWidth = 1; serie1.IsValueShownAsLabel = false; serie1.XValueMember = "Players"; serie1.YValueMembers = "Wins"; serie1.Font = new Font("Tahoma", 8.0f); serie1.BackSecondaryColor = Color.FromArgb(0, 102, 153); serie1.LabelForeColor = Color.FromArgb(100, 100, 100); //add our values var pl = 4; foreach (var r in result.Where(x => x.Team == team).OrderBy(x => x.Players)) { pl++; if (r.Players != pl) { while (pl < r.Players) { serie1.Points.AddXY(pl, 0); pl++; } } serie1.Points.AddXY(r.Players, r.Wins); } //make sure we filled all the points... var top = (int)(serie1.Points.OrderByDescending(x => x.XValue).FirstOrDefault()?.XValue ?? 4); if (top < 35) { top++; while (top <= 35) { serie1.Points.AddXY(top, 0); top++; } } //legend.CustomItems.Add(serie1.Color, team); chart.Series.Add(serie1); } //create chartareas... var ca = new ChartArea(); ca.Name = "ChartArea1"; ca.BackColor = Color.White; ca.BorderColor = Color.FromArgb(26, 59, 105); ca.BorderWidth = 0; ca.BorderDashStyle = ChartDashStyle.Solid; ca.AxisX = new Axis(); ca.AxisY = new Axis(); chart.ChartAreas.Add(ca); chart.Legends.Add(legend); //databind... //chart.DataBind(); //save result var path = Path.Combine(Bot.RootDirectory, "myChart.png"); chart.SaveImage(path, ChartImageFormat.Png); SendImage(path, u.Message.Chat.Id); UpdateHandler.Send( result.Select(x => new { x.Players, x.Games }).Distinct() .Aggregate("", (a, b) => $"{a}\n{b.Players}: {b.Games}"), u.Message.Chat.Id); }
//------------------------------------------------------------------------- private void guardDialog() { // THIS FUNCTION HANDLES THE BEGINNING OF THE SCENE WHERE THE GUARD // IS TALKING TO THE PLAYER // while talking the guard is not patrolling Patrolling.isPatrolling = false; // the guard says the following ... string text = "Don't move from that spot."; string text2 = "If you do, you will regret it. I promise you that."; if (!guardTextStarted_) { manager.Enable(false); BackgroundMusic.SetVolume(0.5f); guardTextStarted_ = true; Color red = new Color(1.0f, 0.0f, 0.0f, 1.0f); DialogField.Display(text, red, 0.0f, 2.0f); DialogField.Display(text2, red, 2.5f, 4.5f); } // switch to patrolling state if (time_ >= 24.7f) { GuardAnimation.Play(1.0f, 0); manager.Enable(true); BackgroundMusic.SetVolume(0.5f); Patrolling.isPatrolling = true; updateHandler_ = guardPatrolling; } }