static void Main(string[] args) { // Null-conditional operator. string name = null; var nameLength = name?.Length; List<string> names = null; nameLength = names?[0].Length; var notifier = new Notifier(); notifier.ChangeState(); notifier.StateChanged += (sender, e) => WriteLine("StateChanged notification received..."); notifier.ChangeState(); // await in catch/finally blocks. notifier.ChangeStateAsync().Wait(); // Auto-property initializers + expression-bodied members + string interpolation. var snapshot = new Snapshot(); WriteLine(snapshot); WriteLine($"{snapshot.UserName} created on {snapshot.Timestamp} with name length of {name?.Length ?? 0}"); // nameof expressions. WriteLine(nameof(args)); WriteLine(nameof(notifier)); WriteLine(nameof(Main)); WriteLine(nameof(Program)); ReadLine(); }
public void SendsAllNotificationsTheFirstTime() { DeleteDataFile(); var expectedResults = new List<MailMessage>(); foreach (var m in messagesToSend) { expectedResults.Add(StandardMailMessage(m, m.Substring(0, m.IndexOf(" ")))); } using (ShimsContext.Create()) { var notificationMails = new List<MailMessage>(); ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); foreach (var m in messagesToSend) { n.SendNotification(notificationName, m, m.Substring(0, m.IndexOf(" "))); } } CollectionAssert.AreEqual(expectedResults, notificationMails, new Comparers.MailMessageComparer(), "Notification emails sent do not match the expected result."); } }
/////////////////////////////////////////////////////////////////////////////// public void Warning( Notifier notifier, string fmt, params object [] args ) { // ****** var ei = null == notifier.ExecutionInfo ? new ExecutionInfo() : notifier.ExecutionInfo; string fileName = ei.FileName; Console.WriteLine( "{0} ({1},0): warning: {2}", fileName, ei.Line, string.Format(fmt, args) ); }
/////////////////////////////////////////////////////////////////////////////// public void Error( Notifier notifier, string msg, params object [] args ) { // ****** task.Errors = true; var ei = null == notifier.ExecutionInfo ? new ExecutionInfo() : notifier.ExecutionInfo; task.Log.LogError( string.Empty, ei.DistressLevel.ToString(), string.Empty, ei.FileName, ei.Line, ei.Column, ei.Line, ei.Column, msg, args ); }
/// <summary> /// Get the appointmentId from the row that was clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void AppointmentsGridView_RowCommand(object sender, GridViewCommandEventArgs e) { LinqDataManipulator apps = new LinqDataManipulator(); Notifier textDoctor; try { GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); int RowIndex = gvr.RowIndex; appointmentId = Convert.ToInt32(gvr.Cells[1].Text); apps.UpdateAppointments(appointmentId); // Text the Doctor about the upcoming appointment doctorText = apps.CreateText(appointmentId); textDoctor = new Notifier(doctorText); Page_Load(sender, e); } catch (Exception) { throw; } }
/////////////////////////////////////////////////////////////////////////////// public void Error( Notifier notifier, string fmt, params object [] args ) { // ****** var ei = null == notifier.ExecutionInfo ? new ExecutionInfo() : notifier.ExecutionInfo; // ****** string fileName = ei.FileName; if( noPathInWarnError ) { fileName = Path.GetFileName( fileName ); } Console.WriteLine( ei.FullMessage ); Console.WriteLine(); Console.WriteLine( "{0} ({1},0): error: {2}", fileName, ei.Line, Helpers.SafeStringFormat( fmt, args ) ); // ****** if( Debugger.IsAttached ) { Debugger.Break(); } //else { // Environment.Exit( 1 ); //} //Die(string.Empty); //throw new ErrorHandledException(); throw new ExitException(1); }
public static void NotifyTheTarget(Notifier n) { INotified inf = notifiedTargetList[n.target]; if (inf != null) { inf.notified(n); } }
/** * A dedicated function to create the game object and tile component from it's parts. * Note: There isn't a way to externally create components. * @param x refers to the grid location * @param y refers to the grid location * @param tileTemplate refers to the template who is the base for the given tile */ public GameObject addTile(int x, int y, componentTile tileTemplate, Notifier notify) { GameObject tileObject = componentTile.generateObject(TILE_OBJECT_NAME + " (" + x + "," + y + ")", tileTemplate, notify); addMapObject(x, y, tileObject); return tileObject; }
public void Detach(Shop shop) { shops.Remove(shop); if (priceNotifier == null) return; priceNotifier -= new Notifier(shop.Update); }
public static GameObject generateObject(string objectName, string spriteName, TypeTerrain tTerrain = null, componentMapObject parent = null, Dictionary<string, List<NotifyBehaviorMapObject>> notifyBehaviors = null, Notifier notify = null) { GameObject playerObject = new GameObject(objectName); attachNewComponent(playerObject, spriteName, tTerrain, parent, notifyBehaviors, notify); return playerObject; }
///////////////////////////////////////////////////////////////////////////// public static void MacroWarning( Notifier notifier, string fmt, params object [] args ) { if( null != Notifications ) { Notifications.MacroWarning( notifier, fmt, args ); } else { throw new Exception( Helpers.SafeStringFormat(fmt, args) ); } }
public static GameObject generateObject(string objectName, string spriteName = null, TypeTerrain tTerrain = null, componentMapObject parent = null, Dictionary<string, List<NotifyBehaviorMapObject>> notifyBehaviors = null, Notifier notify = null) { GameObject tileObject = new GameObject(objectName); componentMapObject cTile = tileObject.AddComponent<componentTile>(); initializeComponent(cTile, spriteName, tTerrain, parent, notifyBehaviors, notify); return tileObject; }
public NotifierForm(Notifier belongModule) : base() { InitializeComponent(); Visible = false; Opacity = 0; ShowInTaskbar = false; WindowState = FormWindowState.Minimized; BelongModule = belongModule; }
/////////////////////////////////////////////////////////////////////////////// public void Error( Notifier notifier, string fmt, params object [] args ) { // ****** var ei = null == notifier.ExecutionInfo ? new ExecutionInfo() : notifier.ExecutionInfo; string errStr = Helpers.SafeStringFormat( "{0} ({1},0): error: {2}", ei.FileName, ei.Line, string.Format(fmt, args) ); if( null != notifier.ExceptionToThrow ) { throw notifier.ExceptionToThrow; } throw new DieException( errStr ); }
internal int Generation; // Used to distinguish older idle handlers from recently-created ones. public IdleHandler(Notifier notifier) { _notifier = notifier; _isCancelled = false; lock (_notifier) { _notifier.IdleList.Add(this); Generation = _notifier.IdleGeneration; if (Thread.CurrentThread != _notifier.PrimaryThread) Monitor.PulseAll(_notifier); } }
public void Run() { if (this.Checker.HasNews()) { Notifier notifier = new Notifier(); notifier.Message = this.Message; notifier.UrlToSend = this.UrlToSend; notifier.IsPlaySound = this.Options.IsNotificationSoundActivate; notifier.Notificater = this.Notificater; notifier.Show(); } }
public void CallingNotifyWillInvokeMethod() { var target = new TestEvent1(); var notifier = new Notifier(); notifier.EnlistTarget(target); Assert.Equal(0, target.Counter); notifier.Notify(target, "Orchard.Tests.Events.TestEvent1_Add_value", new Dictionary<string, object> { { "value", 1 } }); Assert.Equal(1, target.Counter); }
private Notifier CreateNotifierWithTypedSubscriptions() { _notificationResult = ""; Notifier notifier = new Notifier(); notifier.Subscribe(delegate(Notification<string> notification) { _notificationResult += notification.Payload + "A"; }); notifier.Subscribe("x", delegate(Notification<string> notification) { _notificationResult += notification.Payload + "B"; }); notifier.Subscribe("x|y", delegate(Notification<string> notification) { _notificationResult += notification.Payload + "C"; }); notifier.Subscribe("y|z", delegate(Notification<string> notification) { _notificationResult += notification.Payload + "D"; }); notifier.Subscribe(delegate(Notification<int> notification) { _notificationResult += "E"; }); return notifier; }
/////////////////////////////////////////////////////////////////////////////// public void Error( Notifier notifier, string fmt, params object [] args ) { // ****** var ei = null == notifier.ExecutionInfo ? new ExecutionInfo() : notifier.ExecutionInfo; string fileName = ei.FileName; Console.WriteLine( ei.FullMessage ); Console.WriteLine(); Console.WriteLine( "{0} ({1},0): error: {2}", fileName, ei.Line, Helpers.SafeStringFormat( fmt, args ) ); // ****** //throw new ExitException(1); Environment.Exit( 1 ); }
public void notified(Notifier n) { switch (n.command) { case "device_connected": this.sensorConnectionState.Text = "已连接"; this.连接指纹仪CToolStripMenuItem.Enabled = false; this.断开指纹仪DToolStripMenuItem.Enabled = true; break; case "device_connect_error": this.sensorConnectionState.Text = (string)n.para; break; } }
public void TestSingle() { int count = 0; Action mockDelegate = () => { count++; }; using (Notifier nt = new Notifier(mockDelegate)) { nt.StartSingle(0.25); Thread.Sleep(500); } Assert.AreEqual(1, count); }
public void TestPassive() { Notifier notifier = new Notifier(); ISubscription<int> subscription = notifier.Subscribe<int>(null); notifier.Post(null,1); notifier.Post(null,"x"); var notifications = subscription.GetNotifications().ToList(); Assert.AreEqual(1,notifications.Count); Assert.AreEqual(1,notifications[0].Payload); notifications = subscription.GetNotifications().ToList(); Assert.AreEqual(0, notifications.Count); }
private static void initializeComponent(componentMapObject cTile, string spriteName, TypeTerrain tTerrain = null, componentMapObject parent = null, Dictionary<string, List<NotifyBehaviorMapObject>> notifyBehaviors = null, Notifier notify = null) { cTile.setParent(parent); cTile.setSprite(spriteName); cTile.setTypeTerrain(tTerrain); cTile.setRenderSortingLayer(RENDER_SORTING_LAYER); cTile.init(); if(notifyBehaviors != null) { foreach(string key in notifyBehaviors.Keys) { foreach(NotifyBehaviorMapObject behavior in notifyBehaviors[key]) { cTile.addNotifyBehavior(key, new NotifyBehaviorMapObject(behavior)); } } } cTile.setNotifier(notify); }
public void InitializeDoesNotIncludeRouteGroupKeyInParametersList() { var actionContext = new ActionContext(); actionContext.RouteData = new RouteData(); actionContext.RouteData.Values.Add("controller", "account"); actionContext.RouteData.Values.Add("action", "login"); actionContext.RouteData.Values.Add(AttributeRouting.RouteGroupKey, "RouteGroupKey"); var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(new RequestTelemetry(), actionContext); var notifier = new Notifier(new ProxyNotifierMethodAdapter()); var initializer = new OperationNameTelemetryInitializer(contextAccessor, notifier); notifier.Notify(OperationNameTelemetryInitializer.BeforeActionNotificationName, new { httpContext = contextAccessor.HttpContext, routeData = actionContext.RouteData }); var telemetry = new EventTelemetry(); initializer.Initialize(telemetry); Assert.Equal("GET account/login", telemetry.Context.Operation.Name); }
public void TestSingleWithObject() { int count = 0; object obj = null; Action<object> mockDelegate = o => { count++; obj = o; }; using (Notifier nt = new Notifier(mockDelegate, this)) { nt.StartSingle(0.25); Thread.Sleep(500); } Assert.AreEqual(1, count); Assert.AreEqual(this, obj); }
public static GameObject generateObject(string objectName, componentTile tileTemplate, Notifier notify) { GameObject gameObject = generateObject(objectName, tileTemplate.getSpriteName(), tileTemplate.getTypeTerrain(), tileTemplate.getParent(), tileTemplate.getNotifyBehaviors(), notify); BoxCollider2D boxCollider = tileTemplate.gameObject.GetComponent<BoxCollider2D>(); if(boxCollider != null) { BoxCollider2D newBoxCollider = gameObject.AddComponent<BoxCollider2D>(); newBoxCollider.isTrigger = boxCollider.isTrigger; newBoxCollider.size = boxCollider.size; } CircleCollider2D circleCollider = tileTemplate.gameObject.GetComponent<CircleCollider2D>(); if(circleCollider != null) { CircleCollider2D newCircleCollider = gameObject.AddComponent<CircleCollider2D>(); newCircleCollider.isTrigger = circleCollider.isTrigger; newCircleCollider.radius = circleCollider.radius; } return gameObject; }
public static GameObject attachNewComponent(GameObject attachingTo, string spriteName, TypeTerrain tTerrain = null, componentMapObject parent = null, Dictionary<string, List<NotifyBehaviorMapObject>> notifyBehaviors = null, Notifier notify = null) { componentMapObject cMapObject = attachingTo.AddComponent<componentUnitMapObject>(); cMapObject.setParent(parent); cMapObject.setSprite(spriteName); cMapObject.setTypeTerrain(tTerrain); cMapObject.setRenderSortingLayer("gamePieces"); cMapObject.init(); if (notifyBehaviors != null) { foreach (string key in notifyBehaviors.Keys) { foreach (NotifyBehaviorMapObject behavior in notifyBehaviors[key]) { cMapObject.addNotifyBehavior(key, new NotifyBehaviorMapObject(behavior)); } } } cMapObject.setNotifier(notify); return attachingTo; }
public TimerHandler(Notifier n, int milliseconds) { int i; atTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000 + milliseconds; notifier = (Notifier)n; isCancelled = false; /* * Add the event to the queue in the correct position (ordered by * event firing time). * * NOTE: it's very important that if two timer handlers have the * same atTime, the newer timer handler always goes after the * older handler in the list. See comments in * Notifier.TimerEvent.processEvent() for details. */ lock (notifier) { generation = notifier.TimerGeneration; for (i = 0; i < notifier.TimerList.Count; i++) { TimerHandler q = (TimerHandler)notifier.TimerList[i]; if (atTime < q.atTime) { break; } } notifier.TimerList.Insert(i, this); if (System.Threading.Thread.CurrentThread != notifier.PrimaryThread) { System.Threading.Monitor.PulseAll(notifier); } } }
public static GameObject generateObject(string objectName, string spriteName, TypeTerrain tTerrain = null, componentMapObject parent = null, Dictionary<string, List<NotifyBehaviorMapObject>> notifyBehaviors = null, Notifier notify = null) { GameObject tileObject = new GameObject(objectName); componentMapObject cMapObject = tileObject.AddComponent<componentTestObject>(); cMapObject.setParent(parent); cMapObject.setSprite(spriteName); cMapObject.setTypeTerrain(tTerrain); cMapObject.setRenderSortingLayer("gameAbovePieces"); cMapObject.init(); if (notifyBehaviors != null) { foreach (string key in notifyBehaviors.Keys) { foreach (NotifyBehaviorMapObject behavior in notifyBehaviors[key]) { cMapObject.addNotifyBehavior(key, new NotifyBehaviorMapObject(behavior)); } } } cMapObject.setNotifier(notify); return tileObject; }
public virtual ActionResult Checkout(OrderEditModel model) { // validate form if (String.IsNullOrEmpty(model.ShippingAddress.Address1)) { ModelState.AddModelError("ShippingAddress.Address1", "Please include a valid street address."); } if (String.IsNullOrEmpty(model.ShippingAddress.City)) { ModelState.AddModelError("ShippingAddress.City", "Please specify your city."); } if (String.IsNullOrEmpty(model.ShippingAddress.State)) { ModelState.AddModelError("ShippingAddress.State", "Please specify your state."); } if (String.IsNullOrEmpty(model.ShippingAddress.PostalCode)) { ModelState.AddModelError("ShippingAddress.PostalCode", "Please specify your postal code."); } if (String.IsNullOrEmpty(model.ShippingPhone.Number)) { ModelState.AddModelError("ShippingPhone.Number", "Please include a phone number where we can reach you for any questions regarding this order."); } if (!ModelState.IsValid) { return(View(model)); } // update the shopping cart to get current pricing CurrentCart.Update(Catalog, Application.DefaultCatalog); // create order var ticks = DateTime.Now.Ticks.ToString(); var o = new Order { Document = new Document { Id = Document.For <Order>(string.Format( "{0}-{1}-{2}", CurrentUser.Login, DateTime.UtcNow.ToShortDateString(), ticks.Substring(ticks.Length - 4)).ToSlug()) }, User = CurrentUser.Document.Id, State = OrderStateMachine.Create(), ShippingName = model.ShippingName, ShippingAddress = model.ShippingAddress, ShippingPhone = model.ShippingPhone, Items = CurrentCart.Select(x => x.Value.ToOrderItem()).ToArray(), }; // pay for order try { var tx = Accounting.CreateOrderPayment(CurrentUser, o); o.Transaction = tx.Document.Id; } catch { throw; } CurrentUser.Cart = null; Orders.Save(o); UserRepository.Save(CurrentUser); Notifier.Notify( Severity.Success, "Thank you for your order!", "You should receive an email confirmation with your order number shortly, and you can always review your order in My Activity.", o); return(RedirectToAction(MVC.Site.Home.Index())); }
public MainViewModel() { _notifier = CreateNotifier(Corner.BottomRight, PositionProviderType.Screen, NotificationLifetimeType.Basic); //Application.Current.MainWindow.Closing += MainWindowOnClosing; }
private void Awake() { notifier = new Notifier(); }
private void Start() { // NOTIFIER notifier = new Notifier(); }
/// <summary> /// Создание уведомлений по настройкам /// </summary> /// <param name="opt"></param> public Notify(NotifyOptions opt) { notifier = CreateNotifier(opt); }
private void ClientConnected(string clientIP, int portNumber) { Notifier.AddMessage("Accepted connection from " + clientIP + " at port " + portNumber); }
public static void ShowError(this Notifier notifier, string message, MessageConfiguration configuration) { notifier.Notify(() => new ErrorMessage(message, configuration)); }
protected override async Task <WorkflowResult> PerformStep(string input, Subscriber subscriber, long chatId) { await Notifier.AccountInfo(subscriber); return(WorkflowResult.Finished); }
protected override async Task OnParametersSetAsync() { interceptor.RegisterEvent(); Notifier.Adicionar(nameof(DetalheProduto), Iniciar); await Iniciar(); }
public bool RunScheduleTask() { if (ScheduleTask.IsRunning) { Notifier.Information(GetProgressInfo()); return(true); } string scheduleTaskType = ScheduleTaskType; var task = AsyncRunner.Run(container => { try { var svc = container.Resolve <IScheduleTaskService>(); var scheduleTask = svc.GetTaskByType(scheduleTaskType); if (scheduleTask == null) { throw new Exception("Schedule task cannot be loaded"); } var job = new Job(scheduleTask); job.Enabled = true; job.Execute(container, false); } catch (Exception exc) { exc.Dump(); try { _scheduleTaskService.EnsureTaskIsNotRunning(scheduleTaskType); } catch (Exception) { } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(100); if (task.IsCompleted) { if (!task.IsFaulted) { Notifier.Success(GetResource("Admin.System.ScheduleTasks.RunNow.Completed")); } else { var exc = task.Exception.Flatten().InnerException; Notifier.Error(exc.Message); Logger.Error(exc.Message, exc); } } else { Notifier.Information(GetResource("Admin.System.ScheduleTasks.RunNow.Progress")); return(true); } return(false); }
public static void ShowError(this Notifier notifier, string message) { notifier.Notify(() => new ErrorMessage(message)); }
public override void Execute(ParserStateValues state, string trimmedLine) { if (!trimmedLine.StartsWith(".custom", StringComparison.InvariantCulture) && // .custom instance void ['DllExport']'...'.'DllExportAttribute'::.ctor(string) = ( 01 00 06 50 72 69 6E 74 31 00 00 ) // ...Print1.. !trimmedLine.StartsWith(".maxstack", StringComparison.InvariantCulture)) { state.AddLine = false; return; } state.State = ParserState.Method; ExportedClass exportedClass; if (!Exports.ClassesByName.TryGetValue(state.ClassNames.Peek(), out exportedClass)) { state.AddLine = false; return; } ExportedMethod exportMethod = getExportedMethod(state, exportedClass); string declaration = state.Method.Declaration; StringBuilder stringBuilder = new StringBuilder(250); stringBuilder.Append(".method ").Append(state.Method.Attributes.NullSafeTrim()).Append(" "); stringBuilder.Append(state.Method.Result.NullSafeTrim()); stringBuilder.Append(" modopt(['mscorlib']'").Append(AssemblyExports.ConventionTypeNames[exportMethod.CallingConvention]).Append("') "); if (!String.IsNullOrEmpty(state.Method.ResultAttributes)) { stringBuilder.Append(" ").Append(state.Method.ResultAttributes); } stringBuilder.Append(" '").Append(state.Method.Name).Append("'").Append(state.Method.After.NullSafeTrim()); bool flag = ValidateExportNameAndLogError(exportMethod, state); if (flag) { state.Method.Declaration = stringBuilder.ToString(); } if (state.MethodPos != 0) { state.Result.Insert(state.MethodPos, state.Method.Declaration); } if (flag) { Notifier.Notify(-2, DllExportLogginCodes.OldDeclaration, "\t" + Resources.OldDeclaration_0_, declaration); Notifier.Notify(-2, DllExportLogginCodes.NewDeclaration, "\t" + Resources.NewDeclaration_0_, state.Method.Declaration); state.Result.Add( String.Format( CultureInfo.InvariantCulture, " .export [{0}] as '{1}'", exportMethod.VTableOffset, exportMethod.ExportName ) ); Notifier.Notify(-1, DllExportLogginCodes.AddingVtEntry, "\t" + Resources.AddingVtEntry_0_export_1_, exportMethod.VTableOffset, exportMethod.ExportName); } }
private static void BootP2PQuake(bool localMode) { // ViewModel を取得したりイベントハンドラをくっつけたりする while (viewModel == null) { try { App.Current.Dispatcher.Invoke(() => { if (App.Current?.MainWindow?.DataContext != null) { var window = (MainWindow)App.Current?.MainWindow; viewModel = (RootViewModel)window?.DataContext; viewModel.SettingViewModel.LoadFromConfiguration(ConfigurationManager.Configuration); window.OnExit += Window_OnExit; window.OnUserquake += Window_OnUserquake; } }); } catch { // nothing to do } Thread.Sleep(1000); } ; client = new MediatorContext(); client.ConnectionsChanged += Client_ConnectionsChanged; client.StateChanged += Client_StateChanged; client.OnAreapeers += Client_OnAreapeers; client.OnEarthquake += Client_OnEarthquake; client.OnTsunami += Client_OnTsunami; client.OnEEWTest += Client_OnEEWTest; client.OnNewUserquakeEvaluation += Client_OnNewUserquakeEvaluation; client.OnUpdateUserquakeEvaluation += Client_OnUpdateUserquakeEvaluation; configuration.OnChangeEPSPConfiguration += (s, e) => { ReflectEPSPConfiguration(); }; ReflectEPSPConfiguration(); notifier = new Notifier(configuration, client); activator = new Notifications.Activator(configuration, client); player = new Player(configuration, client); if (localMode) { // 検証鍵をテスト用のものに差し替える var verifierType = Type.GetType("PKCSPeerCrypto.Verifier, PKCSPeerCrypto"); var serverProofKey = verifierType.GetField("ServerProofKey", BindingFlags.NonPublic | BindingFlags.Static); serverProofKey.SetValue(null, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDB+t0YTWlu3FFiwTb05u2bHWJRpCQJeAzhia6pWJ5BqsVIXgG7zeiHu4cFWrKME7fHQsjlihjnhtaksEtkmnbODUHnNi26FStSSpyo8ex0FZDfXtoQ9VB0m6UxdrGznpzfO9PWbpC0iSoCAyeqILLcDDbuBv5xY6+0D35kQx74kQIDAQAB"); client.Verification = false; // P2P 地震情報ネットワークに接続せず、 localhost:6910 に接続する var field = client.GetType().GetField("peerContext", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var peerContext = field.GetValue(client); var peerDataType = Type.GetType("Client.Common.General.PeerData, Client"); var peerData = System.Activator.CreateInstance(peerDataType, new object[] { "localhost", 6910, 10 }); var peerDatas = Array.CreateInstance(peerDataType, 1); peerDatas.SetValue(peerData, 0); var connectMethod = Type.GetType("Client.Peer.Context, Client").GetMethod("Connect"); connectMethod.Invoke(peerContext, new object[] { peerDatas }); return; } client.Connect(); ReadHistories(); }
protected override void ExecutePreviewCommand() { Notifier.PreviewInAppNotification(Strings.TestNotification, Top, CloseTime); }
// Use this for initialization void Awake() { notifier = new Notifier(); notifier.Subscribe(StateManager.ON_STATE_ENTER, HandleOnEnter); notifier.Subscribe(StateManager.ON_STATE_EXIT, HandleOnExit); }
private void ClientDisconnected(string clientIP, int portNumber) { Notifier.AddMessage("Disconnected from " + clientIP + " at port " + portNumber); }
protected virtual void HandleMenuSelection() { var args = new ZMMenuOptionEventArgs(_menuOptions[_selectedIndex]); Notifier.SendEventNotification(OnSelectOption, args); }
public static void ShowTimerNotification(this Notifier notifier, DateTime date) { notifier.Notify(() => new TimerNotificationModel(date)); }
public static void Fault(ErrorCode pCode, Notifier initiator) { string message = ""; MessageBoxButtons btns = MessageBoxButtons.OK; switch (pCode) { case ErrorCode.DatabaseError: message = "Hiba történt az adatbázissal!\nKérjük próbálkozzon újra később!"; btns = MessageBoxButtons.RetryCancel; break; case ErrorCode.InvalidCredentialsError: if (initiator is ModifyPasswordNotifier) { message = "A beírt jelszó hibás!\nKérjük írja be újra!"; } else { message = "A beírt felhasználónév, vagy jelszó hibás!\nKérjük ellenőrizze, hogy helyesen írta-e be őket!"; } break; case ErrorCode.InvalidSessionError: message = "Az ön munkamenete 30 perc tétlenség után lejárt!\nKérjük érvényesítse munkamenetét!"; break; case ErrorCode.ModifyConflict: message = "Úgy tűnik a módosítani kívánt adatok közül valamelyet már mások módosították. Kattintson az Igen gombra, ha felülírja saját módosításaival, a Nem gombra, hogyha frissíteni kívánja az adatokat!"; btns = MessageBoxButtons.YesNo; break; case ErrorCode.NonONyRError: message = "A rendszertől független hiba történt!\nKérjük próbálkozzon újra később!"; btns = MessageBoxButtons.RetryCancel; break; case ErrorCode.NoSessionError: message = "A következő művelethez be kell jelentkeznie!"; break; case ErrorCode.ReferenceError: message = "Az elemet, amelyet törölni kíván nem lehet letörölni, ugyanis hivatoznak rá. Kérjük, törlés előtt szüntesse meg a hivatkozást!"; break; case ErrorCode.ClientRuntimeError: case ErrorCode.UnknownError: message = "Ismeretlen hiba történt!\nKérjük próbálkozzon újra később!"; btns = MessageBoxButtons.RetryCancel; break; } DialogResult result = MessageBox.Show(message, "Hiba", btns); if (result == DialogResult.Retry || pCode == ErrorCode.ModifyConflict && result == DialogResult.Yes) { Notifier retryNotifier = initiator.getClone(); retryNotifier.isForced = true; retryNotifier.Handle(); } else if (result == DialogResult.No && pCode == ErrorCode.ModifyConflict) { ONyRClientApplication.RefreshData(); } else if (pCode == ErrorCode.NoSessionError) { ONyRClientApplication.ShowLoginForm(); } }
public Delegate(Notifier pInitiator, N pResponder) { mResponder = pResponder; Initiator = pInitiator; }
private IActionResult NotFound(Guid id) { Notifier.Warning($"未找到id:“{id}”的字典记录。"); return(RedirectToAction(nameof(List))); }
public void ChangePosition(Corner corner, PositionProviderType relation, NotificationLifetimeType lifetime) { _notifier = CreateNotifier(corner, relation, lifetime); }
public override async Task Init(ModuleInitInfo info, VariableValue[] restoreVariableValues, Notifier notifier, ModuleThread moduleThread) { this.moduleName = info.ModuleName; this.notifier = notifier; logger = LogManager.GetLogger(info.ModuleName); var config = info.GetConfigReader(); string cmd = ReplaceReleaseOrDebug(config.GetString("ExternalCommand")); string args = ReplaceReleaseOrDebug(config.GetString("ExternalArgs")); const string portPlaceHolder = "{PORT}"; if (!args.Contains(portPlaceHolder)) { throw new Exception("Missing port placeholder in args parameter: {PORT}"); } var server = TcpConnectorServer.ListenOnFreePort(); int port = server.Port; args = args.Replace(portPlaceHolder, port.ToString()); try { var taskConnect = server.WaitForConnect(TimeSpan.FromSeconds(60)); process = StartProcess(cmd, args); while (!process.HasExited && !taskConnect.IsCompleted) { await Task.Delay(TimeSpan.FromMilliseconds(50)); } if (process.HasExited) { throw new Exception($"Failed to start command \"{cmd}\" with arguments \"{args}\""); } connection = await taskConnect; var parentInfo = new ParentInfoMsg() { PID = Process.GetCurrentProcess().Id }; Task ignored = SendVoidRequest(parentInfo); var initMsg = new InitOrThrowMsg() { InitInfo = info, RestoreVariableValues = restoreVariableValues }; Task tInit = SendVoidRequest(initMsg); taskReceive = connection.ReceiveAndDistribute(onEvent); Task t = await Task.WhenAny(tInit, taskReceive); if (t != tInit) { if (process.HasExited) { throw new Exception("Module process terminated during Init call."); } else { throw new Exception("TCP connection broken to Module process during Init call."); } } await tInit; } catch (Exception) { if (connection != null) { connection.Close("Init failed."); } StopProcess(process); process = null; throw; } finally { server.StopListening(); } }
public NotificationsComponent(Notifier notifier, ActionCollection actions, IContentService contentService) { _notifier = notifier; _actions = actions; _contentService = contentService; }
public AudioService(Notifier notifier) { _notifier = notifier; }
public void OnStoreOpened(StoreModel openedStore) { Repository.Add(openedStore); Notifier.Notify(openedStore); }
public override async Task <IEnumerable <NetworkMessageDTO> > Insert(IEnumerable <NetworkMessageDTO> values) { var messages = await base.Insert(values); var originals = values.ToArray(); if (!originals.Any()) { return(messages); } var sendNotifications = new ConcurrentBag <Notification>(); //Now handle if there are targets or not. If not, then send to all. If there is, then send only to those. for (int j = 0; j < messages.Count(); j++) { var original = originals[j]; Notification notification = new Notification { Subject = original.Subject, Body = original.MessageText }; if (original.Targets == null || !original.Targets.Any()) { notification.Recipients = await(from u in DataContext.Users where u.Active == true && u.Deleted == false select new Recipient { Name = u.FirstName + " " + u.LastName, Email = u.Email, Phone = u.Phone, UserID = u.ID }).ToArrayAsync(); } else { notification.Recipients = await(from u in DataContext.Users where u.Active == true && u.Deleted == false && original.Targets.Contains(u.ID) || u.SecurityGroups.Any(sg => original.Targets.Contains(sg.SecurityGroupID)) select new Recipient { Name = u.FirstName + " " + u.LastName, Email = u.Email, Phone = u.Phone, UserID = u.ID }).ToArrayAsync(); foreach (var item in notification.Recipients) { NetworkMessageUser messageUser = new NetworkMessageUser(); messageUser.NetworkMessageID = original.ID.Value; messageUser.UserID = item.UserID.Value; DataContext.NetworkMessageUsers.Add(messageUser); } await DataContext.SaveChangesAsync(); } //This adds it the aggrigate notification to the list of notifications that will be sent. //Each of these notifications only have one recipient. sendNotifications.Add(notification); } //Create the notifier var notifier = new Notifier { HasPostscript = false, HasSalutation = true }; //Asynchronously send all of the notifications await Task.Run(() => notifier.Notify(sendNotifications.AsEnumerable())); return(messages); }
public static string detEncoding = string.Empty;// 自动检测到的文件类型 public void TransEncoding(string srcFullName, string dstFullName, string dstEncoding = "utf8", bool IsAutoDet = true, string srcEncoding = "gb2312") { Encoding Edst = Encoding.GetEncoding(dstEncoding); Encoding Esrc = Encoding.GetEncoding(srcEncoding); if (IsAutoDet) { #region 检测编码 nsDetector det = new nsDetector(); Notifier not = new Notifier(); det.Init(not); byte[] buf = new byte[1024]; int len; bool done = false; bool isAscii = true; FileStream fs = File.OpenRead(srcFullName); len = fs.Read(buf, 0, buf.Length); while (len > 0) { // Check if the stream is only ascii. if (isAscii) isAscii = det.isAscii(buf, len); // DoIt if non-ascii and not done yet. if (!isAscii && !done) done = det.DoIt(buf, len, false); len = fs.Read(buf, 0, buf.Length); } det.DataEnd(); fs.Close(); if (isAscii) { found = true; detEncoding = "ASCII"; } if (!found) { string[] prob = det.getProbableCharsets(); if (prob.Length > 0) { detEncoding = prob[0]; } else { detEncoding = srcEncoding; } } #endregion Esrc = Encoding.GetEncoding(detEncoding); } #region 编码转换 string strAll = File.ReadAllText(srcFullName, Esrc); File.WriteAllText(dstFullName, strAll, Edst); #endregion }
public static void GetData() { Flags.IsActiveGetData = true; Task.Run(() => { // Create a new instance of the WebSocket class. // // The WebSocket class inherits the System.IDisposable interface, so you can // use the using statement. And the WebSocket connection will be closed with // close status 1001 (going away) when the control leaves the using block. // // If you would like to connect to the server with the secure connection, // you should create a new instance with a wss scheme WebSocket URL. var adr = ""; switch (State.Target) { case State.TARGET.DEMO_01: adr = Constants.ATS_DEMO1; break; case State.TARGET.DEMO_02: adr = Constants.ATS_DEMO2; break; case State.TARGET.DEMO_03: adr = Constants.ATS_DEMO3; break; case State.TARGET.DEMO_04: adr = Constants.ATS_DEMO4; break; } using (var nf = new Notifier()) using (var ws = new WebSocketSharp.WebSocket(adr)) { ws.OnOpen += (sender, e) => ws.Send("Hi, there!"); ws.OnMessage += (sender, e) => { var nf_message = new NotificationMessage { Summary = "WS Mes", Body = !e.IsPing ? e.Data : "Received a ping.", Icon = "notification-message-im" }; //nf.Notify(nf_message); State.VmTestStatus.CommLog += "\n\n\r\n"; //Console.Write("\n\n"); // "> > > "の後の改行と空行 ReceivedMessage rx_mes = new ReceivedMessage(e.Data); State.VmTestStatus.CommLog += "---------- Serialization Before ----------\r\n"; //Console.WriteLine("---------- Serialization Before ----------"); State.VmTestStatus.CommLog += rx_mes.ToString() + "\r\n"; //Console.WriteLine(rx_mes.ToString()); State.VmTestStatus.CommLog += "---------- Serialization Before ----------\r\n"; //Console.WriteLine("---------- Serialization Before ----------"); State.VmTestStatus.CommLog += "\r\n"; //Console.WriteLine(""); var parsed_data = rx_mes.JsonParse(new JavaScriptSerializer()); State.VmTestStatus.CommLog += "---------- Serialization After ----------\r\n"; //Console.WriteLine("---------- Serialization After ----------"); if (parsed_data.type != "keepalive") { //Console.WriteLine(parsed_data..ToString()); State.VmTestStatus.CommLog += "BME280 温度:" + parsed_data.payload.channels[0].value + "\r\n"; State.VmTestStatus.CommLog += "BME280 湿度:" + parsed_data.payload.channels[1].value + "\r\n"; State.VmTestStatus.CommLog += "BME280 気圧:" + parsed_data.payload.channels[2].value + "\r\n"; State.VmTestStatus.CommLog += "SDC10 温度:" + parsed_data.payload.channels[3].value + "\r\n"; State.VmTestStatus.CommLog += "SDC15 温度:" + parsed_data.payload.channels[4].value + "\r\n"; State.TempBme280 = parsed_data.payload.channels[0].value; State.HumidBme280 = parsed_data.payload.channels[1].value; State.PressBme280 = parsed_data.payload.channels[2].value; State.TempSdc10 = parsed_data.payload.channels[3].value; State.TempSdc15 = parsed_data.payload.channels[4].value; //Console.WriteLine("カウント:" + parsed_data.payload.channels[0].value); //Console.WriteLine("温度:" + parsed_data.payload.channels[1].value); //Console.WriteLine("湿度:" + parsed_data.payload.channels[2].value); //Console.WriteLine("気圧:" + parsed_data.payload.channels[3].value); //Console.WriteLine("高度:" + parsed_data.payload.channels[4].value); } else { State.VmTestStatus.CommLog += "keepalive\r\n"; Flags.Connection = true; //State.VmTestStatus.ColorConnection = General.OnBrush; //Console.WriteLine("keepalive"); } State.VmTestStatus.CommLog += "---------- Serialization After ---------\r\n"; State.VmTestStatus.CommLog += "\r\n"; //Console.WriteLine("---------- Serialization After ----------"); //Console.WriteLine(""); }; ws.OnError += (sender, e) => { Flags.Connection = false; //State.VmTestStatus.ColorConnection = General.NgBrush; nf.Notify( new NotificationMessage { Summary = "WebSocket Error", Body = e.Message, Icon = "notification-message-im" } ); }; ws.OnClose += (sender, e) => { Flags.Connection = false; //State.VmTestStatus.ColorConnection = General.NgBrush; nf.Notify( new NotificationMessage { Summary = string.Format("WebSocket Close ({0})", e.Code), Body = e.Reason, Icon = "notification-message-im" } ); }; #if DEBUG // To change the logging level. ws.Log.Level = LogLevel.Trace; // To change the wait time for the response to the Ping or Close. //ws.WaitTime = TimeSpan.FromSeconds (10); // To emit a WebSocket.OnMessage event when receives a ping. //ws.EmitOnPing = true; #endif // To enable the Per-message Compression extension. //ws.Compression = CompressionMethod.Deflate; // To validate the server certificate. /* * ws.SslConfiguration.ServerCertificateValidationCallback = * (sender, certificate, chain, sslPolicyErrors) => { * ws.Log.Debug ( * String.Format ( * "Certificate:\n- Issuer: {0}\n- Subject: {1}", * certificate.Issuer, * certificate.Subject * ) * ); * * return true; // If the server certificate is valid. * }; */ // To send the credentials for the HTTP Authentication (Basic/Digest). //ws.SetCredentials ("nobita", "password", false); // To send the Origin header. //ws.Origin = "http://localhost:4649"; // To send the cookies. //ws.SetCookie (new Cookie ("name", "nobita")); //ws.SetCookie (new Cookie ("roles", "\"idiot, gunfighter\"")); // To connect through the HTTP Proxy server. //ws.SetProxy ("http://localhost:3128", "nobita", "password"); // To enable the redirection. //ws.EnableRedirection = true; // Connect to the server. ws.Connect(); // Connect to the server asynchronously. //ws.ConnectAsync (); State.VmTestStatus.CommLog += "\nType 'exit' to exit.\n"; while (Flags.CanExe) { Thread.Sleep(100); //State.VmTestStatus.CommLog += "> "; // var msg = Console.ReadLine(); // if (msg == "exit") // break; // Send a text message. //ws.Send(msg); } } Flags.IsActiveGetData = false; }); }
public NotifierTestParent(INotifierService s) { N = new Notifier(this, s); N.Subscribe(); }
public static async void ShowToastAsync(this Notifier notifier, string message, ToastBoxNotification.MsgType msgType, MessageOptions messageOptions = null) { await Application.Current.Dispatcher.InvokeAsync(() => notifier.Notify(() => new ToastBoxNotification(message, msgType, messageOptions))); }